Skip to content

Requestify Extension Type Validation #26844

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 4 commits into from
Aug 27, 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
17 changes: 7 additions & 10 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -1671,7 +1671,7 @@ class ExtensionDecl final : public GenericContext, public Decl,
SourceRange Braces;

/// The type being extended.
TypeLoc ExtendedType;
TypeRepr *ExtendedTypeRepr;

/// The nominal type being extended.
NominalTypeDecl *ExtendedNominal = nullptr;
Expand All @@ -1694,7 +1694,7 @@ class ExtensionDecl final : public GenericContext, public Decl,
friend class ConformanceLookupTable;
friend class IterableDeclContext;

ExtensionDecl(SourceLoc extensionLoc, TypeLoc extendedType,
ExtensionDecl(SourceLoc extensionLoc, TypeRepr *extendedType,
MutableArrayRef<TypeLoc> inherited,
DeclContext *parent,
TrailingWhereClause *trailingWhereClause);
Expand All @@ -1718,7 +1718,7 @@ class ExtensionDecl final : public GenericContext, public Decl,

/// Create a new extension declaration.
static ExtensionDecl *create(ASTContext &ctx, SourceLoc extensionLoc,
TypeLoc extendedType,
TypeRepr *extendedType,
MutableArrayRef<TypeLoc> inherited,
DeclContext *parent,
TrailingWhereClause *trailingWhereClause,
Expand All @@ -1738,7 +1738,7 @@ class ExtensionDecl final : public GenericContext, public Decl,
/// Only use this entry point when the complete type, as spelled in the source,
/// is required. For most clients, \c getExtendedNominal(), which provides
/// only the \c NominalTypeDecl, will suffice.
Type getExtendedType() const { return ExtendedType.getType(); }
Type getExtendedType() const;

/// Retrieve the nominal type declaration that is being extended.
NominalTypeDecl *getExtendedNominal() const;
Expand All @@ -1747,12 +1747,9 @@ class ExtensionDecl final : public GenericContext, public Decl,
/// type declaration.
bool alreadyBoundToNominal() const { return NextExtension.getInt(); }

/// Retrieve the extended type location.
TypeLoc &getExtendedTypeLoc() { return ExtendedType; }

/// Retrieve the extended type location.
const TypeLoc &getExtendedTypeLoc() const { return ExtendedType; }

/// Retrieve the extended type definition as written in the source, if it exists.
TypeRepr *getExtendedTypeRepr() const { return ExtendedTypeRepr; }

/// Retrieve the set of protocols that this type inherits (i.e,
/// explicitly conforms to).
MutableArrayRef<TypeLoc> getInherited() { return Inherited; }
Expand Down
18 changes: 18 additions & 0 deletions include/swift/AST/TypeCheckRequests.h
Original file line number Diff line number Diff line change
Expand Up @@ -1104,6 +1104,24 @@ class AbstractGenericSignatureRequest :
}
};

