Skip to content

Commit 9915890

Browse files
committed
Sema: Diagnose DynamicSelfType usages inside stored property initializers
A stored property initializer does not have access to either the 'self' instance or the 'Self' type, so SILGen would just crash when emitting one containing a reference to 'Self'. With some work on SILGen we could probably allow this, but for now let's diagnose instead of crashing. Fixes <rdar://problem/51561208>, <https://bugs.swift.org/browse/SR-10969>.
1 parent db59dc1 commit 9915890

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

include/swift/AST/DiagnosticsSema.def

+2
Original file line numberDiff line numberDiff line change
@@ -2595,6 +2595,8 @@ ERROR(dynamic_self_invalid_subscript,none,
25952595
"covariant 'Self' can only appear at the top level of subscript element type", ())
25962596
ERROR(dynamic_self_invalid_method,none,
25972597
"covariant 'Self' can only appear at the top level of method result type", ())
2598+
ERROR(dynamic_self_stored_property_init,none,
2599+
"covariant 'Self' type cannot be referenced from a stored property initializer", ())
25982600

25992601
//------------------------------------------------------------------------------
26002602
// MARK: Type Check Attributes

lib/Sema/TypeCheckCaptures.cpp

+9
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,10 @@ class FindCapturedVars : public ASTWalker {
8080
return GenericParamCaptureLoc;
8181
}
8282

83+
SourceLoc getDynamicSelfCaptureLoc() const {
84+
return DynamicSelfCaptureLoc;
85+
}
86+
8387
/// Check if the type of an expression references any generic
8488
/// type parameters, or the dynamic Self type.
8589
///
@@ -698,6 +702,11 @@ void TypeChecker::checkPatternBindingCaptures(NominalTypeDecl *typeDecl) {
698702
/*ObjC=*/false);
699703
init->walk(finder);
700704

705+
if (finder.getDynamicSelfCaptureLoc().isValid()) {
706+
diagnose(finder.getDynamicSelfCaptureLoc(),
707+
diag::dynamic_self_stored_property_init);
708+
}
709+
701710
auto captures = finder.getCaptureInfo();
702711
PBD->setCaptureInfo(i, captures);
703712
}

test/type/self.swift

+7
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ class C {
144144

145145
static func staticFunc() -> Self {}
146146
let stored: Self = Self.staticFunc() // expected-error {{stored property cannot have covariant 'Self' type}}
147+
// expected-error@-1 {{covariant 'Self' type cannot be referenced from a stored property initializer}}
147148

148149
var prop: Self { // expected-error {{mutable property cannot have covariant 'Self' type}}
149150
get {
@@ -247,3 +248,9 @@ enum E {
247248
return .e
248249
}
249250
}
251+
252+
class SelfStoredPropertyInit {
253+
static func myValue() -> Int { return 123 }
254+
255+
var value = Self.myValue() // expected-error {{covariant 'Self' type cannot be referenced from a stored property initializer}}
256+
}

0 commit comments

Comments
 (0)