Skip to content

Sema: Simplify for ... in ... type checking #21811

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 11 additions & 64 deletions lib/Sema/CSSimplify.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1463,40 +1463,6 @@ static bool isStringCompatiblePointerBaseType(TypeChecker &TC,
return false;
}

/// Determine whether the first type with the given number of optionals
/// is potentially more optional than the second type with its number of
/// optionals.
static bool isPotentiallyMoreOptionalThan(Type type1, Type type2) {

SmallVector<Type, 2> optionals1;
Type objType1 = type1->lookThroughAllOptionalTypes(optionals1);
auto numOptionals1 = optionals1.size();

SmallVector<Type, 2> optionals2;
type2->lookThroughAllOptionalTypes(optionals2);
auto numOptionals2 = optionals2.size();

if (numOptionals1 <= numOptionals2 && !objType1->isTypeVariableOrMember())
return false;

return true;
}

/// Enumerate all of the applicable optional conversion restrictions
static void enumerateOptionalConversionRestrictions(
Type type1, Type type2,
ConstraintKind kind, ConstraintLocatorBuilder locator,
llvm::function_ref<void(ConversionRestrictionKind)> fn) {
// Optional-to-optional.
if (type1->getOptionalObjectType() && type2->getOptionalObjectType())
fn(ConversionRestrictionKind::OptionalToOptional);

// Inject a value into an optional.
if (isPotentiallyMoreOptionalThan(type2, type1)) {
fn(ConversionRestrictionKind::ValueToOptional);
}
}

