Skip to content

Commit b684431

Browse files
authored
Merge pull request #36818 from ahoppen/pr/rdar76329083
[TypeChecker] Fix assertion failure when using Self in extension that’s not on top-level
2 parents 7e2d238 + 78d6fb2 commit b684431

File tree

2 files changed

+29
-12
lines changed

2 files changed

+29
-12
lines changed

lib/Sema/TypeCheckType.cpp

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1130,21 +1130,26 @@ static Type diagnoseUnknownType(TypeResolution resolution,
11301130
NominalTypeDecl *nominal = nullptr;
11311131
if ((nominalDC = dc->getInnermostTypeContext()) &&
11321132
(nominal = nominalDC->getSelfNominalTypeDecl())) {
1133-
// Attempt to refer to 'Self' within a non-protocol nominal
1134-
// type. Fix this by replacing 'Self' with the nominal type name.
1135-
assert(isa<ClassDecl>(nominal) && "Must be a class");
1133+
if (isa<ClassDecl>(nominal)) {
1134+
// Attempt to refer to 'Self' within a non-protocol nominal
1135+
// type. Fix this by replacing 'Self' with the nominal type name.
11361136

1137-
// Produce a Fix-It replacing 'Self' with the nominal type name.
1138-
auto name = getDeclNameFromContext(dc, nominal);
1139-
diags.diagnose(comp->getNameLoc(), diag::dynamic_self_invalid, name)
1140-
.fixItReplace(comp->getNameLoc().getSourceRange(), name);
1137+
// Produce a Fix-It replacing 'Self' with the nominal type name.
1138+
auto name = getDeclNameFromContext(dc, nominal);
1139+
diags.diagnose(comp->getNameLoc(), diag::dynamic_self_invalid, name)
1140+
.fixItReplace(comp->getNameLoc().getSourceRange(), name);
11411141

1142-
auto type = resolution.mapTypeIntoContext(
1143-
dc->getInnermostTypeContext()->getSelfInterfaceType());
1142+
auto type = resolution.mapTypeIntoContext(
1143+
dc->getInnermostTypeContext()->getSelfInterfaceType());
11441144

1145-
comp->overwriteNameRef(DeclNameRef(nominal->getName()));
1146-
comp->setValue(nominal, nominalDC->getParent());
1147-
return type;
1145+
comp->overwriteNameRef(DeclNameRef(nominal->getName()));
1146+
comp->setValue(nominal, nominalDC->getParent());
1147+
return type;
1148+
} else {
1149+
diags.diagnose(comp->getNameLoc(), diag::cannot_find_type_in_scope,
1150+
comp->getNameRef());
1151+
return ErrorType::get(ctx);
1152+
}
11481153
}
11491154
// Attempt to refer to 'Self' from a free function.
11501155
diags.diagnose(comp->getNameLoc(), diag::dynamic_self_non_method,
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// RUN: not %target-swift-frontend -typecheck %s
2+
protocol Foo {}
3+
4+
func withTrailingClosure(x: (Int) -> Void) {}
5+
6+
_ = withTrailingClosure { (x) in
7+
extension Foo {
8+
func foo() {
9+
_ = MemoryLayout<Self>.size
10+
}
11+
}
12+
}

0 commit comments

Comments
 (0)