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.value_or(
false))
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;
480 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix, C.SemaResult->Kind,
481 C.SemaResult->CursorKind,
482 C.SemaResult->FunctionCanBeCall,
483 &Completion.RequiredQualifier);
485 if (C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
486 if (
const auto *D = C.SemaResult->getDeclaration())
487 if (isa<ConceptDecl>(D))
489 }
else if (C.IndexResult) {
490 S.Signature = std::string(C.IndexResult->Signature);
491 S.SnippetSuffix = std::string(C.IndexResult->CompletionSnippetSuffix);
492 S.ReturnType = std::string(C.IndexResult->ReturnType);
493 if (C.IndexResult->SymInfo.Kind == index::SymbolKind::Concept)
500 if (IsConcept && ContextKind == CodeCompletionContext::CCC_TopLevel) {
501 S.Signature = removeFirstTemplateArg(S.Signature);
504 S.SnippetSuffix = removeFirstTemplateArg(S.SnippetSuffix);
507 if (!Completion.Documentation) {
508 auto SetDoc = [&](llvm::StringRef Doc) {
510 Completion.Documentation.emplace();
515 SetDoc(C.IndexResult->Documentation);
516 }
else if (C.SemaResult) {
517 const auto DocComment =
getDocComment(*ASTCtx, *C.SemaResult,
522 if (Completion.Deprecated) {
524 Completion.Deprecated &=
525 C.SemaResult->Availability == CXAvailability_Deprecated;
527 Completion.Deprecated &=
532 CodeCompletion build() {
533 Completion.ReturnType = summarizeReturnType();
534 Completion.Signature = summarizeSignature();
535 Completion.SnippetSuffix = summarizeSnippet();
536 Completion.BundleSize = Bundled.size();
537 return std::move(Completion);
541 struct BundledEntry {
542 std::string SnippetSuffix;
543 std::string Signature;
544 std::string ReturnType;
548 template <std::
string BundledEntry::*Member>
549 const std::string *onlyValue()
const {
550 auto B = Bundled.begin(), E = Bundled.end();
551 for (
auto *I = B + 1; I != E; ++I)
552 if (I->*Member != B->*Member)
554 return &(B->*Member);
557 template <
bool BundledEntry::*Member>
const bool *onlyValue()
const {
558 auto B = Bundled.begin(), E = Bundled.end();
559 for (
auto *I = B + 1; I != E; ++I)
560 if (I->*Member != B->*Member)
562 return &(B->*Member);
565 std::string summarizeReturnType()
const {
566 if (
auto *RT = onlyValue<&BundledEntry::ReturnType>())
571 std::string summarizeSnippet()
const {
581 if (IsUsingDeclaration)
583 auto *
Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
588 return None ?
"" : (
Open ?
"(" :
"($0)");
601 if (MayHaveArgList) {
605 if (NextTokenKind == tok::less &&
Snippet->front() ==
'<')
608 if (NextTokenKind == tok::l_paren) {
618 else if (
Snippet->at(I) ==
'<')
621 }
while (Balance > 0);
631 if (MayHaveArgList) {
640 bool EmptyArgs = llvm::StringRef(*Snippet).ends_with(
"()");
642 return None ?
"" : (
Open ?
"<" : (EmptyArgs ?
"<$1>()$0" :
"<$1>($0)"));
644 return None ?
"" : (
Open ?
"(" : (EmptyArgs ?
"()" :
"($0)"));
656 if (llvm::StringRef(*Snippet).ends_with(
"<>"))
658 return None ?
"" : (
Open ?
"<" :
"<$0>");
663 std::string summarizeSignature()
const {
664 if (
auto *Signature = onlyValue<&BundledEntry::Signature>())
672 CodeCompletion Completion;
673 llvm::SmallVector<BundledEntry, 1> Bundled;
678 bool IsUsingDeclaration;
679 tok::TokenKind NextTokenKind;
683SymbolID
getSymbolID(
const CodeCompletionResult &R,
const SourceManager &SM) {
685 case CodeCompletionResult::RK_Declaration:
686 case CodeCompletionResult::RK_Pattern: {
692 case CodeCompletionResult::RK_Macro:
694 case CodeCompletionResult::RK_Keyword:
697 llvm_unreachable(
"unknown CodeCompletionResult kind");
702struct SpecifiedScope {
725 std::vector<std::string> AccessibleScopes;
728 std::vector<std::string> QueryScopes;
731 std::optional<std::string> UnresolvedQualifier;
733 std::optional<std::string> EnclosingNamespace;
735 bool AllowAllScopes =
false;
739 std::vector<std::string> scopesForQualification() {
740 std::set<std::string> Results;
741 for (llvm::StringRef AS : AccessibleScopes)
743 (AS + (UnresolvedQualifier ? *UnresolvedQualifier :
"")).str());
744 return {Results.begin(), Results.end()};
749 std::vector<std::string> scopesForIndexQuery() {
751 std::vector<std::string> EnclosingAtFront;
752 if (EnclosingNamespace.has_value())
753 EnclosingAtFront.push_back(*EnclosingNamespace);
754 std::set<std::string> Deduplicated;
755 for (llvm::StringRef S : QueryScopes)
756 if (S != EnclosingNamespace)
757 Deduplicated.insert((S + UnresolvedQualifier.value_or(
"")).str());
759 EnclosingAtFront.reserve(EnclosingAtFront.size() + Deduplicated.size());
760 llvm::copy(Deduplicated, std::back_inserter(EnclosingAtFront));
762 return EnclosingAtFront;
769SpecifiedScope getQueryScopes(CodeCompletionContext &CCContext,
771 const CompletionPrefix &HeuristicPrefix,
772 const CodeCompleteOptions &Opts) {
773 SpecifiedScope Scopes;
774 for (
auto *Context : CCContext.getVisitedContexts()) {
775 if (isa<TranslationUnitDecl>(Context)) {
776 Scopes.QueryScopes.push_back(
"");
777 Scopes.AccessibleScopes.push_back(
"");
778 }
else if (
const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
784 const CXXScopeSpec *SemaSpecifier =
785 CCContext.getCXXScopeSpecifier().value_or(
nullptr);
787 if (!SemaSpecifier) {
790 if (!HeuristicPrefix.Qualifier.empty()) {
791 vlog(
"Sema said no scope specifier, but we saw {0} in the source code",
792 HeuristicPrefix.Qualifier);
793 StringRef SpelledSpecifier = HeuristicPrefix.Qualifier;
794 if (SpelledSpecifier.consume_front(
"::")) {
795 Scopes.AccessibleScopes = {
""};
796 Scopes.QueryScopes = {
""};
798 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
806 Scopes.AllowAllScopes = Opts.AllScopes;
810 if (SemaSpecifier && SemaSpecifier->isValid())
814 Scopes.QueryScopes.push_back(
"");
815 llvm::StringRef SpelledSpecifier = Lexer::getSourceText(
816 CharSourceRange::getCharRange(SemaSpecifier->getRange()),
817 CCSema.SourceMgr, clang::LangOptions());
818 if (SpelledSpecifier.consume_front(
"::"))
819 Scopes.QueryScopes = {
""};
820 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
822 if (!Scopes.UnresolvedQualifier->empty())
823 *Scopes.UnresolvedQualifier +=
"::";
825 Scopes.AccessibleScopes = Scopes.QueryScopes;
832bool contextAllowsIndex(
enum CodeCompletionContext::Kind K) {
834 case CodeCompletionContext::CCC_TopLevel:
835 case CodeCompletionContext::CCC_ObjCInterface:
836 case CodeCompletionContext::CCC_ObjCImplementation:
837 case CodeCompletionContext::CCC_ObjCIvarList:
838 case CodeCompletionContext::CCC_ClassStructUnion:
839 case CodeCompletionContext::CCC_Statement:
840 case CodeCompletionContext::CCC_Expression:
841 case CodeCompletionContext::CCC_ObjCMessageReceiver:
842 case CodeCompletionContext::CCC_EnumTag:
843 case CodeCompletionContext::CCC_UnionTag:
844 case CodeCompletionContext::CCC_ClassOrStructTag:
845 case CodeCompletionContext::CCC_ObjCProtocolName:
846 case CodeCompletionContext::CCC_Namespace:
847 case CodeCompletionContext::CCC_Type:
848 case CodeCompletionContext::CCC_ParenthesizedExpression:
849 case CodeCompletionContext::CCC_ObjCInterfaceName:
850 case CodeCompletionContext::CCC_Symbol:
851 case CodeCompletionContext::CCC_SymbolOrNewName:
852 case CodeCompletionContext::CCC_ObjCClassForwardDecl:
853 case CodeCompletionContext::CCC_TopLevelOrExpression:
855 case CodeCompletionContext::CCC_OtherWithMacros:
856 case CodeCompletionContext::CCC_DotMemberAccess:
857 case CodeCompletionContext::CCC_ArrowMemberAccess:
858 case CodeCompletionContext::CCC_ObjCCategoryName:
859 case CodeCompletionContext::CCC_ObjCPropertyAccess:
860 case CodeCompletionContext::CCC_MacroName:
861 case CodeCompletionContext::CCC_MacroNameUse:
862 case CodeCompletionContext::CCC_PreprocessorExpression:
863 case CodeCompletionContext::CCC_PreprocessorDirective:
864 case CodeCompletionContext::CCC_SelectorName:
865 case CodeCompletionContext::CCC_TypeQualifiers:
866 case CodeCompletionContext::CCC_ObjCInstanceMessage:
867 case CodeCompletionContext::CCC_ObjCClassMessage:
868 case CodeCompletionContext::CCC_IncludedFile:
869 case CodeCompletionContext::CCC_Attribute:
871 case CodeCompletionContext::CCC_Other:
872 case CodeCompletionContext::CCC_NaturalLanguage:
873 case CodeCompletionContext::CCC_Recovery:
874 case CodeCompletionContext::CCC_NewName:
877 llvm_unreachable(
"unknown code completion context");
880static bool isInjectedClass(
const NamedDecl &D) {
881 if (
auto *R = dyn_cast_or_null<CXXRecordDecl>(&D))
882 if (R->isInjectedClassName())
888static bool isExcludedMember(
const NamedDecl &D) {
891 if (D.getKind() == Decl::CXXDestructor)
894 if (isInjectedClass(D))
897 auto NameKind = D.getDeclName().getNameKind();
898 if (NameKind == DeclarationName::CXXOperatorName ||
899 NameKind == DeclarationName::CXXLiteralOperatorName ||
900 NameKind == DeclarationName::CXXConversionFunctionName)
911struct CompletionRecorder :
public CodeCompleteConsumer {
912 CompletionRecorder(
const CodeCompleteOptions &Opts,
913 llvm::unique_function<
void()> ResultsCallback)
914 : CodeCompleteConsumer(Opts.getClangCompleteOpts()),
915 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
916 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
917 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
918 assert(this->ResultsCallback);
921 std::vector<CodeCompletionResult> Results;
922 CodeCompletionContext CCContext;
923 Sema *CCSema =
nullptr;
926 void ProcessCodeCompleteResults(
class Sema &S, CodeCompletionContext Context,
927 CodeCompletionResult *InResults,
928 unsigned NumResults)
final {
937 CodeCompletionContext::Kind ContextKind = Context.getKind();
938 if (ContextKind == CodeCompletionContext::CCC_Recovery) {
939 log(
"Code complete: Ignoring sema code complete callback with Recovery "
946 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
949 log(
"Multiple code complete callbacks (parser backtracked?). "
950 "Dropping results from context {0}, keeping results from {1}.",
951 getCompletionKindString(Context.getKind()),
952 getCompletionKindString(this->CCContext.getKind()));
960 for (
unsigned I = 0; I < NumResults; ++I) {
961 auto &Result = InResults[I];
964 Result.Kind == CodeCompletionResult::RK_Pattern &&
966 ContextKind != CodeCompletionContext::CCC_IncludedFile)
969 if (Result.Hidden && Result.Declaration &&
970 Result.Declaration->isCXXClassMember())
972 if (!Opts.IncludeIneligibleResults &&
973 (Result.Availability == CXAvailability_NotAvailable ||
974 Result.Availability == CXAvailability_NotAccessible))
976 if (Result.Declaration &&
977 !Context.getBaseType().isNull()
978 && isExcludedMember(*Result.Declaration))
982 if (Result.Declaration && !Context.getCXXScopeSpecifier() &&
983 isInjectedClass(*Result.Declaration))
986 Result.StartsNestedNameSpecifier =
false;
987 Results.push_back(Result);
992 CodeCompletionAllocator &getAllocator()
override {
return *CCAllocator; }
993 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
997 llvm::StringRef getName(
const CodeCompletionResult &Result) {
998 switch (Result.Kind) {
999 case CodeCompletionResult::RK_Declaration:
1000 if (
auto *ID = Result.Declaration->getIdentifier())
1001 return ID->getName();
1003 case CodeCompletionResult::RK_Keyword:
1004 return Result.Keyword;
1005 case CodeCompletionResult::RK_Macro:
1006 return Result.Macro->getName();
1007 case CodeCompletionResult::RK_Pattern:
1010 auto *CCS = codeCompletionString(Result);
1011 const CodeCompletionString::Chunk *OnlyText =
nullptr;
1012 for (
auto &C : *CCS) {
1013 if (C.Kind != CodeCompletionString::CK_TypedText)
1016 return CCAllocator->CopyString(CCS->getAllTypedText());
1019 return OnlyText ? OnlyText->Text : llvm::StringRef();
1024 CodeCompletionString *codeCompletionString(
const CodeCompletionResult &R) {
1026 return const_cast<CodeCompletionResult &
>(R).CreateCodeCompletionString(
1027 *CCSema, CCContext, *CCAllocator, CCTUInfo,
1032 CodeCompleteOptions Opts;
1033 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
1034 CodeCompletionTUInfo CCTUInfo;
1035 llvm::unique_function<void()> ResultsCallback;
1038struct ScoredSignature {
1042 SignatureInformation Signature;
1043 SignatureQualitySignals Quality;
1051int paramIndexForArg(
const CodeCompleteConsumer::OverloadCandidate &Candidate,
1053 int NumParams = Candidate.getNumParams();
1054 if (
auto *T = Candidate.getFunctionType()) {
1055 if (
auto *Proto = T->getAs<FunctionProtoType>()) {
1056 if (Proto->isVariadic())
1060 return std::min(Arg, std::max(NumParams - 1, 0));
1063class SignatureHelpCollector final :
public CodeCompleteConsumer {
1065 SignatureHelpCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1066 MarkupKind DocumentationFormat,
1067 const SymbolIndex *Index, SignatureHelp &SigHelp)
1068 : CodeCompleteConsumer(CodeCompleteOpts), SigHelp(SigHelp),
1069 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1070 CCTUInfo(Allocator), Index(Index),
1071 DocumentationFormat(DocumentationFormat) {}
1073 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1074 OverloadCandidate *Candidates,
1075 unsigned NumCandidates,
1076 SourceLocation OpenParLoc,
1077 bool Braced)
override {
1078 assert(!OpenParLoc.isInvalid());
1079 SourceManager &SrcMgr = S.getSourceManager();
1080 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
1081 if (SrcMgr.isInMainFile(OpenParLoc))
1084 elog(
"Location oustide main file in signature help: {0}",
1085 OpenParLoc.printToString(SrcMgr));
1087 std::vector<ScoredSignature> ScoredSignatures;
1088 SigHelp.signatures.reserve(NumCandidates);
1089 ScoredSignatures.reserve(NumCandidates);
1093 SigHelp.activeSignature = 0;
1094 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1095 "too many arguments");
1097 SigHelp.activeParameter =
static_cast<int>(CurrentArg);
1099 for (
unsigned I = 0; I < NumCandidates; ++I) {
1100 OverloadCandidate Candidate = Candidates[I];
1104 if (
auto *Func = Candidate.getFunction()) {
1105 if (
auto *Pattern = Func->getTemplateInstantiationPattern())
1106 Candidate = OverloadCandidate(Pattern);
1108 if (
static_cast<int>(I) == SigHelp.activeSignature) {
1113 SigHelp.activeParameter =
1114 paramIndexForArg(Candidate, SigHelp.activeParameter);
1117 const auto *CCS = Candidate.CreateSignatureString(
1118 CurrentArg, S, *Allocator, CCTUInfo,
1120 assert(CCS &&
"Expected the CodeCompletionString to be non-null");
1121 ScoredSignatures.push_back(processOverloadCandidate(
1123 Candidate.getFunction()
1130 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
1132 LookupRequest IndexRequest;
1133 for (
const auto &S : ScoredSignatures) {
1136 IndexRequest.IDs.insert(S.IDForDoc);
1138 Index->lookup(IndexRequest, [&](
const Symbol &S) {
1139 if (!S.Documentation.empty())
1140 FetchedDocs[S.ID] = std::string(S.Documentation);
1142 vlog(
"SigHelp: requested docs for {0} symbols from the index, got {1} "
1143 "symbols with non-empty docs in the response",
1144 IndexRequest.IDs.size(), FetchedDocs.size());
1147 llvm::sort(ScoredSignatures, [](
const ScoredSignature &L,
1148 const ScoredSignature &R) {
1155 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
1156 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
1157 if (L.Quality.NumberOfOptionalParameters !=
1158 R.Quality.NumberOfOptionalParameters)
1159 return L.Quality.NumberOfOptionalParameters <
1160 R.Quality.NumberOfOptionalParameters;
1161 if (L.Quality.Kind != R.Quality.Kind) {
1162 using OC = CodeCompleteConsumer::OverloadCandidate;
1163 auto KindPriority = [&](OC::CandidateKind K) {
1165 case OC::CK_Aggregate:
1167 case OC::CK_Function:
1169 case OC::CK_FunctionType:
1171 case OC::CK_FunctionProtoTypeLoc:
1173 case OC::CK_FunctionTemplate:
1175 case OC::CK_Template:
1178 llvm_unreachable(
"Unknown overload candidate type.");
1180 return KindPriority(L.Quality.Kind) < KindPriority(R.Quality.Kind);
1182 if (L.Signature.label.size() != R.Signature.label.size())
1183 return L.Signature.label.size() < R.Signature.label.size();
1184 return L.Signature.label < R.Signature.label;
1187 for (
auto &SS : ScoredSignatures) {
1189 SS.IDForDoc ? FetchedDocs.find(SS.IDForDoc) : FetchedDocs.end();
1190 if (IndexDocIt != FetchedDocs.end()) {
1191 markup::Document SignatureComment;
1193 SS.Signature.documentation =
1194 renderDoc(SignatureComment, DocumentationFormat);
1197 SigHelp.signatures.push_back(std::move(SS.Signature));
1201 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1203 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1206 void processParameterChunk(llvm::StringRef ChunkText,
1207 SignatureInformation &Signature)
const {
1209 unsigned ParamStartOffset =
lspLength(Signature.label);
1210 unsigned ParamEndOffset = ParamStartOffset +
lspLength(ChunkText);
1214 Signature.label += ChunkText;
1215 ParameterInformation
Info;
1216 Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset);
1218 Info.labelString = std::string(ChunkText);
1220 Signature.parameters.push_back(std::move(
Info));
1223 void processOptionalChunk(
const CodeCompletionString &CCS,
1224 SignatureInformation &Signature,
1225 SignatureQualitySignals &Signal)
const {
1226 for (
const auto &Chunk : CCS) {
1227 switch (Chunk.Kind) {
1228 case CodeCompletionString::CK_Optional:
1229 assert(Chunk.Optional &&
1230 "Expected the optional code completion string to be non-null.");
1231 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1233 case CodeCompletionString::CK_VerticalSpace:
1235 case CodeCompletionString::CK_CurrentParameter:
1236 case CodeCompletionString::CK_Placeholder:
1237 processParameterChunk(Chunk.Text, Signature);
1238 Signal.NumberOfOptionalParameters++;
1241 Signature.label += Chunk.Text;
1249 ScoredSignature processOverloadCandidate(
const OverloadCandidate &Candidate,
1250 const CodeCompletionString &CCS,
1251 llvm::StringRef DocComment)
const {
1252 SignatureInformation Signature;
1253 SignatureQualitySignals Signal;
1254 const char *ReturnType =
nullptr;
1256 markup::Document OverloadComment;
1258 Signature.documentation = renderDoc(OverloadComment, DocumentationFormat);
1259 Signal.Kind = Candidate.getKind();
1261 for (
const auto &Chunk : CCS) {
1262 switch (Chunk.Kind) {
1263 case CodeCompletionString::CK_ResultType:
1266 assert(!ReturnType &&
"Unexpected CK_ResultType");
1267 ReturnType = Chunk.Text;
1269 case CodeCompletionString::CK_CurrentParameter:
1270 case CodeCompletionString::CK_Placeholder:
1271 processParameterChunk(Chunk.Text, Signature);
1272 Signal.NumberOfParameters++;
1274 case CodeCompletionString::CK_Optional: {
1276 assert(Chunk.Optional &&
1277 "Expected the optional code completion string to be non-null.");
1278 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1281 case CodeCompletionString::CK_VerticalSpace:
1284 Signature.label += Chunk.Text;
1289 Signature.label +=
" -> ";
1290 Signature.label += ReturnType;
1292 dlog(
"Signal for {0}: {1}", Signature, Signal);
1293 ScoredSignature Result;
1294 Result.Signature = std::move(Signature);
1295 Result.Quality = Signal;
1296 const FunctionDecl *Func = Candidate.getFunction();
1297 if (Func && Result.Signature.documentation.value.empty()) {
1305 SignatureHelp &SigHelp;
1306 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1307 CodeCompletionTUInfo CCTUInfo;
1308 const SymbolIndex *Index;
1309 MarkupKind DocumentationFormat;
1314class ParamNameCollector final :
public CodeCompleteConsumer {
1316 ParamNameCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1317 std::set<std::string> &ParamNames)
1318 : CodeCompleteConsumer(CodeCompleteOpts),
1319 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1320 CCTUInfo(Allocator), ParamNames(ParamNames) {}
1322 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1323 OverloadCandidate *Candidates,
1324 unsigned NumCandidates,
1325 SourceLocation OpenParLoc,
1326 bool Braced)
override {
1327 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1328 "too many arguments");
1330 for (
unsigned I = 0; I < NumCandidates; ++I) {
1331 if (
const NamedDecl *ND = Candidates[I].getParamDecl(CurrentArg))
1332 if (
const auto *II = ND->getIdentifier())
1333 ParamNames.emplace(II->getName());
1338 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1340 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1342 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1343 CodeCompletionTUInfo CCTUInfo;
1344 std::set<std::string> &ParamNames;
1347struct SemaCompleteInput {
1351 const std::optional<PreamblePatch> Patch;
1352 const ParseInputs &ParseInput;
1355void loadMainFilePreambleMacros(
const Preprocessor &PP,
1360 ExternalPreprocessorSource *PreambleMacros = PP.getExternalSource();
1363 const auto &ITable = PP.getIdentifierTable();
1364 IdentifierInfoLookup *PreambleIdentifiers =
1365 ITable.getExternalIdentifierLookup();
1367 if (!PreambleIdentifiers || !PreambleMacros)
1369 for (
const auto &MacroName :
Preamble.Macros.Names) {
1370 if (ITable.find(MacroName.getKey()) != ITable.end())
1372 if (
auto *II = PreambleIdentifiers->get(MacroName.getKey()))
1373 if (II->isOutOfDate())
1374 PreambleMacros->updateOutOfDateIdentifier(*II);
1380bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
1381 const clang::CodeCompleteOptions &Options,
1382 const SemaCompleteInput &Input,
1383 IncludeStructure *Includes =
nullptr) {
1384 trace::Span Tracer(
"Sema completion");
1386 IgnoreDiagnostics IgnoreDiags;
1389 elog(
"Couldn't create CompilerInvocation");
1392 auto &FrontendOpts = CI->getFrontendOpts();
1393 FrontendOpts.SkipFunctionBodies =
true;
1395 CI->getLangOpts().SpellChecking =
false;
1399 CI->getLangOpts().DelayedTemplateParsing =
false;
1401 FrontendOpts.CodeCompleteOpts = Options;
1402 FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName);
1403 std::tie(FrontendOpts.CodeCompletionAt.Line,
1404 FrontendOpts.CodeCompletionAt.Column) =
1407 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1408 llvm::MemoryBuffer::getMemBuffer(Input.ParseInput.Contents,
1411 CI->getDiagnosticOpts().IgnoreWarnings =
true;
1418 PreambleBounds PreambleRegion =
1419 ComputePreambleBounds(CI->getLangOpts(), *ContentsBuffer, 0);
1420 bool CompletingInPreamble = Input.Offset < PreambleRegion.Size ||
1421 (!PreambleRegion.PreambleEndsAtStartOfLine &&
1422 Input.Offset == PreambleRegion.Size);
1424 Input.Patch->apply(*CI);
1427 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1428 Input.ParseInput.TFS->view(Input.ParseInput.CompileCommand.Directory);
1429 if (Input.Preamble.StatCache)
1430 VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS));
1432 std::move(CI), !CompletingInPreamble ? &Input.Preamble.Preamble :
nullptr,
1433 std::move(ContentsBuffer), std::move(VFS), IgnoreDiags);
1434 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
1435 Clang->setCodeCompletionConsumer(Consumer.release());
1437 if (Input.Preamble.RequiredModules)
1438 Input.Preamble.RequiredModules->adjustHeaderSearchOptions(Clang->getHeaderSearchOpts());
1441 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1442 log(
"BeginSourceFile() failed when running codeComplete for {0}",
1452 loadMainFilePreambleMacros(Clang->getPreprocessor(), Input.Preamble);
1454 Includes->collect(*Clang);
1455 if (llvm::Error Err = Action.Execute()) {
1456 log(
"Execute() failed when running codeComplete for {0}: {1}",
1457 Input.FileName,
toString(std::move(Err)));
1460 Action.EndSourceFile();
1466bool allowIndex(CodeCompletionContext &CC) {
1467 if (!contextAllowsIndex(CC.getKind()))
1470 auto Scope = CC.getCXXScopeSpecifier();
1475 switch ((*Scope)->getScopeRep().getKind()) {
1476 case NestedNameSpecifier::Kind::Null:
1477 case NestedNameSpecifier::Kind::Global:
1478 case NestedNameSpecifier::Kind::Namespace:
1480 case NestedNameSpecifier::Kind::MicrosoftSuper:
1481 case NestedNameSpecifier::Kind::Type:
1484 llvm_unreachable(
"invalid NestedNameSpecifier kind");
1489bool includeSymbolFromIndex(CodeCompletionContext::Kind Kind,
1490 const Symbol &Sym) {
1494 if (Sym.SymInfo.Kind == index::SymbolKind::Protocol &&
1495 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC)
1496 return Kind == CodeCompletionContext::CCC_ObjCProtocolName;
1497 else if (Kind == CodeCompletionContext::CCC_ObjCProtocolName)
1501 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
1502 return Sym.SymInfo.Kind == index::SymbolKind::Class &&
1503 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC;
1507std::future<std::pair<bool, SymbolSlab>>
1508startAsyncFuzzyFind(
const SymbolIndex &Index,
const FuzzyFindRequest &Req) {
1510 trace::Span Tracer(
"Async fuzzyFind");
1511 SymbolSlab::Builder Syms;
1513 Index.fuzzyFind(Req, [&Syms](
const Symbol &Sym) { Syms.insert(Sym); });
1514 return std::make_pair(Incomplete, std::move(Syms).build());
1521FuzzyFindRequest speculativeFuzzyFindRequestForCompletion(
1522 FuzzyFindRequest CachedReq,
const CompletionPrefix &HeuristicPrefix) {
1523 CachedReq.Query = std::string(HeuristicPrefix.Name);
1531findTokenAfterCompletionPoint(SourceLocation CompletionPoint,
1532 const SourceManager &SM,
1533 const LangOptions &LangOpts) {
1534 SourceLocation Loc = CompletionPoint;
1535 if (Loc.isMacroID()) {
1536 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1537 return std::nullopt;
1545 Loc = Loc.getLocWithOffset(1);
1548 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1551 bool InvalidTemp =
false;
1552 StringRef
File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1554 return std::nullopt;
1556 const char *TokenBegin =
File.data() + LocInfo.second;
1559 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
File.begin(),
1560 TokenBegin,
File.end());
1563 TheLexer.LexFromRawLexer(Tok);
1596class CodeCompleteFlow {
1598 IncludeStructure Includes;
1599 SpeculativeFuzzyFind *SpecFuzzyFind;
1600 const CodeCompleteOptions &Opts;
1603 CompletionRecorder *Recorder =
nullptr;
1604 CodeCompletionContext::Kind CCContextKind = CodeCompletionContext::CCC_Other;
1605 bool IsUsingDeclaration =
false;
1609 tok::TokenKind NextTokenKind = tok::eof;
1611 int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
1612 bool Incomplete =
false;
1613 CompletionPrefix HeuristicPrefix;
1614 std::optional<FuzzyMatcher> Filter;
1615 Range ReplacedRange;
1616 std::vector<std::string> QueryScopes;
1617 std::vector<std::string> AccessibleScopes;
1619 std::optional<ScopeDistance> ScopeProximity;
1620 std::optional<OpaqueType> PreferredType;
1622 bool AllScopes =
false;
1623 llvm::StringSet<> ContextWords;
1626 std::optional<IncludeInserter> Inserter;
1627 std::optional<URIDistance> FileProximity;
1632 std::optional<FuzzyFindRequest> SpecReq;
1636 CodeCompleteFlow(
PathRef FileName,
const IncludeStructure &Includes,
1637 SpeculativeFuzzyFind *SpecFuzzyFind,
1638 const CodeCompleteOptions &Opts)
1639 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1642 CodeCompleteResult
run(
const SemaCompleteInput &SemaCCInput) && {
1643 trace::Span Tracer(
"CodeCompleteFlow");
1645 SemaCCInput.Offset);
1646 populateContextWords(SemaCCInput.ParseInput.Contents);
1647 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq) {
1648 assert(!SpecFuzzyFind->Result.valid());
1649 SpecReq = speculativeFuzzyFindRequestForCompletion(
1650 *SpecFuzzyFind->CachedReq, HeuristicPrefix);
1651 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1657 CodeCompleteResult Output;
1658 auto RecorderOwner = std::make_unique<CompletionRecorder>(Opts, [&]() {
1659 assert(Recorder &&
"Recorder is not set");
1660 CCContextKind = Recorder->CCContext.getKind();
1661 IsUsingDeclaration = Recorder->CCContext.isUsingDeclaration();
1663 SemaCCInput.ParseInput.Contents,
1664 *SemaCCInput.ParseInput.TFS,
false);
1665 const auto NextToken = findTokenAfterCompletionPoint(
1666 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc(),
1667 Recorder->CCSema->getSourceManager(), Recorder->CCSema->LangOpts);
1669 NextTokenKind = NextToken->getKind();
1673 SemaCCInput.FileName, SemaCCInput.ParseInput.Contents, Style,
1674 SemaCCInput.ParseInput.CompileCommand.Directory,
1675 &Recorder->CCSema->getPreprocessor().getHeaderSearchInfo(),
1678 for (
const auto &Inc : Includes.MainFileIncludes)
1679 Inserter->addExisting(Inc);
1685 FileDistanceOptions ProxOpts{};
1686 const auto &SM = Recorder->CCSema->getSourceManager();
1687 llvm::StringMap<SourceParams> ProxSources;
1689 Includes.getID(SM.getFileEntryForID(SM.getMainFileID()));
1691 for (
auto &HeaderIDAndDepth : Includes.includeDepth(*MainFileID)) {
1693 ProxSources[Includes.getRealPath(HeaderIDAndDepth.getFirst())];
1694 Source.Cost = HeaderIDAndDepth.getSecond() * ProxOpts.IncludeCost;
1698 if (HeaderIDAndDepth.getSecond() > 0)
1699 Source.MaxUpTraversals = 1;
1701 FileProximity.emplace(ProxSources, ProxOpts);
1703 Output = runWithSema();
1706 getCompletionKindString(CCContextKind));
1707 log(
"Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1708 "expected type {3}{4}",
1709 getCompletionKindString(CCContextKind),
1710 llvm::join(QueryScopes.begin(), QueryScopes.end(),
","), AllScopes,
1711 PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1713 IsUsingDeclaration ?
", inside using declaration" :
"");
1716 Recorder = RecorderOwner.get();
1718 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1719 SemaCCInput, &Includes);
1720 logResults(Output, Tracer);
1724 void logResults(
const CodeCompleteResult &Output,
const trace::Span &Tracer) {
1727 SPAN_ATTACH(Tracer,
"merged_results", NSemaAndIndex);
1728 SPAN_ATTACH(Tracer,
"identifier_results", NIdent);
1729 SPAN_ATTACH(Tracer,
"returned_results", int64_t(Output.Completions.size()));
1730 SPAN_ATTACH(Tracer,
"incomplete", Output.HasMore);
1731 log(
"Code complete: {0} results from Sema, {1} from Index, "
1732 "{2} matched, {3} from identifiers, {4} returned{5}.",
1733 NSema, NIndex, NSemaAndIndex, NIdent, Output.Completions.size(),
1734 Output.HasMore ?
" (incomplete)" :
"");
1735 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1740 CodeCompleteResult runWithoutSema(llvm::StringRef Content,
size_t Offset,
1741 const ThreadsafeFS &TFS) && {
1742 trace::Span Tracer(
"CodeCompleteWithoutSema");
1745 populateContextWords(Content);
1746 CCContextKind = CodeCompletionContext::CCC_Recovery;
1747 IsUsingDeclaration =
false;
1748 Filter = FuzzyMatcher(HeuristicPrefix.Name);
1750 ReplacedRange.start = ReplacedRange.end = Pos;
1751 ReplacedRange.start.character -= HeuristicPrefix.Name.size();
1753 llvm::StringMap<SourceParams> ProxSources;
1754 ProxSources[FileName].Cost = 0;
1755 FileProximity.emplace(ProxSources);
1759 Inserter.emplace(FileName, Content, Style,
1765 std::vector<RawIdentifier> IdentifierResults;
1766 for (
const auto &IDAndCount : Identifiers) {
1768 ID.Name = IDAndCount.first();
1769 ID.References = IDAndCount.second;
1771 if (ID.Name == HeuristicPrefix.Name)
1773 if (ID.References > 0)
1774 IdentifierResults.push_back(std::move(ID));
1780 SpecifiedScope Scopes;
1782 Content.take_front(Offset), format::getFormattingLangOpts(Style));
1783 for (std::string &S : Scopes.QueryScopes)
1786 if (HeuristicPrefix.Qualifier.empty())
1787 AllScopes = Opts.AllScopes;
1788 else if (HeuristicPrefix.Qualifier.starts_with(
"::")) {
1789 Scopes.QueryScopes = {
""};
1790 Scopes.UnresolvedQualifier =
1791 std::string(HeuristicPrefix.Qualifier.drop_front(2));
1793 Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier);
1795 QueryScopes = Scopes.scopesForIndexQuery();
1796 AccessibleScopes = QueryScopes;
1797 ScopeProximity.emplace(QueryScopes);
1799 SymbolSlab IndexResults = Opts.Index ? queryIndex() : SymbolSlab();
1801 CodeCompleteResult Output = toCodeCompleteResult(mergeResults(
1802 {}, IndexResults, IdentifierResults));
1803 Output.RanParser =
false;
1804 logResults(Output, Tracer);
1809 void populateContextWords(llvm::StringRef Content) {
1811 unsigned RangeEnd = HeuristicPrefix.Qualifier.begin() - Content.data(),
1812 RangeBegin = RangeEnd;
1813 for (
size_t I = 0; I < 3 && RangeBegin > 0; ++I) {
1814 auto PrevNL = Content.rfind(
'\n', RangeBegin);
1815 if (PrevNL == StringRef::npos) {
1819 RangeBegin = PrevNL;
1822 ContextWords =
collectWords(Content.slice(RangeBegin, RangeEnd));
1823 dlog(
"Completion context words: {0}",
1824 llvm::join(ContextWords.keys(),
", "));
1829 CodeCompleteResult runWithSema() {
1830 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1831 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1837 if (CodeCompletionRange.isValid()) {
1839 CodeCompletionRange);
1842 Recorder->CCSema->getSourceManager(),
1843 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1844 ReplacedRange.start = ReplacedRange.end = Pos;
1846 Filter = FuzzyMatcher(
1847 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1848 auto SpecifiedScopes = getQueryScopes(
1849 Recorder->CCContext, *Recorder->CCSema, HeuristicPrefix, Opts);
1851 QueryScopes = SpecifiedScopes.scopesForIndexQuery();
1852 AccessibleScopes = SpecifiedScopes.scopesForQualification();
1853 AllScopes = SpecifiedScopes.AllowAllScopes;
1854 if (!QueryScopes.empty())
1855 ScopeProximity.emplace(QueryScopes);
1858 Recorder->CCContext.getPreferredType());
1864 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1867 trace::Span Tracer(
"Populate CodeCompleteResult");
1870 mergeResults(Recorder->Results, IndexResults, {});
1871 return toCodeCompleteResult(Top);
1875 toCodeCompleteResult(
const std::vector<ScoredBundle> &Scored) {
1876 CodeCompleteResult Output;
1881 llvm::DenseMap<SymbolID, uint32_t> SymbolToCompletion;
1882 for (
auto &C : Scored) {
1883 Output.Completions.push_back(toCodeCompletion(C.first));
1884 Output.Completions.back().Score = C.second;
1885 Output.Completions.back().CompletionTokenRange = ReplacedRange;
1886 if (Opts.Index && !Output.Completions.back().Documentation) {
1887 for (
auto &Cand : C.first) {
1888 if (Cand.SemaResult &&
1889 Cand.SemaResult->Kind == CodeCompletionResult::RK_Declaration) {
1890 const NamedDecl *DeclToLookup = Cand.SemaResult->getDeclaration();
1894 if (
const NamedDecl *Adjusted =
1895 dyn_cast<NamedDecl>(&adjustDeclToTemplate(*DeclToLookup))) {
1896 DeclToLookup = Adjusted;
1902 SymbolToCompletion[ID] = Output.Completions.size() - 1;
1907 Output.HasMore = Incomplete;
1908 Output.Context = CCContextKind;
1909 Output.CompletionRange = ReplacedRange;
1913 Opts.Index->lookup(Req, [&](
const Symbol &S) {
1914 if (S.Documentation.empty())
1916 auto &C = Output.Completions[SymbolToCompletion.at(S.ID)];
1917 C.Documentation.emplace();
1925 SymbolSlab queryIndex() {
1926 trace::Span Tracer(
"Query index");
1927 SPAN_ATTACH(Tracer,
"limit", int64_t(Opts.Limit));
1930 FuzzyFindRequest Req;
1932 Req.Limit = Opts.Limit;
1933 Req.Query = std::string(Filter->pattern());
1934 Req.RestrictForCodeCompletion =
true;
1935 Req.Scopes = QueryScopes;
1936 Req.AnyScope = AllScopes;
1938 Req.ProximityPaths.push_back(std::string(FileName));
1940 Req.PreferredTypes.push_back(std::string(PreferredType->raw()));
1941 vlog(
"Code complete: fuzzyFind({0:2})",
toJSON(Req));
1944 SpecFuzzyFind->NewReq = Req;
1945 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1946 vlog(
"Code complete: speculative fuzzy request matches the actual index "
1947 "request. Waiting for the speculative index results.");
1950 trace::Span WaitSpec(
"Wait speculative results");
1951 auto SpecRes = SpecFuzzyFind->Result.get();
1952 Incomplete |= SpecRes.first;
1953 return std::move(SpecRes.second);
1956 SPAN_ATTACH(Tracer,
"Speculative results",
false);
1959 SymbolSlab::Builder ResultsBuilder;
1960 Incomplete |= Opts.Index->fuzzyFind(
1961 Req, [&](
const Symbol &Sym) { ResultsBuilder.insert(Sym); });
1962 return std::move(ResultsBuilder).build();
1970 std::vector<ScoredBundle>
1971 mergeResults(
const std::vector<CodeCompletionResult> &SemaResults,
1972 const SymbolSlab &IndexResults,
1973 const std::vector<RawIdentifier> &IdentifierResults) {
1974 trace::Span Tracer(
"Merge and score results");
1975 std::vector<CompletionCandidate::Bundle> Bundles;
1976 llvm::DenseMap<size_t, size_t> BundleLookup;
1977 auto AddToBundles = [&](
const CodeCompletionResult *SemaResult,
1978 const Symbol *IndexResult,
1979 const RawIdentifier *IdentifierResult) {
1980 CompletionCandidate C;
1981 C.SemaResult = SemaResult;
1982 C.IndexResult = IndexResult;
1983 C.IdentifierResult = IdentifierResult;
1984 if (C.IndexResult) {
1985 C.Name = IndexResult->Name;
1987 }
else if (C.SemaResult) {
1988 C.Name = Recorder->getName(*SemaResult);
1990 assert(IdentifierResult);
1991 C.Name = IdentifierResult->Name;
1993 if (
auto OverloadSet = C.overloadSet(
1994 Opts, FileName, Inserter ? &*Inserter :
nullptr, CCContextKind)) {
1995 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1997 Bundles.emplace_back();
1998 Bundles[Ret.first->second].push_back(std::move(C));
2000 Bundles.emplace_back();
2001 Bundles.back().push_back(std::move(C));
2004 llvm::DenseSet<const Symbol *> UsedIndexResults;
2005 auto CorrespondingIndexResult =
2006 [&](
const CodeCompletionResult &SemaResult) ->
const Symbol * {
2008 getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
2009 auto I = IndexResults.find(SymID);
2010 if (I != IndexResults.end()) {
2011 UsedIndexResults.insert(&*I);
2018 for (
auto &SemaResult : SemaResults)
2019 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult),
nullptr);
2021 for (
const auto &IndexResult : IndexResults) {
2022 if (UsedIndexResults.count(&IndexResult))
2024 if (!includeSymbolFromIndex(CCContextKind, IndexResult))
2026 AddToBundles(
nullptr, &IndexResult,
nullptr);
2029 for (
const auto &Ident : IdentifierResults)
2030 AddToBundles(
nullptr,
nullptr, &Ident);
2032 TopN<ScoredBundle, ScoredBundleGreater> Top(
2033 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
2034 for (
auto &Bundle : Bundles)
2035 addCandidate(Top, std::move(Bundle));
2036 return std::move(Top).items();
2039 std::optional<float> fuzzyScore(
const CompletionCandidate &C) {
2041 if (((C.SemaResult &&
2042 C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
2044 C.IndexResult->SymInfo.Kind == index::SymbolKind::Macro)) &&
2045 !C.Name.starts_with_insensitive(Filter->pattern()))
2046 return std::nullopt;
2047 return Filter->match(C.Name);
2050 CodeCompletion::Scores
2051 evaluateCompletion(
const SymbolQualitySignals &Quality,
2052 const SymbolRelevanceSignals &Relevance) {
2053 using RM = CodeCompleteOptions::CodeCompletionRankingModel;
2054 CodeCompletion::Scores Scores;
2055 switch (Opts.RankingModel) {
2056 case RM::Heuristics:
2057 Scores.Quality = Quality.evaluateHeuristics();
2058 Scores.Relevance = Relevance.evaluateHeuristics();
2063 Scores.ExcludingName =
2064 Relevance.NameMatch > std::numeric_limits<float>::epsilon()
2065 ? Scores.Total / Relevance.NameMatch
2069 case RM::DecisionForest:
2070 DecisionForestScores DFScores = Opts.DecisionForestScorer(
2071 Quality, Relevance, Opts.DecisionForestBase);
2072 Scores.ExcludingName = DFScores.ExcludingName;
2073 Scores.Total = DFScores.Total;
2076 llvm_unreachable(
"Unhandled CodeCompletion ranking model.");
2080 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
2081 CompletionCandidate::Bundle Bundle) {
2082 SymbolQualitySignals Quality;
2083 SymbolRelevanceSignals Relevance;
2084 Relevance.Context = CCContextKind;
2085 Relevance.Name = Bundle.front().Name;
2086 Relevance.FilterLength = HeuristicPrefix.Name.size();
2088 Relevance.FileProximityMatch = &*FileProximity;
2090 Relevance.ScopeProximityMatch = &*ScopeProximity;
2092 Relevance.HadContextType =
true;
2093 Relevance.ContextWords = &ContextWords;
2094 Relevance.MainFileSignals = Opts.MainFileSignals;
2096 auto &First = Bundle.front();
2097 if (
auto FuzzyScore = fuzzyScore(First))
2098 Relevance.NameMatch = *FuzzyScore;
2102 bool FromIndex =
false;
2103 for (
const auto &Candidate : Bundle) {
2104 if (Candidate.IndexResult) {
2105 Quality.merge(*Candidate.IndexResult);
2106 Relevance.merge(*Candidate.IndexResult);
2107 Origin |= Candidate.IndexResult->Origin;
2109 if (!Candidate.IndexResult->Type.empty())
2110 Relevance.HadSymbolType |=
true;
2111 if (PreferredType &&
2112 PreferredType->raw() == Candidate.IndexResult->Type) {
2113 Relevance.TypeMatchesPreferred =
true;
2116 if (Candidate.SemaResult) {
2117 Quality.merge(*Candidate.SemaResult);
2118 Relevance.merge(*Candidate.SemaResult);
2119 if (PreferredType) {
2121 Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
2122 Relevance.HadSymbolType |=
true;
2123 if (PreferredType == CompletionType)
2124 Relevance.TypeMatchesPreferred =
true;
2129 if (Candidate.IdentifierResult) {
2130 Quality.References = Candidate.IdentifierResult->References;
2136 CodeCompletion::Scores Scores = evaluateCompletion(Quality, Relevance);
2137 if (Opts.RecordCCResult)
2138 Opts.RecordCCResult(toCodeCompletion(Bundle), Quality, Relevance,
2141 dlog(
"CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
2142 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
2143 llvm::to_string(Relevance));
2146 NIndex += FromIndex;
2149 if (Candidates.push({std::move(Bundle), Scores}))
2153 CodeCompletion toCodeCompletion(
const CompletionCandidate::Bundle &Bundle) {
2154 std::optional<CodeCompletionBuilder> Builder;
2155 for (
const auto &Item : Bundle) {
2156 CodeCompletionString *SemaCCS =
2157 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
2160 Builder.emplace(Recorder ? &Recorder->CCSema->getASTContext() :
nullptr,
2161 Item, SemaCCS, AccessibleScopes, *Inserter, FileName,
2162 CCContextKind, Opts, IsUsingDeclaration, NextTokenKind);
2164 Builder->add(Item, SemaCCS, CCContextKind);
2166 return Builder->build();
2173 clang::CodeCompleteOptions
Result;
2174 Result.IncludeCodePatterns =
2176 Result.IncludeMacros =
true;
2177 Result.IncludeGlobals =
true;
2182 Result.IncludeBriefComments =
false;
2187 Result.LoadExternal = ForceLoadPreamble || !Index;
2188 Result.IncludeFixIts = IncludeFixIts;
2195 assert(Offset <= Content.size());
2196 StringRef Rest = Content.take_front(Offset);
2201 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2202 Rest = Rest.drop_back();
2203 Result.
Name = Content.slice(Rest.size(), Offset);
2206 while (Rest.consume_back(
"::") && !Rest.ends_with(
":"))
2207 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2208 Rest = Rest.drop_back();
2210 Content.slice(Rest.size(), Result.
Name.begin() - Content.begin());
2219 llvm::StringRef Prefix,
2223 return CodeCompleteResult();
2225 clang::CodeCompleteOptions Options;
2226 Options.IncludeGlobals =
false;
2227 Options.IncludeMacros =
false;
2228 Options.IncludeCodePatterns =
false;
2229 Options.IncludeBriefComments =
false;
2230 std::set<std::string> ParamNames;
2234 std::make_unique<ParamNameCollector>(Options, ParamNames), Options,
2238 if (ParamNames.empty())
2239 return CodeCompleteResult();
2241 CodeCompleteResult Result;
2242 Range CompletionRange;
2246 CompletionRange.
end =
2248 Result.CompletionRange = CompletionRange;
2249 Result.Context = CodeCompletionContext::CCC_NaturalLanguage;
2250 for (llvm::StringRef Name : ParamNames) {
2251 if (!Name.starts_with(Prefix))
2253 CodeCompletion Item;
2254 Item.Name = Name.str() +
"=*/";
2255 Item.FilterText = Item.Name;
2257 Item.CompletionTokenRange = CompletionRange;
2259 Result.Completions.push_back(Item);
2268std::optional<unsigned>
2270 while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
2271 Content = Content.drop_back();
2272 Content = Content.rtrim();
2273 if (Content.ends_with(
"/*"))
2274 return Content.size() - 2;
2275 return std::nullopt;
2282 SpeculativeFuzzyFind *SpecFuzzyFind) {
2285 elog(
"Code completion position was invalid {0}", Offset.takeError());
2286 return CodeCompleteResult();
2289 auto Content = llvm::StringRef(ParseInput.
Contents).take_front(*Offset);
2296 auto CommentPrefix = Content.substr(*OffsetBeforeComment + 2).trim();
2301 auto Flow = CodeCompleteFlow(
2303 SpecFuzzyFind, Opts);
2304 return (!
Preamble || Opts.RunParser == CodeCompleteOptions::NeverParse)
2305 ? std::move(Flow).runWithoutSema(ParseInput.
Contents, *Offset,
2307 : std::move(Flow).run({FileName, *Offset, *
Preamble,
2320 elog(
"Signature help position was invalid {0}", Offset.takeError());
2324 clang::CodeCompleteOptions Options;
2325 Options.IncludeGlobals =
false;
2326 Options.IncludeMacros =
false;
2327 Options.IncludeCodePatterns =
false;
2328 Options.IncludeBriefComments =
false;
2330 std::make_unique<SignatureHelpCollector>(Options, DocumentationFormat,
2331 ParseInput.
Index, Result),
2333 {FileName, *Offset, Preamble,
2334 PreamblePatch::createFullPatch(FileName, ParseInput, Preamble),
2340 auto InTopLevelScope = [](
const NamedDecl &ND) {
2341 switch (ND.getDeclContext()->getDeclKind()) {
2342 case Decl::TranslationUnit:
2343 case Decl::Namespace:
2344 case Decl::LinkageSpec:
2351 auto InClassScope = [](
const NamedDecl &ND) {
2352 return ND.getDeclContext()->getDeclKind() == Decl::CXXRecord;
2363 if (llvm::isa<ObjCCategoryDecl>(&ND) || llvm::isa<ObjCCategoryImplDecl>(&ND))
2366 if (InTopLevelScope(ND))
2372 if (
const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
2373 return (InTopLevelScope(*EnumDecl) || InClassScope(*EnumDecl));
2378CompletionItem CodeCompletion::render(
const CodeCompleteOptions &Opts)
const {
2380 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
2383 LSP.label = ((InsertInclude && InsertInclude->Insertion)
2384 ? Opts.IncludeIndicator.Insert
2385 : Opts.IncludeIndicator.NoInsert) +
2386 (Opts.ShowOrigins ?
"[" + llvm::to_string(Origin) +
"]" :
"") +
2387 RequiredQualifier + Name;
2388 LSP.labelDetails.emplace();
2389 LSP.labelDetails->detail = Signature;
2392 LSP.detail = BundleSize > 1
2393 ? std::string(llvm::formatv(
"[{0} overloads]", BundleSize))
2398 if (InsertInclude || Documentation) {
2399 markup::Document Doc;
2401 Doc.addParagraph().appendText(
"From ").appendCode(InsertInclude->Header);
2403 Doc.append(*Documentation);
2404 LSP.documentation = renderDoc(Doc, Opts.DocumentationFormat);
2406 LSP.sortText =
sortText(Score.Total, FilterText);
2407 LSP.filterText = FilterText;
2408 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name,
""};
2416 for (
const auto &FixIt : FixIts) {
2417 if (FixIt.range.end == LSP.textEdit->range.start) {
2418 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
2419 LSP.textEdit->range.start = FixIt.range.start;
2421 LSP.additionalTextEdits.push_back(FixIt);
2424 if (Opts.EnableSnippets)
2425 LSP.textEdit->newText += SnippetSuffix;
2429 LSP.insertText = LSP.textEdit->newText;
2433 LSP.insertTextFormat = (Opts.EnableSnippets && !SnippetSuffix.empty())
2436 if (InsertInclude && InsertInclude->Insertion)
2437 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
2439 LSP.score = Score.ExcludingName;
2444llvm::raw_ostream &
operator<<(llvm::raw_ostream &OS,
const CodeCompletion &C) {
2445 OS <<
"Signature: " <<
"\"" << C.Signature <<
"\", "
2446 <<
"SnippetSuffix: " <<
"\"" << C.SnippetSuffix <<
"\""
2453 const CodeCompleteResult &R) {
2454 OS <<
"CodeCompleteResult: " << R.Completions.size() << (R.HasMore ?
"+" :
"")
2455 <<
" (" << getCompletionKindString(R.Context) <<
")"
2457 for (
const auto &C : R.Completions)
2464 Line = Line.ltrim();
2465 if (!Line.consume_front(
"#"))
2467 Line = Line.ltrim();
2468 if (!(Line.consume_front(
"include_next") || Line.consume_front(
"include") ||
2469 Line.consume_front(
"import")))
2471 Line = Line.ltrim();
2472 if (Line.consume_front(
"<"))
2473 return Line.count(
'>') == 0;
2474 if (Line.consume_front(
"\""))
2475 return Line.count(
'"') == 0;
2481 Content = Content.take_front(Offset);
2482 auto Pos = Content.rfind(
'\n');
2483 if (Pos != llvm::StringRef::npos)
2484 Content = Content.substr(Pos + 1);
2487 if (Content.ends_with(
".") || Content.ends_with(
"->") ||
2488 Content.ends_with(
"::") || Content.ends_with(
"/*"))
2491 if ((Content.ends_with(
"<") || Content.ends_with(
"\"") ||
2492 Content.ends_with(
"/")) &&
2497 return !Content.empty() && (isAsciiIdentifierContinue(Content.back()) ||
2498 !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"