Skip to content

ClangImporter: Build type-checked AST for constants #25009

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 7 commits into from
May 23, 2019
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
16 changes: 15 additions & 1 deletion include/swift/AST/ASTContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ namespace swift {
class AvailabilityContext;
class BoundGenericType;
class ClangNode;
class ConcreteDeclRef;
class ConstructorDecl;
class Decl;
class DeclContext;
Expand Down Expand Up @@ -514,7 +515,20 @@ class ASTContext final {
bool hasArrayLiteralIntrinsics() const;

/// Retrieve the declaration of Swift.Bool.init(_builtinBooleanLiteral:)
ConstructorDecl *getBoolBuiltinInitDecl() const;
ConcreteDeclRef getBoolBuiltinInitDecl() const;

/// Retrieve the witness for init(_builtinIntegerLiteral:).
ConcreteDeclRef getIntBuiltinInitDecl(NominalTypeDecl *intDecl) const;

/// Retrieve the witness for init(_builtinFloatLiteral:).
ConcreteDeclRef getFloatBuiltinInitDecl(NominalTypeDecl *floatDecl) const;

/// Retrieve the witness for (_builtinStringLiteral:utf8CodeUnitCount:isASCII:).
ConcreteDeclRef getStringBuiltinInitDecl(NominalTypeDecl *stringDecl) const;

ConcreteDeclRef getBuiltinInitDecl(NominalTypeDecl *decl,
KnownProtocolKind builtinProtocol,
llvm::function_ref<DeclName (ASTContext &ctx)> initName) const;

/// Retrieve the declaration of Swift.==(Int, Int) -> Bool.
FuncDecl *getEqualIntDecl() const;
Expand Down
1 change: 1 addition & 0 deletions include/swift/AST/KnownStdlibTypes.def
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ KNOWN_STDLIB_TYPE_DECL(Float80, NominalTypeDecl, 0)
KNOWN_STDLIB_TYPE_DECL(_MaxBuiltinFloatType, TypeAliasDecl, 0)

KNOWN_STDLIB_TYPE_DECL(String, NominalTypeDecl, 0)
KNOWN_STDLIB_TYPE_DECL(StaticString, NominalTypeDecl, 0)
KNOWN_STDLIB_TYPE_DECL(Substring, NominalTypeDecl, 0)
KNOWN_STDLIB_TYPE_DECL(Array, NominalTypeDecl, 1)
KNOWN_STDLIB_TYPE_DECL(Set, NominalTypeDecl, 1)
Expand Down
90 changes: 72 additions & 18 deletions lib/AST/ASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,6 @@ FOR_KNOWN_FOUNDATION_TYPES(CACHE_FOUNDATION_DECL)
#define FUNC_DECL(Name, Id) FuncDecl *Get##Name = nullptr;
#include "swift/AST/KnownDecls.def"

/// Swift.Bool.init(_builtinBooleanLiteral:)
ConstructorDecl *BoolBuiltinInitDecl = nullptr;

/// func ==(Int, Int) -> Bool
FuncDecl *EqualIntDecl = nullptr;

Expand Down Expand Up @@ -277,6 +274,10 @@ FOR_KNOWN_FOUNDATION_TYPES(CACHE_FOUNDATION_DECL)
/// to the original property with the delegate.
llvm::DenseMap<const VarDecl *, VarDecl *> OriginalDelegatedProperties;

/// The builtin initializer witness for a literal. Used when building
/// LiteralExprs in fully-checked AST.
llvm::DenseMap<const NominalTypeDecl *, ConcreteDeclRef> BuiltinInitWitness;

/// Structure that captures data that is segregated into different
/// arenas.
struct Arena {
Expand Down Expand Up @@ -963,27 +964,80 @@ lookupOperatorFunc(const ASTContext &ctx, StringRef oper, Type contextType,
return nullptr;
}

ConstructorDecl *ASTContext::getBoolBuiltinInitDecl() const {
if (getImpl().BoolBuiltinInitDecl)
return getImpl().BoolBuiltinInitDecl;
ConcreteDeclRef ASTContext::getBoolBuiltinInitDecl() const {
auto fn = [&](ASTContext &ctx) {
return DeclName(ctx, DeclBaseName::createConstructor(),
{ Id_builtinBooleanLiteral });
};
auto builtinProtocolKind =
KnownProtocolKind::ExpressibleByBuiltinBooleanLiteral;
return getBuiltinInitDecl(getBoolDecl(), builtinProtocolKind, fn);
}

if (!getBoolDecl())
return nullptr;
ConcreteDeclRef
ASTContext::getIntBuiltinInitDecl(NominalTypeDecl *intDecl) const {
auto fn = [&](ASTContext &ctx) {
return DeclName(ctx, DeclBaseName::createConstructor(),
{ Id_builtinIntegerLiteral });
};
auto builtinProtocolKind =
KnownProtocolKind::ExpressibleByBuiltinIntegerLiteral;
return getBuiltinInitDecl(intDecl, builtinProtocolKind, fn);
}

DeclName initName(*const_cast<ASTContext *>(this),
DeclBaseName::createConstructor(),
{ Id_builtinBooleanLiteral });
auto members = getBoolDecl()->lookupDirect(initName);
ConcreteDeclRef
ASTContext::getFloatBuiltinInitDecl(NominalTypeDecl *floatDecl) const {
auto fn = [&](ASTContext &ctx) {
return DeclName(ctx, DeclBaseName::createConstructor(),
{ Id_builtinFloatLiteral });
};

if (members.size() != 1)
return nullptr;
auto builtinProtocolKind =
KnownProtocolKind::ExpressibleByBuiltinFloatLiteral;
return getBuiltinInitDecl(floatDecl, builtinProtocolKind, fn);
}

ConcreteDeclRef
ASTContext::getStringBuiltinInitDecl(NominalTypeDecl *stringDecl) const {
auto fn = [&](ASTContext &ctx) {
return DeclName(ctx, DeclBaseName::createConstructor(),
{ Id_builtinStringLiteral,
getIdentifier("utf8CodeUnitCount"),
getIdentifier("isASCII") });
};

auto builtinProtocolKind =
KnownProtocolKind::ExpressibleByBuiltinStringLiteral;
return getBuiltinInitDecl(stringDecl, builtinProtocolKind, fn);
}

ConcreteDeclRef
ASTContext::getBuiltinInitDecl(NominalTypeDecl *decl,
KnownProtocolKind builtinProtocolKind,
llvm::function_ref<DeclName (ASTContext &ctx)> initName) const {
auto &witness = getImpl().BuiltinInitWitness[decl];
if (witness)
return witness;

if (auto init = dyn_cast<ConstructorDecl>(members[0])) {
getImpl().BoolBuiltinInitDecl = init;
return init;
auto type = decl->getDeclaredType();
auto builtinProtocol = getProtocol(builtinProtocolKind);
auto builtinConformance = getStdlibModule()->lookupConformance(
type, builtinProtocol);
if (!builtinConformance) {
assert(false && "Missing required conformance");
witness = ConcreteDeclRef();
return witness;
}

return nullptr;
auto *ctx = const_cast<ASTContext *>(this);
witness = builtinConformance->getWitnessByName(type, initName(*ctx));
if (!witness) {
assert(false && "Missing required witness");
witness = ConcreteDeclRef();
return witness;
}

return witness;
}

FuncDecl *ASTContext::getEqualIntDecl() const {
Expand Down
132 changes: 110 additions & 22 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1001,6 +1001,7 @@ makeUnionFieldAccessors(ClangImporter::Implementation &Impl,
{ inoutSelf },
{ Identifier() });
selfPointer->setType(C.TheRawPointerType);
selfPointer->setThrows(false);

auto initializeFn = cast<FuncDecl>(getBuiltinValueDecl(
C, C.getIdentifier("initialize")));
Expand All @@ -1018,6 +1019,7 @@ makeUnionFieldAccessors(ClangImporter::Implementation &Impl,
{ newValueRef, selfPointer },
{ Identifier(), Identifier() });
initialize->setType(TupleType::getEmpty(C));
initialize->setThrows(false);

auto body = BraceStmt::create(C, SourceLoc(), { initialize }, SourceLoc(),
/*implicit*/ true);
Expand Down Expand Up @@ -1499,15 +1501,19 @@ static void makeStructRawValued(
createValueConstructor(Impl, structDecl, var,
/*wantCtorParamNames=*/false,
/*wantBody=*/!Impl.hasFinishedTypeChecking()));
structDecl->addMember(

auto *initRawValue =
createValueConstructor(Impl, structDecl, var,
/*wantCtorParamNames=*/true,
/*wantBody=*/!Impl.hasFinishedTypeChecking()));
/*wantBody=*/!Impl.hasFinishedTypeChecking());
structDecl->addMember(initRawValue);
structDecl->addMember(patternBinding);
structDecl->addMember(var);
structDecl->addMember(varGetter);

addSynthesizedTypealias(structDecl, ctx.Id_RawValue, underlyingType);
Impl.RawTypes[structDecl] = underlyingType;
Impl.RawInits[structDecl] = initRawValue;
}

/// Create a rawValue-ed constructor that bridges to its underlying storage.
Expand Down Expand Up @@ -1650,6 +1656,8 @@ static void makeStructRawValuedWithBridge(
structDecl->addMember(computedVarGetter);

addSynthesizedTypealias(structDecl, ctx.Id_RawValue, bridgedType);
Impl.RawTypes[structDecl] = bridgedType;
Impl.RawInits[structDecl] = init;
}

/// Build a declaration for an Objective-C subscript getter.
Expand Down Expand Up @@ -2852,6 +2860,8 @@ namespace {
enumDecl->addMember(rawValueBinding);

addSynthesizedTypealias(enumDecl, C.Id_RawValue, underlyingType);
Impl.RawTypes[enumDecl] = underlyingType;
Impl.RawInits[enumDecl] = rawValueConstructor;

// If we have an error wrapper, finish it up now that its
// nested enum has been constructed.
Expand Down Expand Up @@ -3381,7 +3391,7 @@ namespace {
// Create the global constant.
auto result = Impl.createConstant(name, dc, type,
clang::APValue(decl->getInitVal()),
ConstantConvertKind::Coerce,
ConstantConvertKind::None,
/*static*/dc->isTypeContext(), decl);
Impl.ImportedDecls[{decl->getCanonicalDecl(), getVersion()}] = result;

Expand Down Expand Up @@ -5546,11 +5556,15 @@ Decl *SwiftDeclConverter::importEnumCaseAlias(
auto constantRef =
new (Impl.SwiftContext) DeclRefExpr(original, DeclNameLoc(),
/*implicit*/ true);
constantRef->setType(original->getInterfaceType());

Type importedEnumTy = importedEnum->getDeclaredInterfaceType();

auto typeRef = TypeExpr::createImplicit(importedEnumTy, Impl.SwiftContext);
auto instantiate = new (Impl.SwiftContext)
DotSyntaxCallExpr(constantRef, SourceLoc(), typeRef);
instantiate->setType(importedEnumTy);
instantiate->setThrows(false);

Decl *CD = Impl.createConstant(name, importIntoDC, importedEnumTy,
instantiate, ConstantConvertKind::None,
Expand Down Expand Up @@ -8139,6 +8153,21 @@ ClangImporter::Implementation::importDeclContextOf(
return ext;
}

static Type getConstantLiteralType(ClangImporter::Implementation &Impl,
Type type, ConstantConvertKind convertKind) {
switch (convertKind) {
case ConstantConvertKind::Construction:
case ConstantConvertKind::ConstructionWithUnwrap: {
auto found = Impl.RawTypes.find(type->getAnyNominal());
assert(found != Impl.RawTypes.end());
return found->second;
}

default:
return type;
}
}

ValueDecl *
ClangImporter::Implementation::createConstant(Identifier name, DeclContext *dc,
Type type,
Expand Down Expand Up @@ -8180,20 +8209,49 @@ ClangImporter::Implementation::createConstant(Identifier name, DeclContext *dc,
if (isNegative)
printedValue = printedValue.drop_front();

auto literalType = getConstantLiteralType(*this, type, convertKind);

// Create the expression node.
StringRef printedValueCopy(context.AllocateCopy(printedValue));
if (value.getKind() == clang::APValue::Int) {
if (type->getCanonicalType()->isBool()) {
expr = new (context) BooleanLiteralExpr(value.getInt().getBoolValue(),
SourceLoc(),
/**Implicit=*/true);
auto *boolExpr =
new (context) BooleanLiteralExpr(value.getInt().getBoolValue(),
SourceLoc(),
/**Implicit=*/true);

boolExpr->setBuiltinInitializer(
context.getBoolBuiltinInitDecl());
boolExpr->setType(literalType);

expr = boolExpr;
} else {
expr = new (context) IntegerLiteralExpr(printedValueCopy, SourceLoc(),
/*Implicit=*/true);
auto *intExpr =
new (context) IntegerLiteralExpr(printedValueCopy, SourceLoc(),
/*Implicit=*/true);

auto *intDecl = literalType->getAnyNominal();
intExpr->setBuiltinInitializer(
context.getIntBuiltinInitDecl(intDecl));
intExpr->setType(literalType);

expr = intExpr;
}
} else {
expr = new (context) FloatLiteralExpr(printedValueCopy, SourceLoc(),
/*Implicit=*/true);
auto *floatExpr =
new (context) FloatLiteralExpr(printedValueCopy, SourceLoc(),
/*Implicit=*/true);

auto maxFloatTypeDecl = context.get_MaxBuiltinFloatTypeDecl();
floatExpr->setBuiltinType(
maxFloatTypeDecl->getUnderlyingTypeLoc().getType());

auto *floatDecl = literalType->getAnyNominal();
floatExpr->setBuiltinInitializer(
context.getFloatBuiltinInitDecl(floatDecl));
floatExpr->setType(literalType);

expr = floatExpr;
}

if (isNegative)
Expand All @@ -8215,6 +8273,13 @@ ClangImporter::Implementation::createConstant(Identifier name, DeclContext *dc,
bool isStatic,
ClangNode ClangN) {
auto expr = new (SwiftContext) StringLiteralExpr(value, SourceRange());

auto literalType = getConstantLiteralType(*this, type, convertKind);
auto *stringDecl = literalType->getAnyNominal();
expr->setBuiltinInitializer(
SwiftContext.getStringBuiltinInitDecl(stringDecl));
expr->setType(literalType);

return createConstant(name, dc, type, expr, convertKind, isStatic, ClangN);
}

Expand Down Expand Up @@ -8279,20 +8344,42 @@ ClangImporter::Implementation::createConstant(Identifier name, DeclContext *dc,
case ConstantConvertKind::Construction:
case ConstantConvertKind::ConstructionWithUnwrap: {
auto typeRef = TypeExpr::createImplicit(type, C);

expr = CallExpr::createImplicit(C, typeRef, { expr }, { C.Id_rawValue });
if (convertKind == ConstantConvertKind::ConstructionWithUnwrap)
expr = new (C) ForceValueExpr(expr, SourceLoc());
break;
}

case ConstantConvertKind::Coerce:
break;
// Reference init(rawValue: T)
auto found = RawInits.find(type->getAnyNominal());
assert(found != RawInits.end());

auto *init = found->second;
auto initTy = init->getInterfaceType()->removeArgumentLabels(1);
auto declRef =
new (C) DeclRefExpr(init, DeclNameLoc(), /*Implicit=*/true,
AccessSemantics::Ordinary, initTy);

// (Self) -> ...
initTy = initTy->castTo<FunctionType>()->getResult();
auto initRef = new (C) DotSyntaxCallExpr(declRef, SourceLoc(),
typeRef, initTy);
initRef->setThrows(false);

// (rawValue: T) -> ...
initTy = initTy->castTo<FunctionType>()->getResult();

auto initCall = CallExpr::createImplicit(C, initRef, { expr },
{ C.Id_rawValue });
initCall->setType(initTy);
initCall->setThrows(false);

expr = initCall;

// Force unwrap if our init(rawValue:) is failable, which is currently
// the case with enums.
if (convertKind == ConstantConvertKind::ConstructionWithUnwrap) {
initTy = initTy->getOptionalObjectType();
expr = new (C) ForceValueExpr(expr, SourceLoc());
expr->setType(initTy);
}

case ConstantConvertKind::Downcast: {
expr = new (C) ForcedCheckedCastExpr(expr, SourceLoc(), SourceLoc(),
TypeLoc::withoutLoc(type));
expr->setImplicit();
assert(initTy->isEqual(type));
break;
}
}
Expand All @@ -8304,6 +8391,7 @@ ClangImporter::Implementation::createConstant(Identifier name, DeclContext *dc,
func->setBody(BraceStmt::create(C, SourceLoc(),
ASTNode(ret),
SourceLoc()));
func->setBodyTypeCheckedIfPresent();
}

// Mark the function transparent so that we inline it away completely.
Expand Down
Loading