Skip to content

[Distributed] Implicit Codable conformance for distributed actors #41727

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
Mar 11, 2022
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
1 change: 1 addition & 0 deletions include/swift/AST/DistributedDecl.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ getDistributedSerializationRequirements(
llvm::SmallPtrSet<ProtocolDecl *, 2>
extractDistributedSerializationRequirements(
ASTContext &C, ArrayRef<Requirement> allRequirements);

}

#endif /* SWIFT_DECL_TYPECHECKDISTRIBUTED_H */
24 changes: 24 additions & 0 deletions include/swift/AST/TypeCheckRequests.h
Original file line number Diff line number Diff line change
Expand Up @@ -1039,6 +1039,30 @@ class IsDistributedActorRequest :
bool isCached() const { return true; }
};

/// Retrieve the implicit conformance for the given distributed actor type to
/// the Codable protocol protocol.
///
/// Similar to 'GetImplicitSendableRequest'.
class GetDistributedActorImplicitCodableRequest :
public SimpleRequest<GetDistributedActorImplicitCodableRequest,
NormalProtocolConformance *(NominalTypeDecl *, KnownProtocolKind),
RequestFlags::Cached> {
public:
using SimpleRequest::SimpleRequest;

private:
friend SimpleRequest;

NormalProtocolConformance *evaluate(
Evaluator &evaluator,
NominalTypeDecl *nominal,
KnownProtocolKind protoKind) const;

public:
// Caching
bool isCached() const { return true; }
};