/// Determine whether we can bind the given type variable to the given
/// fixed type.
static bool isBindable(TypeVariableType *typeVar, Type type) {
Expand Down Expand Up @@ -2180,15 +2146,8 @@ ConstraintSystem::matchTypes(Type type1, Type type2, ConstraintKind kind,

// Pointer arguments can be converted from pointer-compatible types.
if (kind >= ConstraintKind::ArgumentConversion) {
Type unwrappedType2 = type2;
bool type2IsOptional = false;
if (Type unwrapped = type2->getOptionalObjectType()) {
type2IsOptional = true;
unwrappedType2 = unwrapped;
}
PointerTypeKind pointerKind;
if (Type pointeeTy =
unwrappedType2->getAnyPointerElementType(pointerKind)) {
if (Type pointeeTy = type2->getAnyPointerElementType(pointerKind)) {
switch (pointerKind) {
case PTK_UnsafeRawPointer:
case PTK_UnsafeMutableRawPointer:
Expand Down Expand Up @@ -2217,24 +2176,10 @@ ConstraintSystem::matchTypes(Type type1, Type type2, ConstraintKind kind,

// Operators cannot use these implicit conversions.
if (kind == ConstraintKind::ArgumentConversion) {
// We can potentially convert from an UnsafeMutablePointer
// of a different type, if we're a void pointer.
Type unwrappedType1 = type1;
bool type1IsOptional = false;
if (Type unwrapped = type1->getOptionalObjectType()) {
type1IsOptional = true;
unwrappedType1 = unwrapped;
}

// Don't handle normal optional-related conversions here.
if (unwrappedType1->isEqual(unwrappedType2))
break;

PointerTypeKind type1PointerKind;
bool type1IsPointer{
unwrappedType1->getAnyPointerElementType(type1PointerKind)};
bool optionalityMatches = !type1IsOptional || type2IsOptional;
if (type1IsPointer && optionalityMatches) {
type1->getAnyPointerElementType(type1PointerKind)};
if (type1IsPointer) {
if (type1PointerKind == PTK_UnsafeMutablePointer) {
// Favor an UnsafeMutablePointer-to-UnsafeMutablePointer
// conversion.
Expand Down Expand Up @@ -2275,7 +2220,7 @@ ConstraintSystem::matchTypes(Type type1, Type type2, ConstraintKind kind,
}
}

if (type1IsPointer && optionalityMatches &&
if (type1IsPointer &&
(type1PointerKind == PTK_UnsafePointer ||
type1PointerKind == PTK_AutoreleasingUnsafeMutablePointer)) {
conversionsOrFixes.push_back(
Expand Down Expand Up @@ -2315,11 +2260,13 @@ ConstraintSystem::matchTypes(Type type1, Type type2, ConstraintKind kind,
// A value of type T, T?, or T! can be converted to type U? or U! if
// T is convertible to U.
if (!type1->is<LValueType>() && kind >= ConstraintKind::Subtype) {
enumerateOptionalConversionRestrictions(
type1, type2, kind, locator,
[&](ConversionRestrictionKind restriction) {
conversionsOrFixes.push_back(restriction);
});
if (type1->getOptionalObjectType() && type2->getOptionalObjectType()) {
// Optional-to-optional.
conversionsOrFixes.push_back(ConversionRestrictionKind::OptionalToOptional);
} else if (type2->getOptionalObjectType()) {
// Inject a value into an optional.
conversionsOrFixes.push_back(ConversionRestrictionKind::ValueToOptional);
}
}

// Allow '() -> T' to '() -> ()' and '() -> Never' to '() -> T' for closure
Expand Down
11 changes: 3 additions & 8 deletions lib/Sema/ConstraintLocator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,7 @@ void ConstraintLocator::Profile(llvm::FoldingSetNodeID &id, Expr *anchor,
case ClosureResult:
case ParentType:
case InstanceType:
case SequenceIteratorProtocol:
case GeneratorElementType:
case SequenceElementType:
case AutoclosureResult:
case GenericArgument:
case NamedTupleElement:
Expand Down Expand Up @@ -146,8 +145,8 @@ void ConstraintLocator::dump(SourceManager *sm, raw_ostream &out) {
out << "function result";
break;

case GeneratorElementType:
out << "generator element type";
case SequenceElementType:
out << "sequence element type";
break;

case GenericArgument:
Expand Down Expand Up @@ -190,10 +189,6 @@ void ConstraintLocator::dump(SourceManager *sm, raw_ostream &out) {
out << "rvalue adjustment";
break;

case SequenceIteratorProtocol:
out << "sequence iterator type";
break;

case SubscriptMember:
out << "subscript member";
break;
Expand Down
12 changes: 4 additions & 8 deletions lib/Sema/ConstraintLocator.h
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,8 @@ class ConstraintLocator : public llvm::FoldingSetNode {
ParentType,
/// The instance of a metatype type.
InstanceType,
/// The generic type of a sequence.
SequenceIteratorProtocol,
/// The element type of a generator.
GeneratorElementType,
/// The element type of a sequence in a for ... in ... loop.
SequenceElementType,
/// An argument passed in an autoclosure parameter
/// position, which must match the autoclosure return type.
AutoclosureResult,
Expand Down Expand Up @@ -147,8 +145,7 @@ class ConstraintLocator : public llvm::FoldingSetNode {
case ClosureResult:
case ParentType:
case InstanceType:
case SequenceIteratorProtocol:
case GeneratorElementType:
case SequenceElementType:
case AutoclosureResult:
case Requirement:
case Witness:
Expand Down Expand Up @@ -190,8 +187,7 @@ class ConstraintLocator : public llvm::FoldingSetNode {
case ApplyArgument:
case ApplyFunction:
case ApplyArgToParam:
case SequenceIteratorProtocol:
case GeneratorElementType:
case SequenceElementType:
case ClosureResult:
case ConstructorMember:
case InstanceType:
Expand Down
2 changes: 2 additions & 0 deletions lib/Sema/ConstraintSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1955,6 +1955,8 @@ Type simplifyTypeImpl(ConstraintSystem &cs, Type type, Fn getFixedTypeFn) {
// FIXME: It's kind of weird in general that we have to look
// through lvalue, inout and IUO types here
Type lookupBaseType = newBase->getWithoutSpecifierType();
if (auto selfType = lookupBaseType->getAs<DynamicSelfType>())
lookupBaseType = selfType->getSelfType();

if (lookupBaseType->mayHaveMembers()) {
auto *proto = assocType->getProtocol();
Expand Down
69 changes: 7 additions & 62 deletions lib/Sema/TypeCheckConstraints.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2640,84 +2640,29 @@ bool TypeChecker::typeCheckForEachBinding(DeclContext *dc, ForEachStmt *stmt) {
return true;
}

auto elementAssocType =
cast<AssociatedTypeDecl>(
sequenceProto->lookupDirect(tc.Context.Id_Element).front());

SequenceType = cs.createTypeVariable(Locator);
cs.addConstraint(ConstraintKind::Conversion, cs.getType(expr),
SequenceType, Locator);
cs.addConstraint(ConstraintKind::ConformsTo, SequenceType,
sequenceProto->getDeclaredType(), Locator);

auto iteratorLocator =
cs.getConstraintLocator(Locator,
ConstraintLocator::SequenceIteratorProtocol);
auto elementLocator =
cs.getConstraintLocator(iteratorLocator,
ConstraintLocator::GeneratorElementType);
cs.getConstraintLocator(Locator,
ConstraintLocator::SequenceElementType);

// Collect constraints from the element pattern.
auto pattern = Stmt->getPattern();
InitType = cs.generateConstraints(pattern, elementLocator);
if (!InitType)
return true;

// Manually search for the iterator witness. If no iterator/element pair
// exists, solve for them.
Type iteratorType;
Type elementType;

NameLookupOptions lookupOptions = defaultMemberTypeLookupOptions;
if (isa<AbstractFunctionDecl>(cs.DC))
lookupOptions |= NameLookupFlags::KnownPrivate;

auto sequenceType = cs.getType(expr)->getRValueType();

// Look through one level of optional; this improves recovery but doesn't
// change the result.
if (auto sequenceObjectType = sequenceType->getOptionalObjectType())
sequenceType = sequenceObjectType;

// If the sequence type is an existential, we should not attempt to
// look up the member type at all, since we cannot represent associated
// types of existentials.
//
// We will diagnose it later.
if (!sequenceType->isExistentialType() &&
(sequenceType->mayHaveMembers() ||
sequenceType->isTypeVariableOrMember())) {
ASTContext &ctx = tc.Context;
auto iteratorAssocType =
cast<AssociatedTypeDecl>(
sequenceProto->lookupDirect(ctx.Id_Iterator).front());

auto subs = sequenceType->getContextSubstitutionMap(
cs.DC->getParentModule(),
sequenceProto);
iteratorType = iteratorAssocType->getDeclaredInterfaceType()
.subst(subs);

if (iteratorType) {
auto iteratorProto =
tc.getProtocol(Stmt->getForLoc(),
KnownProtocolKind::IteratorProtocol);
if (!iteratorProto)
return true;

auto elementAssocType =
cast<AssociatedTypeDecl>(
iteratorProto->lookupDirect(ctx.Id_Element).front());

elementType = iteratorType->getTypeOfMember(
cs.DC->getParentModule(),
elementAssocType,
elementAssocType->getDeclaredInterfaceType());
}
}

if (elementType.isNull()) {
elementType = cs.createTypeVariable(elementLocator);
}

// Add a conversion constraint between the element type of the sequence
// and the type of the element pattern.
auto elementType = DependentMemberType::get(SequenceType, elementAssocType);
cs.addConstraint(ConstraintKind::Conversion, elementType, InitType,
elementLocator);

Expand Down
18 changes: 18 additions & 0 deletions test/decl/func/dynamic_self.swift
Original file line number Diff line number Diff line change
Expand Up @@ -393,3 +393,21 @@ final class FinalFactory : FactoryPattern {
self.init(factory: FinalFactory(_string: string))
}
}

// ----------------------------------------------------------------------------
// for ... in loops

struct DummyIterator : IteratorProtocol {
func next() -> Int? { return nil }
}

class Iterable : Sequence {
func returnsSelf() -> Self {
for _ in self {}
return self
}

func makeIterator() -> DummyIterator {
return DummyIterator()
}
}