44#include "clang/AST/Decl.h"
45#include "clang/AST/DeclBase.h"
46#include "clang/Basic/CharInfo.h"
47#include "clang/Basic/LangOptions.h"
48#include "clang/Basic/SourceLocation.h"
49#include "clang/Basic/TokenKinds.h"
50#include "clang/Format/Format.h"
51#include "clang/Frontend/CompilerInstance.h"
52#include "clang/Frontend/FrontendActions.h"
53#include "clang/Lex/ExternalPreprocessorSource.h"
54#include "clang/Lex/Lexer.h"
55#include "clang/Lex/Preprocessor.h"
56#include "clang/Lex/PreprocessorOptions.h"
57#include "clang/Sema/CodeCompleteConsumer.h"
58#include "clang/Sema/DeclSpec.h"
59#include "clang/Sema/Sema.h"
60#include "llvm/ADT/ArrayRef.h"
61#include "llvm/ADT/SmallVector.h"
62#include "llvm/ADT/StringExtras.h"
63#include "llvm/ADT/StringRef.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/Debug.h"
67#include "llvm/Support/Error.h"
68#include "llvm/Support/FormatVariadic.h"
69#include "llvm/Support/ScopedPrinter.h"
77#define DEBUG_TYPE "CodeComplete"
82#if CLANGD_DECISION_FOREST
83const CodeCompleteOptions::CodeCompletionRankingModel
84 CodeCompleteOptions::DefaultRankingModel =
85 CodeCompleteOptions::DecisionForest;
87const CodeCompleteOptions::CodeCompletionRankingModel
88 CodeCompleteOptions::DefaultRankingModel = CodeCompleteOptions::Heuristics;
96toCompletionItemKind(index::SymbolKind Kind,
97 const llvm::StringRef *Signature =
nullptr) {
98 using SK = index::SymbolKind;
102 case SK::IncludeDirective:
107 case SK::NamespaceAlias:
134 case SK::ConversionFunction:
138 case SK::NonTypeTemplateParm:
142 case SK::EnumConstant:
144 case SK::InstanceMethod:
145 case SK::ClassMethod:
146 case SK::StaticMethod:
149 case SK::InstanceProperty:
150 case SK::ClassProperty:
151 case SK::StaticProperty:
153 case SK::Constructor:
155 case SK::TemplateTypeParm:
156 case SK::TemplateTemplateParm:
161 llvm_unreachable(
"Unhandled clang::index::SymbolKind.");
166CompletionItemKind toCompletionItemKind(
const CodeCompletionResult &Res,
167 CodeCompletionContext::Kind CtxKind) {
169 return toCompletionItemKind(index::getSymbolInfo(Res.Declaration).Kind);
170 if (CtxKind == CodeCompletionContext::CCC_IncludedFile)
173 case CodeCompletionResult::RK_Declaration:
174 llvm_unreachable(
"RK_Declaration without Decl");
175 case CodeCompletionResult::RK_Keyword:
177 case CodeCompletionResult::RK_Macro:
181 return Res.MacroDefInfo && Res.MacroDefInfo->isFunctionLike()
184 case CodeCompletionResult::RK_Pattern:
187 llvm_unreachable(
"Unhandled CodeCompletionResult::ResultKind.");
191MarkupContent renderDoc(
const markup::Document &Doc, MarkupKind Kind) {
192 MarkupContent Result;
196 Result.value.append(Doc.asPlainText());
201 Result.value.append(Doc.asEscapedMarkdown());
203 Result.value.append(Doc.asMarkdown());
210 if (!Opts.ImportInsertions || !Opts.MainFileSignals)
212 return Opts.MainFileSignals->InsertionDirective;
216struct RawIdentifier {
217 llvm::StringRef Name;
223struct CompletionCandidate {
224 llvm::StringRef Name;
226 const CodeCompletionResult *SemaResult =
nullptr;
227 const Symbol *IndexResult =
nullptr;
228 const RawIdentifier *IdentifierResult =
nullptr;
229 llvm::SmallVector<SymbolInclude, 1> RankedIncludeHeaders;
233 size_t overloadSet(
const CodeCompleteOptions &Opts, llvm::StringRef FileName,
234 IncludeInserter *Inserter,
235 CodeCompletionContext::Kind CCContextKind)
const {
236 if (!Opts.BundleOverloads.value_or(
false))
242 std::string HeaderForHash;
244 if (
auto Header = headerToInsertIfAllowed(Opts, CCContextKind)) {
245 if (
auto HeaderFile =
toHeaderFile(*Header, FileName)) {
247 Inserter->calculateIncludePath(*HeaderFile, FileName))
250 vlog(
"Code completion header path manipulation failed {0}",
251 HeaderFile.takeError());
256 llvm::SmallString<256> Scratch;
258 switch (IndexResult->SymInfo.Kind) {
259 case index::SymbolKind::ClassMethod:
260 case index::SymbolKind::InstanceMethod:
261 case index::SymbolKind::StaticMethod:
263 llvm_unreachable(
"Don't expect members from index in code completion");
267 case index::SymbolKind::Function:
270 return llvm::hash_combine(
271 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
279 const NamedDecl *D = SemaResult->Declaration;
280 if (!D || !D->isFunctionOrFunctionTemplate())
283 llvm::raw_svector_ostream OS(Scratch);
284 D->printQualifiedName(OS);
286 return llvm::hash_combine(Scratch, HeaderForHash);
288 assert(IdentifierResult);
292 bool contextAllowsHeaderInsertion(CodeCompletionContext::Kind Kind)
const {
295 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
301 std::optional<llvm::StringRef>
302 headerToInsertIfAllowed(
const CodeCompleteOptions &Opts,
303 CodeCompletionContext::Kind ContextKind)
const {
305 RankedIncludeHeaders.empty() ||
306 !contextAllowsHeaderInsertion(ContextKind))
308 if (SemaResult && SemaResult->Declaration) {
311 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
312 for (
const Decl *RD : SemaResult->Declaration->redecls())
313 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
317 for (
const auto &Inc : RankedIncludeHeaders)
318 if ((Inc.Directive & Directive) != 0)
323 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
326 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
327struct ScoredBundleGreater {
328 bool operator()(
const ScoredBundle &L,
const ScoredBundle &R) {
329 if (L.second.Total != R.second.Total)
330 return L.second.Total > R.second.Total;
331 return L.first.front().Name <
332 R.first.front().Name;
338std::string removeFirstTemplateArg(llvm::StringRef Signature) {
339 auto Rest = Signature.split(
",").second;
342 return (
"<" + Rest.ltrim()).str();
352struct CodeCompletionBuilder {
353 CodeCompletionBuilder(ASTContext *ASTCtx,
const CompletionCandidate &C,
354 CodeCompletionString *SemaCCS,
355 llvm::ArrayRef<std::string> AccessibleScopes,
356 const IncludeInserter &Includes,
357 llvm::StringRef FileName,
358 CodeCompletionContext::Kind ContextKind,
359 const CodeCompleteOptions &Opts,
360 bool IsUsingDeclaration, tok::TokenKind NextTokenKind)
361 : ASTCtx(ASTCtx), ArgumentLists(Opts.ArgumentLists),
362 IsUsingDeclaration(IsUsingDeclaration), NextTokenKind(NextTokenKind) {
363 Completion.Deprecated =
true;
364 add(C, SemaCCS, ContextKind);
368 Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText()));
369 Completion.FilterText = SemaCCS->getAllTypedText();
370 if (Completion.Scope.empty()) {
371 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
372 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
373 if (
const auto *D = C.SemaResult->getDeclaration())
374 if (
const auto *ND = dyn_cast<NamedDecl>(D))
375 Completion.Scope = std::string(
378 Completion.Kind = toCompletionItemKind(*C.SemaResult, ContextKind);
382 Completion.Name.back() ==
'/')
384 for (
const auto &FixIt : C.SemaResult->FixIts) {
386 FixIt, ASTCtx->getSourceManager(), ASTCtx->getLangOpts()));
388 llvm::sort(Completion.FixIts, [](
const TextEdit &
X,
const TextEdit &Y) {
389 return std::tie(X.range.start.line, X.range.start.character) <
390 std::tie(Y.range.start.line, Y.range.start.character);
394 Completion.Origin |= C.IndexResult->Origin;
395 if (Completion.Scope.empty())
396 Completion.Scope = std::string(C.IndexResult->Scope);
398 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind,
399 &C.IndexResult->Signature);
400 if (Completion.Name.empty())
401 Completion.Name = std::string(C.IndexResult->Name);
402 if (Completion.FilterText.empty())
403 Completion.FilterText = Completion.Name;
406 if (Completion.RequiredQualifier.empty() && !C.SemaResult) {
407 llvm::StringRef ShortestQualifier = C.IndexResult->Scope;
408 for (llvm::StringRef Scope : AccessibleScopes) {
409 llvm::StringRef Qualifier = C.IndexResult->Scope;
410 if (Qualifier.consume_front(Scope) &&
411 Qualifier.size() < ShortestQualifier.size())
412 ShortestQualifier = Qualifier;
414 Completion.RequiredQualifier = std::string(ShortestQualifier);
417 if (C.IdentifierResult) {
420 Completion.Name = std::string(C.IdentifierResult->Name);
421 Completion.FilterText = Completion.Name;
425 auto Inserted = [&](llvm::StringRef Header)
426 -> llvm::Expected<std::pair<std::string, bool>> {
427 auto ResolvedDeclaring =
428 URI::resolve(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
429 if (!ResolvedDeclaring)
430 return ResolvedDeclaring.takeError();
432 if (!ResolvedInserted)
433 return ResolvedInserted.takeError();
434 auto Spelled = Includes.calculateIncludePath(*ResolvedInserted, FileName);
436 return error(
"Header not on include path");
437 return std::make_pair(
439 Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
442 C.headerToInsertIfAllowed(Opts, ContextKind).has_value();
445 for (
const auto &Inc : C.RankedIncludeHeaders) {
446 if ((Inc.Directive & Directive) == 0)
449 if (
auto ToInclude = Inserted(Inc.Header)) {
450 CodeCompletion::IncludeCandidate Include;
451 Include.Header = ToInclude->first;
452 if (ToInclude->second && ShouldInsert)
453 Include.Insertion = Includes.insert(
455 ? tooling::IncludeDirective::Import
456 : tooling::IncludeDirective::Include);
457 Completion.Includes.push_back(std::move(Include));
459 log(
"Failed to generate include insertion edits for adding header "
460 "(FileURI='{0}', IncludeHeader='{1}') into {2}: {3}",
461 C.IndexResult->CanonicalDeclaration.FileURI, Inc.Header, FileName,
462 ToInclude.takeError());
465 std::stable_partition(Completion.Includes.begin(),
466 Completion.Includes.end(),
467 [](
const CodeCompletion::IncludeCandidate &I) {
468 return !I.Insertion.has_value();
472 void add(
const CompletionCandidate &C, CodeCompletionString *SemaCCS,
473 CodeCompletionContext::Kind ContextKind) {
474 assert(
bool(C.SemaResult) ==
bool(SemaCCS));
475 Bundled.emplace_back();
476 BundledEntry &S = Bundled.back();
477 bool IsConcept =
false;
479 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix, C.SemaResult->Kind,
480 C.SemaResult->CursorKind,
481 C.SemaResult->FunctionCanBeCall,
482 &Completion.RequiredQualifier);
484 if (C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
485 if (
const auto *D = C.SemaResult->getDeclaration())
486 if (isa<ConceptDecl>(D))
488 }
else if (C.IndexResult) {
489 S.Signature = std::string(C.IndexResult->Signature);
490 S.SnippetSuffix = std::string(C.IndexResult->CompletionSnippetSuffix);
491 S.ReturnType = std::string(C.IndexResult->ReturnType);
492 if (C.IndexResult->SymInfo.Kind == index::SymbolKind::Concept)
499 if (IsConcept && ContextKind == CodeCompletionContext::CCC_TopLevel) {
500 S.Signature = removeFirstTemplateArg(S.Signature);
503 S.SnippetSuffix = removeFirstTemplateArg(S.SnippetSuffix);
506 if (!Completion.Documentation) {
507 auto SetDoc = [&](llvm::StringRef Doc) {
509 Completion.Documentation.emplace();
514 SetDoc(C.IndexResult->Documentation);
515 }
else if (C.SemaResult) {
516 const auto DocComment =
getDocComment(*ASTCtx, *C.SemaResult,
521 if (Completion.Deprecated) {
523 Completion.Deprecated &=
524 C.SemaResult->Availability == CXAvailability_Deprecated;
526 Completion.Deprecated &=
531 CodeCompletion build() {
532 Completion.ReturnType = summarizeReturnType();
533 Completion.Signature = summarizeSignature();
534 Completion.SnippetSuffix = summarizeSnippet();
535 Completion.BundleSize = Bundled.size();
536 return std::move(Completion);
540 struct BundledEntry {
541 std::string SnippetSuffix;
542 std::string Signature;
543 std::string ReturnType;
547 template <std::
string BundledEntry::*Member>
548 const std::string *onlyValue()
const {
549 auto B = Bundled.begin(), E = Bundled.end();
550 for (
auto *I = B + 1; I != E; ++I)
551 if (I->*Member != B->*Member)
553 return &(B->*Member);
556 template <
bool BundledEntry::*Member>
const bool *onlyValue()
const {
557 auto B = Bundled.begin(), E = Bundled.end();
558 for (
auto *I = B + 1; I != E; ++I)
559 if (I->*Member != B->*Member)
561 return &(B->*Member);
564 std::string summarizeReturnType()
const {
565 if (
auto *RT = onlyValue<&BundledEntry::ReturnType>())
570 std::string summarizeSnippet()
const {
580 if (IsUsingDeclaration)
582 auto *
Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
587 return None ?
"" : (
Open ?
"(" :
"($0)");
600 if (MayHaveArgList) {
604 if (NextTokenKind == tok::less &&
Snippet->front() ==
'<')
607 if (NextTokenKind == tok::l_paren) {
617 else if (
Snippet->at(I) ==
'<')
620 }
while (Balance > 0);
630 if (MayHaveArgList) {
639 bool EmptyArgs = llvm::StringRef(*Snippet).ends_with(
"()");
641 return None ?
"" : (
Open ?
"<" : (EmptyArgs ?
"<$1>()$0" :
"<$1>($0)"));
643 return None ?
"" : (
Open ?
"(" : (EmptyArgs ?
"()" :
"($0)"));
655 if (llvm::StringRef(*Snippet).ends_with(
"<>"))
657 return None ?
"" : (
Open ?
"<" :
"<$0>");
662 std::string summarizeSignature()
const {
663 if (
auto *Signature = onlyValue<&BundledEntry::Signature>())
671 CodeCompletion Completion;
672 llvm::SmallVector<BundledEntry, 1> Bundled;
677 bool IsUsingDeclaration;
678 tok::TokenKind NextTokenKind;
682SymbolID
getSymbolID(
const CodeCompletionResult &R,
const SourceManager &SM) {
684 case CodeCompletionResult::RK_Declaration:
685 case CodeCompletionResult::RK_Pattern: {
691 case CodeCompletionResult::RK_Macro:
693 case CodeCompletionResult::RK_Keyword:
696 llvm_unreachable(
"unknown CodeCompletionResult kind");
701struct SpecifiedScope {
724 std::vector<std::string> AccessibleScopes;
727 std::vector<std::string> QueryScopes;
730 std::optional<std::string> UnresolvedQualifier;
732 std::optional<std::string> EnclosingNamespace;
734 bool AllowAllScopes =
false;
738 std::vector<std::string> scopesForQualification() {
739 std::set<std::string> Results;
740 for (llvm::StringRef AS : AccessibleScopes)
742 (AS + (UnresolvedQualifier ? *UnresolvedQualifier :
"")).str());
743 return {Results.begin(), Results.end()};
748 std::vector<std::string> scopesForIndexQuery() {
750 std::vector<std::string> EnclosingAtFront;
751 if (EnclosingNamespace.has_value())
752 EnclosingAtFront.push_back(*EnclosingNamespace);
753 std::set<std::string> Deduplicated;
754 for (llvm::StringRef S : QueryScopes)
755 if (S != EnclosingNamespace)
756 Deduplicated.insert((S + UnresolvedQualifier.value_or(
"")).str());
758 EnclosingAtFront.reserve(EnclosingAtFront.size() + Deduplicated.size());
759 llvm::copy(Deduplicated, std::back_inserter(EnclosingAtFront));
761 return EnclosingAtFront;
768SpecifiedScope getQueryScopes(CodeCompletionContext &CCContext,
770 const CompletionPrefix &HeuristicPrefix,
771 const CodeCompleteOptions &Opts) {
772 SpecifiedScope Scopes;
773 for (
auto *Context : CCContext.getVisitedContexts()) {
774 if (isa<TranslationUnitDecl>(Context)) {
775 Scopes.QueryScopes.push_back(
"");
776 Scopes.AccessibleScopes.push_back(
"");
777 }
else if (
const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
783 const CXXScopeSpec *SemaSpecifier =
784 CCContext.getCXXScopeSpecifier().value_or(
nullptr);
786 if (!SemaSpecifier) {
789 if (!HeuristicPrefix.Qualifier.empty()) {
790 vlog(
"Sema said no scope specifier, but we saw {0} in the source code",
791 HeuristicPrefix.Qualifier);
792 StringRef SpelledSpecifier = HeuristicPrefix.Qualifier;
793 if (SpelledSpecifier.consume_front(
"::")) {
794 Scopes.AccessibleScopes = {
""};
795 Scopes.QueryScopes = {
""};
797 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
805 Scopes.AllowAllScopes = Opts.AllScopes;
809 if (SemaSpecifier && SemaSpecifier->isValid())
813 Scopes.QueryScopes.push_back(
"");
814 llvm::StringRef SpelledSpecifier = Lexer::getSourceText(
815 CharSourceRange::getCharRange(SemaSpecifier->getRange()),
816 CCSema.SourceMgr, clang::LangOptions());
817 if (SpelledSpecifier.consume_front(
"::"))
818 Scopes.QueryScopes = {
""};
819 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
821 if (!Scopes.UnresolvedQualifier->empty())
822 *Scopes.UnresolvedQualifier +=
"::";
824 Scopes.AccessibleScopes = Scopes.QueryScopes;
831bool contextAllowsIndex(
enum CodeCompletionContext::Kind K) {
833 case CodeCompletionContext::CCC_TopLevel:
834 case CodeCompletionContext::CCC_ObjCInterface:
835 case CodeCompletionContext::CCC_ObjCImplementation:
836 case CodeCompletionContext::CCC_ObjCIvarList:
837 case CodeCompletionContext::CCC_ClassStructUnion:
838 case CodeCompletionContext::CCC_Statement:
839 case CodeCompletionContext::CCC_Expression:
840 case CodeCompletionContext::CCC_ObjCMessageReceiver:
841 case CodeCompletionContext::CCC_EnumTag:
842 case CodeCompletionContext::CCC_UnionTag:
843 case CodeCompletionContext::CCC_ClassOrStructTag:
844 case CodeCompletionContext::CCC_ObjCProtocolName:
845 case CodeCompletionContext::CCC_Namespace:
846 case CodeCompletionContext::CCC_Type:
847 case CodeCompletionContext::CCC_ParenthesizedExpression:
848 case CodeCompletionContext::CCC_ObjCInterfaceName:
849 case CodeCompletionContext::CCC_Symbol:
850 case CodeCompletionContext::CCC_SymbolOrNewName:
851 case CodeCompletionContext::CCC_ObjCClassForwardDecl:
852 case CodeCompletionContext::CCC_TopLevelOrExpression:
854 case CodeCompletionContext::CCC_OtherWithMacros:
855 case CodeCompletionContext::CCC_DotMemberAccess:
856 case CodeCompletionContext::CCC_ArrowMemberAccess:
857 case CodeCompletionContext::CCC_ObjCCategoryName:
858 case CodeCompletionContext::CCC_ObjCPropertyAccess:
859 case CodeCompletionContext::CCC_MacroName:
860 case CodeCompletionContext::CCC_MacroNameUse:
861 case CodeCompletionContext::CCC_PreprocessorExpression:
862 case CodeCompletionContext::CCC_PreprocessorDirective:
863 case CodeCompletionContext::CCC_SelectorName:
864 case CodeCompletionContext::CCC_TypeQualifiers:
865 case CodeCompletionContext::CCC_ObjCInstanceMessage:
866 case CodeCompletionContext::CCC_ObjCClassMessage:
867 case CodeCompletionContext::CCC_IncludedFile:
868 case CodeCompletionContext::CCC_Attribute:
870 case CodeCompletionContext::CCC_Other:
871 case CodeCompletionContext::CCC_NaturalLanguage:
872 case CodeCompletionContext::CCC_Recovery:
873 case CodeCompletionContext::CCC_NewName:
876 llvm_unreachable(
"unknown code completion context");
879static bool isInjectedClass(
const NamedDecl &D) {
880 if (
auto *R = dyn_cast_or_null<CXXRecordDecl>(&D))
881 if (R->isInjectedClassName())
887static bool isExcludedMember(
const NamedDecl &D) {
890 if (D.getKind() == Decl::CXXDestructor)
893 if (isInjectedClass(D))
896 auto NameKind = D.getDeclName().getNameKind();
897 if (NameKind == DeclarationName::CXXOperatorName ||
898 NameKind == DeclarationName::CXXLiteralOperatorName ||
899 NameKind == DeclarationName::CXXConversionFunctionName)
910struct CompletionRecorder :
public CodeCompleteConsumer {
911 CompletionRecorder(
const CodeCompleteOptions &Opts,
912 llvm::unique_function<
void()> ResultsCallback)
913 : CodeCompleteConsumer(Opts.getClangCompleteOpts()),
914 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
915 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
916 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
917 assert(this->ResultsCallback);
920 std::vector<CodeCompletionResult> Results;
921 CodeCompletionContext CCContext;
922 Sema *CCSema =
nullptr;
925 void ProcessCodeCompleteResults(
class Sema &S, CodeCompletionContext Context,
926 CodeCompletionResult *InResults,
927 unsigned NumResults)
final {
936 CodeCompletionContext::Kind ContextKind = Context.getKind();
937 if (ContextKind == CodeCompletionContext::CCC_Recovery) {
938 log(
"Code complete: Ignoring sema code complete callback with Recovery "
945 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
948 log(
"Multiple code complete callbacks (parser backtracked?). "
949 "Dropping results from context {0}, keeping results from {1}.",
950 getCompletionKindString(Context.getKind()),
951 getCompletionKindString(this->CCContext.getKind()));
959 for (
unsigned I = 0; I < NumResults; ++I) {
960 auto &Result = InResults[I];
963 Result.Kind == CodeCompletionResult::RK_Pattern &&
965 ContextKind != CodeCompletionContext::CCC_IncludedFile)
968 if (Result.Hidden && Result.Declaration &&
969 Result.Declaration->isCXXClassMember())
971 if (!Opts.IncludeIneligibleResults &&
972 (Result.Availability == CXAvailability_NotAvailable ||
973 Result.Availability == CXAvailability_NotAccessible))
975 if (Result.Declaration &&
976 !Context.getBaseType().isNull()
977 && isExcludedMember(*Result.Declaration))
981 if (Result.Declaration && !Context.getCXXScopeSpecifier() &&
982 isInjectedClass(*Result.Declaration))
985 Result.StartsNestedNameSpecifier =
false;
986 Results.push_back(Result);
991 CodeCompletionAllocator &getAllocator()
override {
return *CCAllocator; }
992 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
996 llvm::StringRef getName(
const CodeCompletionResult &Result) {
997 switch (Result.Kind) {
998 case CodeCompletionResult::RK_Declaration:
999 if (
auto *ID = Result.Declaration->getIdentifier())
1000 return ID->getName();
1002 case CodeCompletionResult::RK_Keyword:
1003 return Result.Keyword;
1004 case CodeCompletionResult::RK_Macro:
1005 return Result.Macro->getName();
1006 case CodeCompletionResult::RK_Pattern:
1009 auto *CCS = codeCompletionString(Result);
1010 const CodeCompletionString::Chunk *OnlyText =
nullptr;
1011 for (
auto &C : *CCS) {
1012 if (C.Kind != CodeCompletionString::CK_TypedText)
1015 return CCAllocator->CopyString(CCS->getAllTypedText());
1018 return OnlyText ? OnlyText->Text : llvm::StringRef();
1023 CodeCompletionString *codeCompletionString(
const CodeCompletionResult &R) {
1025 return const_cast<CodeCompletionResult &
>(R).CreateCodeCompletionString(
1026 *CCSema, CCContext, *CCAllocator, CCTUInfo,
1031 CodeCompleteOptions Opts;
1032 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
1033 CodeCompletionTUInfo CCTUInfo;
1034 llvm::unique_function<void()> ResultsCallback;
1037struct ScoredSignature {
1041 SignatureInformation Signature;
1042 SignatureQualitySignals Quality;
1050int paramIndexForArg(
const CodeCompleteConsumer::OverloadCandidate &Candidate,
1052 int NumParams = Candidate.getNumParams();
1053 if (
auto *T = Candidate.getFunctionType()) {
1054 if (
auto *Proto = T->getAs<FunctionProtoType>()) {
1055 if (Proto->isVariadic())
1059 return std::min(Arg, std::max(NumParams - 1, 0));
1062class SignatureHelpCollector final :
public CodeCompleteConsumer {
1064 SignatureHelpCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1065 MarkupKind DocumentationFormat,
1066 const SymbolIndex *Index, SignatureHelp &SigHelp)
1067 : CodeCompleteConsumer(CodeCompleteOpts), SigHelp(SigHelp),
1068 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1069 CCTUInfo(Allocator), Index(Index),
1070 DocumentationFormat(DocumentationFormat) {}
1072 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1073 OverloadCandidate *Candidates,
1074 unsigned NumCandidates,
1075 SourceLocation OpenParLoc,
1076 bool Braced)
override {
1077 assert(!OpenParLoc.isInvalid());
1078 SourceManager &SrcMgr = S.getSourceManager();
1079 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
1080 if (SrcMgr.isInMainFile(OpenParLoc))
1083 elog(
"Location oustide main file in signature help: {0}",
1084 OpenParLoc.printToString(SrcMgr));
1086 std::vector<ScoredSignature> ScoredSignatures;
1087 SigHelp.signatures.reserve(NumCandidates);
1088 ScoredSignatures.reserve(NumCandidates);
1092 SigHelp.activeSignature = 0;
1093 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1094 "too many arguments");
1096 SigHelp.activeParameter =
static_cast<int>(CurrentArg);
1098 for (
unsigned I = 0; I < NumCandidates; ++I) {
1099 OverloadCandidate Candidate = Candidates[I];
1103 if (
auto *Func = Candidate.getFunction()) {
1104 if (
auto *Pattern = Func->getTemplateInstantiationPattern())
1105 Candidate = OverloadCandidate(Pattern);
1107 if (
static_cast<int>(I) == SigHelp.activeSignature) {
1112 SigHelp.activeParameter =
1113 paramIndexForArg(Candidate, SigHelp.activeParameter);
1116 const auto *CCS = Candidate.CreateSignatureString(
1117 CurrentArg, S, *Allocator, CCTUInfo,
1119 assert(CCS &&
"Expected the CodeCompletionString to be non-null");
1120 ScoredSignatures.push_back(processOverloadCandidate(
1122 Candidate.getFunction()
1129 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
1131 LookupRequest IndexRequest;
1132 for (
const auto &S : ScoredSignatures) {
1135 IndexRequest.IDs.insert(S.IDForDoc);
1137 Index->lookup(IndexRequest, [&](
const Symbol &S) {
1138 if (!S.Documentation.empty())
1139 FetchedDocs[S.ID] = std::string(S.Documentation);
1141 vlog(
"SigHelp: requested docs for {0} symbols from the index, got {1} "
1142 "symbols with non-empty docs in the response",
1143 IndexRequest.IDs.size(), FetchedDocs.size());
1146 llvm::sort(ScoredSignatures, [](
const ScoredSignature &L,
1147 const ScoredSignature &R) {
1154 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
1155 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
1156 if (L.Quality.NumberOfOptionalParameters !=
1157 R.Quality.NumberOfOptionalParameters)
1158 return L.Quality.NumberOfOptionalParameters <
1159 R.Quality.NumberOfOptionalParameters;
1160 if (L.Quality.Kind != R.Quality.Kind) {
1161 using OC = CodeCompleteConsumer::OverloadCandidate;
1162 auto KindPriority = [&](OC::CandidateKind K) {
1164 case OC::CK_Aggregate:
1166 case OC::CK_Function:
1168 case OC::CK_FunctionType:
1170 case OC::CK_FunctionProtoTypeLoc:
1172 case OC::CK_FunctionTemplate:
1174 case OC::CK_Template:
1177 llvm_unreachable(
"Unknown overload candidate type.");
1179 return KindPriority(L.Quality.Kind) < KindPriority(R.Quality.Kind);
1181 if (L.Signature.label.size() != R.Signature.label.size())
1182 return L.Signature.label.size() < R.Signature.label.size();
1183 return L.Signature.label < R.Signature.label;
1186 for (
auto &SS : ScoredSignatures) {
1188 SS.IDForDoc ? FetchedDocs.find(SS.IDForDoc) : FetchedDocs.end();
1189 if (IndexDocIt != FetchedDocs.end()) {
1190 markup::Document SignatureComment;
1192 SS.Signature.documentation =
1193 renderDoc(SignatureComment, DocumentationFormat);
1196 SigHelp.signatures.push_back(std::move(SS.Signature));
1200 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1202 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1205 void processParameterChunk(llvm::StringRef ChunkText,
1206 SignatureInformation &Signature)
const {
1208 unsigned ParamStartOffset =
lspLength(Signature.label);
1209 unsigned ParamEndOffset = ParamStartOffset +
lspLength(ChunkText);
1213 Signature.label += ChunkText;
1214 ParameterInformation
Info;
1215 Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset);
1217 Info.labelString = std::string(ChunkText);
1219 Signature.parameters.push_back(std::move(
Info));
1222 void processOptionalChunk(
const CodeCompletionString &CCS,
1223 SignatureInformation &Signature,
1224 SignatureQualitySignals &Signal)
const {
1225 for (
const auto &Chunk : CCS) {
1226 switch (Chunk.Kind) {
1227 case CodeCompletionString::CK_Optional:
1228 assert(Chunk.Optional &&
1229 "Expected the optional code completion string to be non-null.");
1230 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1232 case CodeCompletionString::CK_VerticalSpace:
1234 case CodeCompletionString::CK_CurrentParameter:
1235 case CodeCompletionString::CK_Placeholder:
1236 processParameterChunk(Chunk.Text, Signature);
1237 Signal.NumberOfOptionalParameters++;
1240 Signature.label += Chunk.Text;
1248 ScoredSignature processOverloadCandidate(
const OverloadCandidate &Candidate,
1249 const CodeCompletionString &CCS,
1250 llvm::StringRef DocComment)
const {
1251 SignatureInformation Signature;
1252 SignatureQualitySignals Signal;
1253 const char *ReturnType =
nullptr;
1255 markup::Document OverloadComment;
1257 Signature.documentation = renderDoc(OverloadComment, DocumentationFormat);
1258 Signal.Kind = Candidate.getKind();
1260 for (
const auto &Chunk : CCS) {
1261 switch (Chunk.Kind) {
1262 case CodeCompletionString::CK_ResultType:
1265 assert(!ReturnType &&
"Unexpected CK_ResultType");
1266 ReturnType = Chunk.Text;
1268 case CodeCompletionString::CK_CurrentParameter:
1269 case CodeCompletionString::CK_Placeholder:
1270 processParameterChunk(Chunk.Text, Signature);
1271 Signal.NumberOfParameters++;
1273 case CodeCompletionString::CK_Optional: {
1275 assert(Chunk.Optional &&
1276 "Expected the optional code completion string to be non-null.");
1277 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1280 case CodeCompletionString::CK_VerticalSpace:
1283 Signature.label += Chunk.Text;
1288 Signature.label +=
" -> ";
1289 Signature.label += ReturnType;
1291 dlog(
"Signal for {0}: {1}", Signature, Signal);
1292 ScoredSignature Result;
1293 Result.Signature = std::move(Signature);
1294 Result.Quality = Signal;
1295 const FunctionDecl *Func = Candidate.getFunction();
1296 if (Func && Result.Signature.documentation.value.empty()) {
1304 SignatureHelp &SigHelp;
1305 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1306 CodeCompletionTUInfo CCTUInfo;
1307 const SymbolIndex *Index;
1308 MarkupKind DocumentationFormat;
1313class ParamNameCollector final :
public CodeCompleteConsumer {
1315 ParamNameCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1316 std::set<std::string> &ParamNames)
1317 : CodeCompleteConsumer(CodeCompleteOpts),
1318 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1319 CCTUInfo(Allocator), ParamNames(ParamNames) {}
1321 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1322 OverloadCandidate *Candidates,
1323 unsigned NumCandidates,
1324 SourceLocation OpenParLoc,
1325 bool Braced)
override {
1326 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1327 "too many arguments");
1329 for (
unsigned I = 0; I < NumCandidates; ++I) {
1330 if (
const NamedDecl *ND = Candidates[I].getParamDecl(CurrentArg))
1331 if (
const auto *II = ND->getIdentifier())
1332 ParamNames.emplace(II->getName());
1337 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1339 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1341 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1342 CodeCompletionTUInfo CCTUInfo;
1343 std::set<std::string> &ParamNames;
1346struct SemaCompleteInput {
1350 const std::optional<PreamblePatch> Patch;
1351 const ParseInputs &ParseInput;
1354void loadMainFilePreambleMacros(
const Preprocessor &PP,
1359 ExternalPreprocessorSource *PreambleMacros = PP.getExternalSource();
1362 const auto &ITable = PP.getIdentifierTable();
1363 IdentifierInfoLookup *PreambleIdentifiers =
1364 ITable.getExternalIdentifierLookup();
1366 if (!PreambleIdentifiers || !PreambleMacros)
1368 for (
const auto &MacroName :
Preamble.Macros.Names) {
1369 if (ITable.find(MacroName.getKey()) != ITable.end())
1371 if (
auto *II = PreambleIdentifiers->get(MacroName.getKey()))
1372 if (II->isOutOfDate())
1373 PreambleMacros->updateOutOfDateIdentifier(*II);
1379bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
1380 const clang::CodeCompleteOptions &Options,
1381 const SemaCompleteInput &Input,
1382 IncludeStructure *Includes =
nullptr) {
1383 trace::Span Tracer(
"Sema completion");
1385 IgnoreDiagnostics IgnoreDiags;
1388 elog(
"Couldn't create CompilerInvocation");
1391 auto &FrontendOpts = CI->getFrontendOpts();
1392 FrontendOpts.SkipFunctionBodies =
true;
1394 CI->getLangOpts().SpellChecking =
false;
1398 CI->getLangOpts().DelayedTemplateParsing =
false;
1400 FrontendOpts.CodeCompleteOpts = Options;
1401 FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName);
1402 std::tie(FrontendOpts.CodeCompletionAt.Line,
1403 FrontendOpts.CodeCompletionAt.Column) =
1406 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1407 llvm::MemoryBuffer::getMemBuffer(Input.ParseInput.Contents,
1410 CI->getDiagnosticOpts().IgnoreWarnings =
true;
1417 PreambleBounds PreambleRegion =
1418 ComputePreambleBounds(CI->getLangOpts(), *ContentsBuffer, 0);
1419 bool CompletingInPreamble = Input.Offset < PreambleRegion.Size ||
1420 (!PreambleRegion.PreambleEndsAtStartOfLine &&
1421 Input.Offset == PreambleRegion.Size);
1423 Input.Patch->apply(*CI);
1426 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1427 Input.ParseInput.TFS->view(Input.ParseInput.CompileCommand.Directory);
1428 if (Input.Preamble.StatCache)
1429 VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS));
1431 std::move(CI), !CompletingInPreamble ? &Input.Preamble.Preamble :
nullptr,
1432 std::move(ContentsBuffer), std::move(VFS), IgnoreDiags);
1433 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
1434 Clang->setCodeCompletionConsumer(Consumer.release());
1436 if (Input.Preamble.RequiredModules)
1437 Input.Preamble.RequiredModules->adjustHeaderSearchOptions(Clang->getHeaderSearchOpts());
1440 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1441 log(
"BeginSourceFile() failed when running codeComplete for {0}",
1451 loadMainFilePreambleMacros(Clang->getPreprocessor(), Input.Preamble);
1453 Includes->collect(*Clang);
1454 if (llvm::Error Err = Action.Execute()) {
1455 log(
"Execute() failed when running codeComplete for {0}: {1}",
1456 Input.FileName,
toString(std::move(Err)));
1459 Action.EndSourceFile();
1465bool allowIndex(CodeCompletionContext &CC) {
1466 if (!contextAllowsIndex(CC.getKind()))
1469 auto Scope = CC.getCXXScopeSpecifier();
1474 switch ((*Scope)->getScopeRep().getKind()) {
1475 case NestedNameSpecifier::Kind::Null:
1476 case NestedNameSpecifier::Kind::Global:
1477 case NestedNameSpecifier::Kind::Namespace:
1479 case NestedNameSpecifier::Kind::MicrosoftSuper:
1480 case NestedNameSpecifier::Kind::Type:
1483 llvm_unreachable(
"invalid NestedNameSpecifier kind");
1488bool includeSymbolFromIndex(CodeCompletionContext::Kind Kind,
1489 const Symbol &Sym) {
1493 if (Sym.SymInfo.Kind == index::SymbolKind::Protocol &&
1494 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC)
1495 return Kind == CodeCompletionContext::CCC_ObjCProtocolName;
1496 else if (Kind == CodeCompletionContext::CCC_ObjCProtocolName)
1500 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
1501 return Sym.SymInfo.Kind == index::SymbolKind::Class &&
1502 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC;
1506std::future<std::pair<bool, SymbolSlab>>
1507startAsyncFuzzyFind(
const SymbolIndex &Index,
const FuzzyFindRequest &Req) {
1509 trace::Span Tracer(
"Async fuzzyFind");
1510 SymbolSlab::Builder Syms;
1512 Index.fuzzyFind(Req, [&Syms](
const Symbol &Sym) { Syms.insert(Sym); });
1513 return std::make_pair(Incomplete, std::move(Syms).build());
1520FuzzyFindRequest speculativeFuzzyFindRequestForCompletion(
1521 FuzzyFindRequest CachedReq,
const CompletionPrefix &HeuristicPrefix) {
1522 CachedReq.Query = std::string(HeuristicPrefix.Name);
1530findTokenAfterCompletionPoint(SourceLocation CompletionPoint,
1531 const SourceManager &SM,
1532 const LangOptions &LangOpts) {
1533 SourceLocation Loc = CompletionPoint;
1534 if (Loc.isMacroID()) {
1535 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1536 return std::nullopt;
1544 Loc = Loc.getLocWithOffset(1);
1547 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1550 bool InvalidTemp =
false;
1551 StringRef
File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1553 return std::nullopt;
1555 const char *TokenBegin =
File.data() + LocInfo.second;
1558 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
File.begin(),
1559 TokenBegin,
File.end());
1562 TheLexer.LexFromRawLexer(Tok);
1595class CodeCompleteFlow {
1597 IncludeStructure Includes;
1598 SpeculativeFuzzyFind *SpecFuzzyFind;
1599 const CodeCompleteOptions &Opts;
1602 CompletionRecorder *Recorder =
nullptr;
1603 CodeCompletionContext::Kind CCContextKind = CodeCompletionContext::CCC_Other;
1604 bool IsUsingDeclaration =
false;
1608 tok::TokenKind NextTokenKind = tok::eof;
1610 int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
1611 bool Incomplete =
false;
1612 CompletionPrefix HeuristicPrefix;
1613 std::optional<FuzzyMatcher> Filter;
1614 Range ReplacedRange;
1615 std::vector<std::string> QueryScopes;
1616 std::vector<std::string> AccessibleScopes;
1618 std::optional<ScopeDistance> ScopeProximity;
1619 std::optional<OpaqueType> PreferredType;
1621 bool AllScopes =
false;
1622 llvm::StringSet<> ContextWords;
1625 std::optional<IncludeInserter> Inserter;
1626 std::optional<URIDistance> FileProximity;
1631 std::optional<FuzzyFindRequest> SpecReq;
1635 CodeCompleteFlow(
PathRef FileName,
const IncludeStructure &Includes,
1636 SpeculativeFuzzyFind *SpecFuzzyFind,
1637 const CodeCompleteOptions &Opts)
1638 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1641 CodeCompleteResult
run(
const SemaCompleteInput &SemaCCInput) && {
1642 trace::Span Tracer(
"CodeCompleteFlow");
1644 SemaCCInput.Offset);
1645 populateContextWords(SemaCCInput.ParseInput.Contents);
1646 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq) {
1647 assert(!SpecFuzzyFind->Result.valid());
1648 SpecReq = speculativeFuzzyFindRequestForCompletion(
1649 *SpecFuzzyFind->CachedReq, HeuristicPrefix);
1650 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1656 CodeCompleteResult Output;
1657 auto RecorderOwner = std::make_unique<CompletionRecorder>(Opts, [&]() {
1658 assert(Recorder &&
"Recorder is not set");
1659 CCContextKind = Recorder->CCContext.getKind();
1660 IsUsingDeclaration = Recorder->CCContext.isUsingDeclaration();
1662 SemaCCInput.ParseInput.Contents,
1663 *SemaCCInput.ParseInput.TFS,
false);
1664 const auto NextToken = findTokenAfterCompletionPoint(
1665 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc(),
1666 Recorder->CCSema->getSourceManager(), Recorder->CCSema->LangOpts);
1668 NextTokenKind = NextToken->getKind();
1672 SemaCCInput.FileName, SemaCCInput.ParseInput.Contents, Style,
1673 SemaCCInput.ParseInput.CompileCommand.Directory,
1674 &Recorder->CCSema->getPreprocessor().getHeaderSearchInfo(),
1677 for (
const auto &Inc : Includes.MainFileIncludes)
1678 Inserter->addExisting(Inc);
1684 FileDistanceOptions ProxOpts{};
1685 const auto &SM = Recorder->CCSema->getSourceManager();
1686 llvm::StringMap<SourceParams> ProxSources;
1688 Includes.getID(SM.getFileEntryForID(SM.getMainFileID()));
1690 for (
auto &HeaderIDAndDepth : Includes.includeDepth(*MainFileID)) {
1692 ProxSources[Includes.getRealPath(HeaderIDAndDepth.getFirst())];
1693 Source.Cost = HeaderIDAndDepth.getSecond() * ProxOpts.IncludeCost;
1697 if (HeaderIDAndDepth.getSecond() > 0)
1698 Source.MaxUpTraversals = 1;
1700 FileProximity.emplace(ProxSources, ProxOpts);
1702 Output = runWithSema();
1705 getCompletionKindString(CCContextKind));
1706 log(
"Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1707 "expected type {3}{4}",
1708 getCompletionKindString(CCContextKind),
1709 llvm::join(QueryScopes.begin(), QueryScopes.end(),
","), AllScopes,
1710 PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1712 IsUsingDeclaration ?
", inside using declaration" :
"");
1715 Recorder = RecorderOwner.get();
1717 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1718 SemaCCInput, &Includes);
1719 logResults(Output, Tracer);
1723 void logResults(
const CodeCompleteResult &Output,
const trace::Span &Tracer) {
1726 SPAN_ATTACH(Tracer,
"merged_results", NSemaAndIndex);
1727 SPAN_ATTACH(Tracer,
"identifier_results", NIdent);
1728 SPAN_ATTACH(Tracer,
"returned_results", int64_t(Output.Completions.size()));
1729 SPAN_ATTACH(Tracer,
"incomplete", Output.HasMore);
1730 log(
"Code complete: {0} results from Sema, {1} from Index, "
1731 "{2} matched, {3} from identifiers, {4} returned{5}.",
1732 NSema, NIndex, NSemaAndIndex, NIdent, Output.Completions.size(),
1733 Output.HasMore ?
" (incomplete)" :
"");
1734 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1739 CodeCompleteResult runWithoutSema(llvm::StringRef Content,
size_t Offset,
1740 const ThreadsafeFS &TFS) && {
1741 trace::Span Tracer(
"CodeCompleteWithoutSema");
1744 populateContextWords(Content);
1745 CCContextKind = CodeCompletionContext::CCC_Recovery;
1746 IsUsingDeclaration =
false;
1747 Filter = FuzzyMatcher(HeuristicPrefix.Name);
1749 ReplacedRange.start = ReplacedRange.end = Pos;
1750 ReplacedRange.start.character -= HeuristicPrefix.Name.size();
1752 llvm::StringMap<SourceParams> ProxSources;
1753 ProxSources[FileName].Cost = 0;
1754 FileProximity.emplace(ProxSources);
1758 Inserter.emplace(FileName, Content, Style,
1764 std::vector<RawIdentifier> IdentifierResults;
1765 for (
const auto &IDAndCount : Identifiers) {
1767 ID.Name = IDAndCount.first();
1768 ID.References = IDAndCount.second;
1770 if (ID.Name == HeuristicPrefix.Name)
1772 if (ID.References > 0)
1773 IdentifierResults.push_back(std::move(ID));
1779 SpecifiedScope Scopes;
1781 Content.take_front(Offset), format::getFormattingLangOpts(Style));
1782 for (std::string &S : Scopes.QueryScopes)
1785 if (HeuristicPrefix.Qualifier.empty())
1786 AllScopes = Opts.AllScopes;
1787 else if (HeuristicPrefix.Qualifier.starts_with(
"::")) {
1788 Scopes.QueryScopes = {
""};
1789 Scopes.UnresolvedQualifier =
1790 std::string(HeuristicPrefix.Qualifier.drop_front(2));
1792 Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier);
1794 QueryScopes = Scopes.scopesForIndexQuery();
1795 AccessibleScopes = QueryScopes;
1796 ScopeProximity.emplace(QueryScopes);
1798 SymbolSlab IndexResults = Opts.Index ? queryIndex() : SymbolSlab();
1800 CodeCompleteResult Output = toCodeCompleteResult(mergeResults(
1801 {}, IndexResults, IdentifierResults));
1802 Output.RanParser =
false;
1803 logResults(Output, Tracer);
1808 void populateContextWords(llvm::StringRef Content) {
1810 unsigned RangeEnd = HeuristicPrefix.Qualifier.begin() - Content.data(),
1811 RangeBegin = RangeEnd;
1812 for (
size_t I = 0; I < 3 && RangeBegin > 0; ++I) {
1813 auto PrevNL = Content.rfind(
'\n', RangeBegin);
1814 if (PrevNL == StringRef::npos) {
1818 RangeBegin = PrevNL;
1821 ContextWords =
collectWords(Content.slice(RangeBegin, RangeEnd));
1822 dlog(
"Completion context words: {0}",
1823 llvm::join(ContextWords.keys(),
", "));
1828 CodeCompleteResult runWithSema() {
1829 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1830 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1836 if (CodeCompletionRange.isValid()) {
1838 CodeCompletionRange);
1841 Recorder->CCSema->getSourceManager(),
1842 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1843 ReplacedRange.start = ReplacedRange.end = Pos;
1845 Filter = FuzzyMatcher(
1846 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1847 auto SpecifiedScopes = getQueryScopes(
1848 Recorder->CCContext, *Recorder->CCSema, HeuristicPrefix, Opts);
1850 QueryScopes = SpecifiedScopes.scopesForIndexQuery();
1851 AccessibleScopes = SpecifiedScopes.scopesForQualification();
1852 AllScopes = SpecifiedScopes.AllowAllScopes;
1853 if (!QueryScopes.empty())
1854 ScopeProximity.emplace(QueryScopes);
1857 Recorder->CCContext.getPreferredType());
1863 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1866 trace::Span Tracer(
"Populate CodeCompleteResult");
1869 mergeResults(Recorder->Results, IndexResults, {});
1870 return toCodeCompleteResult(Top);
1874 toCodeCompleteResult(
const std::vector<ScoredBundle> &Scored) {
1875 CodeCompleteResult Output;
1880 llvm::DenseMap<SymbolID, uint32_t> SymbolToCompletion;
1881 for (
auto &C : Scored) {
1882 Output.Completions.push_back(toCodeCompletion(C.first));
1883 Output.Completions.back().Score = C.second;
1884 Output.Completions.back().CompletionTokenRange = ReplacedRange;
1885 if (Opts.Index && !Output.Completions.back().Documentation) {
1886 for (
auto &Cand : C.first) {
1887 if (Cand.SemaResult &&
1888 Cand.SemaResult->Kind == CodeCompletionResult::RK_Declaration) {
1893 SymbolToCompletion[ID] = Output.Completions.size() - 1;
1898 Output.HasMore = Incomplete;
1899 Output.Context = CCContextKind;
1900 Output.CompletionRange = ReplacedRange;
1904 Opts.Index->lookup(Req, [&](
const Symbol &S) {
1905 if (S.Documentation.empty())
1907 auto &C = Output.Completions[SymbolToCompletion.at(S.ID)];
1908 C.Documentation.emplace();
1916 SymbolSlab queryIndex() {
1917 trace::Span Tracer(
"Query index");
1918 SPAN_ATTACH(Tracer,
"limit", int64_t(Opts.Limit));
1921 FuzzyFindRequest Req;
1923 Req.Limit = Opts.Limit;
1924 Req.Query = std::string(Filter->pattern());
1925 Req.RestrictForCodeCompletion =
true;
1926 Req.Scopes = QueryScopes;
1927 Req.AnyScope = AllScopes;
1929 Req.ProximityPaths.push_back(std::string(FileName));
1931 Req.PreferredTypes.push_back(std::string(PreferredType->raw()));
1932 vlog(
"Code complete: fuzzyFind({0:2})",
toJSON(Req));
1935 SpecFuzzyFind->NewReq = Req;
1936 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1937 vlog(
"Code complete: speculative fuzzy request matches the actual index "
1938 "request. Waiting for the speculative index results.");
1941 trace::Span WaitSpec(
"Wait speculative results");
1942 auto SpecRes = SpecFuzzyFind->Result.get();
1943 Incomplete |= SpecRes.first;
1944 return std::move(SpecRes.second);
1947 SPAN_ATTACH(Tracer,
"Speculative results",
false);
1950 SymbolSlab::Builder ResultsBuilder;
1951 Incomplete |= Opts.Index->fuzzyFind(
1952 Req, [&](
const Symbol &Sym) { ResultsBuilder.insert(Sym); });
1953 return std::move(ResultsBuilder).build();
1961 std::vector<ScoredBundle>
1962 mergeResults(
const std::vector<CodeCompletionResult> &SemaResults,
1963 const SymbolSlab &IndexResults,
1964 const std::vector<RawIdentifier> &IdentifierResults) {
1965 trace::Span Tracer(
"Merge and score results");
1966 std::vector<CompletionCandidate::Bundle> Bundles;
1967 llvm::DenseMap<size_t, size_t> BundleLookup;
1968 auto AddToBundles = [&](
const CodeCompletionResult *SemaResult,
1969 const Symbol *IndexResult,
1970 const RawIdentifier *IdentifierResult) {
1971 CompletionCandidate C;
1972 C.SemaResult = SemaResult;
1973 C.IndexResult = IndexResult;
1974 C.IdentifierResult = IdentifierResult;
1975 if (C.IndexResult) {
1976 C.Name = IndexResult->Name;
1978 }
else if (C.SemaResult) {
1979 C.Name = Recorder->getName(*SemaResult);
1981 assert(IdentifierResult);
1982 C.Name = IdentifierResult->Name;
1984 if (
auto OverloadSet = C.overloadSet(
1985 Opts, FileName, Inserter ? &*Inserter :
nullptr, CCContextKind)) {
1986 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1988 Bundles.emplace_back();
1989 Bundles[Ret.first->second].push_back(std::move(C));
1991 Bundles.emplace_back();
1992 Bundles.back().push_back(std::move(C));
1995 llvm::DenseSet<const Symbol *> UsedIndexResults;
1996 auto CorrespondingIndexResult =
1997 [&](
const CodeCompletionResult &SemaResult) ->
const Symbol * {
1999 getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
2000 auto I = IndexResults.find(SymID);
2001 if (I != IndexResults.end()) {
2002 UsedIndexResults.insert(&*I);
2009 for (
auto &SemaResult : SemaResults)
2010 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult),
nullptr);
2012 for (
const auto &IndexResult : IndexResults) {
2013 if (UsedIndexResults.count(&IndexResult))
2015 if (!includeSymbolFromIndex(CCContextKind, IndexResult))
2017 AddToBundles(
nullptr, &IndexResult,
nullptr);
2020 for (
const auto &Ident : IdentifierResults)
2021 AddToBundles(
nullptr,
nullptr, &Ident);
2023 TopN<ScoredBundle, ScoredBundleGreater> Top(
2024 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
2025 for (
auto &Bundle : Bundles)
2026 addCandidate(Top, std::move(Bundle));
2027 return std::move(Top).items();
2030 std::optional<float> fuzzyScore(
const CompletionCandidate &C) {
2032 if (((C.SemaResult &&
2033 C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
2035 C.IndexResult->SymInfo.Kind == index::SymbolKind::Macro)) &&
2036 !C.Name.starts_with_insensitive(Filter->pattern()))
2037 return std::nullopt;
2038 return Filter->match(C.Name);
2041 CodeCompletion::Scores
2042 evaluateCompletion(
const SymbolQualitySignals &Quality,
2043 const SymbolRelevanceSignals &Relevance) {
2044 using RM = CodeCompleteOptions::CodeCompletionRankingModel;
2045 CodeCompletion::Scores Scores;
2046 switch (Opts.RankingModel) {
2047 case RM::Heuristics:
2048 Scores.Quality = Quality.evaluateHeuristics();
2049 Scores.Relevance = Relevance.evaluateHeuristics();
2054 Scores.ExcludingName =
2055 Relevance.NameMatch > std::numeric_limits<float>::epsilon()
2056 ? Scores.Total / Relevance.NameMatch
2060 case RM::DecisionForest:
2061 DecisionForestScores DFScores = Opts.DecisionForestScorer(
2062 Quality, Relevance, Opts.DecisionForestBase);
2063 Scores.ExcludingName = DFScores.ExcludingName;
2064 Scores.Total = DFScores.Total;
2067 llvm_unreachable(
"Unhandled CodeCompletion ranking model.");
2071 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
2072 CompletionCandidate::Bundle Bundle) {
2073 SymbolQualitySignals Quality;
2074 SymbolRelevanceSignals Relevance;
2075 Relevance.Context = CCContextKind;
2076 Relevance.Name = Bundle.front().Name;
2077 Relevance.FilterLength = HeuristicPrefix.Name.size();
2079 Relevance.FileProximityMatch = &*FileProximity;
2081 Relevance.ScopeProximityMatch = &*ScopeProximity;
2083 Relevance.HadContextType =
true;
2084 Relevance.ContextWords = &ContextWords;
2085 Relevance.MainFileSignals = Opts.MainFileSignals;
2087 auto &First = Bundle.front();
2088 if (
auto FuzzyScore = fuzzyScore(First))
2089 Relevance.NameMatch = *FuzzyScore;
2093 bool FromIndex =
false;
2094 for (
const auto &Candidate : Bundle) {
2095 if (Candidate.IndexResult) {
2096 Quality.merge(*Candidate.IndexResult);
2097 Relevance.merge(*Candidate.IndexResult);
2098 Origin |= Candidate.IndexResult->Origin;
2100 if (!Candidate.IndexResult->Type.empty())
2101 Relevance.HadSymbolType |=
true;
2102 if (PreferredType &&
2103 PreferredType->raw() == Candidate.IndexResult->Type) {
2104 Relevance.TypeMatchesPreferred =
true;
2107 if (Candidate.SemaResult) {
2108 Quality.merge(*Candidate.SemaResult);
2109 Relevance.merge(*Candidate.SemaResult);
2110 if (PreferredType) {
2112 Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
2113 Relevance.HadSymbolType |=
true;
2114 if (PreferredType == CompletionType)
2115 Relevance.TypeMatchesPreferred =
true;
2120 if (Candidate.IdentifierResult) {
2121 Quality.References = Candidate.IdentifierResult->References;
2127 CodeCompletion::Scores Scores = evaluateCompletion(Quality, Relevance);
2128 if (Opts.RecordCCResult)
2129 Opts.RecordCCResult(toCodeCompletion(Bundle), Quality, Relevance,
2132 dlog(
"CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
2133 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
2134 llvm::to_string(Relevance));
2137 NIndex += FromIndex;
2140 if (Candidates.push({std::move(Bundle), Scores}))
2144 CodeCompletion toCodeCompletion(
const CompletionCandidate::Bundle &Bundle) {
2145 std::optional<CodeCompletionBuilder> Builder;
2146 for (
const auto &Item : Bundle) {
2147 CodeCompletionString *SemaCCS =
2148 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
2151 Builder.emplace(Recorder ? &Recorder->CCSema->getASTContext() :
nullptr,
2152 Item, SemaCCS, AccessibleScopes, *Inserter, FileName,
2153 CCContextKind, Opts, IsUsingDeclaration, NextTokenKind);
2155 Builder->add(Item, SemaCCS, CCContextKind);
2157 return Builder->build();
2164 clang::CodeCompleteOptions
Result;
2165 Result.IncludeCodePatterns =
2167 Result.IncludeMacros =
true;
2168 Result.IncludeGlobals =
true;
2173 Result.IncludeBriefComments =
false;
2178 Result.LoadExternal = ForceLoadPreamble || !Index;
2179 Result.IncludeFixIts = IncludeFixIts;
2186 assert(Offset <= Content.size());
2187 StringRef Rest = Content.take_front(Offset);
2192 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2193 Rest = Rest.drop_back();
2194 Result.
Name = Content.slice(Rest.size(), Offset);
2197 while (Rest.consume_back(
"::") && !Rest.ends_with(
":"))
2198 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2199 Rest = Rest.drop_back();
2201 Content.slice(Rest.size(), Result.
Name.begin() - Content.begin());
2210 llvm::StringRef Prefix,
2214 return CodeCompleteResult();
2216 clang::CodeCompleteOptions Options;
2217 Options.IncludeGlobals =
false;
2218 Options.IncludeMacros =
false;
2219 Options.IncludeCodePatterns =
false;
2220 Options.IncludeBriefComments =
false;
2221 std::set<std::string> ParamNames;
2225 std::make_unique<ParamNameCollector>(Options, ParamNames), Options,
2229 if (ParamNames.empty())
2230 return CodeCompleteResult();
2232 CodeCompleteResult Result;
2233 Range CompletionRange;
2237 CompletionRange.
end =
2239 Result.CompletionRange = CompletionRange;
2240 Result.Context = CodeCompletionContext::CCC_NaturalLanguage;
2241 for (llvm::StringRef Name : ParamNames) {
2242 if (!Name.starts_with(Prefix))
2244 CodeCompletion Item;
2245 Item.Name = Name.str() +
"=*/";
2246 Item.FilterText = Item.Name;
2248 Item.CompletionTokenRange = CompletionRange;
2250 Result.Completions.push_back(Item);
2259std::optional<unsigned>
2261 while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
2262 Content = Content.drop_back();
2263 Content = Content.rtrim();
2264 if (Content.ends_with(
"/*"))
2265 return Content.size() - 2;
2266 return std::nullopt;
2273 SpeculativeFuzzyFind *SpecFuzzyFind) {
2276 elog(
"Code completion position was invalid {0}", Offset.takeError());
2277 return CodeCompleteResult();
2280 auto Content = llvm::StringRef(ParseInput.
Contents).take_front(*Offset);
2287 auto CommentPrefix = Content.substr(*OffsetBeforeComment + 2).trim();
2292 auto Flow = CodeCompleteFlow(
2294 SpecFuzzyFind, Opts);
2295 return (!
Preamble || Opts.RunParser == CodeCompleteOptions::NeverParse)
2296 ? std::move(Flow).runWithoutSema(ParseInput.
Contents, *Offset,
2298 : std::move(Flow).run({FileName, *Offset, *
Preamble,
2311 elog(
"Signature help position was invalid {0}", Offset.takeError());
2315 clang::CodeCompleteOptions Options;
2316 Options.IncludeGlobals =
false;
2317 Options.IncludeMacros =
false;
2318 Options.IncludeCodePatterns =
false;
2319 Options.IncludeBriefComments =
false;
2321 std::make_unique<SignatureHelpCollector>(Options, DocumentationFormat,
2322 ParseInput.
Index, Result),
2324 {FileName, *Offset, Preamble,
2325 PreamblePatch::createFullPatch(FileName, ParseInput, Preamble),
2331 auto InTopLevelScope = [](
const NamedDecl &ND) {
2332 switch (ND.getDeclContext()->getDeclKind()) {
2333 case Decl::TranslationUnit:
2334 case Decl::Namespace:
2335 case Decl::LinkageSpec:
2342 auto InClassScope = [](
const NamedDecl &ND) {
2343 return ND.getDeclContext()->getDeclKind() == Decl::CXXRecord;
2354 if (llvm::isa<ObjCCategoryDecl>(&ND) || llvm::isa<ObjCCategoryImplDecl>(&ND))
2357 if (InTopLevelScope(ND))
2363 if (
const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
2364 return (InTopLevelScope(*EnumDecl) || InClassScope(*EnumDecl));
2369CompletionItem CodeCompletion::render(
const CodeCompleteOptions &Opts)
const {
2371 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
2374 LSP.label = ((InsertInclude && InsertInclude->Insertion)
2375 ? Opts.IncludeIndicator.Insert
2376 : Opts.IncludeIndicator.NoInsert) +
2377 (Opts.ShowOrigins ?
"[" + llvm::to_string(Origin) +
"]" :
"") +
2378 RequiredQualifier + Name;
2379 LSP.labelDetails.emplace();
2380 LSP.labelDetails->detail = Signature;
2383 LSP.detail = BundleSize > 1
2384 ? std::string(llvm::formatv(
"[{0} overloads]", BundleSize))
2389 if (InsertInclude || Documentation) {
2390 markup::Document Doc;
2392 Doc.addParagraph().appendText(
"From ").appendCode(InsertInclude->Header);
2394 Doc.append(*Documentation);
2395 LSP.documentation = renderDoc(Doc, Opts.DocumentationFormat);
2397 LSP.sortText =
sortText(Score.Total, FilterText);
2398 LSP.filterText = FilterText;
2399 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name,
""};
2407 for (
const auto &FixIt : FixIts) {
2408 if (FixIt.range.end == LSP.textEdit->range.start) {
2409 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
2410 LSP.textEdit->range.start = FixIt.range.start;
2412 LSP.additionalTextEdits.push_back(FixIt);
2415 if (Opts.EnableSnippets)
2416 LSP.textEdit->newText += SnippetSuffix;
2420 LSP.insertText = LSP.textEdit->newText;
2424 LSP.insertTextFormat = (Opts.EnableSnippets && !SnippetSuffix.empty())
2427 if (InsertInclude && InsertInclude->Insertion)
2428 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
2430 LSP.score = Score.ExcludingName;
2435llvm::raw_ostream &
operator<<(llvm::raw_ostream &OS,
const CodeCompletion &C) {
2436 OS <<
"Signature: " <<
"\"" << C.Signature <<
"\", "
2437 <<
"SnippetSuffix: " <<
"\"" << C.SnippetSuffix <<
"\""
2444 const CodeCompleteResult &R) {
2445 OS <<
"CodeCompleteResult: " << R.Completions.size() << (R.HasMore ?
"+" :
"")
2446 <<
" (" << getCompletionKindString(R.Context) <<
")"
2448 for (
const auto &C : R.Completions)
2455 Line = Line.ltrim();
2456 if (!Line.consume_front(
"#"))
2458 Line = Line.ltrim();
2459 if (!(Line.consume_front(
"include_next") || Line.consume_front(
"include") ||
2460 Line.consume_front(
"import")))
2462 Line = Line.ltrim();
2463 if (Line.consume_front(
"<"))
2464 return Line.count(
'>') == 0;
2465 if (Line.consume_front(
"\""))
2466 return Line.count(
'"') == 0;
2472 Content = Content.take_front(Offset);
2473 auto Pos = Content.rfind(
'\n');
2474 if (Pos != llvm::StringRef::npos)
2475 Content = Content.substr(Pos + 1);
2478 if (Content.ends_with(
".") || Content.ends_with(
"->") ||
2479 Content.ends_with(
"::") || Content.ends_with(
"/*"))
2482 if ((Content.ends_with(
"<") || Content.ends_with(
"\"") ||
2483 Content.ends_with(
"/")) &&
2488 return !Content.empty() && (isAsciiIdentifierContinue(Content.back()) ||
2489 !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)
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)
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.
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.
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.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
clang::CodeCompleteOptions getClangCompleteOpts() const
Returns options that can be passed to clang's completion engine.
llvm::StringRef Qualifier
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
struct clang::clangd::Config::@365336221326264215251130354321073040111277322060 Style
Style of the codebase.
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"