/// Obtain the 'remoteCall' function of a 'DistributedActorSystem'.
class GetDistributedActorSystemRemoteCallFunctionRequest :
public SimpleRequest<GetDistributedActorSystemRemoteCallFunctionRequest,
Expand Down
3 changes: 3 additions & 0 deletions include/swift/AST/TypeCheckerTypeIDZone.def
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ SWIFT_REQUEST(TypeChecker, IsDefaultActorRequest,
Cached, NoLocationInfo)
SWIFT_REQUEST(TypeChecker, IsDistributedActorRequest, bool(NominalTypeDecl *),
Cached, NoLocationInfo)
SWIFT_REQUEST(TypeChecker, GetDistributedActorImplicitCodableRequest,
NormalProtocolConformance *(NominalTypeDecl *, KnownProtocolKind),
Cached, NoLocationInfo)
SWIFT_REQUEST(TypeChecker, GetDistributedActorSystemRemoteCallFunctionRequest,
AbstractFunctionDecl *(NominalTypeDecl *, bool),
Cached, NoLocationInfo)
Expand Down
2 changes: 1 addition & 1 deletion lib/AST/DistributedDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ Type swift::getDistributedActorSystemType(NominalTypeDecl *actor) {

auto DA = C.getDistributedActorDecl();
if (!DA)
return ErrorType::get(C);
return ErrorType::get(C); // FIXME(distributed): just use Type()

// Dig out the actor system type.
auto module = actor->getParentModule();
Expand Down
60 changes: 47 additions & 13 deletions lib/AST/Module.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1046,16 +1046,28 @@ ModuleDecl::lookupExistentialConformance(Type type, ProtocolDecl *protocol) {
}

/// Whether we should create missing conformances to the given protocol.
static bool shouldCreateMissingConformances(ProtocolDecl *proto) {
return proto->isSpecificProtocol(KnownProtocolKind::Sendable);
static bool shouldCreateMissingConformances(Type type, ProtocolDecl *proto) {
// Sendable may be able to be synthesized.
if (proto->isSpecificProtocol(KnownProtocolKind::Sendable)) {
return true;
}

// A 'distributed actor' may have to create missing Codable conformances.
if (auto nominal = dyn_cast_or_null<ClassDecl>(type->getAnyNominal())) {
return nominal->isDistributedActor() &&
(proto->isSpecificProtocol(swift::KnownProtocolKind::Decodable) ||
proto->isSpecificProtocol(swift::KnownProtocolKind::Encodable));
}

return false;
}

ProtocolConformanceRef ProtocolConformanceRef::forMissingOrInvalid(
Type type, ProtocolDecl *proto) {
// Introduce "missing" conformances when appropriate, so that type checking
// (and even code generation) can continue.
ASTContext &ctx = proto->getASTContext();
if (shouldCreateMissingConformances(proto)) {
if (shouldCreateMissingConformances(type, proto)) {
return ProtocolConformanceRef(
ctx.getBuiltinConformance(
type, proto, GenericSignature(), { },
Expand Down Expand Up @@ -1087,7 +1099,7 @@ ProtocolConformanceRef ModuleDecl::lookupConformance(Type type,
// If we aren't supposed to allow missing conformances through for this
// protocol, replace the result with an "invalid" result.
if (!allowMissing &&
shouldCreateMissingConformances(protocol) &&
shouldCreateMissingConformances(type, protocol) &&
result.hasMissingConformance(this))
return ProtocolConformanceRef::forInvalid();

Expand Down Expand Up @@ -1307,16 +1319,38 @@ LookupConformanceInModuleRequest::evaluate(
// Find the (unspecialized) conformance.
SmallVector<ProtocolConformance *, 2> conformances;
if (!nominal->lookupConformance(protocol, conformances)) {
if (!protocol->isSpecificProtocol(KnownProtocolKind::Sendable))
return ProtocolConformanceRef::forMissingOrInvalid(type, protocol);

// Try to infer Sendable conformance.
GetImplicitSendableRequest cvRequest{nominal};
if (auto conformance = evaluateOrDefault(
ctx.evaluator, cvRequest, nullptr)) {
conformances.clear();
conformances.push_back(conformance);
if (protocol->isSpecificProtocol(KnownProtocolKind::Sendable)) {
// Try to infer Sendable conformance.
GetImplicitSendableRequest cvRequest{nominal};
if (auto conformance = evaluateOrDefault(
ctx.evaluator, cvRequest, nullptr)) {
conformances.clear();
conformances.push_back(conformance);
} else {
return ProtocolConformanceRef::forMissingOrInvalid(type, protocol);
}
} else if (protocol->isSpecificProtocol(KnownProtocolKind::Encodable) ||
protocol->isSpecificProtocol(KnownProtocolKind::Decodable)) {
if (nominal->isDistributedActor()) {
auto protoKind =
protocol->isSpecificProtocol(KnownProtocolKind::Encodable)
? KnownProtocolKind::Encodable
: KnownProtocolKind::Decodable;
auto request = GetDistributedActorImplicitCodableRequest{
nominal, protoKind};

if (auto conformance =
evaluateOrDefault(ctx.evaluator, request, nullptr)) {
conformances.clear();
conformances.push_back(conformance);
} else {
return ProtocolConformanceRef::forMissingOrInvalid(type, protocol);
}
} else {
return ProtocolConformanceRef::forMissingOrInvalid(type, protocol);
}
} else {
// Was unable to infer the missing conformance.
return ProtocolConformanceRef::forMissingOrInvalid(type, protocol);
}
}
Expand Down
76 changes: 62 additions & 14 deletions lib/AST/ProtocolConformance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#include "swift/AST/ASTContext.h"
#include "swift/AST/Availability.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DistributedDecl.h"
#include "swift/AST/FileUnit.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/LazyResolver.h"
Expand Down Expand Up @@ -63,7 +64,12 @@ Witness::Witness(ValueDecl *decl, SubstitutionMap substitutions,
void Witness::dump() const { dump(llvm::errs()); }

void Witness::dump(llvm::raw_ostream &out) const {
// FIXME: Implement!
out << "Witness: ";
if (auto decl = this->getDecl()) {
decl->print(out);
} else {
out << "<no decl>\n";
}
}

ProtocolConformanceRef::ProtocolConformanceRef(ProtocolDecl *protocol,
Expand Down Expand Up @@ -1293,10 +1299,11 @@ void NominalTypeDecl::prepareConformanceTable() const {

// Actor classes conform to the actor protocol.
if (auto classDecl = dyn_cast<ClassDecl>(mutableThis)) {
if (classDecl->isDistributedActor())
if (classDecl->isDistributedActor()) {
addSynthesized(KnownProtocolKind::DistributedActor);
else if (classDecl->isActor())
} else if (classDecl->isActor()) {
addSynthesized(KnownProtocolKind::Actor);
}
}

// Global actors conform to the GlobalActor protocol.
Expand Down Expand Up @@ -1367,26 +1374,29 @@ IterableDeclContext::getLocalProtocols(ConformanceLookupKind lookupKind) const {
return result;
}

/// Find a synthesized Sendable conformance in this declaration context,
/// if there is one.
static ProtocolConformance *findSynthesizedSendableConformance(
const DeclContext *dc) {


/// Find a synthesized conformance in this declaration context, if there is one.
static ProtocolConformance *
findSynthesizedConformance(
const DeclContext *dc,
KnownProtocolKind protoKind) {
auto nominal = dc->getSelfNominalTypeDecl();
if (!nominal)
return nullptr;

if (isa<ProtocolDecl>(nominal))
// Perform some common checks
if (!nominal)
return nullptr;

if (dc->getParentModule() != nominal->getParentModule())
return nullptr;

auto cvProto = nominal->getASTContext().getProtocol(
KnownProtocolKind::Sendable);
auto &C = nominal->getASTContext();
auto cvProto = C.getProtocol(protoKind);
if (!cvProto)
return nullptr;

auto conformance = dc->getParentModule()->lookupConformance(
auto module = dc->getParentModule();
auto conformance = module->lookupConformance(
nominal->getDeclaredInterfaceType(), cvProto);
if (!conformance || !conformance.isConcrete())
return nullptr;
Expand All @@ -1405,6 +1415,43 @@ static ProtocolConformance *findSynthesizedSendableConformance(
return normal;
}

/// Find any synthesized conformances for given decl context.
///
/// Some protocol conformances can be synthesized by the compiler,
/// for those, we need to add them to "local conformances" because otherwise
/// we'd get missing symbols while attempting to use these.
static SmallVector<ProtocolConformance *, 2> findSynthesizedConformances(
const DeclContext *dc) {
auto nominal = dc->getSelfNominalTypeDecl();
if (!nominal)
return {};

// Try to find specific conformances
SmallVector<ProtocolConformance *, 2> result;

// Sendable may be synthesized for concrete types
if (!isa<ProtocolDecl>(nominal)) {
if (auto sendable =
findSynthesizedConformance(dc, KnownProtocolKind::Sendable)) {
result.push_back(sendable);
}
}

/// Distributed actors can synthesize Encodable/Decodable, so look for those
if (nominal->isDistributedActor()) {
if (auto conformance =
findSynthesizedConformance(dc, KnownProtocolKind::Encodable)) {
result.push_back(conformance);
}
if (auto conformance =
findSynthesizedConformance(dc, KnownProtocolKind::Decodable)) {
result.push_back(conformance);
}
}

return result;
}

std::vector<ProtocolConformance *>
LookupAllConformancesInContextRequest::evaluate(
Evaluator &eval, const IterableDeclContext *IDC) const {
Expand Down Expand Up @@ -1485,8 +1532,9 @@ IterableDeclContext::getLocalConformances(ConformanceLookupKind lookupKind)
// Look for a Sendable conformance globally. If it is synthesized
// and matches this declaration context, use it.
auto dc = getAsGenericContext();
if (auto conformance = findSynthesizedSendableConformance(dc))
for (auto conformance : findSynthesizedConformances(dc)) {
result.push_back(conformance);
}
break;
}

Expand Down
5 changes: 3 additions & 2 deletions lib/SILGen/SILGenConstructor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -836,8 +836,9 @@ void SILGenFunction::emitClassConstructorInitializer(ConstructorDecl *ctor) {
}

// Distributed actor initializers implicitly initialize their transport and id
if (isDesignatedDistActorInit)
emitDistActorImplicitPropertyInits(ctor, selfArg);
if (isDesignatedDistActorInit) {
emitDistributedActorImplicitPropertyInits(ctor, selfArg);
}

// Prepare the end of initializer location.
SILLocation endOfInitLoc = RegularLocation(ctor);
Expand Down
2 changes: 1 addition & 1 deletion lib/SILGen/SILGenDistributed.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ class ResignIdentity : public Cleanup {
};
} // end anonymous namespace

void SILGenFunction::emitDistActorImplicitPropertyInits(
void SILGenFunction::emitDistributedActorImplicitPropertyInits(
ConstructorDecl *ctor, ManagedValue selfArg) {
// Only designated initializers should perform this initialization.
assert(ctor->isDesignatedInit());
Expand Down
2 changes: 1 addition & 1 deletion lib/SILGen/SILGenFunction.h
Original file line number Diff line number Diff line change
Expand Up @@ -2048,7 +2048,7 @@ class LLVM_LIBRARY_VISIBILITY SILGenFunction

/// Initializes the implicit stored properties of a distributed actor that correspond to
/// its transport and identity.
void emitDistActorImplicitPropertyInits(
void emitDistributedActorImplicitPropertyInits(
ConstructorDecl *ctor, ManagedValue selfArg);

/// Given a function representing a distributed actor factory, emits the
Expand Down
3 changes: 2 additions & 1 deletion lib/Sema/CodeSynthesis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -300,12 +300,13 @@ static ConstructorDecl *createImplicitConstructor(NominalTypeDecl *decl,
if (swift::ensureDistributedModuleLoaded(decl)) {
// copy access level of distributed actor init from the nominal decl
accessLevel = decl->getEffectiveAccess();
auto systemTy = getDistributedActorSystemType(classDecl);

// Create the parameter.
auto *arg = new (ctx) ParamDecl(SourceLoc(), Loc, ctx.Id_system, Loc,
ctx.Id_system, decl);
arg->setSpecifier(ParamSpecifier::Default);
arg->setInterfaceType(getDistributedActorSystemType(classDecl));
arg->setInterfaceType(systemTy);
arg->setImplicit();

params.push_back(arg);
Expand Down
Loading