Path: blob/main/contrib/llvm-project/clang/lib/Interpreter/CodeCompletion.cpp
35232 views
//===------ CodeCompletion.cpp - Code Completion for ClangRepl -------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the classes which performs code completion at the REPL.9//10//===----------------------------------------------------------------------===//1112#include "clang/Interpreter/CodeCompletion.h"13#include "clang/AST/ASTImporter.h"14#include "clang/AST/DeclLookups.h"15#include "clang/AST/DeclarationName.h"16#include "clang/AST/ExternalASTSource.h"17#include "clang/Basic/IdentifierTable.h"18#include "clang/Frontend/ASTUnit.h"19#include "clang/Frontend/CompilerInstance.h"20#include "clang/Frontend/FrontendActions.h"21#include "clang/Interpreter/Interpreter.h"22#include "clang/Lex/PreprocessorOptions.h"23#include "clang/Sema/CodeCompleteConsumer.h"24#include "clang/Sema/CodeCompleteOptions.h"25#include "clang/Sema/Sema.h"26#include "llvm/Support/Debug.h"27#define DEBUG_TYPE "REPLCC"2829namespace clang {3031const std::string CodeCompletionFileName = "input_line_[Completion]";3233clang::CodeCompleteOptions getClangCompleteOpts() {34clang::CodeCompleteOptions Opts;35Opts.IncludeCodePatterns = true;36Opts.IncludeMacros = true;37Opts.IncludeGlobals = true;38Opts.IncludeBriefComments = true;39return Opts;40}4142class ReplCompletionConsumer : public CodeCompleteConsumer {43public:44ReplCompletionConsumer(std::vector<std::string> &Results,45ReplCodeCompleter &CC)46: CodeCompleteConsumer(getClangCompleteOpts()),47CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),48CCTUInfo(CCAllocator), Results(Results), CC(CC) {}4950// The entry of handling code completion. When the function is called, we51// create a `Context`-based handler (see classes defined below) to handle each52// completion result.53void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,54CodeCompletionResult *InResults,55unsigned NumResults) final;5657CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }5859CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }6061private:62std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;63CodeCompletionTUInfo CCTUInfo;64std::vector<std::string> &Results;65ReplCodeCompleter &CC;66};6768/// The class CompletionContextHandler contains four interfaces, each of69/// which handles one type of completion result.70/// Its derived classes are used to create concrete handlers based on71/// \c CodeCompletionContext.72class CompletionContextHandler {73protected:74CodeCompletionContext CCC;75std::vector<std::string> &Results;7677private:78Sema &S;7980public:81CompletionContextHandler(Sema &S, CodeCompletionContext CCC,82std::vector<std::string> &Results)83: CCC(CCC), Results(Results), S(S) {}8485virtual ~CompletionContextHandler() = default;86/// Converts a Declaration completion result to a completion string, and then87/// stores it in Results.88virtual void handleDeclaration(const CodeCompletionResult &Result) {89auto PreferredType = CCC.getPreferredType();90if (PreferredType.isNull()) {91Results.push_back(Result.Declaration->getName().str());92return;93}9495if (auto *VD = dyn_cast<VarDecl>(Result.Declaration)) {96auto ArgumentType = VD->getType();97if (PreferredType->isReferenceType()) {98QualType RT = PreferredType->castAs<ReferenceType>()->getPointeeType();99Sema::ReferenceConversions RefConv;100Sema::ReferenceCompareResult RefRelationship =101S.CompareReferenceRelationship(SourceLocation(), RT, ArgumentType,102&RefConv);103switch (RefRelationship) {104case Sema::Ref_Compatible:105case Sema::Ref_Related:106Results.push_back(VD->getName().str());107break;108case Sema::Ref_Incompatible:109break;110}111} else if (S.Context.hasSameType(ArgumentType, PreferredType)) {112Results.push_back(VD->getName().str());113}114}115}116117/// Converts a Keyword completion result to a completion string, and then118/// stores it in Results.119virtual void handleKeyword(const CodeCompletionResult &Result) {120auto Prefix = S.getPreprocessor().getCodeCompletionFilter();121// Add keyword to the completion results only if we are in a type-aware122// situation.123if (!CCC.getBaseType().isNull() || !CCC.getPreferredType().isNull())124return;125if (StringRef(Result.Keyword).starts_with(Prefix))126Results.push_back(Result.Keyword);127}128129/// Converts a Pattern completion result to a completion string, and then130/// stores it in Results.131virtual void handlePattern(const CodeCompletionResult &Result) {}132133/// Converts a Macro completion result to a completion string, and then stores134/// it in Results.135virtual void handleMacro(const CodeCompletionResult &Result) {}136};137138class DotMemberAccessHandler : public CompletionContextHandler {139public:140DotMemberAccessHandler(Sema &S, CodeCompletionContext CCC,141std::vector<std::string> &Results)142: CompletionContextHandler(S, CCC, Results) {}143void handleDeclaration(const CodeCompletionResult &Result) override {144auto *ID = Result.Declaration->getIdentifier();145if (!ID)146return;147if (!isa<CXXMethodDecl>(Result.Declaration))148return;149const auto *Fun = cast<CXXMethodDecl>(Result.Declaration);150if (Fun->getParent()->getCanonicalDecl() ==151CCC.getBaseType()->getAsCXXRecordDecl()->getCanonicalDecl()) {152LLVM_DEBUG(llvm::dbgs() << "[In HandleCodeCompleteDOT] Name : "153<< ID->getName() << "\n");154Results.push_back(ID->getName().str());155}156}157158void handleKeyword(const CodeCompletionResult &Result) override {}159};160161void ReplCompletionConsumer::ProcessCodeCompleteResults(162class Sema &S, CodeCompletionContext Context,163CodeCompletionResult *InResults, unsigned NumResults) {164165auto Prefix = S.getPreprocessor().getCodeCompletionFilter();166CC.Prefix = Prefix;167168std::unique_ptr<CompletionContextHandler> CCH;169170// initialize fine-grained code completion handler based on the code171// completion context.172switch (Context.getKind()) {173case CodeCompletionContext::CCC_DotMemberAccess:174CCH.reset(new DotMemberAccessHandler(S, Context, this->Results));175break;176default:177CCH.reset(new CompletionContextHandler(S, Context, this->Results));178};179180for (unsigned I = 0; I < NumResults; I++) {181auto &Result = InResults[I];182switch (Result.Kind) {183case CodeCompletionResult::RK_Declaration:184if (Result.Hidden) {185break;186}187if (!Result.Declaration->getDeclName().isIdentifier() ||188!Result.Declaration->getName().starts_with(Prefix)) {189break;190}191CCH->handleDeclaration(Result);192break;193case CodeCompletionResult::RK_Keyword:194CCH->handleKeyword(Result);195break;196case CodeCompletionResult::RK_Macro:197CCH->handleMacro(Result);198break;199case CodeCompletionResult::RK_Pattern:200CCH->handlePattern(Result);201break;202}203}204205std::sort(Results.begin(), Results.end());206}207208class IncrementalSyntaxOnlyAction : public SyntaxOnlyAction {209const CompilerInstance *ParentCI;210211public:212IncrementalSyntaxOnlyAction(const CompilerInstance *ParentCI)213: ParentCI(ParentCI) {}214215protected:216void ExecuteAction() override;217};218219class ExternalSource : public clang::ExternalASTSource {220TranslationUnitDecl *ChildTUDeclCtxt;221ASTContext &ParentASTCtxt;222TranslationUnitDecl *ParentTUDeclCtxt;223224std::unique_ptr<ASTImporter> Importer;225226public:227ExternalSource(ASTContext &ChildASTCtxt, FileManager &ChildFM,228ASTContext &ParentASTCtxt, FileManager &ParentFM);229bool FindExternalVisibleDeclsByName(const DeclContext *DC,230DeclarationName Name) override;231void232completeVisibleDeclsMap(const clang::DeclContext *childDeclContext) override;233};234235// This method is intended to set up `ExternalASTSource` to the running236// compiler instance before the super `ExecuteAction` triggers parsing237void IncrementalSyntaxOnlyAction::ExecuteAction() {238CompilerInstance &CI = getCompilerInstance();239ExternalSource *myExternalSource =240new ExternalSource(CI.getASTContext(), CI.getFileManager(),241ParentCI->getASTContext(), ParentCI->getFileManager());242llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> astContextExternalSource(243myExternalSource);244CI.getASTContext().setExternalSource(astContextExternalSource);245CI.getASTContext().getTranslationUnitDecl()->setHasExternalVisibleStorage(246true);247248// Load all external decls into current context. Under the hood, it calls249// ExternalSource::completeVisibleDeclsMap, which make all decls on the redecl250// chain visible.251//252// This is crucial to code completion on dot members, since a bound variable253// before "." would be otherwise treated out-of-scope.254//255// clang-repl> Foo f1;256// clang-repl> f1.<tab>257CI.getASTContext().getTranslationUnitDecl()->lookups();258SyntaxOnlyAction::ExecuteAction();259}260261ExternalSource::ExternalSource(ASTContext &ChildASTCtxt, FileManager &ChildFM,262ASTContext &ParentASTCtxt, FileManager &ParentFM)263: ChildTUDeclCtxt(ChildASTCtxt.getTranslationUnitDecl()),264ParentASTCtxt(ParentASTCtxt),265ParentTUDeclCtxt(ParentASTCtxt.getTranslationUnitDecl()) {266ASTImporter *importer =267new ASTImporter(ChildASTCtxt, ChildFM, ParentASTCtxt, ParentFM,268/*MinimalImport : ON*/ true);269Importer.reset(importer);270}271272bool ExternalSource::FindExternalVisibleDeclsByName(const DeclContext *DC,273DeclarationName Name) {274275IdentifierTable &ParentIdTable = ParentASTCtxt.Idents;276277auto ParentDeclName =278DeclarationName(&(ParentIdTable.get(Name.getAsString())));279280DeclContext::lookup_result lookup_result =281ParentTUDeclCtxt->lookup(ParentDeclName);282283if (!lookup_result.empty()) {284return true;285}286return false;287}288289void ExternalSource::completeVisibleDeclsMap(290const DeclContext *ChildDeclContext) {291assert(ChildDeclContext && ChildDeclContext == ChildTUDeclCtxt &&292"No child decl context!");293294if (!ChildDeclContext->hasExternalVisibleStorage())295return;296297for (auto *DeclCtxt = ParentTUDeclCtxt; DeclCtxt != nullptr;298DeclCtxt = DeclCtxt->getPreviousDecl()) {299for (auto &IDeclContext : DeclCtxt->decls()) {300if (!llvm::isa<NamedDecl>(IDeclContext))301continue;302303NamedDecl *Decl = llvm::cast<NamedDecl>(IDeclContext);304305auto DeclOrErr = Importer->Import(Decl);306if (!DeclOrErr) {307// if an error happens, it usually means the decl has already been308// imported or the decl is a result of a failed import. But in our309// case, every import is fresh each time code completion is310// triggered. So Import usually doesn't fail. If it does, it just means311// the related decl can't be used in code completion and we can safely312// drop it.313llvm::consumeError(DeclOrErr.takeError());314continue;315}316317if (!llvm::isa<NamedDecl>(*DeclOrErr))318continue;319320NamedDecl *importedNamedDecl = llvm::cast<NamedDecl>(*DeclOrErr);321322SetExternalVisibleDeclsForName(ChildDeclContext,323importedNamedDecl->getDeclName(),324importedNamedDecl);325326if (!llvm::isa<CXXRecordDecl>(importedNamedDecl))327continue;328329auto *Record = llvm::cast<CXXRecordDecl>(importedNamedDecl);330331if (auto Err = Importer->ImportDefinition(Decl)) {332// the same as above333consumeError(std::move(Err));334continue;335}336337Record->setHasLoadedFieldsFromExternalStorage(true);338LLVM_DEBUG(llvm::dbgs()339<< "\nCXXRecrod : " << Record->getName() << " size(methods): "340<< std::distance(Record->method_begin(), Record->method_end())341<< " has def?: " << Record->hasDefinition()342<< " # (methods): "343<< std::distance(Record->getDefinition()->method_begin(),344Record->getDefinition()->method_end())345<< "\n");346for (auto *Meth : Record->methods())347SetExternalVisibleDeclsForName(ChildDeclContext, Meth->getDeclName(),348Meth);349}350ChildDeclContext->setHasExternalLexicalStorage(false);351}352}353354void ReplCodeCompleter::codeComplete(CompilerInstance *InterpCI,355llvm::StringRef Content, unsigned Line,356unsigned Col,357const CompilerInstance *ParentCI,358std::vector<std::string> &CCResults) {359auto DiagOpts = DiagnosticOptions();360auto consumer = ReplCompletionConsumer(CCResults, *this);361362auto diag = InterpCI->getDiagnosticsPtr();363std::unique_ptr<ASTUnit> AU(ASTUnit::LoadFromCompilerInvocationAction(364InterpCI->getInvocationPtr(), std::make_shared<PCHContainerOperations>(),365diag));366llvm::SmallVector<clang::StoredDiagnostic, 8> sd = {};367llvm::SmallVector<const llvm::MemoryBuffer *, 1> tb = {};368InterpCI->getFrontendOpts().Inputs[0] = FrontendInputFile(369CodeCompletionFileName, Language::CXX, InputKind::Source);370auto Act = std::make_unique<IncrementalSyntaxOnlyAction>(ParentCI);371std::unique_ptr<llvm::MemoryBuffer> MB =372llvm::MemoryBuffer::getMemBufferCopy(Content, CodeCompletionFileName);373llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;374375RemappedFiles.push_back(std::make_pair(CodeCompletionFileName, MB.get()));376// we don't want the AU destructor to release the memory buffer that MB377// owns twice, because MB handles its resource on its own.378AU->setOwnsRemappedFileBuffers(false);379AU->CodeComplete(CodeCompletionFileName, 1, Col, RemappedFiles, false, false,380false, consumer,381std::make_shared<clang::PCHContainerOperations>(), *diag,382InterpCI->getLangOpts(), InterpCI->getSourceManager(),383InterpCI->getFileManager(), sd, tb, std::move(Act));384}385386} // namespace clang387388389