44#include "clang/AST/Decl.h"
45#include "clang/AST/DeclBase.h"
46#include "clang/AST/DeclTemplate.h"
47#include "clang/Basic/CharInfo.h"
48#include "clang/Basic/LangOptions.h"
49#include "clang/Basic/SourceLocation.h"
50#include "clang/Basic/TokenKinds.h"
51#include "clang/Format/Format.h"
52#include "clang/Frontend/CompilerInstance.h"
53#include "clang/Frontend/FrontendActions.h"
54#include "clang/Lex/ExternalPreprocessorSource.h"
55#include "clang/Lex/Lexer.h"
56#include "clang/Lex/Preprocessor.h"
57#include "clang/Lex/PreprocessorOptions.h"
58#include "clang/Sema/CodeCompleteConsumer.h"
59#include "clang/Sema/DeclSpec.h"
60#include "clang/Sema/Sema.h"
61#include "llvm/ADT/ArrayRef.h"
62#include "llvm/ADT/SmallVector.h"
63#include "llvm/ADT/StringExtras.h"
64#include "llvm/ADT/StringRef.h"
65#include "llvm/Support/Casting.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/Debug.h"
68#include "llvm/Support/Error.h"
69#include "llvm/Support/FormatVariadic.h"
70#include "llvm/Support/ScopedPrinter.h"
78#define DEBUG_TYPE "CodeComplete"
83#if CLANGD_DECISION_FOREST
84const CodeCompleteOptions::CodeCompletionRankingModel
85 CodeCompleteOptions::DefaultRankingModel =
86 CodeCompleteOptions::DecisionForest;
88const CodeCompleteOptions::CodeCompletionRankingModel
89 CodeCompleteOptions::DefaultRankingModel = CodeCompleteOptions::Heuristics;
97toCompletionItemKind(index::SymbolKind Kind,
98 const llvm::StringRef *Signature =
nullptr) {
99 using SK = index::SymbolKind;
103 case SK::IncludeDirective:
108 case SK::NamespaceAlias:
135 case SK::ConversionFunction:
139 case SK::NonTypeTemplateParm:
143 case SK::EnumConstant:
145 case SK::InstanceMethod:
146 case SK::ClassMethod:
147 case SK::StaticMethod:
150 case SK::InstanceProperty:
151 case SK::ClassProperty:
152 case SK::StaticProperty:
154 case SK::Constructor:
156 case SK::TemplateTypeParm:
157 case SK::TemplateTemplateParm:
162 llvm_unreachable(
"Unhandled clang::index::SymbolKind.");
167CompletionItemKind toCompletionItemKind(
const CodeCompletionResult &Res,
168 CodeCompletionContext::Kind CtxKind) {
170 return toCompletionItemKind(index::getSymbolInfo(Res.Declaration).Kind);
171 if (CtxKind == CodeCompletionContext::CCC_IncludedFile)
174 case CodeCompletionResult::RK_Declaration:
175 llvm_unreachable(
"RK_Declaration without Decl");
176 case CodeCompletionResult::RK_Keyword:
178 case CodeCompletionResult::RK_Macro:
182 return Res.MacroDefInfo && Res.MacroDefInfo->isFunctionLike()
185 case CodeCompletionResult::RK_Pattern:
188 llvm_unreachable(
"Unhandled CodeCompletionResult::ResultKind.");
192MarkupContent renderDoc(
const markup::Document &Doc, MarkupKind Kind) {
193 MarkupContent Result;
197 Result.value.append(Doc.asPlainText());
202 Result.value.append(Doc.asEscapedMarkdown());
204 Result.value.append(Doc.asMarkdown());
211 if (!Opts.ImportInsertions || !Opts.MainFileSignals)
213 return Opts.MainFileSignals->InsertionDirective;
217struct RawIdentifier {
218 llvm::StringRef Name;
224struct CompletionCandidate {
225 llvm::StringRef Name;
227 const CodeCompletionResult *SemaResult =
nullptr;
228 const Symbol *IndexResult =
nullptr;
229 const RawIdentifier *IdentifierResult =
nullptr;
230 llvm::SmallVector<SymbolInclude, 1> RankedIncludeHeaders;
234 size_t overloadSet(
const CodeCompleteOptions &Opts, llvm::StringRef FileName,
235 IncludeInserter *Inserter,
236 CodeCompletionContext::Kind CCContextKind)
const {
237 if (!Opts.BundleOverloads)
243 std::string HeaderForHash;
245 if (
auto Header = headerToInsertIfAllowed(Opts, CCContextKind)) {
246 if (
auto HeaderFile =
toHeaderFile(*Header, FileName)) {
248 Inserter->calculateIncludePath(*HeaderFile, FileName))
251 vlog(
"Code completion header path manipulation failed {0}",
252 HeaderFile.takeError());
257 llvm::SmallString<256> Scratch;
259 switch (IndexResult->SymInfo.Kind) {
260 case index::SymbolKind::ClassMethod:
261 case index::SymbolKind::InstanceMethod:
262 case index::SymbolKind::StaticMethod:
264 llvm_unreachable(
"Don't expect members from index in code completion");
268 case index::SymbolKind::Function:
271 return llvm::hash_combine(
272 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
280 const NamedDecl *D = SemaResult->Declaration;
281 if (!D || !D->isFunctionOrFunctionTemplate())
284 llvm::raw_svector_ostream OS(Scratch);
285 D->printQualifiedName(OS);
287 return llvm::hash_combine(Scratch, HeaderForHash);
289 assert(IdentifierResult);
293 bool contextAllowsHeaderInsertion(CodeCompletionContext::Kind Kind)
const {
296 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
302 std::optional<llvm::StringRef>
303 headerToInsertIfAllowed(
const CodeCompleteOptions &Opts,
304 CodeCompletionContext::Kind ContextKind)
const {
306 RankedIncludeHeaders.empty() ||
307 !contextAllowsHeaderInsertion(ContextKind))
309 if (SemaResult && SemaResult->Declaration) {
312 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
313 for (
const Decl *RD : SemaResult->Declaration->redecls())
314 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
318 for (
const auto &Inc : RankedIncludeHeaders)
319 if ((Inc.Directive & Directive) != 0)
324 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
327 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
328struct ScoredBundleGreater {
329 bool operator()(
const ScoredBundle &L,
const ScoredBundle &R) {
330 if (L.second.Total != R.second.Total)
331 return L.second.Total > R.second.Total;
332 return L.first.front().Name <
333 R.first.front().Name;
339std::string removeFirstTemplateArg(llvm::StringRef Signature) {
340 auto Rest = Signature.split(
",").second;
343 return (
"<" + Rest.ltrim()).str();
353struct CodeCompletionBuilder {
354 CodeCompletionBuilder(ASTContext *ASTCtx,
const CompletionCandidate &C,
355 CodeCompletionString *SemaCCS,
356 llvm::ArrayRef<std::string> AccessibleScopes,
357 const IncludeInserter &Includes,
358 llvm::StringRef FileName,
359 CodeCompletionContext::Kind ContextKind,
360 const CodeCompleteOptions &Opts,
361 bool IsUsingDeclaration, tok::TokenKind NextTokenKind)
362 : ASTCtx(ASTCtx), ArgumentLists(Opts.ArgumentLists),
363 IsUsingDeclaration(IsUsingDeclaration), NextTokenKind(NextTokenKind) {
364 Completion.Deprecated =
true;
365 add(C, SemaCCS, ContextKind);
369 Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText()));
370 Completion.FilterText = SemaCCS->getAllTypedText();
371 if (Completion.Scope.empty()) {
372 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
373 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
374 if (
const auto *D = C.SemaResult->getDeclaration())
375 if (
const auto *ND = dyn_cast<NamedDecl>(D))
376 Completion.Scope = std::string(
379 Completion.Kind = toCompletionItemKind(*C.SemaResult, ContextKind);
383 Completion.Name.back() ==
'/')
385 for (
const auto &FixIt : C.SemaResult->FixIts) {
387 FixIt, ASTCtx->getSourceManager(), ASTCtx->getLangOpts()));
389 llvm::sort(Completion.FixIts, [](
const TextEdit &
X,
const TextEdit &Y) {
390 return std::tie(X.range.start.line, X.range.start.character) <
391 std::tie(Y.range.start.line, Y.range.start.character);
395 Completion.Origin |= C.IndexResult->Origin;
396 if (Completion.Scope.empty())
397 Completion.Scope = std::string(C.IndexResult->Scope);
399 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind,
400 &C.IndexResult->Signature);
401 if (Completion.Name.empty())
402 Completion.Name = std::string(C.IndexResult->Name);
403 if (Completion.FilterText.empty())
404 Completion.FilterText = Completion.Name;
407 if (Completion.RequiredQualifier.empty() && !C.SemaResult) {
408 llvm::StringRef ShortestQualifier = C.IndexResult->Scope;
409 for (llvm::StringRef Scope : AccessibleScopes) {
410 llvm::StringRef Qualifier = C.IndexResult->Scope;
411 if (Qualifier.consume_front(Scope) &&
412 Qualifier.size() < ShortestQualifier.size())
413 ShortestQualifier = Qualifier;
415 Completion.RequiredQualifier = std::string(ShortestQualifier);
418 if (C.IdentifierResult) {
421 Completion.Name = std::string(C.IdentifierResult->Name);
422 Completion.FilterText = Completion.Name;
426 auto Inserted = [&](llvm::StringRef Header)
427 -> llvm::Expected<std::pair<std::string, bool>> {
428 auto ResolvedDeclaring =
429 URI::resolve(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
430 if (!ResolvedDeclaring)
431 return ResolvedDeclaring.takeError();
433 if (!ResolvedInserted)
434 return ResolvedInserted.takeError();
435 auto Spelled = Includes.calculateIncludePath(*ResolvedInserted, FileName);
437 return error(
"Header not on include path");
438 return std::make_pair(
440 Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
443 C.headerToInsertIfAllowed(Opts, ContextKind).has_value();
446 for (
const auto &Inc : C.RankedIncludeHeaders) {
447 if ((Inc.Directive & Directive) == 0)
450 if (
auto ToInclude = Inserted(Inc.Header)) {
451 CodeCompletion::IncludeCandidate Include;
452 Include.Header = ToInclude->first;
453 if (ToInclude->second && ShouldInsert)
454 Include.Insertion = Includes.insert(
456 ? tooling::IncludeDirective::Import
457 : tooling::IncludeDirective::Include);
458 Completion.Includes.push_back(std::move(Include));
460 log(
"Failed to generate include insertion edits for adding header "
461 "(FileURI='{0}', IncludeHeader='{1}') into {2}: {3}",
462 C.IndexResult->CanonicalDeclaration.FileURI, Inc.Header, FileName,
463 ToInclude.takeError());
466 std::stable_partition(Completion.Includes.begin(),
467 Completion.Includes.end(),
468 [](
const CodeCompletion::IncludeCandidate &I) {
469 return !I.Insertion.has_value();
473 void add(
const CompletionCandidate &C, CodeCompletionString *SemaCCS,
474 CodeCompletionContext::Kind ContextKind) {
475 assert(
bool(C.SemaResult) ==
bool(SemaCCS));
476 Bundled.emplace_back();
477 BundledEntry &S = Bundled.back();
478 bool IsConcept =
false;
481 *SemaCCS, &S.Signature, &S.SnippetSuffix, C.SemaResult->Kind,
482 C.SemaResult->CursorKind,
483 C.SemaResult->FunctionCanBeCall ||
484 C.SemaResult->DeclaringEntity,
485 &Completion.RequiredQualifier);
487 if (C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
488 if (
const auto *D = C.SemaResult->getDeclaration())
489 if (isa<ConceptDecl>(D))
491 }
else if (C.IndexResult) {
492 S.Signature = std::string(C.IndexResult->Signature);
493 S.SnippetSuffix = std::string(C.IndexResult->CompletionSnippetSuffix);
494 S.ReturnType = std::string(C.IndexResult->ReturnType);
495 if (C.IndexResult->SymInfo.Kind == index::SymbolKind::Concept)
502 if (IsConcept && ContextKind == CodeCompletionContext::CCC_TopLevel) {
503 S.Signature = removeFirstTemplateArg(S.Signature);
506 S.SnippetSuffix = removeFirstTemplateArg(S.SnippetSuffix);
509 if (!Completion.Documentation) {
510 auto SetDoc = [&](llvm::StringRef Doc) {
512 Completion.Documentation.emplace();
517 SetDoc(C.IndexResult->Documentation);
518 }
else if (C.SemaResult) {
519 const auto DocComment =
getDocComment(*ASTCtx, *C.SemaResult,
524 if (Completion.Deprecated) {
526 Completion.Deprecated &=
527 C.SemaResult->Availability == CXAvailability_Deprecated;
529 Completion.Deprecated &=
534 CodeCompletion build() {
535 Completion.ReturnType = summarizeReturnType();
536 Completion.Signature = summarizeSignature();
537 Completion.SnippetSuffix = summarizeSnippet();
538 Completion.BundleSize = Bundled.size();
539 return std::move(Completion);
543 struct BundledEntry {
544 std::string SnippetSuffix;
545 std::string Signature;
546 std::string ReturnType;
550 template <std::
string BundledEntry::*Member>
551 const std::string *onlyValue()
const {
552 auto B = Bundled.begin(), E = Bundled.end();
553 for (
auto *I = B + 1; I != E; ++I)
554 if (I->*Member != B->*Member)
556 return &(B->*Member);
559 template <
bool BundledEntry::*Member>
const bool *onlyValue()
const {
560 auto B = Bundled.begin(), E = Bundled.end();
561 for (
auto *I = B + 1; I != E; ++I)
562 if (I->*Member != B->*Member)
564 return &(B->*Member);
567 std::string summarizeReturnType()
const {
568 if (
auto *RT = onlyValue<&BundledEntry::ReturnType>())
573 std::string summarizeSnippet()
const {
583 if (IsUsingDeclaration)
585 auto *
Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
590 return None ?
"" : (
Open ?
"(" :
"($0)");
595 bool MayHaveArgList =
605 if (MayHaveArgList) {
609 if (NextTokenKind == tok::less &&
Snippet->front() ==
'<')
612 if (NextTokenKind == tok::l_paren) {
622 else if (
Snippet->at(I) ==
'<')
625 }
while (Balance > 0);
635 if (MayHaveArgList && llvm::StringRef(*Snippet).contains(
"(")) {
644 bool EmptyArgs = llvm::StringRef(*Snippet).ends_with(
"()");
646 return None ?
"" : (
Open ?
"<" : (EmptyArgs ?
"<$1>()$0" :
"<$1>($0)"));
648 return None ?
"" : (
Open ?
"(" : (EmptyArgs ?
"()" :
"($0)"));
660 if (llvm::StringRef(*Snippet).ends_with(
"<>"))
662 return None ?
"" : (
Open ?
"<" :
"<$0>");
667 std::string summarizeSignature()
const {
668 if (
auto *Signature = onlyValue<&BundledEntry::Signature>())
676 CodeCompletion Completion;
677 llvm::SmallVector<BundledEntry, 1> Bundled;
682 bool IsUsingDeclaration;
683 tok::TokenKind NextTokenKind;
687SymbolID
getSymbolID(
const CodeCompletionResult &R,
const SourceManager &SM) {
689 case CodeCompletionResult::RK_Declaration:
690 case CodeCompletionResult::RK_Pattern: {
696 case CodeCompletionResult::RK_Macro:
698 case CodeCompletionResult::RK_Keyword:
701 llvm_unreachable(
"unknown CodeCompletionResult kind");
706struct SpecifiedScope {
729 std::vector<std::string> AccessibleScopes;
732 std::vector<std::string> QueryScopes;
735 std::optional<std::string> UnresolvedQualifier;
737 std::optional<std::string> EnclosingNamespace;
739 bool AllowAllScopes =
false;
743 std::vector<std::string> scopesForQualification() {
744 std::set<std::string> Results;
745 for (llvm::StringRef AS : AccessibleScopes)
747 (AS + (UnresolvedQualifier ? *UnresolvedQualifier :
"")).str());
748 return {Results.begin(), Results.end()};
753 std::vector<std::string> scopesForIndexQuery() {
755 std::vector<std::string> EnclosingAtFront;
756 if (EnclosingNamespace.has_value())
757 EnclosingAtFront.push_back(*EnclosingNamespace);
758 std::set<std::string> Deduplicated;
759 for (llvm::StringRef S : QueryScopes)
760 if (S != EnclosingNamespace)
761 Deduplicated.insert((S + UnresolvedQualifier.value_or(
"")).str());
763 EnclosingAtFront.reserve(EnclosingAtFront.size() + Deduplicated.size());
764 llvm::copy(Deduplicated, std::back_inserter(EnclosingAtFront));
766 return EnclosingAtFront;
773SpecifiedScope getQueryScopes(CodeCompletionContext &CCContext,
775 const CompletionPrefix &HeuristicPrefix,
776 const CodeCompleteOptions &Opts) {
777 SpecifiedScope Scopes;
778 for (
auto *Context : CCContext.getVisitedContexts()) {
779 if (isa<TranslationUnitDecl>(Context)) {
780 Scopes.QueryScopes.push_back(
"");
781 Scopes.AccessibleScopes.push_back(
"");
782 }
else if (
const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
788 const CXXScopeSpec *SemaSpecifier =
789 CCContext.getCXXScopeSpecifier().value_or(
nullptr);
791 if (!SemaSpecifier) {
794 if (!HeuristicPrefix.Qualifier.empty()) {
795 vlog(
"Sema said no scope specifier, but we saw {0} in the source code",
796 HeuristicPrefix.Qualifier);
797 StringRef SpelledSpecifier = HeuristicPrefix.Qualifier;
798 if (SpelledSpecifier.consume_front(
"::")) {
799 Scopes.AccessibleScopes = {
""};
800 Scopes.QueryScopes = {
""};
802 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
810 Scopes.AllowAllScopes = Opts.AllScopes;
814 if (SemaSpecifier && SemaSpecifier->isValid())
818 Scopes.QueryScopes.push_back(
"");
819 llvm::StringRef SpelledSpecifier = Lexer::getSourceText(
820 CharSourceRange::getCharRange(SemaSpecifier->getRange()),
821 CCSema.SourceMgr, clang::LangOptions());
822 if (SpelledSpecifier.consume_front(
"::"))
823 Scopes.QueryScopes = {
""};
824 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
826 if (!Scopes.UnresolvedQualifier->empty())
827 *Scopes.UnresolvedQualifier +=
"::";
829 Scopes.AccessibleScopes = Scopes.QueryScopes;
836bool contextAllowsIndex(
enum CodeCompletionContext::Kind K) {
838 case CodeCompletionContext::CCC_TopLevel:
839 case CodeCompletionContext::CCC_ObjCInterface:
840 case CodeCompletionContext::CCC_ObjCImplementation:
841 case CodeCompletionContext::CCC_ObjCIvarList:
842 case CodeCompletionContext::CCC_ClassStructUnion:
843 case CodeCompletionContext::CCC_Statement:
844 case CodeCompletionContext::CCC_Expression:
845 case CodeCompletionContext::CCC_ObjCMessageReceiver:
846 case CodeCompletionContext::CCC_EnumTag:
847 case CodeCompletionContext::CCC_UnionTag:
848 case CodeCompletionContext::CCC_ClassOrStructTag:
849 case CodeCompletionContext::CCC_ObjCProtocolName:
850 case CodeCompletionContext::CCC_Namespace:
851 case CodeCompletionContext::CCC_Type:
852 case CodeCompletionContext::CCC_ParenthesizedExpression:
853 case CodeCompletionContext::CCC_ObjCInterfaceName:
854 case CodeCompletionContext::CCC_Symbol:
855 case CodeCompletionContext::CCC_SymbolOrNewName:
856 case CodeCompletionContext::CCC_ObjCClassForwardDecl:
857 case CodeCompletionContext::CCC_TopLevelOrExpression:
859 case CodeCompletionContext::CCC_OtherWithMacros:
860 case CodeCompletionContext::CCC_DotMemberAccess:
861 case CodeCompletionContext::CCC_ArrowMemberAccess:
862 case CodeCompletionContext::CCC_ObjCCategoryName:
863 case CodeCompletionContext::CCC_ObjCPropertyAccess:
864 case CodeCompletionContext::CCC_MacroName:
865 case CodeCompletionContext::CCC_MacroNameUse:
866 case CodeCompletionContext::CCC_PreprocessorExpression:
867 case CodeCompletionContext::CCC_PreprocessorDirective:
868 case CodeCompletionContext::CCC_SelectorName:
869 case CodeCompletionContext::CCC_TypeQualifiers:
870 case CodeCompletionContext::CCC_ObjCInstanceMessage:
871 case CodeCompletionContext::CCC_ObjCClassMessage:
872 case CodeCompletionContext::CCC_IncludedFile:
873 case CodeCompletionContext::CCC_Attribute:
875 case CodeCompletionContext::CCC_Other:
876 case CodeCompletionContext::CCC_NaturalLanguage:
877 case CodeCompletionContext::CCC_Recovery:
878 case CodeCompletionContext::CCC_NewName:
881 llvm_unreachable(
"unknown code completion context");
884static bool isInjectedClass(
const NamedDecl &D) {
885 if (
auto *R = dyn_cast_or_null<CXXRecordDecl>(&D))
886 if (R->isInjectedClassName())
892static bool isExcludedMember(
const NamedDecl &D) {
895 if (D.getKind() == Decl::CXXDestructor)
898 if (isInjectedClass(D))
901 auto NameKind = D.getDeclName().getNameKind();
902 if (NameKind == DeclarationName::CXXOperatorName ||
903 NameKind == DeclarationName::CXXLiteralOperatorName ||
904 NameKind == DeclarationName::CXXConversionFunctionName)
915struct CompletionRecorder :
public CodeCompleteConsumer {
916 CompletionRecorder(
const CodeCompleteOptions &Opts,
917 llvm::unique_function<
void()> ResultsCallback)
918 : CodeCompleteConsumer(Opts.getClangCompleteOpts()),
919 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
920 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
921 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
922 assert(this->ResultsCallback);
925 std::vector<CodeCompletionResult> Results;
926 CodeCompletionContext CCContext;
927 Sema *CCSema =
nullptr;
930 void ProcessCodeCompleteResults(
class Sema &S, CodeCompletionContext Context,
931 CodeCompletionResult *InResults,
932 unsigned NumResults)
final {
941 CodeCompletionContext::Kind ContextKind = Context.getKind();
942 if (ContextKind == CodeCompletionContext::CCC_Recovery) {
943 log(
"Code complete: Ignoring sema code complete callback with Recovery "
950 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
953 log(
"Multiple code complete callbacks (parser backtracked?). "
954 "Dropping results from context {0}, keeping results from {1}.",
955 getCompletionKindString(Context.getKind()),
956 getCompletionKindString(this->CCContext.getKind()));
964 for (
unsigned I = 0; I < NumResults; ++I) {
965 auto &Result = InResults[I];
968 Result.Kind == CodeCompletionResult::RK_Pattern &&
970 ContextKind != CodeCompletionContext::CCC_IncludedFile)
973 if (Result.Hidden && Result.Declaration &&
974 Result.Declaration->isCXXClassMember())
976 if (!Opts.IncludeIneligibleResults &&
977 (Result.Availability == CXAvailability_NotAvailable ||
978 Result.Availability == CXAvailability_NotAccessible))
980 if (Result.Declaration &&
981 !Context.getBaseType().isNull()
982 && isExcludedMember(*Result.Declaration))
986 if (Result.Declaration && !Context.getCXXScopeSpecifier() &&
987 isInjectedClass(*Result.Declaration))
990 Result.StartsNestedNameSpecifier =
false;
991 Results.push_back(Result);
996 CodeCompletionAllocator &getAllocator()
override {
return *CCAllocator; }
997 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1001 llvm::StringRef getName(
const CodeCompletionResult &Result) {
1002 switch (Result.Kind) {
1003 case CodeCompletionResult::RK_Declaration:
1004 if (
auto *ID = Result.Declaration->getIdentifier())
1005 return ID->getName();
1007 case CodeCompletionResult::RK_Keyword:
1008 return Result.Keyword;
1009 case CodeCompletionResult::RK_Macro:
1010 return Result.Macro->getName();
1011 case CodeCompletionResult::RK_Pattern:
1014 auto *CCS = codeCompletionString(Result);
1015 const CodeCompletionString::Chunk *OnlyText =
nullptr;
1016 for (
auto &C : *CCS) {
1017 if (C.Kind != CodeCompletionString::CK_TypedText)
1020 return CCAllocator->CopyString(CCS->getAllTypedText());
1023 return OnlyText ? OnlyText->Text : llvm::StringRef();
1028 CodeCompletionString *codeCompletionString(
const CodeCompletionResult &R) {
1030 return const_cast<CodeCompletionResult &
>(R).CreateCodeCompletionString(
1031 *CCSema, CCContext, *CCAllocator, CCTUInfo,
1036 CodeCompleteOptions Opts;
1037 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
1038 CodeCompletionTUInfo CCTUInfo;
1039 llvm::unique_function<void()> ResultsCallback;
1042struct ScoredSignature {
1046 SignatureInformation Signature;
1047 SignatureQualitySignals Quality;
1055int paramIndexForArg(
const CodeCompleteConsumer::OverloadCandidate &Candidate,
1057 int NumParams = Candidate.getNumParams();
1058 if (
auto *T = Candidate.getFunctionType()) {
1059 if (
auto *Proto = T->getAs<FunctionProtoType>()) {
1060 if (Proto->isVariadic())
1064 return std::min(Arg, std::max(NumParams - 1, 0));
1067class SignatureHelpCollector final :
public CodeCompleteConsumer {
1069 SignatureHelpCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1070 MarkupKind DocumentationFormat,
1071 const SymbolIndex *Index, SignatureHelp &SigHelp)
1072 : CodeCompleteConsumer(CodeCompleteOpts), SigHelp(SigHelp),
1073 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1074 CCTUInfo(Allocator), Index(Index),
1075 DocumentationFormat(DocumentationFormat) {}
1077 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1078 OverloadCandidate *Candidates,
1079 unsigned NumCandidates,
1080 SourceLocation OpenParLoc,
1081 bool Braced)
override {
1082 assert(!OpenParLoc.isInvalid());
1083 SourceManager &SrcMgr = S.getSourceManager();
1084 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
1085 if (SrcMgr.isInMainFile(OpenParLoc))
1088 elog(
"Location oustide main file in signature help: {0}",
1089 OpenParLoc.printToString(SrcMgr));
1091 std::vector<ScoredSignature> ScoredSignatures;
1092 SigHelp.signatures.reserve(NumCandidates);
1093 ScoredSignatures.reserve(NumCandidates);
1097 SigHelp.activeSignature = 0;
1098 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1099 "too many arguments");
1101 SigHelp.activeParameter =
static_cast<int>(CurrentArg);
1103 for (
unsigned I = 0; I < NumCandidates; ++I) {
1104 OverloadCandidate Candidate = Candidates[I];
1108 if (
auto *Func = Candidate.getFunction()) {
1109 if (
auto *Pattern = Func->getTemplateInstantiationPattern())
1110 Candidate = OverloadCandidate(Pattern);
1112 if (
static_cast<int>(I) == SigHelp.activeSignature) {
1117 SigHelp.activeParameter =
1118 paramIndexForArg(Candidate, SigHelp.activeParameter);
1121 const auto *CCS = Candidate.CreateSignatureString(
1122 CurrentArg, S, *Allocator, CCTUInfo,
1124 assert(CCS &&
"Expected the CodeCompletionString to be non-null");
1125 ScoredSignatures.push_back(processOverloadCandidate(
1127 Candidate.getFunction()
1134 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
1136 LookupRequest IndexRequest;
1137 for (
const auto &S : ScoredSignatures) {
1140 IndexRequest.IDs.insert(S.IDForDoc);
1142 Index->lookup(IndexRequest, [&](
const Symbol &S) {
1143 if (!S.Documentation.empty())
1144 FetchedDocs[S.ID] = std::string(S.Documentation);
1146 vlog(
"SigHelp: requested docs for {0} symbols from the index, got {1} "
1147 "symbols with non-empty docs in the response",
1148 IndexRequest.IDs.size(), FetchedDocs.size());
1151 llvm::sort(ScoredSignatures, [](
const ScoredSignature &L,
1152 const ScoredSignature &R) {
1159 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
1160 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
1161 if (L.Quality.NumberOfOptionalParameters !=
1162 R.Quality.NumberOfOptionalParameters)
1163 return L.Quality.NumberOfOptionalParameters <
1164 R.Quality.NumberOfOptionalParameters;
1165 if (L.Quality.Kind != R.Quality.Kind) {
1166 using OC = CodeCompleteConsumer::OverloadCandidate;
1167 auto KindPriority = [&](OC::CandidateKind K) {
1169 case OC::CK_Aggregate:
1171 case OC::CK_Function:
1173 case OC::CK_FunctionType:
1175 case OC::CK_FunctionProtoTypeLoc:
1177 case OC::CK_FunctionTemplate:
1179 case OC::CK_Template:
1182 llvm_unreachable(
"Unknown overload candidate type.");
1184 return KindPriority(L.Quality.Kind) < KindPriority(R.Quality.Kind);
1186 if (L.Signature.label.size() != R.Signature.label.size())
1187 return L.Signature.label.size() < R.Signature.label.size();
1188 return L.Signature.label < R.Signature.label;
1191 for (
auto &SS : ScoredSignatures) {
1193 SS.IDForDoc ? FetchedDocs.find(SS.IDForDoc) : FetchedDocs.end();
1194 if (IndexDocIt != FetchedDocs.end()) {
1195 markup::Document SignatureComment;
1197 SS.Signature.documentation =
1198 renderDoc(SignatureComment, DocumentationFormat);
1201 SigHelp.signatures.push_back(std::move(SS.Signature));
1205 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1207 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1210 void processParameterChunk(llvm::StringRef ChunkText,
1211 SignatureInformation &Signature)
const {
1213 unsigned ParamStartOffset =
lspLength(Signature.label);
1214 unsigned ParamEndOffset = ParamStartOffset +
lspLength(ChunkText);
1218 Signature.label += ChunkText;
1219 ParameterInformation
Info;
1220 Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset);
1222 Info.labelString = std::string(ChunkText);
1224 Signature.parameters.push_back(std::move(
Info));
1227 void processOptionalChunk(
const CodeCompletionString &CCS,
1228 SignatureInformation &Signature,
1229 SignatureQualitySignals &Signal)
const {
1230 for (
const auto &Chunk : CCS) {
1231 switch (Chunk.Kind) {
1232 case CodeCompletionString::CK_Optional:
1233 assert(Chunk.Optional &&
1234 "Expected the optional code completion string to be non-null.");
1235 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1237 case CodeCompletionString::CK_VerticalSpace:
1239 case CodeCompletionString::CK_CurrentParameter:
1240 case CodeCompletionString::CK_Placeholder:
1241 processParameterChunk(Chunk.Text, Signature);
1242 Signal.NumberOfOptionalParameters++;
1245 Signature.label += Chunk.Text;
1253 ScoredSignature processOverloadCandidate(
const OverloadCandidate &Candidate,
1254 const CodeCompletionString &CCS,
1255 llvm::StringRef DocComment)
const {
1256 SignatureInformation Signature;
1257 SignatureQualitySignals Signal;
1258 const char *ReturnType =
nullptr;
1260 markup::Document OverloadComment;
1262 Signature.documentation = renderDoc(OverloadComment, DocumentationFormat);
1263 Signal.Kind = Candidate.getKind();
1265 for (
const auto &Chunk : CCS) {
1266 switch (Chunk.Kind) {
1267 case CodeCompletionString::CK_ResultType:
1270 assert(!ReturnType &&
"Unexpected CK_ResultType");
1271 ReturnType = Chunk.Text;
1273 case CodeCompletionString::CK_CurrentParameter:
1274 case CodeCompletionString::CK_Placeholder:
1275 processParameterChunk(Chunk.Text, Signature);
1276 Signal.NumberOfParameters++;
1278 case CodeCompletionString::CK_Optional: {
1280 assert(Chunk.Optional &&
1281 "Expected the optional code completion string to be non-null.");
1282 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1285 case CodeCompletionString::CK_VerticalSpace:
1288 Signature.label += Chunk.Text;
1293 Signature.label +=
" -> ";
1294 Signature.label += ReturnType;
1296 dlog(
"Signal for {0}: {1}", Signature, Signal);
1297 ScoredSignature Result;
1298 Result.Signature = std::move(Signature);
1299 Result.Quality = Signal;
1300 const FunctionDecl *Func = Candidate.getFunction();
1301 if (Func && Result.Signature.documentation.value.empty()) {
1309 SignatureHelp &SigHelp;
1310 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1311 CodeCompletionTUInfo CCTUInfo;
1312 const SymbolIndex *Index;
1313 MarkupKind DocumentationFormat;
1318class ParamNameCollector final :
public CodeCompleteConsumer {
1320 ParamNameCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1321 std::set<std::string> &ParamNames)
1322 : CodeCompleteConsumer(CodeCompleteOpts),
1323 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1324 CCTUInfo(Allocator), ParamNames(ParamNames) {}
1326 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1327 OverloadCandidate *Candidates,
1328 unsigned NumCandidates,
1329 SourceLocation OpenParLoc,
1330 bool Braced)
override {
1331 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1332 "too many arguments");
1334 for (
unsigned I = 0; I < NumCandidates; ++I) {
1335 if (
const NamedDecl *ND = Candidates[I].getParamDecl(CurrentArg))
1336 if (
const auto *II = ND->getIdentifier())
1337 ParamNames.emplace(II->getName());
1342 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1344 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1346 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1347 CodeCompletionTUInfo CCTUInfo;
1348 std::set<std::string> &ParamNames;
1351struct SemaCompleteInput {
1355 const std::optional<PreamblePatch> Patch;
1356 const ParseInputs &ParseInput;
1359void loadMainFilePreambleMacros(
const Preprocessor &PP,
1364 ExternalPreprocessorSource *PreambleMacros = PP.getExternalSource();
1367 const auto &ITable = PP.getIdentifierTable();
1368 IdentifierInfoLookup *PreambleIdentifiers =
1369 ITable.getExternalIdentifierLookup();
1371 if (!PreambleIdentifiers || !PreambleMacros)
1373 for (
const auto &MacroName :
Preamble.Macros.Names) {
1374 if (ITable.find(MacroName.getKey()) != ITable.end())
1376 if (
auto *II = PreambleIdentifiers->get(MacroName.getKey()))
1377 if (II->isOutOfDate())
1378 PreambleMacros->updateOutOfDateIdentifier(*II);
1384bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
1385 const clang::CodeCompleteOptions &Options,
1386 const SemaCompleteInput &Input,
1387 IncludeStructure *Includes =
nullptr,
1388 std::unique_ptr<CompilerInvocation> CI =
nullptr) {
1389 trace::Span Tracer(
"Sema completion");
1391 IgnoreDiagnostics IgnoreDiags;
1395 elog(
"Couldn't create CompilerInvocation");
1399 auto &FrontendOpts = CI->getFrontendOpts();
1400 FrontendOpts.SkipFunctionBodies =
true;
1402 CI->getLangOpts().SpellChecking =
false;
1406 CI->getLangOpts().DelayedTemplateParsing =
false;
1408 FrontendOpts.CodeCompleteOpts = Options;
1409 FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName);
1410 std::tie(FrontendOpts.CodeCompletionAt.Line,
1411 FrontendOpts.CodeCompletionAt.Column) =
1414 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1415 llvm::MemoryBuffer::getMemBuffer(Input.ParseInput.Contents,
1418 CI->getDiagnosticOpts().IgnoreWarnings =
true;
1425 PreambleBounds PreambleRegion =
1427 Input.ParseInput.Opts.SkipPreambleBuild);
1428 bool CompletingInPreamble = Input.Offset < PreambleRegion.Size ||
1429 (!PreambleRegion.PreambleEndsAtStartOfLine &&
1430 Input.Offset == PreambleRegion.Size);
1432 Input.Patch->apply(*CI);
1435 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1436 Input.ParseInput.TFS->view(Input.ParseInput.CompileCommand.Directory);
1437 if (Input.Preamble.StatCache)
1438 VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS));
1441 (!CompletingInPreamble && !Input.ParseInput.Opts.SkipPreambleBuild)
1442 ? &Input.Preamble.Preamble
1444 std::move(ContentsBuffer), std::move(VFS), IgnoreDiags);
1445 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
1446 Clang->setCodeCompletionConsumer(Consumer.release());
1448 if (Input.Preamble.RequiredModules)
1449 Input.Preamble.RequiredModules->adjustHeaderSearchOptions(
1450 Clang->getHeaderSearchOpts());
1453 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1454 log(
"BeginSourceFile() failed when running codeComplete for {0}",
1464 loadMainFilePreambleMacros(Clang->getPreprocessor(), Input.Preamble);
1466 Includes->collect(*Clang);
1467 if (llvm::Error Err = Action.Execute()) {
1468 log(
"Execute() failed when running codeComplete for {0}: {1}",
1469 Input.FileName,
toString(std::move(Err)));
1472 Action.EndSourceFile();
1478bool allowIndex(CodeCompletionContext &CC) {
1479 if (!contextAllowsIndex(CC.getKind()))
1482 auto Scope = CC.getCXXScopeSpecifier();
1487 switch ((*Scope)->getScopeRep().getKind()) {
1488 case NestedNameSpecifier::Kind::Null:
1489 case NestedNameSpecifier::Kind::Global:
1490 case NestedNameSpecifier::Kind::Namespace:
1492 case NestedNameSpecifier::Kind::MicrosoftSuper:
1493 case NestedNameSpecifier::Kind::Type:
1496 llvm_unreachable(
"invalid NestedNameSpecifier kind");
1501bool includeSymbolFromIndex(CodeCompletionContext::Kind Kind,
1502 const Symbol &Sym) {
1506 if (Sym.SymInfo.Kind == index::SymbolKind::Protocol &&
1507 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC)
1508 return Kind == CodeCompletionContext::CCC_ObjCProtocolName;
1509 else if (Kind == CodeCompletionContext::CCC_ObjCProtocolName)
1513 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
1514 return Sym.SymInfo.Kind == index::SymbolKind::Class &&
1515 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC;
1519std::future<std::pair<bool, SymbolSlab>>
1520startAsyncFuzzyFind(
const SymbolIndex &Index,
const FuzzyFindRequest &Req) {
1522 trace::Span Tracer(
"Async fuzzyFind");
1523 SymbolSlab::Builder Syms;
1525 Index.fuzzyFind(Req, [&Syms](
const Symbol &Sym) { Syms.insert(Sym); });
1526 return std::make_pair(Incomplete, std::move(Syms).build());
1533FuzzyFindRequest speculativeFuzzyFindRequestForCompletion(
1534 FuzzyFindRequest CachedReq,
const CompletionPrefix &HeuristicPrefix) {
1535 CachedReq.Query = std::string(HeuristicPrefix.Name);
1543findTokenAfterCompletionPoint(SourceLocation CompletionPoint,
1544 const SourceManager &SM,
1545 const LangOptions &LangOpts) {
1546 SourceLocation Loc = CompletionPoint;
1547 if (Loc.isMacroID()) {
1548 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1549 return std::nullopt;
1557 Loc = Loc.getLocWithOffset(1);
1560 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1563 bool InvalidTemp =
false;
1564 StringRef
File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1566 return std::nullopt;
1568 const char *TokenBegin =
File.data() + LocInfo.second;
1571 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
File.begin(),
1572 TokenBegin,
File.end());
1575 TheLexer.LexFromRawLexer(Tok);
1608class CodeCompleteFlow {
1610 IncludeStructure Includes;
1611 SpeculativeFuzzyFind *SpecFuzzyFind;
1612 const CodeCompleteOptions &Opts;
1615 CompletionRecorder *Recorder =
nullptr;
1616 CodeCompletionContext::Kind CCContextKind = CodeCompletionContext::CCC_Other;
1617 bool IsUsingDeclaration =
false;
1621 tok::TokenKind NextTokenKind = tok::eof;
1623 int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
1624 bool Incomplete =
false;
1625 CompletionPrefix HeuristicPrefix;
1626 std::optional<FuzzyMatcher> Filter;
1628 std::optional<Range> ReplaceRange;
1629 std::vector<std::string> QueryScopes;
1630 std::vector<std::string> AccessibleScopes;
1632 std::optional<ScopeDistance> ScopeProximity;
1633 std::optional<OpaqueType> PreferredType;
1635 bool AllScopes =
false;
1636 llvm::StringSet<> ContextWords;
1639 std::optional<IncludeInserter> Inserter;
1640 std::optional<URIDistance> FileProximity;
1645 std::optional<FuzzyFindRequest> SpecReq;
1649 CodeCompleteFlow(
PathRef FileName,
const IncludeStructure &Includes,
1650 SpeculativeFuzzyFind *SpecFuzzyFind,
1651 const CodeCompleteOptions &Opts)
1652 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1655 CodeCompleteResult
run(
const SemaCompleteInput &SemaCCInput) && {
1656 trace::Span Tracer(
"CodeCompleteFlow");
1658 SemaCCInput.Offset);
1659 populateContextWords(SemaCCInput.ParseInput.Contents);
1660 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq) {
1661 assert(!SpecFuzzyFind->Result.valid());
1662 SpecReq = speculativeFuzzyFindRequestForCompletion(
1663 *SpecFuzzyFind->CachedReq, HeuristicPrefix);
1664 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1670 CodeCompleteResult Output;
1671 auto RecorderOwner = std::make_unique<CompletionRecorder>(Opts, [&]() {
1672 assert(Recorder &&
"Recorder is not set");
1673 CCContextKind = Recorder->CCContext.getKind();
1674 IsUsingDeclaration = Recorder->CCContext.isUsingDeclaration();
1676 SemaCCInput.ParseInput.Contents,
1677 *SemaCCInput.ParseInput.TFS,
false);
1678 const auto NextToken = findTokenAfterCompletionPoint(
1679 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc(),
1680 Recorder->CCSema->getSourceManager(), Recorder->CCSema->LangOpts);
1682 NextTokenKind = NextToken->getKind();
1686 SemaCCInput.FileName, SemaCCInput.ParseInput.Contents, Style,
1687 SemaCCInput.ParseInput.CompileCommand.Directory,
1688 &Recorder->CCSema->getPreprocessor().getHeaderSearchInfo(),
1691 for (
const auto &Inc : Includes.MainFileIncludes)
1692 Inserter->addExisting(Inc);
1698 FileDistanceOptions ProxOpts{};
1699 const auto &SM = Recorder->CCSema->getSourceManager();
1700 llvm::StringMap<SourceParams> ProxSources;
1702 Includes.getID(SM.getFileEntryForID(SM.getMainFileID()));
1704 for (
auto &HeaderIDAndDepth : Includes.includeDepth(*MainFileID)) {
1706 ProxSources[Includes.getRealPath(HeaderIDAndDepth.getFirst())];
1707 Source.Cost = HeaderIDAndDepth.getSecond() * ProxOpts.IncludeCost;
1711 if (HeaderIDAndDepth.getSecond() > 0)
1712 Source.MaxUpTraversals = 1;
1714 FileProximity.emplace(ProxSources, ProxOpts);
1716 Output = runWithSema();
1719 getCompletionKindString(CCContextKind));
1720 log(
"Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1721 "expected type {3}{4}",
1722 getCompletionKindString(CCContextKind),
1723 llvm::join(QueryScopes.begin(), QueryScopes.end(),
","), AllScopes,
1724 PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1726 IsUsingDeclaration ?
", inside using declaration" :
"");
1729 Recorder = RecorderOwner.get();
1731 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1732 SemaCCInput, &Includes);
1733 logResults(Output, Tracer);
1737 void logResults(
const CodeCompleteResult &Output,
const trace::Span &Tracer) {
1740 SPAN_ATTACH(Tracer,
"merged_results", NSemaAndIndex);
1741 SPAN_ATTACH(Tracer,
"identifier_results", NIdent);
1742 SPAN_ATTACH(Tracer,
"returned_results", int64_t(Output.Completions.size()));
1743 SPAN_ATTACH(Tracer,
"incomplete", Output.HasMore);
1744 log(
"Code complete: {0} results from Sema, {1} from Index, "
1745 "{2} matched, {3} from identifiers, {4} returned{5}.",
1746 NSema, NIndex, NSemaAndIndex, NIdent, Output.Completions.size(),
1747 Output.HasMore ?
" (incomplete)" :
"");
1748 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1753 CodeCompleteResult runWithoutSema(llvm::StringRef Content,
size_t Offset,
1754 const ThreadsafeFS &TFS) && {
1755 trace::Span Tracer(
"CodeCompleteWithoutSema");
1758 populateContextWords(Content);
1759 CCContextKind = CodeCompletionContext::CCC_Recovery;
1760 IsUsingDeclaration =
false;
1761 Filter = FuzzyMatcher(HeuristicPrefix.Name);
1763 InsertRange.start = InsertRange.end = Pos;
1764 InsertRange.start.character -= HeuristicPrefix.Name.size();
1766 if (Opts.EnableInsertReplace) {
1767 ReplaceRange.emplace();
1768 ReplaceRange->start = InsertRange.start;
1770 size_t ReplaceEnd = Offset;
1771 while (ReplaceEnd < Content.size() &&
1772 isAsciiIdentifierContinue(Content[ReplaceEnd]))
1777 llvm::StringMap<SourceParams> ProxSources;
1778 ProxSources[FileName].Cost = 0;
1779 FileProximity.emplace(ProxSources);
1783 Inserter.emplace(FileName, Content, Style,
1789 std::vector<RawIdentifier> IdentifierResults;
1790 for (
const auto &IDAndCount : Identifiers) {
1792 ID.Name = IDAndCount.first();
1793 ID.References = IDAndCount.second;
1795 if (ID.Name == HeuristicPrefix.Name)
1797 if (ID.References > 0)
1798 IdentifierResults.push_back(std::move(ID));
1804 SpecifiedScope Scopes;
1806 Content.take_front(Offset), format::getFormattingLangOpts(Style));
1807 for (std::string &S : Scopes.QueryScopes)
1810 if (HeuristicPrefix.Qualifier.empty())
1811 AllScopes = Opts.AllScopes;
1812 else if (HeuristicPrefix.Qualifier.starts_with(
"::")) {
1813 Scopes.QueryScopes = {
""};
1814 Scopes.UnresolvedQualifier =
1815 std::string(HeuristicPrefix.Qualifier.drop_front(2));
1817 Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier);
1819 QueryScopes = Scopes.scopesForIndexQuery();
1820 AccessibleScopes = QueryScopes;
1821 ScopeProximity.emplace(QueryScopes);
1823 SymbolSlab IndexResults = Opts.Index ? queryIndex() : SymbolSlab();
1825 CodeCompleteResult Output = toCodeCompleteResult(mergeResults(
1826 {}, IndexResults, IdentifierResults));
1827 Output.RanParser =
false;
1828 logResults(Output, Tracer);
1833 void populateContextWords(llvm::StringRef Content) {
1835 unsigned RangeEnd = HeuristicPrefix.Qualifier.begin() - Content.data(),
1836 RangeBegin = RangeEnd;
1837 for (
size_t I = 0; I < 3 && RangeBegin > 0; ++I) {
1838 auto PrevNL = Content.rfind(
'\n', RangeBegin);
1839 if (PrevNL == StringRef::npos) {
1843 RangeBegin = PrevNL;
1846 ContextWords =
collectWords(Content.slice(RangeBegin, RangeEnd));
1847 dlog(
"Completion context words: {0}",
1848 llvm::join(ContextWords.keys(),
", "));
1853 CodeCompleteResult runWithSema() {
1854 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1855 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1857 const SourceManager &SM = Recorder->CCSema->getSourceManager();
1864 if (CodeCompletionRange.isValid()) {
1868 SM, Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1869 InsertRange.start = InsertRange.end = Pos;
1872 if (Opts.EnableInsertReplace) {
1873 ReplaceRange.emplace();
1874 ReplaceRange->start = InsertRange.start;
1875 ReplaceRange->end = getEndOfCodeCompletionReplace(SM);
1877 Filter = FuzzyMatcher(
1878 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1879 auto SpecifiedScopes = getQueryScopes(
1880 Recorder->CCContext, *Recorder->CCSema, HeuristicPrefix, Opts);
1882 QueryScopes = SpecifiedScopes.scopesForIndexQuery();
1883 AccessibleScopes = SpecifiedScopes.scopesForQualification();
1884 AllScopes = SpecifiedScopes.AllowAllScopes;
1885 if (!QueryScopes.empty())
1886 ScopeProximity.emplace(QueryScopes);
1889 Recorder->CCContext.getPreferredType());
1895 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1898 trace::Span Tracer(
"Populate CodeCompleteResult");
1901 mergeResults(Recorder->Results, IndexResults, {});
1902 return toCodeCompleteResult(Top);
1907 Position getEndOfCodeCompletionReplace(
const SourceManager &SM) {
1908 const Preprocessor &PP = Recorder->CCSema->getPreprocessor();
1909 const LangOptions &LangOpts = Recorder->CCSema->getLangOpts();
1915 const SourceLocation SuffixBegin =
1916 PP.getCodeCompletionLoc().getLocWithOffset(1);
1918 SM, Lexer::findEndOfIdentifierContinuation(SuffixBegin, SM, LangOpts));
1926 toCodeCompleteResult(
const std::vector<ScoredBundle> &Scored) {
1927 CodeCompleteResult Output;
1932 llvm::DenseMap<SymbolID, uint32_t> SymbolToCompletion;
1933 for (
auto &C : Scored) {
1934 Output.Completions.push_back(toCodeCompletion(C.first));
1935 Output.Completions.back().Score = C.second;
1936 Output.Completions.back().CompletionInsertRange = InsertRange;
1937 Output.Completions.back().CompletionReplaceRange = ReplaceRange;
1938 if (Opts.Index && !Output.Completions.back().Documentation) {
1939 for (
auto &Cand : C.first) {
1940 if (Cand.SemaResult &&
1941 Cand.SemaResult->Kind == CodeCompletionResult::RK_Declaration) {
1942 const NamedDecl *DeclToLookup = Cand.SemaResult->getDeclaration();
1946 if (
const NamedDecl *Adjusted =
1947 dyn_cast<NamedDecl>(&adjustDeclToTemplate(*DeclToLookup))) {
1948 DeclToLookup = Adjusted;
1954 SymbolToCompletion[ID] = Output.Completions.size() - 1;
1959 Output.HasMore = Incomplete;
1960 Output.Context = CCContextKind;
1961 Output.InsertRange = InsertRange;
1962 Output.ReplaceRange = ReplaceRange;
1966 Opts.Index->lookup(Req, [&](
const Symbol &S) {
1967 if (S.Documentation.empty())
1969 auto &C = Output.Completions[SymbolToCompletion.at(S.ID)];
1970 C.Documentation.emplace();
1978 SymbolSlab queryIndex() {
1979 trace::Span Tracer(
"Query index");
1980 SPAN_ATTACH(Tracer,
"limit", int64_t(Opts.Limit));
1983 FuzzyFindRequest Req;
1985 Req.Limit = Opts.Limit;
1986 Req.Query = std::string(Filter->pattern());
1987 Req.RestrictForCodeCompletion =
true;
1988 Req.Scopes = QueryScopes;
1989 Req.AnyScope = AllScopes;
1991 Req.ProximityPaths.push_back(std::string(FileName));
1993 Req.PreferredTypes.push_back(std::string(PreferredType->raw()));
1994 vlog(
"Code complete: fuzzyFind({0:2})",
toJSON(Req));
1997 SpecFuzzyFind->NewReq = Req;
1998 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1999 vlog(
"Code complete: speculative fuzzy request matches the actual index "
2000 "request. Waiting for the speculative index results.");
2003 trace::Span WaitSpec(
"Wait speculative results");
2004 auto SpecRes = SpecFuzzyFind->Result.get();
2005 Incomplete |= SpecRes.first;
2006 return std::move(SpecRes.second);
2009 SPAN_ATTACH(Tracer,
"Speculative results",
false);
2012 SymbolSlab::Builder ResultsBuilder;
2013 Incomplete |= Opts.Index->fuzzyFind(
2014 Req, [&](
const Symbol &Sym) { ResultsBuilder.insert(Sym); });
2015 return std::move(ResultsBuilder).build();
2023 std::vector<ScoredBundle>
2024 mergeResults(
const std::vector<CodeCompletionResult> &SemaResults,
2025 const SymbolSlab &IndexResults,
2026 const std::vector<RawIdentifier> &IdentifierResults) {
2027 trace::Span Tracer(
"Merge and score results");
2028 std::vector<CompletionCandidate::Bundle> Bundles;
2029 llvm::DenseMap<size_t, size_t> BundleLookup;
2030 auto AddToBundles = [&](
const CodeCompletionResult *SemaResult,
2031 const Symbol *IndexResult,
2032 const RawIdentifier *IdentifierResult) {
2033 CompletionCandidate C;
2034 C.SemaResult = SemaResult;
2035 C.IndexResult = IndexResult;
2036 C.IdentifierResult = IdentifierResult;
2037 if (C.IndexResult) {
2038 C.Name = IndexResult->Name;
2040 }
else if (C.SemaResult) {
2041 C.Name = Recorder->getName(*SemaResult);
2043 assert(IdentifierResult);
2044 C.Name = IdentifierResult->Name;
2046 if (
auto OverloadSet = C.overloadSet(
2047 Opts, FileName, Inserter ? &*Inserter :
nullptr, CCContextKind)) {
2048 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
2050 Bundles.emplace_back();
2051 Bundles[Ret.first->second].push_back(std::move(C));
2053 Bundles.emplace_back();
2054 Bundles.back().push_back(std::move(C));
2057 llvm::DenseSet<const Symbol *> UsedIndexResults;
2058 auto CorrespondingIndexResult =
2059 [&](
const CodeCompletionResult &SemaResult) ->
const Symbol * {
2061 getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
2062 auto I = IndexResults.find(SymID);
2063 if (I != IndexResults.end()) {
2064 UsedIndexResults.insert(&*I);
2071 for (
auto &SemaResult : SemaResults)
2072 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult),
nullptr);
2074 for (
const auto &IndexResult : IndexResults) {
2075 if (UsedIndexResults.count(&IndexResult))
2077 if (!includeSymbolFromIndex(CCContextKind, IndexResult))
2079 AddToBundles(
nullptr, &IndexResult,
nullptr);
2082 for (
const auto &Ident : IdentifierResults)
2083 AddToBundles(
nullptr,
nullptr, &Ident);
2085 TopN<ScoredBundle, ScoredBundleGreater> Top(
2086 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
2087 for (
auto &Bundle : Bundles)
2088 addCandidate(Top, std::move(Bundle));
2089 return std::move(Top).items();
2092 std::optional<float> fuzzyScore(
const CompletionCandidate &C) {
2095 const auto IsMacroResult =
2097 C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
2099 C.IndexResult->SymInfo.Kind == index::SymbolKind::Macro));
2102 return Filter->match(C.Name);
2105 bool RequireExactPrefix =
2106 Opts.MacroFilter == MacroFilterPolicy::ExactPrefix ||
2107 C.Name.starts_with_insensitive(
"_") ||
2108 C.Name.ends_with_insensitive(
"_");
2110 if (RequireExactPrefix &&
2111 !C.Name.starts_with_insensitive(Filter->pattern())) {
2112 return std::nullopt;
2115 return Filter->match(C.Name);
2118 CodeCompletion::Scores
2119 evaluateCompletion(
const SymbolQualitySignals &Quality,
2120 const SymbolRelevanceSignals &Relevance) {
2121 using RM = CodeCompleteOptions::CodeCompletionRankingModel;
2122 CodeCompletion::Scores Scores;
2123 switch (Opts.RankingModel) {
2124 case RM::Heuristics:
2125 Scores.Quality = Quality.evaluateHeuristics();
2126 Scores.Relevance = Relevance.evaluateHeuristics();
2131 Scores.ExcludingName =
2132 Relevance.NameMatch > std::numeric_limits<float>::epsilon()
2133 ? Scores.Total / Relevance.NameMatch
2137 case RM::DecisionForest:
2138 DecisionForestScores DFScores = Opts.DecisionForestScorer(
2139 Quality, Relevance, Opts.DecisionForestBase);
2140 Scores.ExcludingName = DFScores.ExcludingName;
2141 Scores.Total = DFScores.Total;
2144 llvm_unreachable(
"Unhandled CodeCompletion ranking model.");
2148 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
2149 CompletionCandidate::Bundle Bundle) {
2150 SymbolQualitySignals Quality;
2151 SymbolRelevanceSignals Relevance;
2152 Relevance.Context = CCContextKind;
2153 Relevance.Name = Bundle.front().Name;
2154 Relevance.FilterLength = HeuristicPrefix.Name.size();
2156 Relevance.FileProximityMatch = &*FileProximity;
2158 Relevance.ScopeProximityMatch = &*ScopeProximity;
2160 Relevance.HadContextType =
true;
2161 Relevance.ContextWords = &ContextWords;
2162 Relevance.MainFileSignals = Opts.MainFileSignals;
2164 auto &First = Bundle.front();
2165 if (
auto FuzzyScore = fuzzyScore(First))
2166 Relevance.NameMatch = *FuzzyScore;
2170 bool FromIndex =
false;
2171 for (
const auto &Candidate : Bundle) {
2172 if (Candidate.IndexResult) {
2173 Quality.merge(*Candidate.IndexResult);
2174 Relevance.merge(*Candidate.IndexResult);
2175 Origin |= Candidate.IndexResult->Origin;
2177 if (!Candidate.IndexResult->Type.empty())
2178 Relevance.HadSymbolType |=
true;
2179 if (PreferredType &&
2180 PreferredType->raw() == Candidate.IndexResult->Type) {
2181 Relevance.TypeMatchesPreferred =
true;
2184 if (Candidate.SemaResult) {
2185 Quality.merge(*Candidate.SemaResult);
2186 Relevance.merge(*Candidate.SemaResult);
2187 if (PreferredType) {
2189 Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
2190 Relevance.HadSymbolType |=
true;
2191 if (PreferredType == CompletionType)
2192 Relevance.TypeMatchesPreferred =
true;
2197 if (Candidate.IdentifierResult) {
2198 Quality.References = Candidate.IdentifierResult->References;
2204 CodeCompletion::Scores Scores = evaluateCompletion(Quality, Relevance);
2205 if (Opts.RecordCCResult)
2206 Opts.RecordCCResult(toCodeCompletion(Bundle), Quality, Relevance,
2209 dlog(
"CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
2210 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
2211 llvm::to_string(Relevance));
2214 NIndex += FromIndex;
2217 if (Candidates.push({std::move(Bundle), Scores}))
2221 CodeCompletion toCodeCompletion(
const CompletionCandidate::Bundle &Bundle) {
2222 std::optional<CodeCompletionBuilder> Builder;
2223 for (
const auto &Item : Bundle) {
2224 CodeCompletionString *SemaCCS =
2225 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
2228 Builder.emplace(Recorder ? &Recorder->CCSema->getASTContext() :
nullptr,
2229 Item, SemaCCS, AccessibleScopes, *Inserter, FileName,
2230 CCContextKind, Opts, IsUsingDeclaration, NextTokenKind);
2232 Builder->add(Item, SemaCCS, CCContextKind);
2234 return Builder->build();
2241 clang::CodeCompleteOptions
Result;
2242 Result.IncludeCodePatterns =
2244 Result.IncludeMacros =
true;
2245 Result.IncludeGlobals =
true;
2250 Result.IncludeBriefComments =
false;
2255 Result.LoadExternal = ForceLoadPreamble || !Index;
2256 Result.IncludeFixIts = IncludeFixIts;
2263 assert(Offset <= Content.size());
2264 StringRef Rest = Content.take_front(Offset);
2269 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2270 Rest = Rest.drop_back();
2271 Result.
Name = Content.slice(Rest.size(), Offset);
2274 while (Rest.consume_back(
"::") && !Rest.ends_with(
":"))
2275 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2276 Rest = Rest.drop_back();
2278 Content.slice(Rest.size(), Result.
Name.begin() - Content.begin());
2286static std::optional<unsigned>
2288 const llvm::StringRef Content,
2289 const LangOptions &LangOpts) {
2290 if (Offset > Content.size())
2291 return std::nullopt;
2293 SourceManagerForFile FileSM(FileName, Content);
2294 const SourceManager &SM = FileSM.get();
2295 const SourceLocation Cursor = SM.getComposedLoc(SM.getMainFileID(), Offset);
2296 const SourceLocation EndOfSuffix =
2297 Lexer::findEndOfIdentifierContinuation(Cursor, SM, LangOpts);
2298 const unsigned EndOfSuffixOffset = SM.getFileOffset(EndOfSuffix);
2300 const llvm::StringRef Rest = Content.drop_front(EndOfSuffixOffset);
2301 llvm::StringRef RestTrimmed = Rest.ltrim();
2303 if (RestTrimmed.starts_with(
"="))
2304 RestTrimmed = RestTrimmed.drop_front(1).ltrim();
2305 if (RestTrimmed.starts_with(
"*/"))
2306 return EndOfSuffixOffset + (Rest.size() - RestTrimmed.size()) + 2;
2307 return std::nullopt;
2315 unsigned OutsideStartOffset, llvm::StringRef Prefix,
2319 return CodeCompleteResult();
2324 return CodeCompleteResult();
2326 std::optional<unsigned> OutsideEndOffset;
2327 if (Opts.EnableInsertReplace)
2329 FileName, CursorOffset, ParseInput.
Contents, CI->getLangOpts());
2331 clang::CodeCompleteOptions Options;
2332 Options.IncludeGlobals =
false;
2333 Options.IncludeMacros =
false;
2334 Options.IncludeCodePatterns =
false;
2335 Options.IncludeBriefComments =
false;
2336 std::set<std::string> ParamNames;
2340 std::make_unique<ParamNameCollector>(Options, ParamNames), Options,
2341 {FileName, OutsideStartOffset, *
Preamble,
2344 nullptr, std::move(CI));
2345 if (ParamNames.empty())
2346 return CodeCompleteResult();
2348 CodeCompleteResult Result;
2351 const unsigned InsideStartOffset = OutsideStartOffset + 2;
2355 Result.InsertRange = InsertRange;
2357 if (Opts.EnableInsertReplace) {
2363 Result.ReplaceRange = ReplaceRange;
2366 Result.Context = CodeCompletionContext::CCC_NaturalLanguage;
2367 for (llvm::StringRef Name : ParamNames) {
2368 if (!Name.starts_with(Prefix))
2370 CodeCompletion Item;
2371 Item.Name = Name.str() +
"=*/";
2372 Item.FilterText = Item.Name;
2374 Item.CompletionInsertRange = InsertRange;
2375 Item.CompletionReplaceRange = Result.ReplaceRange;
2377 Result.Completions.push_back(Item);
2386std::optional<unsigned>
2388 while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
2389 Content = Content.drop_back();
2390 Content = Content.rtrim();
2391 if (Content.ends_with(
"/*"))
2392 return Content.size() - 2;
2393 return std::nullopt;
2400 SpeculativeFuzzyFind *SpecFuzzyFind) {
2403 elog(
"Code completion position was invalid {0}", Offset.takeError());
2404 return CodeCompleteResult();
2407 auto Content = llvm::StringRef(ParseInput.
Contents).take_front(*Offset);
2414 auto CommentPrefix = Content.substr(*OffsetBeforeComment + 2).trim();
2416 CommentPrefix,
Preamble, ParseInput, Opts);
2419 auto Flow = CodeCompleteFlow(
2421 SpecFuzzyFind, Opts);
2422 return (!
Preamble || Opts.RunParser == CodeCompleteOptions::NeverParse)
2423 ? std::move(Flow).runWithoutSema(ParseInput.
Contents, *Offset,
2425 : std::move(Flow).run({FileName, *Offset, *
Preamble,
2438 elog(
"Signature help position was invalid {0}", Offset.takeError());
2442 clang::CodeCompleteOptions Options;
2443 Options.IncludeGlobals =
false;
2444 Options.IncludeMacros =
false;
2445 Options.IncludeCodePatterns =
false;
2446 Options.IncludeBriefComments =
false;
2448 std::make_unique<SignatureHelpCollector>(Options, DocumentationFormat,
2449 ParseInput.
Index, Result),
2451 {FileName, *Offset, Preamble,
2452 PreamblePatch::createFullPatch(FileName, ParseInput, Preamble),
2458 auto InTopLevelScope = [](
const NamedDecl &ND) {
2459 switch (ND.getDeclContext()->getDeclKind()) {
2460 case Decl::TranslationUnit:
2461 case Decl::Namespace:
2462 case Decl::LinkageSpec:
2469 auto InClassScope = [](
const NamedDecl &ND) {
2470 return ND.getDeclContext()->getDeclKind() == Decl::CXXRecord;
2481 if (llvm::isa<ObjCCategoryDecl>(&ND) || llvm::isa<ObjCCategoryImplDecl>(&ND))
2484 if (InTopLevelScope(ND))
2490 if (
const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
2491 return (InTopLevelScope(*EnumDecl) || InClassScope(*EnumDecl));
2496CompletionItem CodeCompletion::render(
const CodeCompleteOptions &Opts)
const {
2498 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
2501 LSP.label = ((InsertInclude && InsertInclude->Insertion)
2502 ? Opts.IncludeIndicator.Insert
2503 : Opts.IncludeIndicator.NoInsert) +
2504 (Opts.ShowOrigins ?
"[" + llvm::to_string(Origin) +
"]" :
"") +
2505 RequiredQualifier + Name;
2506 LSP.labelDetails.emplace();
2507 LSP.labelDetails->detail = Signature;
2510 LSP.detail = BundleSize > 1
2511 ? std::string(llvm::formatv(
"[{0} overloads]", BundleSize))
2516 if (InsertInclude || Documentation) {
2517 markup::Document Doc;
2519 Doc.addParagraph().appendText(
"From ").appendCode(InsertInclude->Header);
2521 Doc.append(*Documentation);
2522 LSP.documentation = renderDoc(Doc, Opts.DocumentationFormat);
2524 LSP.sortText =
sortText(Score.Total, FilterText);
2525 LSP.filterText = FilterText;
2527 Edit.range = CompletionInsertRange;
2528 Edit.newText = RequiredQualifier + Name;
2536 for (
const auto &FixIt : FixIts) {
2537 if (FixIt.range.end == Edit.range.start) {
2538 Edit.newText = FixIt.newText + Edit.newText;
2539 Edit.range.start = FixIt.range.start;
2541 LSP.additionalTextEdits.push_back(FixIt);
2544 if (Opts.EnableSnippets)
2545 Edit.newText += SnippetSuffix;
2549 LSP.insertText =
Edit.newText;
2550 if (Opts.EnableInsertReplace) {
2551 assert(CompletionReplaceRange &&
2552 "CompletionReplaceRange must be already set before render() "
2553 "when EnableInsertReplace is on");
2556 IRE.insert =
Edit.range;
2557 IRE.replace = *CompletionReplaceRange;
2560 IRE.replace.start = IRE.insert.start;
2561 LSP.textEdit = std::move(IRE);
2563 LSP.textEdit = std::move(
Edit);
2568 LSP.insertTextFormat = (Opts.EnableSnippets && !SnippetSuffix.empty())
2571 if (InsertInclude && InsertInclude->Insertion)
2572 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
2574 LSP.score = Score.ExcludingName;
2579llvm::raw_ostream &
operator<<(llvm::raw_ostream &OS,
const CodeCompletion &C) {
2580 OS <<
"Signature: " <<
"\"" << C.Signature <<
"\", "
2581 <<
"SnippetSuffix: " <<
"\"" << C.SnippetSuffix <<
"\""
2588 const CodeCompleteResult &R) {
2589 OS <<
"CodeCompleteResult: " << R.Completions.size() << (R.HasMore ?
"+" :
"")
2590 <<
" (" << getCompletionKindString(R.Context) <<
")"
2592 for (
const auto &C : R.Completions)
2599 Line = Line.ltrim();
2600 if (!Line.consume_front(
"#"))
2602 Line = Line.ltrim();
2603 if (!(Line.consume_front(
"include_next") || Line.consume_front(
"include") ||
2604 Line.consume_front(
"import")))
2606 Line = Line.ltrim();
2607 if (Line.consume_front(
"<"))
2608 return Line.count(
'>') == 0;
2609 if (Line.consume_front(
"\""))
2610 return Line.count(
'"') == 0;
2616 Content = Content.take_front(Offset);
2617 auto Pos = Content.rfind(
'\n');
2618 if (Pos != llvm::StringRef::npos)
2619 Content = Content.substr(Pos + 1);
2622 if (Content.ends_with(
".") || Content.ends_with(
"->") ||
2623 Content.ends_with(
"::") || Content.ends_with(
"/*"))
2626 if ((Content.ends_with(
"<") || Content.ends_with(
"\"") ||
2627 Content.ends_with(
"/")) &&
2632 return !Content.empty() && (isAsciiIdentifierContinue(Content.back()) ||
2633 !llvm::isASCII(Content.back()));
static clang::FrontendPluginRegistry::Add< clang::tidy::ClangTidyPluginAction > X("clang-tidy", "clang-tidy")
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
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 PreamblePatch createMacroPatch(llvm::StringRef FileName, const ParseInputs &Modified, const PreambleData &Baseline)
static PreamblePatch createFullPatch(llvm::StringRef FileName, const ParseInputs &Modified, const PreambleData &Baseline)
Builds a patch that contains new PP directives introduced to the preamble section of Modified compare...
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
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.
bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset)
void vlog(const char *Fmt, Ts &&... Vals)
static const char * toString(OffsetEncoding OE)
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)
std::future< T > runAsync(llvm::unique_function< T()> Action)
Runs Action asynchronously with a new std::thread.
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::StringRef PathRef
A typedef to represent a ref to file path.
CodeCompleteResult codeCompleteComment(PathRef FileName, const unsigned CursorOffset, unsigned OutsideStartOffset, llvm::StringRef Prefix, const PreambleData *Preamble, const ParseInputs &ParseInput, const CodeCompleteOptions &Opts)
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.
@ Full
Documents are synced by always sending the full content of the document.
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.
@ PlainText
The primary text to be inserted is treated as a plain string.
@ Snippet
The primary text to be inserted is treated as a snippet.
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
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.
static std::optional< unsigned > maybeFunctionArgumentCommentEnd(const PathRef FileName, const unsigned Offset, const llvm::StringRef Content, const LangOptions &LangOpts)
std::string printNamespaceScope(const DeclContext &DC)
Returns the first enclosing namespace scope starting from DC.
bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx)
PreambleBounds computePreambleBounds(const LangOptions &LangOpts, const llvm::MemoryBufferRef &Buffer, bool SkipPreambleBuild)
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.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
clang::CodeCompleteOptions getClangCompleteOpts() const
Returns options that can be passed to clang's completion engine.
llvm::StringRef Qualifier
struct clang::clangd::Config::@314053012031341203055315320366267371313202370174 Style
Style of the codebase.
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
ArgumentListsPolicy
controls the completion options for argument lists.
@ None
nothing, no argument list and also NO Delimiters "()" or "<>".
@ Delimiters
empty pair of delimiters "()" or "<>".
@ OpenDelimiter
open, only opening delimiter "(" or "<".
@ FullPlaceholders
full name of both type and variable.
@ PlainText
Treat comments as plain text.
std::vector< std::function< bool(llvm::StringRef)> > QuotedHeaders
CodePatternsPolicy CodePatterns
Enables code patterns & snippets suggestions.
CommentFormatPolicy CommentFormat
std::vector< std::function< bool(llvm::StringRef)> > AngledHeaders
A set of edits generated for a single file.
std::string newText
The string to be inserted.
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.
@ Deprecated
Indicates if the symbol is deprecated.
@ Include
#include "header.h"
@ Import
#import "header.h"