Skip to content

Support for lifetime dependence specifiers on initializers #71353

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 2 commits into from
Feb 5, 2024
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
5 changes: 5 additions & 0 deletions include/swift/AST/AnyFunctionRef.h
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@ class AnyFunctionRef {
if (auto *AFD = TheFunction.dyn_cast<AbstractFunctionDecl *>()) {
if (auto *FD = dyn_cast<FuncDecl>(AFD))
return FD->mapTypeIntoContext(FD->getResultInterfaceType());
if (auto *CD = dyn_cast<ConstructorDecl>(AFD)) {
if (CD->hasLifetimeDependentReturn()) {
return CD->getResultInterfaceType();
}
}
return TupleType::getEmpty(AFD->getASTContext());
}
return TheFunction.get<AbstractClosureExpr *>()->getResultType();
Expand Down
15 changes: 12 additions & 3 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -8299,15 +8299,18 @@ class ConstructorDecl : public AbstractFunctionDecl {
/// inserted at the end of the initializer by SILGen.
Expr *CallToSuperInit = nullptr;

/// Valid when lifetime dependence specifiers are present.
TypeLoc InitRetType;

public:
ConstructorDecl(DeclName Name, SourceLoc ConstructorLoc,
ConstructorDecl(DeclName Name, SourceLoc ConstructorLoc,
bool Failable, SourceLoc FailabilityLoc,
bool Async, SourceLoc AsyncLoc,
bool Throws, SourceLoc ThrowsLoc,
TypeLoc thrownTy,
ParameterList *BodyParams,
GenericParamList *GenericParams,
DeclContext *Parent);
GenericParamList *GenericParams,
DeclContext *Parent, TypeRepr *InitRetTy);

static ConstructorDecl *
createImported(ASTContext &ctx, ClangNode clangNode, DeclName name,
Expand All @@ -8329,6 +8332,10 @@ class ConstructorDecl : public AbstractFunctionDecl {
/// Get the interface type of the initializing constructor.
Type getInitializerInterfaceType();

TypeRepr *getResultTypeRepr() const { return InitRetType.getTypeRepr(); }

void setDeserializedResultTypeLoc(TypeLoc ResultTyR);

/// Get the typechecked call to super.init expression, which needs to be
/// inserted at the end of the initializer by SILGen.
Expr *getSuperInitCall() { return CallToSuperInit; }
Expand Down Expand Up @@ -8408,6 +8415,8 @@ class ConstructorDecl : public AbstractFunctionDecl {
Bits.ConstructorDecl.HasStubImplementation = stub;
}

bool hasLifetimeDependentReturn() const;

ConstructorDecl *getOverriddenDecl() const {
return cast_or_null<ConstructorDecl>(
AbstractFunctionDecl::getOverriddenDecl());
Expand Down
8 changes: 8 additions & 0 deletions include/swift/AST/DiagnosticsParse.def
Original file line number Diff line number Diff line change
Expand Up @@ -2179,6 +2179,10 @@ ERROR(requires_experimental_feature, none,
"%2 is enabled",
(StringRef, bool, StringRef))

//------------------------------------------------------------------------------
// MARK: Lifetime dependence
//------------------------------------------------------------------------------

ERROR(expected_lparen_after_lifetime_dependence, PointsToFirstBadToken,
"expected '(' after lifetime dependence specifier", ())

Expand All @@ -2193,5 +2197,9 @@ ERROR(expected_rparen_after_lifetime_dependence, PointsToFirstBadToken,
ERROR(expected_param_index_lifetime_dependence, PointsToFirstBadToken,
"expected unsigned parameter index in lifetime dependence specifier", ())

ERROR(lifetime_dependence_invalid_init_return, PointsToFirstBadToken,
"expected Self return type for initializers with lifetime dependence "
"specifiers",
())
#define UNDEFINE_DIAGNOSTIC_MACROS
#include "DefineDiagnosticMacros.h"
4 changes: 4 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -7827,5 +7827,9 @@ ERROR(pack_iteration_where_clause_not_supported, none,
"cannot infer lifetime dependence, no ~Escapable or ~Copyable "
"parameters with ownership modifiers present",
())
ERROR(lifetime_dependence_ctor_non_self_or_nil_return, none,
"expected nil or self as return values in an initializer with "
"lifetime dependent specifiers",
())
#define UNDEFINE_DIAGNOSTIC_MACROS
#include "DefineDiagnosticMacros.h"
5 changes: 3 additions & 2 deletions lib/AST/ASTBridging.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -943,12 +943,13 @@ BridgedConstructorDecl BridgedConstructorDecl_createParsed(
auto throwsLoc = cThrowsLoc.unbridged();
auto failabilityMarkLoc = cFailabilityMarkLoc.unbridged();
// FIXME: rethrows

// TODO: Handle LifetimeDependentReturnTypeRepr here.
auto *decl = new (context) ConstructorDecl(
declName, cInitKeywordLoc.unbridged(), failabilityMarkLoc.isValid(),
failabilityMarkLoc, asyncLoc.isValid(), asyncLoc, throwsLoc.isValid(),
throwsLoc, thrownType.unbridged(), parameterList,
genericParams.unbridged(), cDeclContext.unbridged());
genericParams.unbridged(), cDeclContext.unbridged(),
/*InitRetTy*/ nullptr);
decl->setTrailingWhereClause(genericWhereClause.unbridged());
decl->setImplicitlyUnwrappedOptional(isIUO);

Expand Down
22 changes: 15 additions & 7 deletions lib/AST/ASTVerifier.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1075,17 +1075,25 @@ class Verifier : public ASTWalker {
resultType = FD->mapTypeIntoContext(resultType);
} else if (auto closure = dyn_cast<AbstractClosureExpr>(func)) {
resultType = closure->getResultType();
} else if (auto *CD = dyn_cast<ConstructorDecl>(func)) {
if (CD->hasLifetimeDependentReturn()) {
resultType = CD->getResultInterfaceType();
} else {
resultType = TupleType::getEmpty(Ctx);
}
} else {
resultType = TupleType::getEmpty(Ctx);
}

if (S->hasResult()) {
if (isa<ConstructorDecl>(func)) {
Out << "Expected ReturnStmt not to have a result. A constructor "
"should not return a result. Returned expression: ";
S->getResult()->dump(Out);
Out << "\n";
abort();
if (auto *CD = dyn_cast<ConstructorDecl>(func)) {
if (!CD->hasLifetimeDependentReturn()) {
Out << "Expected ReturnStmt not to have a result. A constructor "
"should not return a result. Returned expression: ";
S->getResult()->dump(Out);
Out << "\n";
abort();
}
}

auto result = S->getResult();
Expand Down
18 changes: 15 additions & 3 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3577,6 +3577,8 @@ TypeRepr *ValueDecl::getResultTypeRepr() const {
returnRepr = SD->getElementTypeRepr();
} else if (auto *MD = dyn_cast<MacroDecl>(this)) {
returnRepr = MD->resultType.getTypeRepr();
} else if (auto *CD = dyn_cast<ConstructorDecl>(this)) {
returnRepr = CD->getResultTypeRepr();
}

return returnRepr;
Expand Down Expand Up @@ -10383,7 +10385,7 @@ ConstructorDecl::ConstructorDecl(DeclName Name, SourceLoc ConstructorLoc,
TypeLoc ThrownType,
ParameterList *BodyParams,
GenericParamList *GenericParams,
DeclContext *Parent)
DeclContext *Parent, TypeRepr *ResultTyR)
: AbstractFunctionDecl(DeclKind::Constructor, Parent, Name, ConstructorLoc,
Async, AsyncLoc, Throws, ThrowsLoc, ThrownType,
/*HasImplicitSelfDecl=*/true,
Expand All @@ -10393,7 +10395,8 @@ ConstructorDecl::ConstructorDecl(DeclName Name, SourceLoc ConstructorLoc,
{
if (BodyParams)
setParameters(BodyParams);


InitRetType = TypeLoc(ResultTyR);
Bits.ConstructorDecl.HasStubImplementation = 0;
Bits.ConstructorDecl.Failable = Failable;

Expand All @@ -10414,11 +10417,16 @@ ConstructorDecl *ConstructorDecl::createImported(
failable, failabilityLoc,
async, asyncLoc,
throws, throwsLoc, TypeLoc::withoutLoc(thrownType),
bodyParams, genericParams, parent);
bodyParams, genericParams, parent,
/*LifetimeDependenceTypeRepr*/ nullptr);
ctor->setClangNode(clangNode);
return ctor;
}

void ConstructorDecl::setDeserializedResultTypeLoc(TypeLoc ResultTyR) {
InitRetType = ResultTyR;
}

bool ConstructorDecl::isObjCZeroParameterWithLongSelector() const {
// The initializer must have a single, non-empty argument name.
if (getName().getArgumentNames().size() != 1 ||
Expand All @@ -10432,6 +10440,10 @@ bool ConstructorDecl::isObjCZeroParameterWithLongSelector() const {
return params->get(0)->getInterfaceType()->isVoid();
}

bool ConstructorDecl::hasLifetimeDependentReturn() const {
return isa_and_nonnull<LifetimeDependentReturnTypeRepr>(getResultTypeRepr());
}

DestructorDecl::DestructorDecl(SourceLoc DestructorLoc, DeclContext *Parent)
: AbstractFunctionDecl(DeclKind::Destructor, Parent,
DeclBaseName::createDestructor(), DestructorLoc,
Expand Down
9 changes: 6 additions & 3 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3646,7 +3646,8 @@ namespace {
/*failable=*/false, /*FailabilityLoc=*/SourceLoc(),
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*ThrownType=*/TypeLoc(), bodyParams, genericParams, dc);
/*ThrownType=*/TypeLoc(), bodyParams, genericParams, dc,
/*LifetimeDependentReturnTypeRepr*/ nullptr);
} else {
auto resultTy = importedType.getType();

Expand Down Expand Up @@ -6221,7 +6222,8 @@ Decl *SwiftDeclConverter::importGlobalAsInitializer(
failable, /*FailabilityLoc=*/SourceLoc(),
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(), /*ThrownType=*/TypeLoc(),
parameterList, /*GenericParams=*/nullptr, dc);
parameterList, /*GenericParams=*/nullptr, dc,
/*LifetimeDependentReturnTypeRepr*/ nullptr);
result->setImplicitlyUnwrappedOptional(isIUO);
result->getASTContext().evaluator.cacheOutput(InitKindRequest{result},
std::move(initKind));
Expand Down Expand Up @@ -6735,7 +6737,8 @@ ConstructorDecl *SwiftDeclConverter::importConstructor(
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/importedName.getErrorInfo().has_value(),
/*ThrowsLoc=*/SourceLoc(), /*ThrownType=*/TypeLoc(), bodyParams,
/*GenericParams=*/nullptr, const_cast<DeclContext *>(dc));
/*GenericParams=*/nullptr, const_cast<DeclContext *>(dc),
/*LifetimeDependentReturnTypeRepr*/ nullptr);

addObjCAttribute(result, selector);
recordMemberInContext(dc, result);
Expand Down
25 changes: 14 additions & 11 deletions lib/ClangImporter/SwiftDeclSynthesizer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -493,9 +493,10 @@ SwiftDeclSynthesizer::createDefaultConstructor(NominalTypeDecl *structDecl) {
ConstructorDecl(name, structDecl->getLoc(),
/*Failable=*/false, /*FailabilityLoc=*/SourceLoc(),
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*ThrownType=*/TypeLoc(), emptyPL,
/*GenericParams=*/nullptr, structDecl);
/*GenericParams=*/nullptr, structDecl,
/*LifetimeDependentReturnTypeRepr*/ nullptr);

constructor->setAccess(AccessLevel::Public);

Expand Down Expand Up @@ -623,9 +624,10 @@ ConstructorDecl *SwiftDeclSynthesizer::createValueConstructor(
ConstructorDecl(name, structDecl->getLoc(),
/*Failable=*/false, /*FailabilityLoc=*/SourceLoc(),
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*ThrownType=*/TypeLoc(), paramList,
/*GenericParams=*/nullptr, structDecl);
/*GenericParams=*/nullptr, structDecl,
/*LifetimeDependentReturnTypeRepr*/ nullptr);

constructor->setAccess(AccessLevel::Public);

Expand Down Expand Up @@ -1271,13 +1273,14 @@ SwiftDeclSynthesizer::makeEnumRawValueConstructor(EnumDecl *enumDecl) {
auto paramPL = ParameterList::createWithoutLoc(param);

DeclName name(C, DeclBaseName::createConstructor(), paramPL);
auto *ctorDecl = new (C)
ConstructorDecl(name, enumDecl->getLoc(),
/*Failable=*/true, /*FailabilityLoc=*/SourceLoc(),
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*ThrownType=*/TypeLoc(), paramPL,
/*GenericParams=*/nullptr, enumDecl);
auto *ctorDecl =
new (C) ConstructorDecl(name, enumDecl->getLoc(),
/*Failable=*/true, /*FailabilityLoc=*/SourceLoc(),
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*ThrownType=*/TypeLoc(), paramPL,
/*GenericParams=*/nullptr, enumDecl,
/*LifetimeDependentReturnTypeRepr*/ nullptr);
ctorDecl->setImplicit();
ctorDecl->setAccess(AccessLevel::Public);
ctorDecl->setBodySynthesizer(synthesizeEnumRawValueConstructorBody, enumDecl);
Expand Down
13 changes: 11 additions & 2 deletions lib/Parse/ParseDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9817,7 +9817,16 @@ Parser::parseDeclInit(ParseDeclOptions Flags, DeclAttributes &Attributes) {
isAsync = true;
}

if (FuncRetTy) {
if (auto *lifetimeTyR =
dyn_cast_or_null<LifetimeDependentReturnTypeRepr>(FuncRetTy)) {
auto *identTyR = dyn_cast<SimpleIdentTypeRepr>(lifetimeTyR->getBase());
if (!identTyR ||
identTyR->getNameRef().getBaseIdentifier() != Context.Id_Self) {
diagnose(FuncRetTy->getStartLoc(),
diag::lifetime_dependence_invalid_init_return);
return nullptr;
}
} else if (FuncRetTy) {
diagnose(FuncRetTy->getStartLoc(), diag::initializer_result_type)
.fixItRemove(FuncRetTy->getSourceRange());
}
Expand All @@ -9836,7 +9845,7 @@ Parser::parseDeclInit(ParseDeclOptions Flags, DeclAttributes &Attributes) {
isAsync, asyncLoc,
throwsLoc.isValid(), throwsLoc,
thrownTy, BodyParams, GenericParams,
CurDeclContext);
CurDeclContext, FuncRetTy);
CD->setImplicitlyUnwrappedOptional(IUO);
CD->getAttrs() = Attributes;

Expand Down
15 changes: 11 additions & 4 deletions lib/SILGen/SILGenConstructor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -680,10 +680,13 @@ void SILGenFunction::emitValueConstructor(ConstructorDecl *ctor) {
// Create a basic block to jump to for the implicit 'self' return.
// We won't emit this until after we've emitted the body.
// The epilog takes a void return because the return of 'self' is implicit.
// When lifetime dependence specifiers are present, epilog will take the
// explicit 'self' return.
prepareEpilog(ctor,
llvm::None,
ctor->getEffectiveThrownErrorType(),
CleanupLocation(ctor));
ctor->hasLifetimeDependentReturn()
? llvm::Optional<Type>(ctor->getResultInterfaceType())
: llvm::None,
ctor->getEffectiveThrownErrorType(), CleanupLocation(ctor));

// If the constructor can fail, set up an alternative epilog for constructor
// failure.
Expand Down Expand Up @@ -767,7 +770,11 @@ void SILGenFunction::emitValueConstructor(ConstructorDecl *ctor) {
// Emit the constructor body.
emitStmt(ctor->getTypecheckedBody());


if (ctor->hasLifetimeDependentReturn()) {
emitEpilog(ctor, /*UsesCustomEpilog*/ false);
return;
}

// Build a custom epilog block, since the AST representation of the
// constructor decl (which has no self in the return type) doesn't match the
// SIL representation.
Expand Down
6 changes: 4 additions & 2 deletions lib/Sema/CodeSynthesis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,8 @@ static ConstructorDecl *createImplicitConstructor(NominalTypeDecl *decl,
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*ThrownType=*/TypeLoc(),
paramList, /*GenericParams=*/nullptr, decl);
paramList, /*GenericParams=*/nullptr, decl,
/*LifetimeDependentReturnTypeRepr*/ nullptr);

// Mark implicit.
ctor->setImplicit();
Expand Down Expand Up @@ -830,7 +831,8 @@ createDesignatedInitOverride(ClassDecl *classDecl,
/*Throws=*/superclassCtor->hasThrows(),
/*ThrowsLoc=*/SourceLoc(),
TypeLoc::withoutLoc(thrownType),
bodyParams, genericParams, implCtx);
bodyParams, genericParams, implCtx,
/*LifetimeDependentReturnTypeRepr*/ nullptr);

ctor->setImplicit();

Expand Down
5 changes: 3 additions & 2 deletions lib/Sema/DerivedConformanceCodable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1888,11 +1888,12 @@ static ValueDecl *deriveDecodable_init(DerivedConformance &derived) {

auto *initDecl =
new (C) ConstructorDecl(name, SourceLoc(),
/*Failable=*/false,SourceLoc(),
/*Failable=*/false, SourceLoc(),
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/true, SourceLoc(),
/*ThrownType=*/TypeLoc(), paramList,
/*GenericParams=*/nullptr, conformanceDC);
/*GenericParams=*/nullptr, conformanceDC,
/*LifetimeDependentReturnTypeRepr*/ nullptr);
initDecl->setImplicit();
initDecl->setSynthesized();

Expand Down
3 changes: 2 additions & 1 deletion lib/Sema/DerivedConformanceCodingKey.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ static ValueDecl *deriveInitDecl(DerivedConformance &derived, Type paramType,
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*ThrownType=*/TypeLoc(),
paramList,
/*GenericParams=*/nullptr, parentDC);
/*GenericParams=*/nullptr, parentDC,
/*LifetimeDependentReturnTypeRepr*/ nullptr);

initDecl->setImplicit();

Expand Down
17 changes: 9 additions & 8 deletions lib/Sema/DerivedConformanceRawRepresentable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -423,15 +423,16 @@ deriveRawRepresentable_init(DerivedConformance &derived) {
auto paramList = ParameterList::createWithoutLoc(rawDecl);

DeclName name(C, DeclBaseName::createConstructor(), paramList);

auto initDecl =
new (C) ConstructorDecl(name, SourceLoc(),
/*Failable=*/ true, /*FailabilityLoc=*/SourceLoc(),
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*ThrownType=*/TypeLoc(), paramList,
/*GenericParams=*/nullptr, parentDC);

new (C) ConstructorDecl(name, SourceLoc(),
/*Failable=*/true, /*FailabilityLoc=*/SourceLoc(),
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*ThrownType=*/TypeLoc(), paramList,
/*GenericParams=*/nullptr, parentDC,
/*LifetimeDependentReturnTypeRepr*/ nullptr);

initDecl->setImplicit();
initDecl->setBodySynthesizer(&deriveBodyRawRepresentable_init);
addNonIsolatedToSynthesized(enumDecl, initDecl);
Expand Down
Loading