Skip to content

[Sema] RuntimeMetadata: Add support for mutating/async methods and functions via a thunk #62738

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 3 commits into from
Jan 3, 2023
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
228 changes: 183 additions & 45 deletions lib/Sema/TypeCheckRuntimeMetadataAttr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@
//
//===----------------------------------------------------------------------===//

#include "TypeCheckConcurrency.h"
#include "TypeChecker.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ActorIsolation.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Initializer.h"
Expand Down Expand Up @@ -46,6 +48,184 @@ ValueDecl::getRuntimeDiscoverableAttributeGenerator(CustomAttr *attr) const {
return std::make_pair(body, init->getType()->mapTypeOutOfContext());
}

static TypeRepr *buildTypeRepr(DeclContext *typeContext) {
assert(typeContext->isTypeContext());

SmallVector<ComponentIdentTypeRepr *, 2> components;

auto &ctx = typeContext->getASTContext();
DeclContext *DC = typeContext;
while (!DC->isModuleContext()) {
auto *NTD = DC->getSelfNominalTypeDecl();
// Only contiguous chains of nominals and extensions thereof.
if (!NTD)
break;

auto *component = new (ctx) SimpleIdentTypeRepr(
/*Loc=*/DeclNameLoc(), NTD->createNameRef());

// Resolve the component right away, instead of
// involving name lookup. This plays well with
// the fact that initializer is anchored on a
// source file.
component->setValue(NTD, NTD->getDeclContext());

components.push_back(component);
DC = NTD->getDeclContext();
}

// Reverse the components to form a valid outer-to-inner name sequence.
std::reverse(components.begin(), components.end());

if (components.size() == 1)
return components.front();

return CompoundIdentTypeRepr::create(ctx, components);
}

/// Synthesizes a closure thunk that forwards all of the arguments
/// to the underlying method. This is required to support mutating
/// methods and create uniform signatures where for instance methods
/// first parameter is always `self` (with or without `inout`).
static ClosureExpr *synthesizeMethodThunk(DeclContext *thunkDC,
NominalTypeDecl *nominal,
FuncDecl *method) {
auto &ctx = method->getASTContext();

// If this is a method, let's form a thunk so that attribute initializer
// gets `([inout] T, Argument, ...) -> Result` signature.
auto *funcParams = method->getParameters();

SmallVector<ParamDecl *, 4> closureParams;

NullablePtr<ParamDecl> selfParam;
if (!method->isStatic()) {
auto *self = ParamDecl::createImplicit(
ctx,
/*argumentName=*/Identifier(),
/*parameterName=*/ctx.Id_self,
/*type=*/nominal->getDeclaredInterfaceType(), thunkDC,
method->isMutating() ? ParamSpecifier::InOut : ParamSpecifier::Default);

// This is very important for the solver, without a type repr
// it would create a type variable and attempt infer the type
// from the body.
self->setTypeRepr(buildTypeRepr(nominal));

closureParams.push_back(self);
selfParam = self;
}

if (funcParams) {
unsigned anonIdx = 0;
for (auto *param : *funcParams) {
auto name = param->getParameterName();
// Cannot leave parameter anonymous because it would be
// referenced in the body.
if (name.empty())
name = ctx.getIdentifier((Twine("$anon") + Twine(anonIdx++)).str());

auto *closureParam = ParamDecl::createImplicit(
ctx,
/*argumentName=*/Identifier(),
/*parameterName=*/name, param->getInterfaceType(), thunkDC,
param->getSpecifier());
closureParam->setTypeRepr(param->getTypeRepr());

closureParams.push_back(closureParam);
}
}

// return self.<func>(<arguments>)
SmallVector<ASTNode, 2> body;
{
NullablePtr<Expr> baseExpr;
if (method->isStatic()) {
baseExpr =
TypeExpr::createImplicit(nominal->getDeclaredInterfaceType(), ctx);
} else {
baseExpr = new (ctx) DeclRefExpr({selfParam.get()}, /*Loc=*/DeclNameLoc(),
/*implicit=*/true);
}

auto *memberRef = new (ctx) MemberRefExpr(
baseExpr.get(), /*dotLoc=*/SourceLoc(), {method}, /*loc=*/DeclNameLoc(),
/*Implicit=*/true);

SmallVector<Argument, 4> arguments;
if (funcParams) {
for (unsigned i = 0, n = funcParams->size(); i != n; ++i) {
const auto *param = funcParams->get(i);

Expr *argExpr = new (ctx)
DeclRefExpr({closureParams[method->isStatic() ? i : i + 1]},
/*Loc=*/DeclNameLoc(),
/*implicit=*/true);

if (param->isInOut()) {
argExpr = new (ctx) InOutExpr(/*operLoc=*/SourceLoc(), argExpr,
Type(), /*implicit=*/true);
}

arguments.push_back(
{/*labelLoc=*/SourceLoc(), param->getArgumentName(), argExpr});
}
}

Expr *call = CallExpr::createImplicit(
ctx, memberRef, ArgumentList::createImplicit(ctx, arguments));

bool isAsync = false;
bool isThrows = method->hasThrows();

switch (getActorIsolation(method)) {
case ActorIsolation::Unspecified:
case ActorIsolation::Independent: {
isAsync = method->hasAsync();
break;
}

case ActorIsolation::ActorInstance: {
isAsync = true;
isThrows |= nominal->isDistributedActor();
break;
}

case ActorIsolation::GlobalActor:
isAsync = true;
LLVM_FALLTHROUGH;
case ActorIsolation::GlobalActorUnsafe: {
break;
}
}

if (isAsync)
call = AwaitExpr::createImplicit(ctx, /*awaitLoc=*/SourceLoc(), call);

if (isThrows)
call = TryExpr::createImplicit(ctx, /*tryLoc=*/SourceLoc(), call);

body.push_back(new (ctx) ReturnStmt(/*ReturnLoc=*/SourceLoc(), call,
/*implicit=*/true));
}

DeclAttributes attrs;
auto *closure = new (ctx) ClosureExpr(
attrs, /*bracketRange=*/SourceRange(),
/*capturedSelf=*/nullptr, ParameterList::create(ctx, closureParams),
/*asyncLoc=*/SourceLoc(),
/*throwsLoc=*/SourceLoc(),
/*arrowLoc=*/SourceLoc(),
/*inLoc=*/SourceLoc(),
/*explicitResultType=*/nullptr, thunkDC);

closure->setBody(BraceStmt::createImplicit(ctx, body),
/*isSingleExpr=*/true);
closure->setImplicit();

return closure;
}

