Skip to content

Fix inheritance of generic initializers #17316

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
Jun 21, 2018
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
41 changes: 20 additions & 21 deletions lib/AST/Type.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3261,31 +3261,33 @@ TypeBase::getContextSubstitutions(const DeclContext *dc,
assert(ownerNominal == baseTy->getAnyNominal());

// Gather all of the substitutions for all levels of generic arguments.
GenericParamList *curGenericParams = dc->getGenericParamsOfContext();
if (!curGenericParams)
auto *genericSig = dc->getGenericSignatureOfContext();
if (!genericSig)
return substitutions;

while (baseTy && curGenericParams) {
auto params = genericSig->getGenericParams();
unsigned n = params.size();

while (baseTy && n > 0) {
// For a bound generic type, gather the generic parameter -> generic
// argument substitutions.
if (auto boundGeneric = baseTy->getAs<BoundGenericType>()) {
auto params = curGenericParams->getParams();
auto args = boundGeneric->getGenericArgs();
for (unsigned i = 0, n = args.size(); i != n; ++i) {
substitutions[params[i]->getDeclaredInterfaceType()->getCanonicalType()
for (unsigned i = 0, e = args.size(); i < e; ++i) {
substitutions[params[n - e + i]->getCanonicalType()
->castTo<GenericTypeParamType>()] = args[i];
}

// Continue looking into the parent.
baseTy = boundGeneric->getParent();
curGenericParams = curGenericParams->getOuterParameters();
n -= args.size();
continue;
}

// Continue looking into the parent.
if (auto protocolTy = baseTy->getAs<ProtocolType>()) {
baseTy = protocolTy->getParent();
curGenericParams = curGenericParams->getOuterParameters();
n--;
continue;
}

Expand All @@ -3298,19 +3300,16 @@ TypeBase::getContextSubstitutions(const DeclContext *dc,
llvm_unreachable("Bad base type");
}

if (genericEnv) {
auto *parentDC = dc;
while (parentDC->isTypeContext())
parentDC = parentDC->getParent();
if (auto *outerSig = parentDC->getGenericSignatureOfContext()) {
for (auto gp : outerSig->getGenericParams()) {
auto result = substitutions.insert(
{gp->getCanonicalType()->castTo<GenericTypeParamType>(),
genericEnv->mapTypeIntoContext(gp)});
assert(result.second);
(void) result;
}
}
while (n > 0) {
auto *gp = params[--n];
auto substTy = (genericEnv
? genericEnv->mapTypeIntoContext(gp)
: gp);
auto result = substitutions.insert(
{gp->getCanonicalType()->castTo<GenericTypeParamType>(),
substTy});
assert(result.second);
(void) result;
}

return substitutions;
Expand Down
156 changes: 121 additions & 35 deletions lib/Sema/CodeSynthesis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
#include "swift/AST/Availability.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ProtocolConformance.h"
Expand Down Expand Up @@ -2011,6 +2012,104 @@ static void createStubBody(TypeChecker &tc, ConstructorDecl *ctor) {
ctor->setStubImplementation(true);
}

static std::tuple<GenericSignature *, GenericEnvironment *,
GenericParamList *, SubstitutionMap>
configureGenericDesignatedInitOverride(ASTContext &ctx,
ClassDecl *classDecl,
Type superclassTy,
ConstructorDecl *superclassCtor) {
auto *superclassDecl = superclassTy->getAnyNominal();

auto *moduleDecl = classDecl->getParentModule();
auto subMap = superclassTy->getContextSubstitutionMap(
moduleDecl, superclassDecl);

GenericSignature *genericSig;
GenericEnvironment *genericEnv;

// Inheriting initializers that have their own generic parameters
auto *genericParams = superclassCtor->getGenericParams();
if (genericParams) {
SmallVector<GenericTypeParamDecl *, 4> newParams;

// First, clone the superclass constructor's generic parameter list,
// but change the depth of the generic parameters to be one greater
// than the depth of the subclass.
unsigned depth = 0;
if (auto *genericSig = classDecl->getGenericSignature())
depth = genericSig->getGenericParams().back()->getDepth() + 1;

for (auto *param : genericParams->getParams()) {
auto *newParam = new (ctx) GenericTypeParamDecl(classDecl,
param->getName(),
SourceLoc(),
depth,
param->getIndex());
newParams.push_back(newParam);
}

// Substitution map that maps the generic parameters of the superclass
// to the generic parameters of the derived class, and the generic
// parameters of the superclass initializer to the generic parameters
// of the derived class initializer.
auto *superclassSig = superclassCtor->getGenericSignature();
if (superclassSig) {
unsigned superclassDepth = 0;
if (auto *genericSig = superclassDecl->getGenericSignature())
superclassDepth = genericSig->getGenericParams().back()->getDepth() + 1;

subMap = SubstitutionMap::get(
superclassSig,
[&](SubstitutableType *type) -> Type {
auto *gp = cast<GenericTypeParamType>(type);
if (gp->getDepth() < superclassDepth)
return Type(gp).subst(subMap);
return CanGenericTypeParamType::get(
gp->getDepth() - superclassDepth + depth,
gp->getIndex(),
ctx);
},
[&](CanType depTy, Type substTy, ProtocolDecl *proto)
-> Optional<ProtocolConformanceRef> {
if (auto conf = subMap.lookupConformance(depTy, proto))
return conf;

return ProtocolConformanceRef(proto);
});
}

// We don't have to clone the requirements, because they're not
// used for anything.
genericParams = GenericParamList::create(ctx,
SourceLoc(),
newParams,
SourceLoc(),
ArrayRef<RequirementRepr>(),
SourceLoc());
genericParams->setOuterParameters(classDecl->getGenericParamsOfContext());

GenericSignatureBuilder builder(ctx);
builder.addGenericSignature(classDecl->getGenericSignature());

for (auto *newParam : newParams)
builder.addGenericParameter(newParam);

auto source =
GenericSignatureBuilder::FloatingRequirementSource::forAbstract();
for (auto reqt : superclassSig->getRequirements())
if (auto substReqt = reqt.subst(subMap))
builder.addRequirement(*substReqt, source, nullptr);

genericSig = std::move(builder).computeGenericSignature(SourceLoc());
genericEnv = genericSig->createGenericEnvironment();
} else {
genericEnv = classDecl->getGenericEnvironment();
genericSig = classDecl->getGenericSignature();
}

return std::make_tuple(genericSig, genericEnv, genericParams, subMap);
}

static void configureDesignatedInitAttributes(TypeChecker &tc,
ClassDecl *classDecl,
ConstructorDecl *ctor,
Expand Down Expand Up @@ -2088,9 +2187,7 @@ swift::createDesignatedInitOverride(TypeChecker &tc,
ClassDecl *classDecl,
ConstructorDecl *superclassCtor,
DesignatedInitKind kind) {
// FIXME: Inheriting initializers that have their own generic parameters
if (superclassCtor->getGenericParams())
return nullptr;
auto &ctx = tc.Context;

// Lookup will sometimes give us initializers that are from the ancestors of
// our immediate superclass. So, from the superclass constructor, we look
Expand All @@ -2104,54 +2201,42 @@ swift::createDesignatedInitOverride(TypeChecker &tc,
superclassCtor->getDeclContext()
->getAsNominalTypeOrNominalTypeExtensionContext();
Type superclassTy = classDecl->getSuperclass();
Type superclassTyInContext = classDecl->mapTypeIntoContext(superclassTy);
NominalTypeDecl *superclassDecl = superclassTy->getAnyNominal();
if (superclassCtorDecl != superclassDecl) {
return nullptr;
}

GenericSignature *genericSig;
GenericEnvironment *genericEnv;
GenericParamList *genericParams;
SubstitutionMap subMap;

std::tie(genericSig, genericEnv, genericParams, subMap) =
configureGenericDesignatedInitOverride(ctx,
classDecl,
superclassTy,
superclassCtor);

// Determine the initializer parameters.
auto &ctx = tc.Context;

// Create the 'self' declaration and patterns.
auto *selfDecl = ParamDecl::createSelf(SourceLoc(), classDecl);

// Create the initializer parameter patterns.
OptionSet<ParameterList::CloneFlags> options = ParameterList::Implicit;
options |= ParameterList::Inherited;
auto *bodyParams = superclassCtor->getParameterList(1)->clone(ctx,options);
auto *bodyParams = superclassCtor->getParameterList(1)->clone(ctx, options);

// If the superclass is generic, we need to map the superclass constructor's
// parameter types into the generic context of our class.
//
// We might have to apply substitutions, if for example we have a declaration
// like 'class A : B<Int>'.
if (superclassDecl->getGenericSignatureOfContext()) {
auto *moduleDecl = classDecl->getParentModule();
auto subMap = superclassTyInContext->getContextSubstitutionMap(
moduleDecl,
superclassDecl,
classDecl->getGenericEnvironment());

for (auto *decl : *bodyParams) {
auto paramTy = decl->getInterfaceType()->getInOutObjectType();

// Apply the superclass substitutions to produce a contextual
// type in terms of the derived class archetypes.
auto paramSubstTy = paramTy.subst(subMap);
decl->setType(paramSubstTy);

// Map it to an interface type in terms of the derived class
// generic signature.
decl->setInterfaceType(paramSubstTy->mapTypeOutOfContext());
}
} else {
for (auto *decl : *bodyParams) {
if (!decl->hasType())
decl->setType(
classDecl->mapTypeIntoContext(
decl->getInterfaceType()->getInOutObjectType()));
}
for (auto *decl : *bodyParams) {
auto paramTy = decl->getInterfaceType();
auto substTy = paramTy.subst(subMap);
decl->setInterfaceType(substTy);
decl->setType(GenericEnvironment::mapTypeIntoContext(genericEnv, substTy));
}

// Create the initializer declaration, inheriting the name,
Expand All @@ -2164,13 +2249,14 @@ swift::createDesignatedInitOverride(TypeChecker &tc,
/*Throws=*/superclassCtor->hasThrows(),
/*ThrowsLoc=*/SourceLoc(),
selfDecl, bodyParams,
/*GenericParams=*/nullptr, classDecl);
genericParams, classDecl);

ctor->setImplicit();

// Set the interface type of the initializer.
ctor->setGenericEnvironment(classDecl->getGenericEnvironmentOfContext());
tc.configureInterfaceType(ctor, ctor->getGenericSignature());
ctor->setGenericEnvironment(genericEnv);

tc.configureInterfaceType(ctor, genericSig);
ctor->setValidationStarted();

configureDesignatedInitAttributes(tc, classDecl,
Expand Down
Loading