Skip to content

[CSGen] Emulate separate type-checking of $generator variable of for-in loop #59560

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

Merged
merged 1 commit into from
Jun 21, 2022
Merged
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
14 changes: 13 additions & 1 deletion lib/Sema/CSGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3944,8 +3944,20 @@ generateForEachStmtConstraints(
forEachStmtInfo.makeIteratorVar = PB;

// Type of sequence expression has to conform to Sequence protocol.
//
// Note that the following emulates having `$generator` separately
// type-checked by introducing a `TVO_PrefersSubtypeBinding` type
// variable that would make sure that result of `.makeIterator` would
// get ranked standalone.
{
cs.addConstraint(ConstraintKind::ConformsTo, cs.getType(sequenceExpr),
auto *externalIteratorType = cs.createTypeVariable(
cs.getConstraintLocator(sequenceExpr), TVO_PrefersSubtypeBinding);

cs.addConstraint(ConstraintKind::Equal, externalIteratorType,
cs.getType(sequenceExpr),
externalIteratorType->getImpl().getLocator());

cs.addConstraint(ConstraintKind::ConformsTo, externalIteratorType,
sequenceProto->getDeclaredInterfaceType(),
contextualLocator);

Expand Down
5 changes: 5 additions & 0 deletions test/stmt/foreach.swift
Original file line number Diff line number Diff line change
Expand Up @@ -245,3 +245,8 @@ func testForEachWhereWithClosure(_ x: [Int]) {
for i in x where x.contains(where: { $0.byteSwapped == i }) {}
}

// https://github.com/apple/swift/issues/59522 - use of `prefix` with generic base causes ambiguity in for-in statement
func test_no_ambiguity_with_prefix_iterator<C: Collection>(c: C) {
for _ in c.prefix(1) { // Ok
}
}