43#include "clang/AST/Decl.h"
44#include "clang/AST/DeclBase.h"
45#include "clang/Basic/CharInfo.h"
46#include "clang/Basic/LangOptions.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/TokenKinds.h"
49#include "clang/Format/Format.h"
50#include "clang/Frontend/CompilerInstance.h"
51#include "clang/Frontend/FrontendActions.h"
52#include "clang/Lex/ExternalPreprocessorSource.h"
53#include "clang/Lex/Lexer.h"
54#include "clang/Lex/Preprocessor.h"
55#include "clang/Lex/PreprocessorOptions.h"
56#include "clang/Sema/CodeCompleteConsumer.h"
57#include "clang/Sema/DeclSpec.h"
58#include "clang/Sema/Sema.h"
59#include "llvm/ADT/ArrayRef.h"
60#include "llvm/ADT/SmallVector.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/ADT/StringRef.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/Compiler.h"
65#include "llvm/Support/Debug.h"
66#include "llvm/Support/Error.h"
67#include "llvm/Support/FormatVariadic.h"
68#include "llvm/Support/ScopedPrinter.h"
76#define DEBUG_TYPE "CodeComplete"
81#if CLANGD_DECISION_FOREST
95toCompletionItemKind(index::SymbolKind
Kind,
96 const llvm::StringRef *
Signature =
nullptr) {
97 using SK = index::SymbolKind;
103 case SK::NamespaceAlias:
130 case SK::ConversionFunction:
134 case SK::NonTypeTemplateParm:
138 case SK::EnumConstant:
140 case SK::InstanceMethod:
141 case SK::ClassMethod:
142 case SK::StaticMethod:
145 case SK::InstanceProperty:
146 case SK::ClassProperty:
147 case SK::StaticProperty:
149 case SK::Constructor:
151 case SK::TemplateTypeParm:
152 case SK::TemplateTemplateParm:
157 llvm_unreachable(
"Unhandled clang::index::SymbolKind.");
163 CodeCompletionContext::Kind CtxKind) {
165 return toCompletionItemKind(index::getSymbolInfo(Res.Declaration).Kind);
166 if (CtxKind == CodeCompletionContext::CCC_IncludedFile)
169 case CodeCompletionResult::RK_Declaration:
170 llvm_unreachable(
"RK_Declaration without Decl");
171 case CodeCompletionResult::RK_Keyword:
173 case CodeCompletionResult::RK_Macro:
177 return Res.MacroDefInfo && Res.MacroDefInfo->isFunctionLike()
180 case CodeCompletionResult::RK_Pattern:
183 llvm_unreachable(
"Unhandled CodeCompletionResult::ResultKind.");
187MarkupContent renderDoc(
const markup::Document &Doc,
MarkupKind Kind) {
188 MarkupContent Result;
192 Result.value.append(Doc.asPlainText());
195 Result.value.append(Doc.asMarkdown());
208struct RawIdentifier {
215struct CompletionCandidate {
216 llvm::StringRef
Name;
225 size_t overloadSet(
const CodeCompleteOptions &Opts, llvm::StringRef
FileName,
226 IncludeInserter *Inserter,
227 CodeCompletionContext::Kind CCContextKind)
const {
228 if (!Opts.BundleOverloads.value_or(
false))
234 std::string HeaderForHash;
236 if (
auto Header = headerToInsertIfAllowed(Opts, CCContextKind)) {
239 Inserter->calculateIncludePath(*HeaderFile,
FileName))
242 vlog(
"Code completion header path manipulation failed {0}",
243 HeaderFile.takeError());
248 llvm::SmallString<256> Scratch;
251 case index::SymbolKind::ClassMethod:
252 case index::SymbolKind::InstanceMethod:
253 case index::SymbolKind::StaticMethod:
255 llvm_unreachable(
"Don't expect members from index in code completion");
259 case index::SymbolKind::Function:
262 return llvm::hash_combine(
272 if (!D || !D->isFunctionOrFunctionTemplate())
275 llvm::raw_svector_ostream
OS(Scratch);
276 D->printQualifiedName(
OS);
278 return llvm::hash_combine(Scratch, HeaderForHash);
284 bool contextAllowsHeaderInsertion(CodeCompletionContext::Kind
Kind)
const {
287 if (
Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
293 std::optional<llvm::StringRef>
294 headerToInsertIfAllowed(
const CodeCompleteOptions &Opts,
295 CodeCompletionContext::Kind ContextKind)
const {
298 !contextAllowsHeaderInsertion(ContextKind))
303 auto &SM =
SemaResult->Declaration->getASTContext().getSourceManager();
305 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
309 for (
const auto &Inc : RankedIncludeHeaders)
315 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
318 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
319struct ScoredBundleGreater {
320 bool operator()(
const ScoredBundle &L,
const ScoredBundle &R) {
321 if (L.second.Total != R.second.Total)
322 return L.second.Total > R.second.Total;
323 return L.first.front().Name <
324 R.first.front().Name;
330std::string removeFirstTemplateArg(llvm::StringRef
Signature) {
334 return (
"<" + Rest.ltrim()).str();
344struct CodeCompletionBuilder {
345 CodeCompletionBuilder(ASTContext *ASTCtx,
const CompletionCandidate &
C,
346 CodeCompletionString *SemaCCS,
348 const IncludeInserter &Includes,
350 CodeCompletionContext::Kind ContextKind,
351 const CodeCompleteOptions &Opts,
352 bool IsUsingDeclaration, tok::TokenKind NextTokenKind)
354 EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets),
355 IsUsingDeclaration(IsUsingDeclaration), NextTokenKind(NextTokenKind) {
356 Completion.Deprecated =
true;
357 add(
C, SemaCCS, ContextKind);
361 Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText()));
362 Completion.FilterText = SemaCCS->getAllTypedText();
363 if (Completion.Scope.empty()) {
364 if ((
C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
365 (
C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
366 if (
const auto *D =
C.SemaResult->getDeclaration())
367 if (
const auto *ND = dyn_cast<NamedDecl>(D))
368 Completion.Scope = std::string(
371 Completion.Kind = toCompletionItemKind(*
C.SemaResult, ContextKind);
375 Completion.Name.back() ==
'/')
377 for (
const auto &
FixIt :
C.SemaResult->FixIts) {
379 FixIt, ASTCtx->getSourceManager(), ASTCtx->getLangOpts()));
381 llvm::sort(Completion.FixIts, [](
const TextEdit &
X,
const TextEdit &Y) {
382 return std::tie(X.range.start.line, X.range.start.character) <
383 std::tie(Y.range.start.line, Y.range.start.character);
387 Completion.Origin |=
C.IndexResult->Origin;
388 if (Completion.Scope.empty())
389 Completion.Scope = std::string(
C.IndexResult->Scope);
391 Completion.Kind = toCompletionItemKind(
C.IndexResult->SymInfo.Kind,
392 &
C.IndexResult->Signature);
393 if (Completion.Name.empty())
394 Completion.Name = std::string(
C.IndexResult->Name);
395 if (Completion.FilterText.empty())
396 Completion.FilterText = Completion.Name;
399 if (Completion.RequiredQualifier.empty() && !
C.SemaResult) {
400 llvm::StringRef ShortestQualifier =
C.IndexResult->Scope;
402 llvm::StringRef Qualifier =
C.IndexResult->Scope;
403 if (Qualifier.consume_front(Scope) &&
404 Qualifier.size() < ShortestQualifier.size())
405 ShortestQualifier = Qualifier;
407 Completion.RequiredQualifier = std::string(ShortestQualifier);
410 if (
C.IdentifierResult) {
413 Completion.Name = std::string(
C.IdentifierResult->Name);
414 Completion.FilterText = Completion.Name;
418 auto Inserted = [&](llvm::StringRef Header)
419 -> llvm::Expected<std::pair<std::string, bool>> {
420 auto ResolvedDeclaring =
422 if (!ResolvedDeclaring)
423 return ResolvedDeclaring.takeError();
425 if (!ResolvedInserted)
426 return ResolvedInserted.takeError();
427 auto Spelled = Includes.calculateIncludePath(*ResolvedInserted,
FileName);
429 return error(
"Header not on include path");
430 return std::make_pair(
432 Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
435 C.headerToInsertIfAllowed(Opts, ContextKind).has_value();
438 for (
const auto &Inc :
C.RankedIncludeHeaders) {
442 if (
auto ToInclude = Inserted(Inc.Header)) {
443 CodeCompletion::IncludeCandidate Include;
444 Include.Header = ToInclude->first;
445 if (ToInclude->second && ShouldInsert)
446 Include.Insertion = Includes.insert(
448 ? tooling::IncludeDirective::Import
449 : tooling::IncludeDirective::Include);
450 Completion.Includes.push_back(std::move(Include));
452 log(
"Failed to generate include insertion edits for adding header "
453 "(FileURI='{0}', IncludeHeader='{1}') into {2}: {3}",
454 C.IndexResult->CanonicalDeclaration.FileURI, Inc.Header,
FileName,
455 ToInclude.takeError());
458 std::stable_partition(Completion.Includes.begin(),
459 Completion.Includes.end(),
460 [](
const CodeCompletion::IncludeCandidate &I) {
461 return !I.Insertion.has_value();
465 void add(
const CompletionCandidate &
C, CodeCompletionString *SemaCCS,
466 CodeCompletionContext::Kind ContextKind) {
467 assert(
bool(
C.SemaResult) ==
bool(SemaCCS));
468 Bundled.emplace_back();
469 BundledEntry &S = Bundled.back();
470 bool IsConcept =
false;
472 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
C.SemaResult->Kind,
473 C.SemaResult->CursorKind,
474 C.SemaResult->FunctionCanBeCall,
475 &Completion.RequiredQualifier);
477 if (
C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
478 if (
const auto *D =
C.SemaResult->getDeclaration())
479 if (isa<ConceptDecl>(D))
481 }
else if (
C.IndexResult) {
482 S.Signature = std::string(
C.IndexResult->Signature);
483 S.SnippetSuffix = std::string(
C.IndexResult->CompletionSnippetSuffix);
484 S.ReturnType = std::string(
C.IndexResult->ReturnType);
485 if (
C.IndexResult->SymInfo.Kind == index::SymbolKind::Concept)
492 if (IsConcept && ContextKind == CodeCompletionContext::CCC_TopLevel) {
493 S.Signature = removeFirstTemplateArg(S.Signature);
496 S.SnippetSuffix = removeFirstTemplateArg(S.SnippetSuffix);
499 if (!Completion.Documentation) {
500 auto SetDoc = [&](llvm::StringRef Doc) {
502 Completion.Documentation.emplace();
507 SetDoc(
C.IndexResult->Documentation);
508 }
else if (
C.SemaResult) {
514 if (Completion.Deprecated) {
516 Completion.Deprecated &=
517 C.SemaResult->Availability == CXAvailability_Deprecated;
519 Completion.Deprecated &=
524 CodeCompletion build() {
525 Completion.ReturnType = summarizeReturnType();
526 Completion.Signature = summarizeSignature();
527 Completion.SnippetSuffix = summarizeSnippet();
528 Completion.BundleSize = Bundled.size();
529 return std::move(Completion);
533 struct BundledEntry {
540 template <std::
string BundledEntry::*Member>
541 const std::string *onlyValue()
const {
542 auto B = Bundled.begin(),
E = Bundled.end();
543 for (
auto *I =
B + 1; I !=
E; ++I)
544 if (I->*Member !=
B->*Member)
546 return &(
B->*Member);
549 template <
bool BundledEntry::*Member>
const bool *onlyValue()
const {
550 auto B = Bundled.begin(),
E = Bundled.end();
551 for (
auto *I = B + 1; I !=
E; ++I)
552 if (I->*Member !=
B->*Member)
554 return &(
B->*Member);
557 std::string summarizeReturnType()
const {
558 if (
auto *RT = onlyValue<&BundledEntry::ReturnType>())
563 std::string summarizeSnippet()
const {
564 if (IsUsingDeclaration)
566 auto *
Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
584 if (MayHaveArgList) {
588 if (NextTokenKind == tok::less &&
Snippet->front() ==
'<')
591 if (NextTokenKind == tok::l_paren) {
601 else if (
Snippet->at(I) ==
'<')
604 }
while (Balance > 0);
610 if (EnableFunctionArgSnippets)
614 if (MayHaveArgList) {
623 bool EmptyArgs = llvm::StringRef(*Snippet).ends_with(
"()");
625 return EmptyArgs ?
"<$1>()$0" :
"<$1>($0)";
627 return EmptyArgs ?
"()" :
"($0)";
639 if (llvm::StringRef(*Snippet).ends_with(
"<>"))
646 std::string summarizeSignature()
const {
647 if (
auto *
Signature = onlyValue<&BundledEntry::Signature>())
655 CodeCompletion Completion;
656 llvm::SmallVector<BundledEntry, 1> Bundled;
657 bool EnableFunctionArgSnippets;
660 bool IsUsingDeclaration;
661 tok::TokenKind NextTokenKind;
667 case CodeCompletionResult::RK_Declaration:
668 case CodeCompletionResult::RK_Pattern: {
674 case CodeCompletionResult::RK_Macro:
676 case CodeCompletionResult::RK_Keyword:
679 llvm_unreachable(
"unknown CodeCompletionResult kind");
684struct SpecifiedScope {
721 std::vector<std::string> scopesForQualification() {
731 std::vector<std::string> scopesForIndexQuery() {
733 std::vector<std::string> EnclosingAtFront;
735 EnclosingAtFront.push_back(*EnclosingNamespace);
736 std::set<std::string> Deduplicated;
737 for (llvm::StringRef S : QueryScopes)
738 if (S != EnclosingNamespace)
741 EnclosingAtFront.reserve(EnclosingAtFront.size() + Deduplicated.size());
742 llvm::copy(Deduplicated, std::back_inserter(EnclosingAtFront));
744 return EnclosingAtFront;
751SpecifiedScope getQueryScopes(CodeCompletionContext &
CCContext,
753 const CompletionPrefix &HeuristicPrefix,
754 const CodeCompleteOptions &Opts) {
755 SpecifiedScope Scopes;
756 for (
auto *Context :
CCContext.getVisitedContexts()) {
757 if (isa<TranslationUnitDecl>(Context)) {
758 Scopes.QueryScopes.push_back(
"");
759 Scopes.AccessibleScopes.push_back(
"");
760 }
else if (
const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
766 const CXXScopeSpec *SemaSpecifier =
767 CCContext.getCXXScopeSpecifier().value_or(
nullptr);
769 if (!SemaSpecifier) {
772 if (!HeuristicPrefix.
Qualifier.empty()) {
773 vlog(
"Sema said no scope specifier, but we saw {0} in the source code",
775 StringRef SpelledSpecifier = HeuristicPrefix.
Qualifier;
776 if (SpelledSpecifier.consume_front(
"::")) {
777 Scopes.AccessibleScopes = {
""};
778 Scopes.QueryScopes = {
""};
780 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
792 if (SemaSpecifier && SemaSpecifier->isValid())
796 Scopes.QueryScopes.push_back(
"");
797 llvm::StringRef SpelledSpecifier = Lexer::getSourceText(
798 CharSourceRange::getCharRange(SemaSpecifier->getRange()),
799 CCSema.SourceMgr, clang::LangOptions());
800 if (SpelledSpecifier.consume_front(
"::"))
801 Scopes.QueryScopes = {
""};
802 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
804 if (!Scopes.UnresolvedQualifier->empty())
805 *Scopes.UnresolvedQualifier +=
"::";
807 Scopes.AccessibleScopes = Scopes.QueryScopes;
814bool contextAllowsIndex(
enum CodeCompletionContext::Kind
K) {
816 case CodeCompletionContext::CCC_TopLevel:
817 case CodeCompletionContext::CCC_ObjCInterface:
818 case CodeCompletionContext::CCC_ObjCImplementation:
819 case CodeCompletionContext::CCC_ObjCIvarList:
820 case CodeCompletionContext::CCC_ClassStructUnion:
821 case CodeCompletionContext::CCC_Statement:
822 case CodeCompletionContext::CCC_Expression:
823 case CodeCompletionContext::CCC_ObjCMessageReceiver:
824 case CodeCompletionContext::CCC_EnumTag:
825 case CodeCompletionContext::CCC_UnionTag:
826 case CodeCompletionContext::CCC_ClassOrStructTag:
827 case CodeCompletionContext::CCC_ObjCProtocolName:
828 case CodeCompletionContext::CCC_Namespace:
829 case CodeCompletionContext::CCC_Type:
830 case CodeCompletionContext::CCC_ParenthesizedExpression:
831 case CodeCompletionContext::CCC_ObjCInterfaceName:
832 case CodeCompletionContext::CCC_Symbol:
833 case CodeCompletionContext::CCC_SymbolOrNewName:
834 case CodeCompletionContext::CCC_ObjCClassForwardDecl:
835 case CodeCompletionContext::CCC_TopLevelOrExpression:
837 case CodeCompletionContext::CCC_OtherWithMacros:
838 case CodeCompletionContext::CCC_DotMemberAccess:
839 case CodeCompletionContext::CCC_ArrowMemberAccess:
840 case CodeCompletionContext::CCC_ObjCCategoryName:
841 case CodeCompletionContext::CCC_ObjCPropertyAccess:
842 case CodeCompletionContext::CCC_MacroName:
843 case CodeCompletionContext::CCC_MacroNameUse:
844 case CodeCompletionContext::CCC_PreprocessorExpression:
845 case CodeCompletionContext::CCC_PreprocessorDirective:
846 case CodeCompletionContext::CCC_SelectorName:
847 case CodeCompletionContext::CCC_TypeQualifiers:
848 case CodeCompletionContext::CCC_ObjCInstanceMessage:
849 case CodeCompletionContext::CCC_ObjCClassMessage:
850 case CodeCompletionContext::CCC_IncludedFile:
851 case CodeCompletionContext::CCC_Attribute:
853 case CodeCompletionContext::CCC_Other:
854 case CodeCompletionContext::CCC_NaturalLanguage:
855 case CodeCompletionContext::CCC_Recovery:
856 case CodeCompletionContext::CCC_NewName:
859 llvm_unreachable(
"unknown code completion context");
862static bool isInjectedClass(
const NamedDecl &D) {
863 if (
auto *R = dyn_cast_or_null<RecordDecl>(&D))
864 if (R->isInjectedClassName())
870static bool isExcludedMember(
const NamedDecl &D) {
873 if (D.getKind() == Decl::CXXDestructor)
876 if (isInjectedClass(D))
879 auto NameKind = D.getDeclName().getNameKind();
880 if (NameKind == DeclarationName::CXXOperatorName ||
881 NameKind == DeclarationName::CXXLiteralOperatorName ||
882 NameKind == DeclarationName::CXXConversionFunctionName)
893struct CompletionRecorder :
public CodeCompleteConsumer {
894 CompletionRecorder(
const CodeCompleteOptions &Opts,
895 llvm::unique_function<
void()> ResultsCallback)
896 : CodeCompleteConsumer(Opts.getClangCompleteOpts()),
897 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
898 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
899 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
900 assert(this->ResultsCallback);
908 void ProcessCodeCompleteResults(
class Sema &S, CodeCompletionContext Context,
909 CodeCompletionResult *InResults,
910 unsigned NumResults)
final {
919 if (Context.getKind() == CodeCompletionContext::CCC_Recovery) {
920 log(
"Code complete: Ignoring sema code complete callback with Recovery "
927 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
930 log(
"Multiple code complete callbacks (parser backtracked?). "
931 "Dropping results from context {0}, keeping results from {1}.",
932 getCompletionKindString(Context.getKind()),
933 getCompletionKindString(this->CCContext.getKind()));
941 for (
unsigned I = 0; I < NumResults; ++I) {
942 auto &Result = InResults[I];
944 if (Result.Hidden && Result.Declaration &&
945 Result.Declaration->isCXXClassMember())
947 if (!Opts.IncludeIneligibleResults &&
948 (Result.Availability == CXAvailability_NotAvailable ||
949 Result.Availability == CXAvailability_NotAccessible))
951 if (Result.Declaration &&
952 !Context.getBaseType().isNull()
953 && isExcludedMember(*Result.Declaration))
957 if (Result.Declaration && !Context.getCXXScopeSpecifier() &&
958 isInjectedClass(*Result.Declaration))
961 Result.StartsNestedNameSpecifier =
false;
967 CodeCompletionAllocator &getAllocator()
override {
return *CCAllocator; }
968 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
972 llvm::StringRef getName(
const CodeCompletionResult &Result) {
973 switch (Result.Kind) {
974 case CodeCompletionResult::RK_Declaration:
975 if (
auto *
ID = Result.Declaration->getIdentifier())
976 return ID->getName();
978 case CodeCompletionResult::RK_Keyword:
979 return Result.Keyword;
980 case CodeCompletionResult::RK_Macro:
981 return Result.Macro->getName();
982 case CodeCompletionResult::RK_Pattern:
985 auto *CCS = codeCompletionString(Result);
986 const CodeCompletionString::Chunk *OnlyText =
nullptr;
987 for (
auto &
C : *CCS) {
988 if (
C.Kind != CodeCompletionString::CK_TypedText)
991 return CCAllocator->CopyString(CCS->getAllTypedText());
994 return OnlyText ? OnlyText->Text : llvm::StringRef();
999 CodeCompletionString *codeCompletionString(
const CodeCompletionResult &R) {
1001 return const_cast<CodeCompletionResult &
>(R).CreateCodeCompletionString(
1002 *CCSema, CCContext, *CCAllocator, CCTUInfo,
1007 CodeCompleteOptions Opts;
1008 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
1009 CodeCompletionTUInfo CCTUInfo;
1010 llvm::unique_function<void()> ResultsCallback;
1013struct ScoredSignature {
1026int paramIndexForArg(
const CodeCompleteConsumer::OverloadCandidate &
Candidate,
1028 int NumParams =
Candidate.getNumParams();
1030 if (
auto *Proto =
T->getAs<FunctionProtoType>()) {
1031 if (Proto->isVariadic())
1035 return std::min(Arg, std::max(NumParams - 1, 0));
1038class SignatureHelpCollector final :
public CodeCompleteConsumer {
1040 SignatureHelpCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1042 const SymbolIndex *Index, SignatureHelp &SigHelp)
1043 : CodeCompleteConsumer(CodeCompleteOpts), SigHelp(SigHelp),
1044 Allocator(std::make_shared<
clang::GlobalCodeCompletionAllocator>()),
1045 CCTUInfo(Allocator), Index(Index),
1046 DocumentationFormat(DocumentationFormat) {}
1048 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1049 OverloadCandidate *Candidates,
1050 unsigned NumCandidates,
1051 SourceLocation OpenParLoc,
1052 bool Braced)
override {
1053 assert(!OpenParLoc.isInvalid());
1054 SourceManager &SrcMgr = S.getSourceManager();
1055 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
1056 if (SrcMgr.isInMainFile(OpenParLoc))
1059 elog(
"Location oustide main file in signature help: {0}",
1060 OpenParLoc.printToString(SrcMgr));
1062 std::vector<ScoredSignature> ScoredSignatures;
1063 SigHelp.signatures.reserve(NumCandidates);
1064 ScoredSignatures.reserve(NumCandidates);
1068 SigHelp.activeSignature = 0;
1069 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1070 "too many arguments");
1072 SigHelp.activeParameter =
static_cast<int>(CurrentArg);
1074 for (
unsigned I = 0; I < NumCandidates; ++I) {
1075 OverloadCandidate
Candidate = Candidates[I];
1079 if (
auto *Func =
Candidate.getFunction()) {
1080 if (
auto *Pattern = Func->getTemplateInstantiationPattern())
1083 if (
static_cast<int>(I) == SigHelp.activeSignature) {
1088 SigHelp.activeParameter =
1089 paramIndexForArg(
Candidate, SigHelp.activeParameter);
1092 const auto *CCS =
Candidate.CreateSignatureString(
1093 CurrentArg, S, *Allocator, CCTUInfo,
1095 assert(CCS &&
"Expected the CodeCompletionString to be non-null");
1096 ScoredSignatures.push_back(processOverloadCandidate(
1105 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
1107 LookupRequest IndexRequest;
1108 for (
const auto &S : ScoredSignatures) {
1111 IndexRequest.IDs.insert(S.IDForDoc);
1113 Index->lookup(IndexRequest, [&](
const Symbol &S) {
1114 if (!S.Documentation.empty())
1115 FetchedDocs[S.ID] = std::string(S.Documentation);
1117 vlog(
"SigHelp: requested docs for {0} symbols from the index, got {1} "
1118 "symbols with non-empty docs in the response",
1119 IndexRequest.IDs.size(), FetchedDocs.size());
1122 llvm::sort(ScoredSignatures, [](
const ScoredSignature &L,
1123 const ScoredSignature &R) {
1130 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
1131 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
1132 if (L.Quality.NumberOfOptionalParameters !=
1133 R.Quality.NumberOfOptionalParameters)
1134 return L.Quality.NumberOfOptionalParameters <
1135 R.Quality.NumberOfOptionalParameters;
1136 if (L.Quality.Kind != R.Quality.Kind) {
1137 using OC = CodeCompleteConsumer::OverloadCandidate;
1138 auto KindPriority = [&](OC::CandidateKind K) {
1140 case OC::CK_Aggregate:
1142 case OC::CK_Function:
1144 case OC::CK_FunctionType:
1146 case OC::CK_FunctionProtoTypeLoc:
1148 case OC::CK_FunctionTemplate:
1150 case OC::CK_Template:
1153 llvm_unreachable(
"Unknown overload candidate type.");
1155 return KindPriority(L.Quality.Kind) < KindPriority(R.Quality.Kind);
1157 if (L.Signature.label.size() != R.Signature.label.size())
1158 return L.Signature.label.size() < R.Signature.label.size();
1159 return L.Signature.label < R.Signature.label;
1162 for (
auto &SS : ScoredSignatures) {
1164 SS.IDForDoc ? FetchedDocs.find(SS.IDForDoc) : FetchedDocs.end();
1165 if (IndexDocIt != FetchedDocs.end()) {
1166 markup::Document SignatureComment;
1168 SS.Signature.documentation =
1169 renderDoc(SignatureComment, DocumentationFormat);
1172 SigHelp.signatures.push_back(std::move(SS.Signature));
1176 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1178 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1181 void processParameterChunk(llvm::StringRef ChunkText,
1182 SignatureInformation &
Signature)
const {
1185 unsigned ParamEndOffset = ParamStartOffset +
lspLength(ChunkText);
1190 ParameterInformation
Info;
1191 Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset);
1193 Info.labelString = std::string(ChunkText);
1198 void processOptionalChunk(
const CodeCompletionString &CCS,
1200 SignatureQualitySignals &Signal)
const {
1201 for (
const auto &Chunk : CCS) {
1202 switch (Chunk.Kind) {
1203 case CodeCompletionString::CK_Optional:
1204 assert(Chunk.Optional &&
1205 "Expected the optional code completion string to be non-null.");
1206 processOptionalChunk(*Chunk.Optional,
Signature, Signal);
1208 case CodeCompletionString::CK_VerticalSpace:
1210 case CodeCompletionString::CK_CurrentParameter:
1211 case CodeCompletionString::CK_Placeholder:
1212 processParameterChunk(Chunk.Text,
Signature);
1213 Signal.NumberOfOptionalParameters++;
1224 ScoredSignature processOverloadCandidate(
const OverloadCandidate &
Candidate,
1225 const CodeCompletionString &CCS,
1226 llvm::StringRef DocComment)
const {
1228 SignatureQualitySignals Signal;
1231 markup::Document OverloadComment;
1233 Signature.documentation = renderDoc(OverloadComment, DocumentationFormat);
1236 for (
const auto &Chunk : CCS) {
1237 switch (Chunk.Kind) {
1238 case CodeCompletionString::CK_ResultType:
1241 assert(!
ReturnType &&
"Unexpected CK_ResultType");
1244 case CodeCompletionString::CK_CurrentParameter:
1245 case CodeCompletionString::CK_Placeholder:
1246 processParameterChunk(Chunk.Text,
Signature);
1247 Signal.NumberOfParameters++;
1249 case CodeCompletionString::CK_Optional: {
1251 assert(Chunk.Optional &&
1252 "Expected the optional code completion string to be non-null.");
1253 processOptionalChunk(*Chunk.Optional,
Signature, Signal);
1256 case CodeCompletionString::CK_VerticalSpace:
1268 ScoredSignature Result;
1269 Result.Signature = std::move(
Signature);
1270 Result.Quality = Signal;
1271 const FunctionDecl *Func =
Candidate.getFunction();
1272 if (Func && Result.Signature.documentation.value.empty()) {
1280 SignatureHelp &SigHelp;
1281 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1282 CodeCompletionTUInfo CCTUInfo;
1283 const SymbolIndex *Index;
1289class ParamNameCollector final :
public CodeCompleteConsumer {
1291 ParamNameCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1292 std::set<std::string> &ParamNames)
1293 : CodeCompleteConsumer(CodeCompleteOpts),
1294 Allocator(std::make_shared<
clang::GlobalCodeCompletionAllocator>()),
1295 CCTUInfo(Allocator), ParamNames(ParamNames) {}
1297 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1298 OverloadCandidate *Candidates,
1299 unsigned NumCandidates,
1300 SourceLocation OpenParLoc,
1301 bool Braced)
override {
1302 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1303 "too many arguments");
1305 for (
unsigned I = 0; I < NumCandidates; ++I) {
1306 if (
const NamedDecl *ND = Candidates[I].getParamDecl(CurrentArg))
1307 if (
const auto *II = ND->getIdentifier())
1308 ParamNames.emplace(II->getName());
1313 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1315 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1317 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1318 CodeCompletionTUInfo CCTUInfo;
1319 std::set<std::string> &ParamNames;
1322struct SemaCompleteInput {
1326 const std::optional<PreamblePatch>
Patch;
1330void loadMainFilePreambleMacros(
const Preprocessor &PP,
1335 ExternalPreprocessorSource *PreambleMacros = PP.getExternalSource();
1338 const auto &ITable = PP.getIdentifierTable();
1339 IdentifierInfoLookup *PreambleIdentifiers =
1340 ITable.getExternalIdentifierLookup();
1342 if (!PreambleIdentifiers || !PreambleMacros)
1345 if (ITable.find(
MacroName.getKey()) != ITable.end())
1347 if (
auto *II = PreambleIdentifiers->get(
MacroName.getKey()))
1348 if (II->isOutOfDate())
1349 PreambleMacros->updateOutOfDateIdentifier(*II);
1355bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
1356 const clang::CodeCompleteOptions &Options,
1357 const SemaCompleteInput &Input,
1358 IncludeStructure *Includes =
nullptr) {
1359 trace::Span Tracer(
"Sema completion");
1364 elog(
"Couldn't create CompilerInvocation");
1367 auto &FrontendOpts =
CI->getFrontendOpts();
1368 FrontendOpts.SkipFunctionBodies =
true;
1370 CI->getLangOpts().SpellChecking =
false;
1374 CI->getLangOpts().DelayedTemplateParsing =
false;
1376 FrontendOpts.CodeCompleteOpts = Options;
1377 FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName);
1378 std::tie(FrontendOpts.CodeCompletionAt.Line,
1379 FrontendOpts.CodeCompletionAt.Column) =
1382 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1383 llvm::MemoryBuffer::getMemBuffer(Input.ParseInput.Contents,
1386 CI->getDiagnosticOpts().IgnoreWarnings =
true;
1393 PreambleBounds PreambleRegion =
1394 ComputePreambleBounds(
CI->getLangOpts(), *ContentsBuffer, 0);
1395 bool CompletingInPreamble = Input.Offset < PreambleRegion.Size ||
1396 (!PreambleRegion.PreambleEndsAtStartOfLine &&
1397 Input.Offset == PreambleRegion.Size);
1399 Input.Patch->apply(*
CI);
1402 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1403 Input.ParseInput.TFS->view(Input.ParseInput.CompileCommand.Directory);
1404 if (Input.Preamble.StatCache)
1405 VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS));
1407 std::move(
CI), !CompletingInPreamble ? &Input.Preamble.Preamble :
nullptr,
1408 std::move(ContentsBuffer), std::move(VFS),
IgnoreDiags);
1409 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
1410 Clang->setCodeCompletionConsumer(Consumer.release());
1414 log(
"BeginSourceFile() failed when running codeComplete for {0}",
1424 loadMainFilePreambleMacros(
Clang->getPreprocessor(), Input.Preamble);
1427 if (llvm::Error Err =
Action.Execute()) {
1428 log(
"Execute() failed when running codeComplete for {0}: {1}",
1429 Input.FileName,
toString(std::move(Err)));
1438bool allowIndex(CodeCompletionContext &
CC) {
1439 if (!contextAllowsIndex(
CC.getKind()))
1442 auto Scope =
CC.getCXXScopeSpecifier();
1445 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
1450 switch (NameSpec->getKind()) {
1451 case NestedNameSpecifier::Global:
1452 case NestedNameSpecifier::Namespace:
1453 case NestedNameSpecifier::NamespaceAlias:
1455 case NestedNameSpecifier::Super:
1456 case NestedNameSpecifier::TypeSpec:
1457 case NestedNameSpecifier::TypeSpecWithTemplate:
1459 case NestedNameSpecifier::Identifier:
1462 llvm_unreachable(
"invalid NestedNameSpecifier kind");
1467bool includeSymbolFromIndex(CodeCompletionContext::Kind
Kind,
1468 const Symbol &Sym) {
1472 if (Sym.SymInfo.Kind == index::SymbolKind::Protocol &&
1473 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC)
1474 return Kind == CodeCompletionContext::CCC_ObjCProtocolName;
1475 else if (
Kind == CodeCompletionContext::CCC_ObjCProtocolName)
1479 if (
Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
1480 return Sym.SymInfo.Kind == index::SymbolKind::Class &&
1481 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC;
1485std::future<std::pair<bool, SymbolSlab>>
1486startAsyncFuzzyFind(
const SymbolIndex &Index,
const FuzzyFindRequest &Req) {
1487 return runAsync<std::pair<bool, SymbolSlab>>([&Index, Req]() {
1488 trace::Span Tracer(
"Async fuzzyFind");
1489 SymbolSlab::Builder Syms;
1491 Index.fuzzyFind(Req, [&Syms](
const Symbol &Sym) { Syms.insert(Sym); });
1492 return std::make_pair(Incomplete, std::move(Syms).build());
1499FuzzyFindRequest speculativeFuzzyFindRequestForCompletion(
1500 FuzzyFindRequest CachedReq,
const CompletionPrefix &HeuristicPrefix) {
1501 CachedReq.Query = std::string(HeuristicPrefix.
Name);
1509findTokenAfterCompletionPoint(SourceLocation CompletionPoint,
1510 const SourceManager &SM,
1511 const LangOptions &LangOpts) {
1512 SourceLocation
Loc = CompletionPoint;
1513 if (
Loc.isMacroID()) {
1514 if (!Lexer::isAtEndOfMacroExpansion(
Loc, SM, LangOpts, &
Loc))
1515 return std::nullopt;
1523 Loc =
Loc.getLocWithOffset(1);
1526 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(
Loc);
1529 bool InvalidTemp =
false;
1530 StringRef
File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1532 return std::nullopt;
1534 const char *TokenBegin =
File.data() + LocInfo.second;
1537 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
File.begin(),
1538 TokenBegin,
File.end());
1541 TheLexer.LexFromRawLexer(Tok);
1574class CodeCompleteFlow {
1576 IncludeStructure Includes;
1577 SpeculativeFuzzyFind *SpecFuzzyFind;
1578 const CodeCompleteOptions &Opts;
1581 CompletionRecorder *Recorder =
nullptr;
1582 CodeCompletionContext::Kind CCContextKind = CodeCompletionContext::CCC_Other;
1583 bool IsUsingDeclaration =
false;
1587 tok::TokenKind NextTokenKind = tok::eof;
1589 int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
1590 bool Incomplete =
false;
1591 CompletionPrefix HeuristicPrefix;
1592 std::optional<FuzzyMatcher> Filter;
1593 Range ReplacedRange;
1597 std::optional<ScopeDistance> ScopeProximity;
1598 std::optional<OpaqueType> PreferredType;
1600 bool AllScopes =
false;
1601 llvm::StringSet<> ContextWords;
1604 std::optional<IncludeInserter> Inserter;
1605 std::optional<URIDistance> FileProximity;
1610 std::optional<FuzzyFindRequest> SpecReq;
1614 CodeCompleteFlow(
PathRef FileName,
const IncludeStructure &Includes,
1615 SpeculativeFuzzyFind *SpecFuzzyFind,
1616 const CodeCompleteOptions &Opts)
1620 CodeCompleteResult
run(
const SemaCompleteInput &SemaCCInput) && {
1621 trace::Span Tracer(
"CodeCompleteFlow");
1623 SemaCCInput.Offset);
1624 populateContextWords(SemaCCInput.ParseInput.Contents);
1625 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq) {
1626 assert(!SpecFuzzyFind->Result.valid());
1627 SpecReq = speculativeFuzzyFindRequestForCompletion(
1628 *SpecFuzzyFind->CachedReq, HeuristicPrefix);
1629 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1635 CodeCompleteResult
Output;
1636 auto RecorderOwner = std::make_unique<CompletionRecorder>(Opts, [&]() {
1637 assert(Recorder &&
"Recorder is not set");
1638 CCContextKind = Recorder->CCContext.getKind();
1639 IsUsingDeclaration = Recorder->CCContext.isUsingDeclaration();
1641 SemaCCInput.ParseInput.Contents,
1642 *SemaCCInput.ParseInput.TFS,
false);
1643 const auto NextToken = findTokenAfterCompletionPoint(
1644 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc(),
1645 Recorder->CCSema->getSourceManager(), Recorder->CCSema->LangOpts);
1647 NextTokenKind = NextToken->getKind();
1651 SemaCCInput.FileName, SemaCCInput.ParseInput.Contents, Style,
1652 SemaCCInput.ParseInput.CompileCommand.Directory,
1653 &Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
1654 for (
const auto &Inc : Includes.MainFileIncludes)
1655 Inserter->addExisting(Inc);
1661 FileDistanceOptions ProxOpts{};
1662 const auto &SM = Recorder->CCSema->getSourceManager();
1663 llvm::StringMap<SourceParams> ProxSources;
1665 Includes.getID(SM.getFileEntryForID(SM.getMainFileID()));
1667 for (
auto &HeaderIDAndDepth : Includes.includeDepth(*MainFileID)) {
1669 ProxSources[Includes.getRealPath(HeaderIDAndDepth.getFirst())];
1670 Source.Cost = HeaderIDAndDepth.getSecond() * ProxOpts.IncludeCost;
1674 if (HeaderIDAndDepth.getSecond() > 0)
1675 Source.MaxUpTraversals = 1;
1677 FileProximity.emplace(ProxSources, ProxOpts);
1682 getCompletionKindString(CCContextKind));
1683 log(
"Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1684 "expected type {3}{4}",
1685 getCompletionKindString(CCContextKind),
1687 PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1689 IsUsingDeclaration ?
", inside using declaration" :
"");
1692 Recorder = RecorderOwner.get();
1694 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1695 SemaCCInput, &Includes);
1696 logResults(
Output, Tracer);
1700 void logResults(
const CodeCompleteResult &
Output,
const trace::Span &Tracer) {
1703 SPAN_ATTACH(Tracer,
"merged_results", NSemaAndIndex);
1704 SPAN_ATTACH(Tracer,
"identifier_results", NIdent);
1707 log(
"Code complete: {0} results from Sema, {1} from Index, "
1708 "{2} matched, {3} from identifiers, {4} returned{5}.",
1709 NSema, NIndex, NSemaAndIndex, NIdent,
Output.Completions.size(),
1710 Output.HasMore ?
" (incomplete)" :
"");
1711 assert(!Opts.Limit ||
Output.Completions.size() <= Opts.Limit);
1716 CodeCompleteResult runWithoutSema(llvm::StringRef Content,
size_t Offset,
1717 const ThreadsafeFS &TFS) && {
1718 trace::Span Tracer(
"CodeCompleteWithoutSema");
1721 populateContextWords(Content);
1722 CCContextKind = CodeCompletionContext::CCC_Recovery;
1723 IsUsingDeclaration =
false;
1724 Filter = FuzzyMatcher(HeuristicPrefix.Name);
1726 ReplacedRange.start = ReplacedRange.end =
Pos;
1727 ReplacedRange.start.character -= HeuristicPrefix.Name.size();
1729 llvm::StringMap<SourceParams> ProxSources;
1731 FileProximity.emplace(ProxSources);
1735 Inserter.emplace(FileName, Content, Style,
1739 std::vector<RawIdentifier> IdentifierResults;
1740 for (
const auto &IDAndCount : Identifiers) {
1742 ID.Name = IDAndCount.first();
1743 ID.References = IDAndCount.second;
1745 if (
ID.Name == HeuristicPrefix.Name)
1747 if (
ID.References > 0)
1748 IdentifierResults.push_back(std::move(
ID));
1754 SpecifiedScope Scopes;
1756 Content.take_front(
Offset), format::getFormattingLangOpts(Style));
1757 for (std::string &S : Scopes.QueryScopes)
1760 if (HeuristicPrefix.Qualifier.empty())
1761 AllScopes = Opts.AllScopes;
1762 else if (HeuristicPrefix.Qualifier.starts_with(
"::")) {
1763 Scopes.QueryScopes = {
""};
1764 Scopes.UnresolvedQualifier =
1765 std::string(HeuristicPrefix.Qualifier.drop_front(2));
1767 Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier);
1771 ScopeProximity.emplace(QueryScopes);
1773 SymbolSlab IndexResults = Opts.Index ? queryIndex() : SymbolSlab();
1775 CodeCompleteResult
Output = toCodeCompleteResult(mergeResults(
1776 {}, IndexResults, IdentifierResults));
1777 Output.RanParser =
false;
1778 logResults(
Output, Tracer);
1783 void populateContextWords(llvm::StringRef Content) {
1785 unsigned RangeEnd = HeuristicPrefix.Qualifier.begin() - Content.data(),
1786 RangeBegin = RangeEnd;
1787 for (
size_t I = 0; I < 3 && RangeBegin > 0; ++I) {
1788 auto PrevNL = Content.rfind(
'\n', RangeBegin);
1789 if (PrevNL == StringRef::npos) {
1793 RangeBegin = PrevNL;
1796 ContextWords =
collectWords(Content.slice(RangeBegin, RangeEnd));
1797 dlog(
"Completion context words: {0}",
1798 llvm::join(ContextWords.keys(),
", "));
1803 CodeCompleteResult runWithSema() {
1804 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1805 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1811 if (CodeCompletionRange.isValid()) {
1813 CodeCompletionRange);
1816 Recorder->CCSema->getSourceManager(),
1817 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1818 ReplacedRange.start = ReplacedRange.end =
Pos;
1820 Filter = FuzzyMatcher(
1821 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1822 auto SpecifiedScopes = getQueryScopes(
1823 Recorder->CCContext, *Recorder->CCSema, HeuristicPrefix, Opts);
1825 QueryScopes = SpecifiedScopes.scopesForIndexQuery();
1827 AllScopes = SpecifiedScopes.AllowAllScopes;
1829 ScopeProximity.emplace(QueryScopes);
1832 Recorder->CCContext.getPreferredType());
1838 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1841 trace::Span Tracer(
"Populate CodeCompleteResult");
1844 mergeResults(Recorder->Results, IndexResults, {});
1845 return toCodeCompleteResult(Top);
1849 toCodeCompleteResult(
const std::vector<ScoredBundle> &Scored) {
1850 CodeCompleteResult
Output;
1853 for (
auto &
C : Scored) {
1854 Output.Completions.push_back(toCodeCompletion(
C.first));
1855 Output.Completions.back().Score =
C.second;
1856 Output.Completions.back().CompletionTokenRange = ReplacedRange;
1858 Output.HasMore = Incomplete;
1859 Output.Context = CCContextKind;
1860 Output.CompletionRange = ReplacedRange;
1864 SymbolSlab queryIndex() {
1865 trace::Span Tracer(
"Query index");
1866 SPAN_ATTACH(Tracer,
"limit", int64_t(Opts.Limit));
1869 FuzzyFindRequest Req;
1871 Req.Limit = Opts.Limit;
1872 Req.Query = std::string(Filter->pattern());
1873 Req.RestrictForCodeCompletion =
true;
1875 Req.AnyScope = AllScopes;
1877 Req.ProximityPaths.push_back(std::string(FileName));
1879 Req.PreferredTypes.push_back(std::string(PreferredType->raw()));
1880 vlog(
"Code complete: fuzzyFind({0:2})",
toJSON(Req));
1883 SpecFuzzyFind->NewReq = Req;
1884 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1885 vlog(
"Code complete: speculative fuzzy request matches the actual index "
1886 "request. Waiting for the speculative index results.");
1889 trace::Span WaitSpec(
"Wait speculative results");
1890 auto SpecRes = SpecFuzzyFind->Result.get();
1891 Incomplete |= SpecRes.first;
1892 return std::move(SpecRes.second);
1895 SPAN_ATTACH(Tracer,
"Speculative results",
false);
1898 SymbolSlab::Builder ResultsBuilder;
1899 Incomplete |= Opts.Index->fuzzyFind(
1900 Req, [&](
const Symbol &Sym) { ResultsBuilder.insert(Sym); });
1901 return std::move(ResultsBuilder).build();
1909 std::vector<ScoredBundle>
1910 mergeResults(
const std::vector<CodeCompletionResult> &SemaResults,
1911 const SymbolSlab &IndexResults,
1912 const std::vector<RawIdentifier> &IdentifierResults) {
1913 trace::Span Tracer(
"Merge and score results");
1914 std::vector<CompletionCandidate::Bundle> Bundles;
1915 llvm::DenseMap<size_t, size_t> BundleLookup;
1916 auto AddToBundles = [&](
const CodeCompletionResult *
SemaResult,
1919 CompletionCandidate
C;
1923 if (
C.IndexResult) {
1926 }
else if (
C.SemaResult) {
1932 if (
auto OverloadSet =
C.overloadSet(
1933 Opts, FileName, Inserter ? &*Inserter :
nullptr, CCContextKind)) {
1934 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1936 Bundles.emplace_back();
1937 Bundles[Ret.first->second].push_back(std::move(
C));
1939 Bundles.emplace_back();
1940 Bundles.back().push_back(std::move(
C));
1943 llvm::DenseSet<const Symbol *> UsedIndexResults;
1944 auto CorrespondingIndexResult =
1945 [&](
const CodeCompletionResult &
SemaResult) ->
const Symbol * {
1948 auto I = IndexResults.find(SymID);
1949 if (I != IndexResults.end()) {
1950 UsedIndexResults.insert(&*I);
1963 if (!includeSymbolFromIndex(CCContextKind,
IndexResult))
1968 for (
const auto &Ident : IdentifierResults)
1969 AddToBundles(
nullptr,
nullptr, &Ident);
1971 TopN<ScoredBundle, ScoredBundleGreater> Top(
1972 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1973 for (
auto &Bundle : Bundles)
1974 addCandidate(Top, std::move(Bundle));
1975 return std::move(Top).items();
1978 std::optional<float> fuzzyScore(
const CompletionCandidate &
C) {
1980 if (((
C.SemaResult &&
1981 C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
1983 C.IndexResult->SymInfo.Kind == index::SymbolKind::Macro)) &&
1984 !
C.Name.starts_with_insensitive(Filter->pattern()))
1985 return std::nullopt;
1986 return Filter->match(
C.Name);
1989 CodeCompletion::Scores
1990 evaluateCompletion(
const SymbolQualitySignals &
Quality,
1991 const SymbolRelevanceSignals &Relevance) {
1993 CodeCompletion::Scores Scores;
1994 switch (Opts.RankingModel) {
1995 case RM::Heuristics:
1996 Scores.Quality =
Quality.evaluateHeuristics();
1997 Scores.Relevance = Relevance.evaluateHeuristics();
2002 Scores.ExcludingName =
2003 Relevance.NameMatch > std::numeric_limits<float>::epsilon()
2004 ? Scores.Total / Relevance.NameMatch
2008 case RM::DecisionForest:
2009 DecisionForestScores DFScores = Opts.DecisionForestScorer(
2010 Quality, Relevance, Opts.DecisionForestBase);
2011 Scores.ExcludingName = DFScores.ExcludingName;
2012 Scores.Total = DFScores.Total;
2015 llvm_unreachable(
"Unhandled CodeCompletion ranking model.");
2019 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
2020 CompletionCandidate::Bundle Bundle) {
2022 SymbolRelevanceSignals Relevance;
2023 Relevance.Context = CCContextKind;
2024 Relevance.Name = Bundle.front().Name;
2025 Relevance.FilterLength = HeuristicPrefix.Name.size();
2027 Relevance.FileProximityMatch = &*FileProximity;
2029 Relevance.ScopeProximityMatch = &*ScopeProximity;
2031 Relevance.HadContextType =
true;
2032 Relevance.ContextWords = &ContextWords;
2033 Relevance.MainFileSignals = Opts.MainFileSignals;
2035 auto &First = Bundle.front();
2036 if (
auto FuzzyScore = fuzzyScore(First))
2037 Relevance.NameMatch = *FuzzyScore;
2041 bool FromIndex =
false;
2045 Relevance.merge(*
Candidate.IndexResult);
2046 Origin |=
Candidate.IndexResult->Origin;
2048 if (!
Candidate.IndexResult->Type.empty())
2049 Relevance.HadSymbolType |=
true;
2050 if (PreferredType &&
2051 PreferredType->raw() ==
Candidate.IndexResult->Type) {
2052 Relevance.TypeMatchesPreferred =
true;
2058 if (PreferredType) {
2060 Recorder->CCSema->getASTContext(), *
Candidate.SemaResult)) {
2061 Relevance.HadSymbolType |=
true;
2062 if (PreferredType == CompletionType)
2063 Relevance.TypeMatchesPreferred =
true;
2075 CodeCompletion::Scores Scores = evaluateCompletion(
Quality, Relevance);
2076 if (Opts.RecordCCResult)
2077 Opts.RecordCCResult(toCodeCompletion(Bundle),
Quality, Relevance,
2080 dlog(
"CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
2081 llvm::to_string(Origin), Scores.Total, llvm::to_string(
Quality),
2082 llvm::to_string(Relevance));
2085 NIndex += FromIndex;
2088 if (Candidates.push({std::move(Bundle), Scores}))
2092 CodeCompletion toCodeCompletion(
const CompletionCandidate::Bundle &Bundle) {
2093 std::optional<CodeCompletionBuilder>
Builder;
2094 for (
const auto &Item : Bundle) {
2095 CodeCompletionString *SemaCCS =
2096 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
2099 Builder.emplace(Recorder ? &Recorder->CCSema->getASTContext() :
nullptr,
2100 Item, SemaCCS, AccessibleScopes, *Inserter, FileName,
2101 CCContextKind, Opts, IsUsingDeclaration, NextTokenKind);
2103 Builder->add(Item, SemaCCS, CCContextKind);
2111clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts()
const {
2112 clang::CodeCompleteOptions Result;
2113 Result.IncludeCodePatterns = EnableSnippets;
2114 Result.IncludeMacros =
true;
2115 Result.IncludeGlobals =
true;
2120 Result.IncludeBriefComments =
false;
2125 Result.LoadExternal = !Index;
2126 Result.IncludeFixIts = IncludeFixIts;
2133 assert(
Offset <= Content.size());
2134 StringRef Rest = Content.take_front(
Offset);
2139 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2140 Rest = Rest.drop_back();
2141 Result.Name = Content.slice(Rest.size(),
Offset);
2144 while (Rest.consume_back(
"::") && !Rest.ends_with(
":"))
2145 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2146 Rest = Rest.drop_back();
2148 Content.slice(Rest.size(), Result.Name.begin() - Content.begin());
2157 llvm::StringRef Prefix,
2163 clang::CodeCompleteOptions Options;
2164 Options.IncludeGlobals =
false;
2165 Options.IncludeMacros =
false;
2166 Options.IncludeCodePatterns =
false;
2167 Options.IncludeBriefComments =
false;
2168 std::set<std::string> ParamNames;
2172 std::make_unique<ParamNameCollector>(Options, ParamNames), Options,
2176 if (ParamNames.empty())
2180 Range CompletionRange;
2184 CompletionRange.
end =
2186 Result.CompletionRange = CompletionRange;
2187 Result.Context = CodeCompletionContext::CCC_NaturalLanguage;
2188 for (llvm::StringRef
Name : ParamNames) {
2189 if (!
Name.starts_with(Prefix))
2194 Item.
Kind = CompletionItemKind::Text;
2196 Item.
Origin = SymbolOrigin::AST;
2197 Result.Completions.push_back(Item);
2206std::optional<unsigned>
2208 while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
2209 Content = Content.drop_back();
2210 Content = Content.rtrim();
2211 if (Content.ends_with(
"/*"))
2212 return Content.size() - 2;
2213 return std::nullopt;
2223 elog(
"Code completion position was invalid {0}",
Offset.takeError());
2234 auto CommentPrefix = Content.substr(*OffsetBeforeComment + 2).trim();
2239 auto Flow = CodeCompleteFlow(
2241 SpecFuzzyFind, Opts);
2242 return (!
Preamble || Opts.RunParser == CodeCompleteOptions::NeverParse)
2247 PreamblePatch::createMacroPatch(
2258 elog(
"Signature help position was invalid {0}",
Offset.takeError());
2262 clang::CodeCompleteOptions Options;
2263 Options.IncludeGlobals =
false;
2264 Options.IncludeMacros =
false;
2265 Options.IncludeCodePatterns =
false;
2266 Options.IncludeBriefComments =
false;
2268 std::make_unique<SignatureHelpCollector>(Options, DocumentationFormat,
2271 {FileName, *Offset, Preamble,
2272 PreamblePatch::createFullPatch(FileName, ParseInput, Preamble),
2278 auto InTopLevelScope = [](
const NamedDecl &ND) {
2279 switch (ND.getDeclContext()->getDeclKind()) {
2280 case Decl::TranslationUnit:
2281 case Decl::Namespace:
2282 case Decl::LinkageSpec:
2289 auto InClassScope = [](
const NamedDecl &ND) {
2290 return ND.getDeclContext()->getDeclKind() == Decl::CXXRecord;
2301 if (llvm::isa<ObjCCategoryDecl>(&ND) || llvm::isa<ObjCCategoryImplDecl>(&ND))
2304 if (InTopLevelScope(ND))
2310 if (
const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
2311 return (InTopLevelScope(*EnumDecl) || InClassScope(*EnumDecl));
2318 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
2321 LSP.
label = ((InsertInclude && InsertInclude->Insertion)
2322 ? Opts.IncludeIndicator.Insert
2323 : Opts.IncludeIndicator.NoInsert) +
2324 (Opts.ShowOrigins ?
"[" + llvm::to_string(Origin) +
"]" :
"") +
2325 RequiredQualifier +
Name;
2330 LSP.
detail = BundleSize > 1
2331 ? std::string(llvm::formatv(
"[{0} overloads]", BundleSize))
2336 if (InsertInclude || Documentation) {
2341 Doc.
append(*Documentation);
2342 LSP.
documentation = renderDoc(Doc, Opts.DocumentationFormat);
2346 LSP.
textEdit = {CompletionTokenRange, RequiredQualifier +
Name,
""};
2354 for (
const auto &
FixIt : FixIts) {
2362 if (Opts.EnableSnippets)
2372 ? InsertTextFormat::Snippet
2373 : InsertTextFormat::PlainText;
2374 if (InsertInclude && InsertInclude->Insertion)
2390 <<
" (" << getCompletionKindString(R.
Context) <<
")"
2400 if (!
Line.consume_front(
"#"))
2403 if (!(
Line.consume_front(
"include_next") ||
Line.consume_front(
"include") ||
2404 Line.consume_front(
"import")))
2407 if (
Line.consume_front(
"<"))
2408 return Line.count(
'>') == 0;
2409 if (
Line.consume_front(
"\""))
2410 return Line.count(
'"') == 0;
2416 Content = Content.take_front(
Offset);
2417 auto Pos = Content.rfind(
'\n');
2418 if (
Pos != llvm::StringRef::npos)
2419 Content = Content.substr(
Pos + 1);
2422 if (Content.ends_with(
".") || Content.ends_with(
"->") ||
2423 Content.ends_with(
"::") || Content.ends_with(
"/*"))
2426 if ((Content.ends_with(
"<") || Content.ends_with(
"\"") ||
2427 Content.ends_with(
"/")) &&
2432 return !Content.empty() && (isAsciiIdentifierContinue(Content.back()) ||
2433 !llvm::isASCII(Content.back()));
const FunctionDecl * Decl
llvm::SmallString< 256U > Name
const ParseInputs & ParseInput
std::vector< std::string > AccessibleScopes
std::optional< std::string > UnresolvedQualifier
CodeCompletionContext CCContext
llvm::SmallVector< SymbolInclude, 1 > RankedIncludeHeaders
const RawIdentifier * IdentifierResult
const Symbol * IndexResult
std::vector< std::string > QueryScopes
std::vector< CodeCompletionResult > Results
std::optional< std::string > EnclosingNamespace
const std::optional< PreamblePatch > Patch
std::string SnippetSuffix
SignatureQualitySignals Quality
const PreambleData & Preamble
const CodeCompletionResult * SemaResult
CodeCompletionBuilder Builder
std::optional< float > Score
CharSourceRange Range
SourceRange for the file name.
const MacroDirective * Directive
std::unique_ptr< CompilerInvocation > CI
llvm::raw_string_ostream OS
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
std::optional< FixItHint > FixIt
void collect(const CompilerInstance &CI)
static std::optional< OpaqueType > fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R)
Create a type from a code completion result.
static std::optional< OpaqueType > fromType(ASTContext &Ctx, QualType Type)
Construct an instance from a clang::QualType.
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
A format-agnostic representation for structured text.
Paragraph & addParagraph()
Adds a semantical block that will be separate from others.
void append(Document Other)
Paragraph & appendText(llvm::StringRef Text)
Append plain text to the end of the string.
Paragraph & appendCode(llvm::StringRef Code, bool Preserve=false)
Append inline code, this translates to the ` block in markdown.
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
@ Info
An information message.
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
std::string formatDocumentation(const CodeCompletionString &CCS, llvm::StringRef DocComment)
Assembles formatted documentation for a completion result.
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
std::string sortText(float Score, llvm::StringRef Name)
Returns a string that sorts in the same order as (-Score, Tiebreak), for LSP.
std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl)
Similar to getDocComment, but returns the comment for a NamedDecl.
bool isIncludeFile(llvm::StringRef Line)
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, const LangOptions &L)
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
size_t lspLength(llvm::StringRef Code)
CompletionPrefix guessCompletionPrefix(llvm::StringRef Content, unsigned Offset)
std::unique_ptr< CompilerInvocation > buildCompilerInvocation(const ParseInputs &Inputs, clang::DiagnosticConsumer &D, std::vector< std::string > *CC1Args)
Builds compiler invocation that could be used to build AST or preamble.
bool isExplicitTemplateSpecialization(const NamedDecl *D)
Indicates if D is an explicit template specialization, e.g.
CompletionItemKind
The kind of a completion entry.
bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset)
void vlog(const char *Fmt, Ts &&... Vals)
static const char * toString(OffsetEncoding OE)
CodeCompleteResult codeCompleteComment(PathRef FileName, unsigned Offset, llvm::StringRef Prefix, const PreambleData *Preamble, const ParseInputs &ParseInput)
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
std::string getReturnType(const CodeCompletionString &CCS)
Gets detail to be used as the detail field in an LSP completion item.
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
llvm::StringMap< unsigned > collectIdentifiers(llvm::StringRef Content, const format::FormatStyle &Style)
Collects identifiers with counts in the source code.
bool hasUnstableLinkage(const Decl *D)
Whether we must avoid computing linkage for D during code completion.
llvm::json::Value toJSON(const FuzzyFindRequest &Request)
std::vector< std::string > visibleNamespaces(llvm::StringRef Code, const LangOptions &LangOpts)
Heuristically determine namespaces visible at a point, without parsing Code.
llvm::Expected< HeaderFile > toHeaderFile(llvm::StringRef Header, llvm::StringRef HintPath)
Creates a HeaderFile from Header which can be either a URI or a literal include.
std::unique_ptr< CompilerInstance > prepareCompilerInstance(std::unique_ptr< clang::CompilerInvocation > CI, const PrecompiledPreamble *Preamble, std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, DiagnosticConsumer &DiagsClient)
void log(const char *Fmt, Ts &&... Vals)
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
std::optional< unsigned > maybeFunctionArgumentCommentStart(llvm::StringRef Content)
llvm::StringSet collectWords(llvm::StringRef Content)
Collects words from the source code.
void getSignature(const CodeCompletionString &CCS, std::string *Signature, std::string *Snippet, CodeCompletionResult::ResultKind ResultKind, CXCursorKind CursorKind, bool IncludeFunctionArguments, std::string *RequiredQualifiers)
Formats the signature for an item, as a display string and snippet.
llvm::SmallVector< SymbolInclude, 1 > getRankedIncludes(const Symbol &Sym)
std::pair< size_t, size_t > offsetToClangLineColumn(llvm::StringRef Code, size_t Offset)
@ Deprecated
Deprecated or obsolete code.
void parseDocumentation(llvm::StringRef Input, markup::Document &Output)
float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance)
Combine symbol quality and relevance into a single score.
CodeCompleteResult codeComplete(PathRef FileName, Position Pos, const PreambleData *Preamble, const ParseInputs &ParseInput, CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind)
Gets code completions at a specified Pos in FileName.
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
llvm::StringRef PathRef
A typedef to represent a ref to file path.
SignatureHelp signatureHelp(PathRef FileName, Position Pos, const PreambleData &Preamble, const ParseInputs &ParseInput, MarkupKind DocumentationFormat)
Get signature help at a specified Pos in FileName.
void elog(const char *Fmt, Ts &&... Vals)
std::string getDocComment(const ASTContext &Ctx, const CodeCompletionResult &Result, bool CommentsFromHeaders)
Gets a minimally formatted documentation comment of Result, with comment markers stripped.
std::string printNamespaceScope(const DeclContext &DC)
Returns the first enclosing namespace scope starting from DC.
bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx)
format::FormatStyle getFormatStyleForFile(llvm::StringRef File, llvm::StringRef Content, const ThreadsafeFS &TFS, bool FormatFile)
Choose the clang-format style we should apply to a certain file.
std::array< uint8_t, 20 > SymbolID
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Symbol::IncludeDirective InsertionDirective
Preferred preprocessor directive to use for inclusions by the file.
static const CodeCompletionRankingModel DefaultRankingModel
CodeCompletionRankingModel
Model to use for ranking code completion candidates.
const ASTSignals * MainFileSignals
bool ImportInsertions
Whether include insertions for Objective-C code should use #import instead of #include.
bool AllScopes
Whether to include index symbols that are not defined in the scopes visible from the code completion ...
std::vector< CodeCompletion > Completions
CodeCompletionContext::Kind Context
Range CompletionTokenRange
Holds the range of the token we are going to replace with this completion.
std::string sortText
A string that should be used when comparing this item with other items.
std::optional< TextEdit > textEdit
An edit which is applied to a document when selecting this completion.
std::string filterText
A string that should be used when filtering a set of completion items.
std::string detail
A human-readable string with additional information about this item, like type or symbol information.
InsertTextFormat insertTextFormat
The format of the insert text.
CompletionItemKind kind
The kind of this completion item.
std::vector< TextEdit > additionalTextEdits
An optional array of additional text edits that are applied when selecting this completion.
std::optional< MarkupContent > documentation
A human-readable string that represents a doc-comment.
std::string insertText
A string that should be inserted to a document when selecting this completion.
bool deprecated
Indicates if this item is deprecated.
std::optional< CompletionItemLabelDetails > labelDetails
Additional details for the label.
float score
The score that clangd calculates to rank the returned completions.
std::string label
The label of this completion item.
llvm::StringRef Qualifier
The parsed preamble and associated data.
Position start
The range's start position.
Position end
The range's end position.
Represents the signature of a callable.
A speculative and asynchronous fuzzy find index request (based on cached request) that can be sent be...
@ Deprecated
Indicates if the symbol is deprecated.
@ Include
#include "header.h"
@ Import
#import "header.h"