Skip to content

Commit aadd8e4

Browse files
committed
Allow parsing Self? as result type in initializers with explicit lifetime dependence
1 parent c0847e3 commit aadd8e4

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

lib/Parse/ParseDecl.cpp

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9921,8 +9921,19 @@ Parser::parseDeclInit(ParseDeclOptions Flags, DeclAttributes &Attributes) {
99219921

99229922
if (auto *lifetimeTyR =
99239923
dyn_cast_or_null<LifetimeDependentReturnTypeRepr>(FuncRetTy)) {
9924-
if (!lifetimeTyR->getBase()->isSimpleUnqualifiedIdentifier(
9925-
Context.Id_Self)) {
9924+
auto *base = lifetimeTyR->getBase();
9925+
9926+
auto isOptionalSimpleUnqualifiedIdentifier = [](TypeRepr *typeRepr,
9927+
Identifier str) {
9928+
if (auto *optionalTR = dyn_cast<OptionalTypeRepr>(typeRepr)) {
9929+
return optionalTR->getBase()->isSimpleUnqualifiedIdentifier(str);
9930+
}
9931+
return false;
9932+
};
9933+
9934+
// Diagnose if return type is not Self or Self?
9935+
if (!base->isSimpleUnqualifiedIdentifier(Context.Id_Self) &&
9936+
!isOptionalSimpleUnqualifiedIdentifier(base, Context.Id_Self)) {
99269937
diagnose(FuncRetTy->getStartLoc(),
99279938
diag::lifetime_dependence_invalid_init_return);
99289939
return nullptr;

test/Sema/explicit_lifetime_dependence_specifiers1.swift

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,27 @@ struct BufferView : ~Escapable {
1111
init(_ ptr: UnsafeRawBufferPointer) {
1212
self.ptr = ptr
1313
}
14-
init(_ c: borrowing Container) -> _borrow(c) Self { // expected-error{{invalid lifetime dependence on bitwise copyable type}}
15-
self.ptr = c.ptr
16-
return self
17-
}
1814
init(_ ptr: UnsafeRawBufferPointer, _ arr: borrowing Array<Int>) -> _borrow(arr) Self {
1915
self.ptr = ptr
2016
return self
2117
}
2218
init(_ ptr: UnsafeRawBufferPointer, _ arr: borrowing Array<Double>) -> _borrow(arr) Self {
2319
self.ptr = ptr
2420
}
21+
// TODO: Once Optional is ~Escapable, the error will go away
22+
init?(_ ptr: UnsafeRawBufferPointer, _ arr: borrowing Array<Float>) -> _borrow(arr) Self? { // expected-error{{lifetime dependence can only be specified on ~Escapable results}}
23+
if (Int.random(in: 1..<100) == 0) {
24+
return nil
25+
}
26+
self.ptr = ptr
27+
}
28+
init?(_ ptr: UnsafeRawBufferPointer, _ arr: borrowing Array<String>) -> _borrow(arr) Self? { // expected-error{{lifetime dependence can only be specified on ~Escapable results}}
29+
if (Int.random(in: 1..<100) == 0) {
30+
return nil
31+
}
32+
self.ptr = ptr
33+
return self
34+
}
2535
}
2636

2737
struct MutableBufferView : ~Escapable, ~Copyable {

0 commit comments

Comments
 (0)