Expr *SynthesizeRuntimeMetadataAttrGenerator::evaluate(
Evaluator &evaluator, CustomAttr *attr, ValueDecl *attachedTo) const {
auto &ctx = attachedTo->getASTContext();
Expand Down Expand Up @@ -77,13 +257,7 @@ Expr *SynthesizeRuntimeMetadataAttrGenerator::evaluate(
DotSelfExpr(metatype, /*dot=*/SourceLoc(), /*self=*/SourceLoc());
} else if (auto *func = dyn_cast<FuncDecl>(attachedTo)) {
if (auto *nominal = func->getDeclContext()->getSelfNominalTypeDecl()) {
auto *baseExpr =
TypeExpr::createImplicit(nominal->getDeclaredInterfaceType(), ctx);

// Form an initializer call passing in the function reference
initArgument = new (ctx) MemberRefExpr(baseExpr, /*dotLoc=*/SourceLoc(),
{func}, /*loc=*/DeclNameLoc(),
/*Implicit=*/true);
initArgument = synthesizeMethodThunk(initContext, nominal, func);
} else {
initArgument = new (ctx)
DeclRefExpr({func}, /*Loc=*/DeclNameLoc(), /*implicit=*/true);
Expand All @@ -102,44 +276,7 @@ Expr *SynthesizeRuntimeMetadataAttrGenerator::evaluate(
// Build a type repr for base of the key path, since attribute
// could be attached to an inner type, we need to go up decl
// contexts and add every parent type.
{
SmallVector<ComponentIdentTypeRepr *, 2> baseNameComponents;

auto *DC = var->getDeclContext();
while (!DC->isModuleContext()) {
auto *NTD = DC->getSelfNominalTypeDecl();
// Only contiguous chains of nominals and extensions thereof.
if (!NTD)
break;

auto *component = new (ctx) SimpleIdentTypeRepr(
/*Loc=*/DeclNameLoc(), NTD->createNameRef());

// Resolve the component right away, instead of
// involving name lookup. This plays well with
// the fact that initializer is anchored on a
// source file.
component->setValue(NTD, NTD->getDeclContext());

baseNameComponents.push_back(component);
DC = NTD->getDeclContext();
}

// Reverse the components to form a valid outer-to-inner name sequence.
std::reverse(baseNameComponents.begin(), baseNameComponents.end());

// Set the 'root' of the key path to the newly build base name.
// We cannot do this via `parsedRoot` because it has strict
// rules about leading-dot.
TypeRepr *rootName = nullptr;
if (baseNameComponents.size() == 1) {
rootName = baseNameComponents.front();
} else {
rootName = CompoundIdentTypeRepr::create(ctx, baseNameComponents);
}

keyPath->setRootType(rootName);
}
keyPath->setRootType(buildTypeRepr(var->getDeclContext()));

initArgument = keyPath;
}
Expand Down Expand Up @@ -177,6 +314,7 @@ Expr *SynthesizeRuntimeMetadataAttrGenerator::evaluate(
return nullptr;

TypeChecker::contextualizeInitializer(initContext, result);
checkInitializerActorIsolation(initContext, result);
TypeChecker::checkInitializerEffects(initContext, result);

return result;
Expand Down
Loading