class ExtendedTypeRequest
: public SimpleRequest<ExtendedTypeRequest,
Type(ExtensionDecl *),
CacheKind::Cached> {
public:
using SimpleRequest::SimpleRequest;

private:
friend SimpleRequest;

// Evaluation.
llvm::Expected<Type> evaluate(Evaluator &eval, ExtensionDecl *) const;

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

// Allow AnyValue to compare two Type values, even though Type doesn't
// support ==.
template<>
Expand Down
1 change: 1 addition & 0 deletions include/swift/AST/TypeCheckerTypeIDZone.def
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,4 @@ SWIFT_TYPEID(EmittedMembersRequest)
SWIFT_TYPEID(IsImplicitlyUnwrappedOptionalRequest)
SWIFT_TYPEID(ClassAncestryFlagsRequest)
SWIFT_TYPEID(AbstractGenericSignatureRequest)
SWIFT_TYPEID(ExtendedTypeRequest)
10 changes: 8 additions & 2 deletions lib/AST/ASTPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2107,9 +2107,15 @@ void PrintAST::printExtension(ExtensionDecl *decl) {
recordDeclLoc(decl, [&]{
// We cannot extend sugared types.
Type extendedType = decl->getExtendedType();
if (!extendedType || !extendedType->getAnyNominal()) {
if (!extendedType) {
// Fallback to TypeRepr.
printTypeLoc(decl->getExtendedTypeLoc());
printTypeLoc(decl->getExtendedTypeRepr());
return;
}
if (!extendedType->getAnyNominal()) {
// Fallback to the type. This usually means we're trying to print an
// UnboundGenericType.
printTypeLoc(TypeLoc::withoutLoc(extendedType));
return;
}
printExtendedTypeName(extendedType, Printer, Options);
Expand Down
5 changes: 3 additions & 2 deletions lib/AST/ASTWalker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,9 @@ class Traversal : public ASTVisitor<Traversal, Expr*, Stmt*,
}

bool visitExtensionDecl(ExtensionDecl *ED) {
if (doIt(ED->getExtendedTypeLoc()))
return true;
if (auto *typeRepr = ED->getExtendedTypeRepr())
if (doIt(typeRepr))
return true;
for (auto &Inherit : ED->getInherited()) {
if (doIt(Inherit))
return true;
Expand Down
15 changes: 11 additions & 4 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1053,15 +1053,15 @@ NominalTypeDecl::takeConformanceLoaderSlow() {
}

ExtensionDecl::ExtensionDecl(SourceLoc extensionLoc,
TypeLoc extendedType,
TypeRepr *extendedType,
MutableArrayRef<TypeLoc> inherited,
DeclContext *parent,
TrailingWhereClause *trailingWhereClause)
: GenericContext(DeclContextKind::ExtensionDecl, parent),
Decl(DeclKind::Extension, parent),
IterableDeclContext(IterableDeclContextKind::ExtensionDecl),
ExtensionLoc(extensionLoc),
ExtendedType(extendedType),
ExtendedTypeRepr(extendedType),
Inherited(inherited)
{
Bits.ExtensionDecl.DefaultAndMaxAccessLevel = 0;
Expand All @@ -1070,7 +1070,7 @@ ExtensionDecl::ExtensionDecl(SourceLoc extensionLoc,
}

ExtensionDecl *ExtensionDecl::create(ASTContext &ctx, SourceLoc extensionLoc,
TypeLoc extendedType,
TypeRepr *extendedType,
MutableArrayRef<TypeLoc> inherited,
DeclContext *parent,
TrailingWhereClause *trailingWhereClause,
Expand Down Expand Up @@ -1151,6 +1151,13 @@ AccessLevel ExtensionDecl::getMaxAccessLevel() const {
DefaultAndMaxAccessLevelRequest{const_cast<ExtensionDecl *>(this)},
{AccessLevel::Private, AccessLevel::Private}).second;
}

Type ExtensionDecl::getExtendedType() const {
ASTContext &ctx = getASTContext();
return evaluateOrDefault(ctx.evaluator,
ExtendedTypeRequest{const_cast<ExtensionDecl *>(this)},
ErrorType::get(ctx));
}

/// Clone the given generic parameters in the given list. We don't need any
/// of the requirements, because they will be inferred.
Expand Down Expand Up @@ -7618,7 +7625,7 @@ void swift::simple_display(llvm::raw_ostream &out, const Decl *decl) {
simple_display(out, value);
} else if (auto ext = dyn_cast<ExtensionDecl>(decl)) {
out << "extension of ";
if (auto typeRepr = ext->getExtendedTypeLoc().getTypeRepr())
if (auto typeRepr = ext->getExtendedTypeRepr())
typeRepr->print(out);
else
ext->getSelfNominalTypeDecl()->dumpRef(out);
Expand Down
5 changes: 2 additions & 3 deletions lib/AST/NameLookup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2128,10 +2128,9 @@ ExtendedNominalRequest::evaluate(Evaluator &evaluator,
ASTContext &ctx = ext->getASTContext();

// Prefer syntactic information when we have it.
TypeLoc &typeLoc = ext->getExtendedTypeLoc();
if (auto typeRepr = typeLoc.getTypeRepr()) {
if (auto typeRepr = ext->getExtendedTypeRepr()) {
referenced = directReferencesForTypeRepr(evaluator, ctx, typeRepr, ext);
} else if (auto type = typeLoc.getType()) {
} else if (auto type = ext->getExtendedType()) {
// Fall back to semantic types.
// FIXME: In the long run, we shouldn't need this. Non-syntactic results
// should be cached.
Expand Down
13 changes: 9 additions & 4 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4545,9 +4545,13 @@ namespace {
auto loc = Impl.importSourceLoc(decl->getBeginLoc());
auto result = ExtensionDecl::create(
Impl.SwiftContext, loc,
TypeLoc::withoutLoc(objcClass->getDeclaredType()),
nullptr,
{ }, dc, nullptr, decl);

Impl.SwiftContext
.evaluator
.cacheOutput(ExtendedTypeRequest{result},
objcClass->getDeclaredType());

// Determine the type and generic args of the extension.
if (objcClass->getGenericParams()) {
result->createGenericParamsIfMissing(objcClass);
Expand Down Expand Up @@ -8143,9 +8147,10 @@ ClangImporter::Implementation::importDeclContextOf(
return knownExtension->second;

// Create a new extension for this nominal type/Clang submodule pair.
auto swiftTyLoc = TypeLoc::withoutLoc(nominal->getDeclaredType());
auto ext = ExtensionDecl::create(SwiftContext, SourceLoc(), swiftTyLoc, {},
auto ext = ExtensionDecl::create(SwiftContext, SourceLoc(), nullptr, {},
getClangModuleForDecl(decl), nullptr);
SwiftContext.evaluator.cacheOutput(ExtendedTypeRequest{ext},
nominal->getDeclaredType());
ext->setValidationToChecked();
ext->setMemberLoader(this, reinterpret_cast<uintptr_t>(declSubmodule));

Expand Down
8 changes: 6 additions & 2 deletions lib/IDE/SourceEntityWalker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,9 @@ bool SemaAnnotator::walkToDeclPre(Decl *D) {
return false;
}
} else if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
SourceRange SR = ED->getExtendedTypeLoc().getSourceRange();
SourceRange SR = SourceRange();
if (auto *repr = ED->getExtendedTypeRepr())
SR = repr->getSourceRange();
Loc = SR.Start;
if (Loc.isValid())
NameLen = ED->getASTContext().SourceMgr.getByteDistance(SR.Start, SR.End);
Expand Down Expand Up @@ -645,7 +647,9 @@ passReference(ValueDecl *D, Type Ty, SourceLoc BaseNameLoc, SourceRange Range,
}

if (!ExtDecls.empty() && BaseNameLoc.isValid()) {
auto ExtTyLoc = ExtDecls.back()->getExtendedTypeLoc().getLoc();
SourceLoc ExtTyLoc = SourceLoc();
if (auto *repr = ExtDecls.back()->getExtendedTypeRepr())
ExtTyLoc = repr->getLoc();
if (ExtTyLoc.isValid() && ExtTyLoc == BaseNameLoc) {
ExtDecl = ExtDecls.back();
}
Expand Down
4 changes: 3 additions & 1 deletion lib/IDE/SyntaxModel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,9 @@ bool ModelASTWalker::walkToDeclPre(Decl *D) {
SN.Kind = SyntaxStructureKind::Extension;
SN.Range = charSourceRangeFromSourceRange(SM, ED->getSourceRange());
SN.BodyRange = innerCharSourceRangeFromSourceRange(SM, ED->getBraces());
SourceRange NSR = ED->getExtendedTypeLoc().getSourceRange();
SourceRange NSR = SourceRange();
if (auto *repr = ED->getExtendedTypeRepr())
NSR = repr->getSourceRange();
SN.NameRange = charSourceRangeFromSourceRange(SM, NSR);

for (const TypeLoc &TL : ED->getInherited()) {
Expand Down
5 changes: 4 additions & 1 deletion lib/Index/Index.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,10 @@ static SourceLoc getLocForExtension(ExtensionDecl *D) {
// Use the 'End' token of the range, in case it is a compound name, e.g.
// extension A.B {}
// we want the location of 'B' token.
return D->getExtendedTypeLoc().getSourceRange().End;
if (auto *repr = D->getExtendedTypeRepr()) {
return repr->getSourceRange().End;
}
return SourceLoc();
}

namespace {
Expand Down
2 changes: 1 addition & 1 deletion lib/Parse/ParseDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3087,7 +3087,7 @@ Parser::parseDecl(ParseDeclOptions Flags,
diagnose(nominal->getLoc(), diag::note_in_decl_extension, false,
nominal->getName());
} else if (auto extension = dyn_cast<ExtensionDecl>(CurDeclContext)) {
if (auto repr = extension->getExtendedTypeLoc().getTypeRepr()) {
if (auto repr = extension->getExtendedTypeRepr()) {
if (auto idRepr = dyn_cast<IdentTypeRepr>(repr)) {
diagnose(extension->getLoc(), diag::note_in_decl_extension, true,
idRepr->getComponentRange().front()->getIdentifier());
Expand Down
2 changes: 1 addition & 1 deletion lib/Sema/TypeCheckAccess.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1939,7 +1939,7 @@ class ExportabilityChecker : public DeclVisitor<ExportabilityChecker> {
});

if (hasPublicMembers) {
checkType(ED->getExtendedTypeLoc(), ED,
checkType(ED->getExtendedType(), ED->getExtendedTypeRepr(), ED,
getDiagnoseCallback(ED, Reason::ExtensionWithPublicMembers),
getDiagnoseCallback(ED, Reason::ExtensionWithPublicMembers));
}
Expand Down
22 changes: 11 additions & 11 deletions lib/Sema/TypeCheckDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4414,23 +4414,23 @@ static bool isNonGenericTypeAliasType(Type type) {
return false;
}

static Type validateExtendedType(ExtensionDecl *ext) {
llvm::Expected<Type>
ExtendedTypeRequest::evaluate(Evaluator &eval, ExtensionDecl *ext) const {
auto error = [&ext]() {
ext->setInvalid();
return ErrorType::get(ext->getASTContext());
};

// If we didn't parse a type, fill in an error type and bail out.
if (!ext->getExtendedTypeLoc().getTypeRepr())
auto *extendedRepr = ext->getExtendedTypeRepr();
if (!extendedRepr)
return error();

// Compute the extended type.
TypeResolutionOptions options(TypeResolverContext::ExtensionBinding);
options |= TypeResolutionFlags::AllowUnboundGenerics;
auto tr = TypeResolution::forStructural(ext->getDeclContext());
auto extendedType = tr.resolveType(ext->getExtendedTypeLoc().getTypeRepr(),
options);
ext->getExtendedTypeLoc().setType(extendedType);
auto extendedType = tr.resolveType(extendedRepr, options);

if (extendedType->hasError())
return error();
Expand All @@ -4451,14 +4451,14 @@ static Type validateExtendedType(ExtensionDecl *ext) {
// Cannot extend a metatype.
if (extendedType->is<AnyMetatypeType>()) {
diags.diagnose(ext->getLoc(), diag::extension_metatype, extendedType)
.highlight(ext->getExtendedTypeLoc().getSourceRange());
.highlight(extendedRepr->getSourceRange());
return error();
}

// Cannot extend function types, tuple types, etc.
if (!extendedType->getAnyNominal()) {
diags.diagnose(ext->getLoc(), diag::non_nominal_extension, extendedType)
.highlight(ext->getExtendedTypeLoc().getSourceRange());
.highlight(extendedRepr->getSourceRange());
return error();
}

Expand All @@ -4468,7 +4468,7 @@ static Type validateExtendedType(ExtensionDecl *ext) {
!isNonGenericTypeAliasType(extendedType)) {
diags.diagnose(ext->getLoc(), diag::extension_specialization,
extendedType->getAnyNominal()->getName())
.highlight(ext->getExtendedTypeLoc().getSourceRange());
.highlight(extendedRepr->getSourceRange());
return error();
}

Expand All @@ -4483,7 +4483,9 @@ void TypeChecker::validateExtension(ExtensionDecl *ext) {

DeclValidationRAII IBV(ext);

auto extendedType = validateExtendedType(ext);
auto extendedType = evaluateOrDefault(Context.evaluator,
ExtendedTypeRequest{ext},
ErrorType::get(ext->getASTContext()));

if (auto *nominal = ext->getExtendedNominal()) {
// If this extension was not already bound, it means it is either in an
Expand All @@ -4496,8 +4498,6 @@ void TypeChecker::validateExtension(ExtensionDecl *ext) {
// Validate the nominal type declaration being extended.
validateDecl(nominal);

ext->getExtendedTypeLoc().setType(extendedType);

if (auto *genericParams = ext->getGenericParams()) {
GenericEnvironment *env =
checkExtensionGenericParams(*this, ext, extendedType, genericParams);
Expand Down
5 changes: 3 additions & 2 deletions lib/Serialization/Deserialization.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3791,7 +3791,7 @@ class swift::DeclDeserializer {
if (declOrOffset.isComplete())
return declOrOffset;

auto extension = ExtensionDecl::create(ctx, SourceLoc(), TypeLoc(), { },
auto extension = ExtensionDecl::create(ctx, SourceLoc(), nullptr, { },
DC, nullptr);
declOrOffset = extension;

Expand All @@ -3811,7 +3811,8 @@ class swift::DeclDeserializer {
MF.configureGenericEnvironment(extension, genericEnvID);

auto baseTy = MF.getType(baseID);
extension->getExtendedTypeLoc().setType(baseTy);
ctx.evaluator.cacheOutput(ExtendedTypeRequest{extension},
std::move(baseTy));
auto nominal = extension->getExtendedNominal();

if (isImplicit)
Expand Down
3 changes: 0 additions & 3 deletions test/SourceKit/InterfaceGen/Inputs/UnresolvedExtension.swift

This file was deleted.

3 changes: 0 additions & 3 deletions test/SourceKit/InterfaceGen/gen_swift_source.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,5 @@
// CHECK1: s:4Foo219FooOverlayClassBaseC
// CHECK1: FooOverlayClassBase.Type

// RUN: %sourcekitd-test -req=interface-gen %S/Inputs/UnresolvedExtension.swift -- %S/Inputs/UnresolvedExtension.swift | %FileCheck -check-prefix=CHECK2 %s
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@akyrtzi Can you remember what this test was trying to do? It seems like pure coincidence that it passed before.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't quite remember but I'd guess this is likely to have been checking that this test case doesn't trigger a crash.

// CHECK2: extension ET

// RUN: %sourcekitd-test -req=interface-gen %S/Inputs/Foo3.swift -- %S/Inputs/Foo3.swift | %FileCheck -check-prefix=CHECK3 %s
// CHECK3: public class C {