Skip to content

[NFC] Refactor getRenameDecl to use the request evaluator #38615

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 1 commit into from
Jul 26, 2021
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
10 changes: 9 additions & 1 deletion include/swift/AST/Module.h
Original file line number Diff line number Diff line change
Expand Up @@ -774,7 +774,6 @@ class ModuleDecl : public DeclContext, public TypeDecl {
void collectBasicSourceFileInfo(
llvm::function_ref<void(const BasicSourceFileInfo &)> callback) const;

public:
/// Retrieve a fingerprint value that summarizes the contents of this module.
///
/// This interface hash a of a module is guaranteed to change if the interface
Expand All @@ -787,6 +786,15 @@ class ModuleDecl : public DeclContext, public TypeDecl {
/// contents have been made.
Fingerprint getFingerprint() const;

/// Returns an approximation of whether the given module could be
/// redistributed and consumed by external clients.
///
/// FIXME: The scope of this computation should be limited entirely to
/// RenamedDeclRequest. Unfortunately, it has been co-opted to support the
/// \c SerializeOptionsForDebugging hack. Once this information can be
/// transferred from module files to the dSYMs, remove this.
bool isExternallyConsumed() const;

SourceRange getSourceRange() const { return SourceRange(); }

static bool classof(const DeclContext *DC) {
Expand Down
17 changes: 17 additions & 0 deletions include/swift/AST/TypeCheckRequests.h
Original file line number Diff line number Diff line change
Expand Up @@ -3003,6 +3003,23 @@ class AsyncAlternativeRequest
bool isCached() const { return true; }
};

class RenamedDeclRequest
: public SimpleRequest<RenamedDeclRequest,
ValueDecl *(const ValueDecl *, const AvailableAttr *),
RequestFlags::Cached> {
public:
using SimpleRequest::SimpleRequest;

private:
friend SimpleRequest;

ValueDecl *evaluate(Evaluator &evaluator, const ValueDecl *attached,
const AvailableAttr *attr) const;

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

void simple_display(llvm::raw_ostream &out, Type value);
void simple_display(llvm::raw_ostream &out, const TypeRepr *TyR);
void simple_display(llvm::raw_ostream &out, ImplicitMemberAction action);
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 @@ -334,3 +334,6 @@ SWIFT_REQUEST(TypeChecker, GetImplicitSendableRequest,
SWIFT_REQUEST(TypeChecker, AsyncAlternativeRequest,
AbstractFunctionDecl *(AbstractFunctionDecl *),
Cached, NoLocationInfo)
SWIFT_REQUEST(TypeChecker, RenamedDeclRequest,
ValueDecl *(const ValueDecl *),
Cached, NoLocationInfo)
9 changes: 0 additions & 9 deletions include/swift/Frontend/Frontend.h
Original file line number Diff line number Diff line change
Expand Up @@ -403,15 +403,6 @@ class CompilerInvocation {
SerializationOptions
computeSerializationOptions(const SupplementaryOutputPaths &outs,
const ModuleDecl *module) const;

/// Returns an approximation of whether the given module could be
/// redistributed and consumed by external clients.
///
/// FIXME: The scope of this computation should be limited entirely to
/// PrintAsObjC. Unfortunately, it has been co-opted to support the
/// \c SerializeOptionsForDebugging hack. Once this information can be
/// transferred from module files to the dSYMs, remove this.
bool isModuleExternallyConsumed(const ModuleDecl *mod) const;
};

/// A class which manages the state and execution of the compiler.
Expand Down
3 changes: 1 addition & 2 deletions include/swift/PrintAsObjC/PrintAsObjC.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ namespace swift {
/// header.
///
/// Returns true on error.
bool printAsObjC(raw_ostream &out, ModuleDecl *M, StringRef bridgingHeader,
AccessLevel minRequiredAccess);
bool printAsObjC(raw_ostream &out, ModuleDecl *M, StringRef bridgingHeader);
}

#endif
26 changes: 26 additions & 0 deletions lib/AST/Module.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1638,6 +1638,32 @@ Fingerprint ModuleDecl::getFingerprint() const {
return Fingerprint{std::move(hasher)};
}

bool ModuleDecl::isExternallyConsumed() const {
// Modules for executables aren't expected to be consumed by other modules.
// This picks up all kinds of entrypoints, including script mode,
// @UIApplicationMain and @NSApplicationMain.
if (hasEntryPoint()) {
return false;
}

// If an implicit Objective-C header was needed to construct this module, it
// must be the product of a library target.
if (!getImplicitImportInfo().BridgingHeaderPath.empty()) {
return false;
}

// App extensions are special beasts because they build without entrypoints
// like library targets, but they behave like executable targets because
// their associated modules are not suitable for distribution.
if (getASTContext().LangOpts.EnableAppExtensionRestrictions) {
return false;
}

// FIXME: This is still a lousy approximation of whether the module file will
// be externally consumed.
return true;
}

//===----------------------------------------------------------------------===//
// Cross-Import Overlays
//===----------------------------------------------------------------------===//
Expand Down
27 changes: 0 additions & 27 deletions lib/Frontend/CompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2118,30 +2118,3 @@ CompilerInvocation::setUpInputForSILTool(
}
return fileBufOrErr;
}

bool CompilerInvocation::isModuleExternallyConsumed(
const ModuleDecl *mod) const {
// Modules for executables aren't expected to be consumed by other modules.
// This picks up all kinds of entrypoints, including script mode,
// @UIApplicationMain and @NSApplicationMain.
if (mod->hasEntryPoint()) {
return false;
}

// If an implicit Objective-C header was needed to construct this module, it
// must be the product of a library target.
if (!getFrontendOptions().ImplicitObjCHeaderPath.empty()) {
return false;
}

// App extensions are special beasts because they build without entrypoints
// like library targets, but they behave like executable targets because
// their associated modules are not suitable for distribution.
if (mod->getASTContext().LangOpts.EnableAppExtensionRestrictions) {
return false;
}

// FIXME: This is still a lousy approximation of whether the module file will
// be externally consumed.
return true;
}
2 changes: 1 addition & 1 deletion lib/Frontend/Frontend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ SerializationOptions CompilerInvocation::computeSerializationOptions(
// the public.
serializationOpts.SerializeOptionsForDebugging =
opts.SerializeOptionsForDebugging.getValueOr(
!isModuleExternallyConsumed(module));
!module->isExternallyConsumed());

serializationOpts.DisableCrossModuleIncrementalInfo =
opts.DisableCrossModuleIncrementalBuild;
Expand Down
9 changes: 3 additions & 6 deletions lib/FrontendTool/FrontendTool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -174,14 +174,12 @@ static bool writeSIL(SILModule &SM, const PrimarySpecificPaths &PSPs,
///
/// \see swift::printAsObjC
static bool printAsObjCIfNeeded(StringRef outputPath, ModuleDecl *M,
StringRef bridgingHeader, bool moduleIsPublic) {
StringRef bridgingHeader) {
if (outputPath.empty())
return false;
return withOutputFile(M->getDiags(), outputPath,
[&](raw_ostream &out) -> bool {
auto requiredAccess = moduleIsPublic ? AccessLevel::Public
: AccessLevel::Internal;
return printAsObjC(out, M, bridgingHeader, requiredAccess);
return printAsObjC(out, M, bridgingHeader);
});
}

Expand Down Expand Up @@ -853,8 +851,7 @@ static bool emitAnyWholeModulePostTypeCheckSupplementaryOutputs(
}
hadAnyError |= printAsObjCIfNeeded(
Invocation.getObjCHeaderOutputPathForAtMostOnePrimary(),
Instance.getMainModule(), BridgingHeaderPathForPrint,
Invocation.isModuleExternallyConsumed(Instance.getMainModule()));
Instance.getMainModule(), BridgingHeaderPathForPrint);
}

// Only want the header if there's been any errors, ie. there's not much
Expand Down
90 changes: 5 additions & 85 deletions lib/PrintAsObjC/DeclAndTypePrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SwiftNameTranslation.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeVisitor.h"
#include "swift/IDE/CommentConversion.h"
#include "swift/Parse/Lexer.h"
Expand Down Expand Up @@ -927,96 +928,15 @@ class DeclAndTypePrinter::Implementation
return hasPrintedAnything;
}

const ValueDecl *getRenameDecl(const ValueDecl *D,
const ParsedDeclName renamedParsedDeclName) {
auto declContext = D->getDeclContext();
ASTContext &astContext = D->getASTContext();
auto renamedDeclName = renamedParsedDeclName.formDeclNameRef(astContext);

if (isa<ClassDecl>(D) || isa<ProtocolDecl>(D)) {
if (!renamedParsedDeclName.ContextName.empty()) {
return nullptr;
}
SmallVector<ValueDecl *, 1> decls;
declContext->lookupQualified(declContext->getParentModule(),
renamedDeclName.withoutArgumentLabels(),
NL_OnlyTypes,
decls);
if (decls.size() == 1)
return decls[0];
return nullptr;
}

TypeDecl *typeDecl = declContext->getSelfNominalTypeDecl();

const ValueDecl *renamedDecl = nullptr;
SmallVector<ValueDecl *, 4> lookupResults;
declContext->lookupQualified(typeDecl->getDeclaredInterfaceType(),
renamedDeclName, NL_QualifiedDefault,
lookupResults);

if (lookupResults.size() == 1) {
auto candidate = lookupResults[0];
if (!shouldInclude(candidate))
return nullptr;
if (candidate->getKind() != D->getKind() ||
(candidate->isInstanceMember() !=
cast<ValueDecl>(D)->isInstanceMember()))
return nullptr;

renamedDecl = candidate;
} else {
for (auto candidate : lookupResults) {
if (!shouldInclude(candidate))
continue;

if (candidate->getKind() != D->getKind() ||
(candidate->isInstanceMember() !=
cast<ValueDecl>(D)->isInstanceMember()))
continue;

if (isa<AbstractFunctionDecl>(candidate)) {
auto cParams = cast<AbstractFunctionDecl>(candidate)->getParameters();
auto dParams = cast<AbstractFunctionDecl>(D)->getParameters();

if (cParams->size() != dParams->size())
continue;

bool hasSameParameterTypes = true;
for (auto index : indices(*cParams)) {
auto cParamsType = cParams->get(index)->getType();
auto dParamsType = dParams->get(index)->getType();
if (!cParamsType->matchesParameter(dParamsType,
TypeMatchOptions())) {
hasSameParameterTypes = false;
break;
}
}

if (!hasSameParameterTypes) {
continue;
}
}

if (renamedDecl) {
// If we found a duplicated candidate then we would silently fail.
renamedDecl = nullptr;
break;
}
renamedDecl = candidate;
}
}
return renamedDecl;
}

void printRenameForDecl(const AvailableAttr *AvAttr, const ValueDecl *D,
bool includeQuotes) {
assert(!AvAttr->Rename.empty());

const ValueDecl *renamedDecl =
getRenameDecl(D, parseDeclName(AvAttr->Rename));

auto *renamedDecl = evaluateOrDefault(
getASTContext().evaluator, RenamedDeclRequest{D, AvAttr}, nullptr);
if (renamedDecl) {
assert(shouldInclude(renamedDecl) &&
"ObjC printer logic mismatch with renamed decl");
SmallString<128> scratch;
auto renamedObjCRuntimeName =
renamedDecl->getObjCRuntimeName()->getString(scratch);
Expand Down
6 changes: 4 additions & 2 deletions lib/PrintAsObjC/ModuleContentsWriter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,8 @@ class ModuleWriter {
void
swift::printModuleContentsAsObjC(raw_ostream &os,
llvm::SmallPtrSetImpl<ImportModuleTy> &imports,
ModuleDecl &M, AccessLevel minRequiredAccess) {
ModuleWriter(os, imports, M, minRequiredAccess).write();
ModuleDecl &M) {
auto requiredAccess = M.isExternallyConsumed() ? AccessLevel::Public
: AccessLevel::Internal;
ModuleWriter(os, imports, M, requiredAccess).write();
}
6 changes: 3 additions & 3 deletions lib/PrintAsObjC/ModuleContentsWriter.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ class ModuleDecl;

using ImportModuleTy = PointerUnion<ModuleDecl*, const clang::Module*>;

/// Prints the declarations of \p M to \p os, filtering by \p minRequiredAccess
/// and collecting imports in \p imports along the way.
/// Prints the declarations of \p M to \p os and collecting imports in
/// \p imports along the way.
void printModuleContentsAsObjC(raw_ostream &os,
llvm::SmallPtrSetImpl<ImportModuleTy> &imports,
ModuleDecl &M, AccessLevel minRequiredAccess);
ModuleDecl &M);

} // end namespace swift

Expand Down
5 changes: 2 additions & 3 deletions lib/PrintAsObjC/PrintAsObjC.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -383,14 +383,13 @@ static void writeEpilogue(raw_ostream &os) {
}

bool swift::printAsObjC(raw_ostream &os, ModuleDecl *M,
StringRef bridgingHeader,
AccessLevel minRequiredAccess) {
StringRef bridgingHeader) {
llvm::PrettyStackTraceString trace("While generating Objective-C header");

SmallPtrSet<ImportModuleTy, 8> imports;
std::string moduleContentsBuf;
llvm::raw_string_ostream moduleContents{moduleContentsBuf};
printModuleContentsAsObjC(moduleContents, imports, *M, minRequiredAccess);
printModuleContentsAsObjC(moduleContents, imports, *M);
std::string macroGuard = (llvm::Twine(M->getNameStr().upper()) + "_SWIFT_H").str();
writePrologue(os, M->getASTContext(), macroGuard);
writeImports(os, imports, *M, bridgingHeader);
Expand Down
Loading