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)");
593 bool MayHaveArgList =
603 if (MayHaveArgList) {
607 if (NextTokenKind == tok::less &&
Snippet->front() ==
'<')
610 if (NextTokenKind == tok::l_paren) {
620 else if (
Snippet->at(I) ==
'<')
623 }
while (Balance > 0);
633 if (MayHaveArgList && llvm::StringRef(*Snippet).contains(
"(")) {
642 bool EmptyArgs = llvm::StringRef(*Snippet).ends_with(
"()");
644 return None ?
"" : (
Open ?
"<" : (EmptyArgs ?
"<$1>()$0" :
"<$1>($0)"));
646 return None ?
"" : (
Open ?
"(" : (EmptyArgs ?
"()" :
"($0)"));
658 if (llvm::StringRef(*Snippet).ends_with(
"<>"))
660 return None ?
"" : (
Open ?
"<" :
"<$0>");
665 std::string summarizeSignature()
const {
666 if (
auto *Signature = onlyValue<&BundledEntry::Signature>())
674 CodeCompletion Completion;
675 llvm::SmallVector<BundledEntry, 1> Bundled;
680 bool IsUsingDeclaration;
681 tok::TokenKind NextTokenKind;
685SymbolID
getSymbolID(
const CodeCompletionResult &R,
const SourceManager &SM) {
687 case CodeCompletionResult::RK_Declaration:
688 case CodeCompletionResult::RK_Pattern: {
694 case CodeCompletionResult::RK_Macro:
696 case CodeCompletionResult::RK_Keyword:
699 llvm_unreachable(
"unknown CodeCompletionResult kind");
704struct SpecifiedScope {
727 std::vector<std::string> AccessibleScopes;
730 std::vector<std::string> QueryScopes;
733 std::optional<std::string> UnresolvedQualifier;
735 std::optional<std::string> EnclosingNamespace;
737 bool AllowAllScopes =
false;
741 std::vector<std::string> scopesForQualification() {
742 std::set<std::string> Results;
743 for (llvm::StringRef AS : AccessibleScopes)
745 (AS + (UnresolvedQualifier ? *UnresolvedQualifier :
"")).str());
746 return {Results.begin(), Results.end()};
751 std::vector<std::string> scopesForIndexQuery() {
753 std::vector<std::string> EnclosingAtFront;
754 if (EnclosingNamespace.has_value())
755 EnclosingAtFront.push_back(*EnclosingNamespace);
756 std::set<std::string> Deduplicated;
757 for (llvm::StringRef S : QueryScopes)
758 if (S != EnclosingNamespace)
759 Deduplicated.insert((S + UnresolvedQualifier.value_or(
"")).str());
761 EnclosingAtFront.reserve(EnclosingAtFront.size() + Deduplicated.size());
762 llvm::copy(Deduplicated, std::back_inserter(EnclosingAtFront));
764 return EnclosingAtFront;
771SpecifiedScope getQueryScopes(CodeCompletionContext &CCContext,
773 const CompletionPrefix &HeuristicPrefix,
774 const CodeCompleteOptions &Opts) {
775 SpecifiedScope Scopes;
776 for (
auto *Context : CCContext.getVisitedContexts()) {
777 if (isa<TranslationUnitDecl>(Context)) {
778 Scopes.QueryScopes.push_back(
"");
779 Scopes.AccessibleScopes.push_back(
"");
780 }
else if (
const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
786 const CXXScopeSpec *SemaSpecifier =
787 CCContext.getCXXScopeSpecifier().value_or(
nullptr);
789 if (!SemaSpecifier) {
792 if (!HeuristicPrefix.Qualifier.empty()) {
793 vlog(
"Sema said no scope specifier, but we saw {0} in the source code",
794 HeuristicPrefix.Qualifier);
795 StringRef SpelledSpecifier = HeuristicPrefix.Qualifier;
796 if (SpelledSpecifier.consume_front(
"::")) {
797 Scopes.AccessibleScopes = {
""};
798 Scopes.QueryScopes = {
""};
800 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
808 Scopes.AllowAllScopes = Opts.AllScopes;
812 if (SemaSpecifier && SemaSpecifier->isValid())
816 Scopes.QueryScopes.push_back(
"");
817 llvm::StringRef SpelledSpecifier = Lexer::getSourceText(
818 CharSourceRange::getCharRange(SemaSpecifier->getRange()),
819 CCSema.SourceMgr, clang::LangOptions());
820 if (SpelledSpecifier.consume_front(
"::"))
821 Scopes.QueryScopes = {
""};
822 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
824 if (!Scopes.UnresolvedQualifier->empty())
825 *Scopes.UnresolvedQualifier +=
"::";
827 Scopes.AccessibleScopes = Scopes.QueryScopes;
834bool contextAllowsIndex(
enum CodeCompletionContext::Kind K) {
836 case CodeCompletionContext::CCC_TopLevel:
837 case CodeCompletionContext::CCC_ObjCInterface:
838 case CodeCompletionContext::CCC_ObjCImplementation:
839 case CodeCompletionContext::CCC_ObjCIvarList:
840 case CodeCompletionContext::CCC_ClassStructUnion:
841 case CodeCompletionContext::CCC_Statement:
842 case CodeCompletionContext::CCC_Expression:
843 case CodeCompletionContext::CCC_ObjCMessageReceiver:
844 case CodeCompletionContext::CCC_EnumTag:
845 case CodeCompletionContext::CCC_UnionTag:
846 case CodeCompletionContext::CCC_ClassOrStructTag:
847 case CodeCompletionContext::CCC_ObjCProtocolName:
848 case CodeCompletionContext::CCC_Namespace:
849 case CodeCompletionContext::CCC_Type:
850 case CodeCompletionContext::CCC_ParenthesizedExpression:
851 case CodeCompletionContext::CCC_ObjCInterfaceName:
852 case CodeCompletionContext::CCC_Symbol:
853 case CodeCompletionContext::CCC_SymbolOrNewName:
854 case CodeCompletionContext::CCC_ObjCClassForwardDecl:
855 case CodeCompletionContext::CCC_TopLevelOrExpression:
857 case CodeCompletionContext::CCC_OtherWithMacros:
858 case CodeCompletionContext::CCC_DotMemberAccess:
859 case CodeCompletionContext::CCC_ArrowMemberAccess:
860 case CodeCompletionContext::CCC_ObjCCategoryName:
861 case CodeCompletionContext::CCC_ObjCPropertyAccess:
862 case CodeCompletionContext::CCC_MacroName:
863 case CodeCompletionContext::CCC_MacroNameUse:
864 case CodeCompletionContext::CCC_PreprocessorExpression:
865 case CodeCompletionContext::CCC_PreprocessorDirective:
866 case CodeCompletionContext::CCC_SelectorName:
867 case CodeCompletionContext::CCC_TypeQualifiers:
868 case CodeCompletionContext::CCC_ObjCInstanceMessage:
869 case CodeCompletionContext::CCC_ObjCClassMessage:
870 case CodeCompletionContext::CCC_IncludedFile:
871 case CodeCompletionContext::CCC_Attribute:
873 case CodeCompletionContext::CCC_Other:
874 case CodeCompletionContext::CCC_NaturalLanguage:
875 case CodeCompletionContext::CCC_Recovery:
876 case CodeCompletionContext::CCC_NewName:
879 llvm_unreachable(
"unknown code completion context");
882static bool isInjectedClass(
const NamedDecl &D) {
883 if (
auto *R = dyn_cast_or_null<CXXRecordDecl>(&D))
884 if (R->isInjectedClassName())
890static bool isExcludedMember(
const NamedDecl &D) {
893 if (D.getKind() == Decl::CXXDestructor)
896 if (isInjectedClass(D))
899 auto NameKind = D.getDeclName().getNameKind();
900 if (NameKind == DeclarationName::CXXOperatorName ||
901 NameKind == DeclarationName::CXXLiteralOperatorName ||
902 NameKind == DeclarationName::CXXConversionFunctionName)
913struct CompletionRecorder :
public CodeCompleteConsumer {
914 CompletionRecorder(
const CodeCompleteOptions &Opts,
915 llvm::unique_function<
void()> ResultsCallback)
916 : CodeCompleteConsumer(Opts.getClangCompleteOpts()),
917 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
918 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
919 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
920 assert(this->ResultsCallback);
923 std::vector<CodeCompletionResult> Results;
924 CodeCompletionContext CCContext;
925 Sema *CCSema =
nullptr;
928 void ProcessCodeCompleteResults(
class Sema &S, CodeCompletionContext Context,
929 CodeCompletionResult *InResults,
930 unsigned NumResults)
final {
939 CodeCompletionContext::Kind ContextKind = Context.getKind();
940 if (ContextKind == CodeCompletionContext::CCC_Recovery) {
941 log(
"Code complete: Ignoring sema code complete callback with Recovery "
948 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
951 log(
"Multiple code complete callbacks (parser backtracked?). "
952 "Dropping results from context {0}, keeping results from {1}.",
953 getCompletionKindString(Context.getKind()),
954 getCompletionKindString(this->CCContext.getKind()));
962 for (
unsigned I = 0; I < NumResults; ++I) {
963 auto &Result = InResults[I];
966 Result.Kind == CodeCompletionResult::RK_Pattern &&
968 ContextKind != CodeCompletionContext::CCC_IncludedFile)
971 if (Result.Hidden && Result.Declaration &&
972 Result.Declaration->isCXXClassMember())
974 if (!Opts.IncludeIneligibleResults &&
975 (Result.Availability == CXAvailability_NotAvailable ||
976 Result.Availability == CXAvailability_NotAccessible))
978 if (Result.Declaration &&
979 !Context.getBaseType().isNull()
980 && isExcludedMember(*Result.Declaration))
984 if (Result.Declaration && !Context.getCXXScopeSpecifier() &&
985 isInjectedClass(*Result.Declaration))
988 Result.StartsNestedNameSpecifier =
false;
989 Results.push_back(Result);
994 CodeCompletionAllocator &getAllocator()
override {
return *CCAllocator; }
995 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
999 llvm::StringRef getName(
const CodeCompletionResult &Result) {
1000 switch (Result.Kind) {
1001 case CodeCompletionResult::RK_Declaration:
1002 if (
auto *ID = Result.Declaration->getIdentifier())
1003 return ID->getName();
1005 case CodeCompletionResult::RK_Keyword:
1006 return Result.Keyword;
1007 case CodeCompletionResult::RK_Macro:
1008 return Result.Macro->getName();
1009 case CodeCompletionResult::RK_Pattern:
1012 auto *CCS = codeCompletionString(Result);
1013 const CodeCompletionString::Chunk *OnlyText =
nullptr;
1014 for (
auto &C : *CCS) {
1015 if (C.Kind != CodeCompletionString::CK_TypedText)
1018 return CCAllocator->CopyString(CCS->getAllTypedText());
1021 return OnlyText ? OnlyText->Text : llvm::StringRef();
1026 CodeCompletionString *codeCompletionString(
const CodeCompletionResult &R) {
1028 return const_cast<CodeCompletionResult &
>(R).CreateCodeCompletionString(
1029 *CCSema, CCContext, *CCAllocator, CCTUInfo,
1034 CodeCompleteOptions Opts;
1035 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
1036 CodeCompletionTUInfo CCTUInfo;
1037 llvm::unique_function<void()> ResultsCallback;
1040struct ScoredSignature {
1044 SignatureInformation Signature;
1045 SignatureQualitySignals Quality;
1053int paramIndexForArg(
const CodeCompleteConsumer::OverloadCandidate &Candidate,
1055 int NumParams = Candidate.getNumParams();
1056 if (
auto *T = Candidate.getFunctionType()) {
1057 if (
auto *Proto = T->getAs<FunctionProtoType>()) {
1058 if (Proto->isVariadic())
1062 return std::min(Arg, std::max(NumParams - 1, 0));
1065class SignatureHelpCollector final :
public CodeCompleteConsumer {
1067 SignatureHelpCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1068 MarkupKind DocumentationFormat,
1069 const SymbolIndex *Index, SignatureHelp &SigHelp)
1070 : CodeCompleteConsumer(CodeCompleteOpts), SigHelp(SigHelp),
1071 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1072 CCTUInfo(Allocator), Index(Index),
1073 DocumentationFormat(DocumentationFormat) {}
1075 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1076 OverloadCandidate *Candidates,
1077 unsigned NumCandidates,
1078 SourceLocation OpenParLoc,
1079 bool Braced)
override {
1080 assert(!OpenParLoc.isInvalid());
1081 SourceManager &SrcMgr = S.getSourceManager();
1082 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
1083 if (SrcMgr.isInMainFile(OpenParLoc))
1086 elog(
"Location oustide main file in signature help: {0}",
1087 OpenParLoc.printToString(SrcMgr));
1089 std::vector<ScoredSignature> ScoredSignatures;
1090 SigHelp.signatures.reserve(NumCandidates);
1091 ScoredSignatures.reserve(NumCandidates);
1095 SigHelp.activeSignature = 0;
1096 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1097 "too many arguments");
1099 SigHelp.activeParameter =
static_cast<int>(CurrentArg);
1101 for (
unsigned I = 0; I < NumCandidates; ++I) {
1102 OverloadCandidate Candidate = Candidates[I];
1106 if (
auto *Func = Candidate.getFunction()) {
1107 if (
auto *Pattern = Func->getTemplateInstantiationPattern())
1108 Candidate = OverloadCandidate(Pattern);
1110 if (
static_cast<int>(I) == SigHelp.activeSignature) {
1115 SigHelp.activeParameter =
1116 paramIndexForArg(Candidate, SigHelp.activeParameter);
1119 const auto *CCS = Candidate.CreateSignatureString(
1120 CurrentArg, S, *Allocator, CCTUInfo,
1122 assert(CCS &&
"Expected the CodeCompletionString to be non-null");
1123 ScoredSignatures.push_back(processOverloadCandidate(
1125 Candidate.getFunction()
1132 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
1134 LookupRequest IndexRequest;
1135 for (
const auto &S : ScoredSignatures) {
1138 IndexRequest.IDs.insert(S.IDForDoc);
1140 Index->lookup(IndexRequest, [&](
const Symbol &S) {
1141 if (!S.Documentation.empty())
1142 FetchedDocs[S.ID] = std::string(S.Documentation);
1144 vlog(
"SigHelp: requested docs for {0} symbols from the index, got {1} "
1145 "symbols with non-empty docs in the response",
1146 IndexRequest.IDs.size(), FetchedDocs.size());
1149 llvm::sort(ScoredSignatures, [](
const ScoredSignature &L,
1150 const ScoredSignature &R) {
1157 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
1158 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
1159 if (L.Quality.NumberOfOptionalParameters !=
1160 R.Quality.NumberOfOptionalParameters)
1161 return L.Quality.NumberOfOptionalParameters <
1162 R.Quality.NumberOfOptionalParameters;
1163 if (L.Quality.Kind != R.Quality.Kind) {
1164 using OC = CodeCompleteConsumer::OverloadCandidate;
1165 auto KindPriority = [&](OC::CandidateKind K) {
1167 case OC::CK_Aggregate:
1169 case OC::CK_Function:
1171 case OC::CK_FunctionType:
1173 case OC::CK_FunctionProtoTypeLoc:
1175 case OC::CK_FunctionTemplate:
1177 case OC::CK_Template:
1180 llvm_unreachable(
"Unknown overload candidate type.");
1182 return KindPriority(L.Quality.Kind) < KindPriority(R.Quality.Kind);
1184 if (L.Signature.label.size() != R.Signature.label.size())
1185 return L.Signature.label.size() < R.Signature.label.size();
1186 return L.Signature.label < R.Signature.label;
1189 for (
auto &SS : ScoredSignatures) {
1191 SS.IDForDoc ? FetchedDocs.find(SS.IDForDoc) : FetchedDocs.end();
1192 if (IndexDocIt != FetchedDocs.end()) {
1193 markup::Document SignatureComment;
1195 SS.Signature.documentation =
1196 renderDoc(SignatureComment, DocumentationFormat);
1199 SigHelp.signatures.push_back(std::move(SS.Signature));
1203 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1205 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1208 void processParameterChunk(llvm::StringRef ChunkText,
1209 SignatureInformation &Signature)
const {
1211 unsigned ParamStartOffset =
lspLength(Signature.label);
1212 unsigned ParamEndOffset = ParamStartOffset +
lspLength(ChunkText);
1216 Signature.label += ChunkText;
1217 ParameterInformation
Info;
1218 Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset);
1220 Info.labelString = std::string(ChunkText);
1222 Signature.parameters.push_back(std::move(
Info));
1225 void processOptionalChunk(
const CodeCompletionString &CCS,
1226 SignatureInformation &Signature,
1227 SignatureQualitySignals &Signal)
const {
1228 for (
const auto &Chunk : CCS) {
1229 switch (Chunk.Kind) {
1230 case CodeCompletionString::CK_Optional:
1231 assert(Chunk.Optional &&
1232 "Expected the optional code completion string to be non-null.");
1233 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1235 case CodeCompletionString::CK_VerticalSpace:
1237 case CodeCompletionString::CK_CurrentParameter:
1238 case CodeCompletionString::CK_Placeholder:
1239 processParameterChunk(Chunk.Text, Signature);
1240 Signal.NumberOfOptionalParameters++;
1243 Signature.label += Chunk.Text;
1251 ScoredSignature processOverloadCandidate(
const OverloadCandidate &Candidate,
1252 const CodeCompletionString &CCS,
1253 llvm::StringRef DocComment)
const {
1254 SignatureInformation Signature;
1255 SignatureQualitySignals Signal;
1256 const char *ReturnType =
nullptr;
1258 markup::Document OverloadComment;
1260 Signature.documentation = renderDoc(OverloadComment, DocumentationFormat);
1261 Signal.Kind = Candidate.getKind();
1263 for (
const auto &Chunk : CCS) {
1264 switch (Chunk.Kind) {
1265 case CodeCompletionString::CK_ResultType:
1268 assert(!ReturnType &&
"Unexpected CK_ResultType");
1269 ReturnType = Chunk.Text;
1271 case CodeCompletionString::CK_CurrentParameter:
1272 case CodeCompletionString::CK_Placeholder:
1273 processParameterChunk(Chunk.Text, Signature);
1274 Signal.NumberOfParameters++;
1276 case CodeCompletionString::CK_Optional: {
1278 assert(Chunk.Optional &&
1279 "Expected the optional code completion string to be non-null.");
1280 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1283 case CodeCompletionString::CK_VerticalSpace:
1286 Signature.label += Chunk.Text;
1291 Signature.label +=
" -> ";
1292 Signature.label += ReturnType;
1294 dlog(
"Signal for {0}: {1}", Signature, Signal);
1295 ScoredSignature Result;
1296 Result.Signature = std::move(Signature);
1297 Result.Quality = Signal;
1298 const FunctionDecl *Func = Candidate.getFunction();
1299 if (Func && Result.Signature.documentation.value.empty()) {
1307 SignatureHelp &SigHelp;
1308 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1309 CodeCompletionTUInfo CCTUInfo;
1310 const SymbolIndex *Index;
1311 MarkupKind DocumentationFormat;
1316class ParamNameCollector final :
public CodeCompleteConsumer {
1318 ParamNameCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1319 std::set<std::string> &ParamNames)
1320 : CodeCompleteConsumer(CodeCompleteOpts),
1321 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1322 CCTUInfo(Allocator), ParamNames(ParamNames) {}
1324 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1325 OverloadCandidate *Candidates,
1326 unsigned NumCandidates,
1327 SourceLocation OpenParLoc,
1328 bool Braced)
override {
1329 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1330 "too many arguments");
1332 for (
unsigned I = 0; I < NumCandidates; ++I) {
1333 if (
const NamedDecl *ND = Candidates[I].getParamDecl(CurrentArg))
1334 if (
const auto *II = ND->getIdentifier())
1335 ParamNames.emplace(II->getName());
1340 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1342 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1344 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1345 CodeCompletionTUInfo CCTUInfo;
1346 std::set<std::string> &ParamNames;
1349struct SemaCompleteInput {
1353 const std::optional<PreamblePatch> Patch;
1354 const ParseInputs &ParseInput;
1357void loadMainFilePreambleMacros(
const Preprocessor &PP,
1362 ExternalPreprocessorSource *PreambleMacros = PP.getExternalSource();
1365 const auto &ITable = PP.getIdentifierTable();
1366 IdentifierInfoLookup *PreambleIdentifiers =
1367 ITable.getExternalIdentifierLookup();
1369 if (!PreambleIdentifiers || !PreambleMacros)
1371 for (
const auto &MacroName :
Preamble.Macros.Names) {
1372 if (ITable.find(MacroName.getKey()) != ITable.end())
1374 if (
auto *II = PreambleIdentifiers->get(MacroName.getKey()))
1375 if (II->isOutOfDate())
1376 PreambleMacros->updateOutOfDateIdentifier(*II);
1382bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
1383 const clang::CodeCompleteOptions &Options,
1384 const SemaCompleteInput &Input,
1385 IncludeStructure *Includes =
nullptr) {
1386 trace::Span Tracer(
"Sema completion");
1388 IgnoreDiagnostics IgnoreDiags;
1391 elog(
"Couldn't create CompilerInvocation");
1394 auto &FrontendOpts = CI->getFrontendOpts();
1395 FrontendOpts.SkipFunctionBodies =
true;
1397 CI->getLangOpts().SpellChecking =
false;
1401 CI->getLangOpts().DelayedTemplateParsing =
false;
1403 FrontendOpts.CodeCompleteOpts = Options;
1404 FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName);
1405 std::tie(FrontendOpts.CodeCompletionAt.Line,
1406 FrontendOpts.CodeCompletionAt.Column) =
1409 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1410 llvm::MemoryBuffer::getMemBuffer(Input.ParseInput.Contents,
1413 CI->getDiagnosticOpts().IgnoreWarnings =
true;
1420 PreambleBounds PreambleRegion =
1421 ComputePreambleBounds(CI->getLangOpts(), *ContentsBuffer, 0);
1422 bool CompletingInPreamble = Input.Offset < PreambleRegion.Size ||
1423 (!PreambleRegion.PreambleEndsAtStartOfLine &&
1424 Input.Offset == PreambleRegion.Size);
1426 Input.Patch->apply(*CI);
1429 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1430 Input.ParseInput.TFS->view(Input.ParseInput.CompileCommand.Directory);
1431 if (Input.Preamble.StatCache)
1432 VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS));
1434 std::move(CI), !CompletingInPreamble ? &Input.Preamble.Preamble :
nullptr,
1435 std::move(ContentsBuffer), std::move(VFS), IgnoreDiags);
1436 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
1437 Clang->setCodeCompletionConsumer(Consumer.release());
1439 if (Input.Preamble.RequiredModules)
1440 Input.Preamble.RequiredModules->adjustHeaderSearchOptions(
1441 Clang->getHeaderSearchOpts());
1444 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1445 log(
"BeginSourceFile() failed when running codeComplete for {0}",
1455 loadMainFilePreambleMacros(Clang->getPreprocessor(), Input.Preamble);
1457 Includes->collect(*Clang);
1458 if (llvm::Error Err = Action.Execute()) {
1459 log(
"Execute() failed when running codeComplete for {0}: {1}",
1460 Input.FileName,
toString(std::move(Err)));
1463 Action.EndSourceFile();
1469bool allowIndex(CodeCompletionContext &CC) {
1470 if (!contextAllowsIndex(CC.getKind()))
1473 auto Scope = CC.getCXXScopeSpecifier();
1478 switch ((*Scope)->getScopeRep().getKind()) {
1479 case NestedNameSpecifier::Kind::Null:
1480 case NestedNameSpecifier::Kind::Global:
1481 case NestedNameSpecifier::Kind::Namespace:
1483 case NestedNameSpecifier::Kind::MicrosoftSuper:
1484 case NestedNameSpecifier::Kind::Type:
1487 llvm_unreachable(
"invalid NestedNameSpecifier kind");
1492bool includeSymbolFromIndex(CodeCompletionContext::Kind Kind,
1493 const Symbol &Sym) {
1497 if (Sym.SymInfo.Kind == index::SymbolKind::Protocol &&
1498 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC)
1499 return Kind == CodeCompletionContext::CCC_ObjCProtocolName;
1500 else if (Kind == CodeCompletionContext::CCC_ObjCProtocolName)
1504 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
1505 return Sym.SymInfo.Kind == index::SymbolKind::Class &&
1506 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC;
1510std::future<std::pair<bool, SymbolSlab>>
1511startAsyncFuzzyFind(
const SymbolIndex &Index,
const FuzzyFindRequest &Req) {
1513 trace::Span Tracer(
"Async fuzzyFind");
1514 SymbolSlab::Builder Syms;
1516 Index.fuzzyFind(Req, [&Syms](
const Symbol &Sym) { Syms.insert(Sym); });
1517 return std::make_pair(Incomplete, std::move(Syms).build());
1524FuzzyFindRequest speculativeFuzzyFindRequestForCompletion(
1525 FuzzyFindRequest CachedReq,
const CompletionPrefix &HeuristicPrefix) {
1526 CachedReq.Query = std::string(HeuristicPrefix.Name);
1534findTokenAfterCompletionPoint(SourceLocation CompletionPoint,
1535 const SourceManager &SM,
1536 const LangOptions &LangOpts) {
1537 SourceLocation Loc = CompletionPoint;
1538 if (Loc.isMacroID()) {
1539 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1540 return std::nullopt;
1548 Loc = Loc.getLocWithOffset(1);
1551 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1554 bool InvalidTemp =
false;
1555 StringRef
File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1557 return std::nullopt;
1559 const char *TokenBegin =
File.data() + LocInfo.second;
1562 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
File.begin(),
1563 TokenBegin,
File.end());
1566 TheLexer.LexFromRawLexer(Tok);
1599class CodeCompleteFlow {
1601 IncludeStructure Includes;
1602 SpeculativeFuzzyFind *SpecFuzzyFind;
1603 const CodeCompleteOptions &Opts;
1606 CompletionRecorder *Recorder =
nullptr;
1607 CodeCompletionContext::Kind CCContextKind = CodeCompletionContext::CCC_Other;
1608 bool IsUsingDeclaration =
false;
1612 tok::TokenKind NextTokenKind = tok::eof;
1614 int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
1615 bool Incomplete =
false;
1616 CompletionPrefix HeuristicPrefix;
1617 std::optional<FuzzyMatcher> Filter;
1618 Range ReplacedRange;
1619 std::vector<std::string> QueryScopes;
1620 std::vector<std::string> AccessibleScopes;
1622 std::optional<ScopeDistance> ScopeProximity;
1623 std::optional<OpaqueType> PreferredType;
1625 bool AllScopes =
false;
1626 llvm::StringSet<> ContextWords;
1629 std::optional<IncludeInserter> Inserter;
1630 std::optional<URIDistance> FileProximity;
1635 std::optional<FuzzyFindRequest> SpecReq;
1639 CodeCompleteFlow(
PathRef FileName,
const IncludeStructure &Includes,
1640 SpeculativeFuzzyFind *SpecFuzzyFind,
1641 const CodeCompleteOptions &Opts)
1642 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1645 CodeCompleteResult
run(
const SemaCompleteInput &SemaCCInput) && {
1646 trace::Span Tracer(
"CodeCompleteFlow");
1648 SemaCCInput.Offset);
1649 populateContextWords(SemaCCInput.ParseInput.Contents);
1650 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq) {
1651 assert(!SpecFuzzyFind->Result.valid());
1652 SpecReq = speculativeFuzzyFindRequestForCompletion(
1653 *SpecFuzzyFind->CachedReq, HeuristicPrefix);
1654 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1660 CodeCompleteResult Output;
1661 auto RecorderOwner = std::make_unique<CompletionRecorder>(Opts, [&]() {
1662 assert(Recorder &&
"Recorder is not set");
1663 CCContextKind = Recorder->CCContext.getKind();
1664 IsUsingDeclaration = Recorder->CCContext.isUsingDeclaration();
1666 SemaCCInput.ParseInput.Contents,
1667 *SemaCCInput.ParseInput.TFS,
false);
1668 const auto NextToken = findTokenAfterCompletionPoint(
1669 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc(),
1670 Recorder->CCSema->getSourceManager(), Recorder->CCSema->LangOpts);
1672 NextTokenKind = NextToken->getKind();
1676 SemaCCInput.FileName, SemaCCInput.ParseInput.Contents, Style,
1677 SemaCCInput.ParseInput.CompileCommand.Directory,
1678 &Recorder->CCSema->getPreprocessor().getHeaderSearchInfo(),
1681 for (
const auto &Inc : Includes.MainFileIncludes)
1682 Inserter->addExisting(Inc);
1688 FileDistanceOptions ProxOpts{};
1689 const auto &SM = Recorder->CCSema->getSourceManager();
1690 llvm::StringMap<SourceParams> ProxSources;
1692 Includes.getID(SM.getFileEntryForID(SM.getMainFileID()));
1694 for (
auto &HeaderIDAndDepth : Includes.includeDepth(*MainFileID)) {
1696 ProxSources[Includes.getRealPath(HeaderIDAndDepth.getFirst())];
1697 Source.Cost = HeaderIDAndDepth.getSecond() * ProxOpts.IncludeCost;
1701 if (HeaderIDAndDepth.getSecond() > 0)
1702 Source.MaxUpTraversals = 1;
1704 FileProximity.emplace(ProxSources, ProxOpts);
1706 Output = runWithSema();
1709 getCompletionKindString(CCContextKind));
1710 log(
"Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1711 "expected type {3}{4}",
1712 getCompletionKindString(CCContextKind),
1713 llvm::join(QueryScopes.begin(), QueryScopes.end(),
","), AllScopes,
1714 PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1716 IsUsingDeclaration ?
", inside using declaration" :
"");
1719 Recorder = RecorderOwner.get();
1721 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1722 SemaCCInput, &Includes);
1723 logResults(Output, Tracer);
1727 void logResults(
const CodeCompleteResult &Output,
const trace::Span &Tracer) {
1730 SPAN_ATTACH(Tracer,
"merged_results", NSemaAndIndex);
1731 SPAN_ATTACH(Tracer,
"identifier_results", NIdent);
1732 SPAN_ATTACH(Tracer,
"returned_results", int64_t(Output.Completions.size()));
1733 SPAN_ATTACH(Tracer,
"incomplete", Output.HasMore);
1734 log(
"Code complete: {0} results from Sema, {1} from Index, "
1735 "{2} matched, {3} from identifiers, {4} returned{5}.",
1736 NSema, NIndex, NSemaAndIndex, NIdent, Output.Completions.size(),
1737 Output.HasMore ?
" (incomplete)" :
"");
1738 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1743 CodeCompleteResult runWithoutSema(llvm::StringRef Content,
size_t Offset,
1744 const ThreadsafeFS &TFS) && {
1745 trace::Span Tracer(
"CodeCompleteWithoutSema");
1748 populateContextWords(Content);
1749 CCContextKind = CodeCompletionContext::CCC_Recovery;
1750 IsUsingDeclaration =
false;
1751 Filter = FuzzyMatcher(HeuristicPrefix.Name);
1753 ReplacedRange.start = ReplacedRange.end = Pos;
1754 ReplacedRange.start.character -= HeuristicPrefix.Name.size();
1756 llvm::StringMap<SourceParams> ProxSources;
1757 ProxSources[FileName].Cost = 0;
1758 FileProximity.emplace(ProxSources);
1762 Inserter.emplace(FileName, Content, Style,
1768 std::vector<RawIdentifier> IdentifierResults;
1769 for (
const auto &IDAndCount : Identifiers) {
1771 ID.Name = IDAndCount.first();
1772 ID.References = IDAndCount.second;
1774 if (ID.Name == HeuristicPrefix.Name)
1776 if (ID.References > 0)
1777 IdentifierResults.push_back(std::move(ID));
1783 SpecifiedScope Scopes;
1785 Content.take_front(Offset), format::getFormattingLangOpts(Style));
1786 for (std::string &S : Scopes.QueryScopes)
1789 if (HeuristicPrefix.Qualifier.empty())
1790 AllScopes = Opts.AllScopes;
1791 else if (HeuristicPrefix.Qualifier.starts_with(
"::")) {
1792 Scopes.QueryScopes = {
""};
1793 Scopes.UnresolvedQualifier =
1794 std::string(HeuristicPrefix.Qualifier.drop_front(2));
1796 Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier);
1798 QueryScopes = Scopes.scopesForIndexQuery();
1799 AccessibleScopes = QueryScopes;
1800 ScopeProximity.emplace(QueryScopes);
1802 SymbolSlab IndexResults = Opts.Index ? queryIndex() : SymbolSlab();
1804 CodeCompleteResult Output = toCodeCompleteResult(mergeResults(
1805 {}, IndexResults, IdentifierResults));
1806 Output.RanParser =
false;
1807 logResults(Output, Tracer);
1812 void populateContextWords(llvm::StringRef Content) {
1814 unsigned RangeEnd = HeuristicPrefix.Qualifier.begin() - Content.data(),
1815 RangeBegin = RangeEnd;
1816 for (
size_t I = 0; I < 3 && RangeBegin > 0; ++I) {
1817 auto PrevNL = Content.rfind(
'\n', RangeBegin);
1818 if (PrevNL == StringRef::npos) {
1822 RangeBegin = PrevNL;
1825 ContextWords =
collectWords(Content.slice(RangeBegin, RangeEnd));
1826 dlog(
"Completion context words: {0}",
1827 llvm::join(ContextWords.keys(),
", "));
1832 CodeCompleteResult runWithSema() {
1833 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1834 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1840 if (CodeCompletionRange.isValid()) {
1842 CodeCompletionRange);
1845 Recorder->CCSema->getSourceManager(),
1846 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1847 ReplacedRange.start = ReplacedRange.end = Pos;
1849 Filter = FuzzyMatcher(
1850 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1851 auto SpecifiedScopes = getQueryScopes(
1852 Recorder->CCContext, *Recorder->CCSema, HeuristicPrefix, Opts);
1854 QueryScopes = SpecifiedScopes.scopesForIndexQuery();
1855 AccessibleScopes = SpecifiedScopes.scopesForQualification();
1856 AllScopes = SpecifiedScopes.AllowAllScopes;
1857 if (!QueryScopes.empty())
1858 ScopeProximity.emplace(QueryScopes);
1861 Recorder->CCContext.getPreferredType());
1867 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1870 trace::Span Tracer(
"Populate CodeCompleteResult");
1873 mergeResults(Recorder->Results, IndexResults, {});
1874 return toCodeCompleteResult(Top);
1878 toCodeCompleteResult(
const std::vector<ScoredBundle> &Scored) {
1879 CodeCompleteResult Output;
1884 llvm::DenseMap<SymbolID, uint32_t> SymbolToCompletion;
1885 for (
auto &C : Scored) {
1886 Output.Completions.push_back(toCodeCompletion(C.first));
1887 Output.Completions.back().Score = C.second;
1888 Output.Completions.back().CompletionTokenRange = ReplacedRange;
1889 if (Opts.Index && !Output.Completions.back().Documentation) {
1890 for (
auto &Cand : C.first) {
1891 if (Cand.SemaResult &&
1892 Cand.SemaResult->Kind == CodeCompletionResult::RK_Declaration) {
1893 const NamedDecl *DeclToLookup = Cand.SemaResult->getDeclaration();
1897 if (
const NamedDecl *Adjusted =
1898 dyn_cast<NamedDecl>(&adjustDeclToTemplate(*DeclToLookup))) {
1899 DeclToLookup = Adjusted;
1905 SymbolToCompletion[ID] = Output.Completions.size() - 1;
1910 Output.HasMore = Incomplete;
1911 Output.Context = CCContextKind;
1912 Output.CompletionRange = ReplacedRange;
1916 Opts.Index->lookup(Req, [&](
const Symbol &S) {
1917 if (S.Documentation.empty())
1919 auto &C = Output.Completions[SymbolToCompletion.at(S.ID)];
1920 C.Documentation.emplace();
1928 SymbolSlab queryIndex() {
1929 trace::Span Tracer(
"Query index");
1930 SPAN_ATTACH(Tracer,
"limit", int64_t(Opts.Limit));
1933 FuzzyFindRequest Req;
1935 Req.Limit = Opts.Limit;
1936 Req.Query = std::string(Filter->pattern());
1937 Req.RestrictForCodeCompletion =
true;
1938 Req.Scopes = QueryScopes;
1939 Req.AnyScope = AllScopes;
1941 Req.ProximityPaths.push_back(std::string(FileName));
1943 Req.PreferredTypes.push_back(std::string(PreferredType->raw()));
1944 vlog(
"Code complete: fuzzyFind({0:2})",
toJSON(Req));
1947 SpecFuzzyFind->NewReq = Req;
1948 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1949 vlog(
"Code complete: speculative fuzzy request matches the actual index "
1950 "request. Waiting for the speculative index results.");
1953 trace::Span WaitSpec(
"Wait speculative results");
1954 auto SpecRes = SpecFuzzyFind->Result.get();
1955 Incomplete |= SpecRes.first;
1956 return std::move(SpecRes.second);
1959 SPAN_ATTACH(Tracer,
"Speculative results",
false);
1962 SymbolSlab::Builder ResultsBuilder;
1963 Incomplete |= Opts.Index->fuzzyFind(
1964 Req, [&](
const Symbol &Sym) { ResultsBuilder.insert(Sym); });
1965 return std::move(ResultsBuilder).build();
1973 std::vector<ScoredBundle>
1974 mergeResults(
const std::vector<CodeCompletionResult> &SemaResults,
1975 const SymbolSlab &IndexResults,
1976 const std::vector<RawIdentifier> &IdentifierResults) {
1977 trace::Span Tracer(
"Merge and score results");
1978 std::vector<CompletionCandidate::Bundle> Bundles;
1979 llvm::DenseMap<size_t, size_t> BundleLookup;
1980 auto AddToBundles = [&](
const CodeCompletionResult *SemaResult,
1981 const Symbol *IndexResult,
1982 const RawIdentifier *IdentifierResult) {
1983 CompletionCandidate C;
1984 C.SemaResult = SemaResult;
1985 C.IndexResult = IndexResult;
1986 C.IdentifierResult = IdentifierResult;
1987 if (C.IndexResult) {
1988 C.Name = IndexResult->Name;
1990 }
else if (C.SemaResult) {
1991 C.Name = Recorder->getName(*SemaResult);
1993 assert(IdentifierResult);
1994 C.Name = IdentifierResult->Name;
1996 if (
auto OverloadSet = C.overloadSet(
1997 Opts, FileName, Inserter ? &*Inserter :
nullptr, CCContextKind)) {
1998 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
2000 Bundles.emplace_back();
2001 Bundles[Ret.first->second].push_back(std::move(C));
2003 Bundles.emplace_back();
2004 Bundles.back().push_back(std::move(C));
2007 llvm::DenseSet<const Symbol *> UsedIndexResults;
2008 auto CorrespondingIndexResult =
2009 [&](
const CodeCompletionResult &SemaResult) ->
const Symbol * {
2011 getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
2012 auto I = IndexResults.find(SymID);
2013 if (I != IndexResults.end()) {
2014 UsedIndexResults.insert(&*I);
2021 for (
auto &SemaResult : SemaResults)
2022 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult),
nullptr);
2024 for (
const auto &IndexResult : IndexResults) {
2025 if (UsedIndexResults.count(&IndexResult))
2027 if (!includeSymbolFromIndex(CCContextKind, IndexResult))
2029 AddToBundles(
nullptr, &IndexResult,
nullptr);
2032 for (
const auto &Ident : IdentifierResults)
2033 AddToBundles(
nullptr,
nullptr, &Ident);
2035 TopN<ScoredBundle, ScoredBundleGreater> Top(
2036 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
2037 for (
auto &Bundle : Bundles)
2038 addCandidate(Top, std::move(Bundle));
2039 return std::move(Top).items();
2042 std::optional<float> fuzzyScore(
const CompletionCandidate &C) {
2045 const auto IsMacroResult =
2047 C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
2049 C.IndexResult->SymInfo.Kind == index::SymbolKind::Macro));
2052 return Filter->match(C.Name);
2055 bool RequireExactPrefix =
2056 Opts.MacroFilter == MacroFilterPolicy::ExactPrefix ||
2057 C.Name.starts_with_insensitive(
"_") ||
2058 C.Name.ends_with_insensitive(
"_");
2060 if (RequireExactPrefix &&
2061 !C.Name.starts_with_insensitive(Filter->pattern())) {
2062 return std::nullopt;
2065 return Filter->match(C.Name);
2068 CodeCompletion::Scores
2069 evaluateCompletion(
const SymbolQualitySignals &Quality,
2070 const SymbolRelevanceSignals &Relevance) {
2071 using RM = CodeCompleteOptions::CodeCompletionRankingModel;
2072 CodeCompletion::Scores Scores;
2073 switch (Opts.RankingModel) {
2074 case RM::Heuristics:
2075 Scores.Quality = Quality.evaluateHeuristics();
2076 Scores.Relevance = Relevance.evaluateHeuristics();
2081 Scores.ExcludingName =
2082 Relevance.NameMatch > std::numeric_limits<float>::epsilon()
2083 ? Scores.Total / Relevance.NameMatch
2087 case RM::DecisionForest:
2088 DecisionForestScores DFScores = Opts.DecisionForestScorer(
2089 Quality, Relevance, Opts.DecisionForestBase);
2090 Scores.ExcludingName = DFScores.ExcludingName;
2091 Scores.Total = DFScores.Total;
2094 llvm_unreachable(
"Unhandled CodeCompletion ranking model.");
2098 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
2099 CompletionCandidate::Bundle Bundle) {
2100 SymbolQualitySignals Quality;
2101 SymbolRelevanceSignals Relevance;
2102 Relevance.Context = CCContextKind;
2103 Relevance.Name = Bundle.front().Name;
2104 Relevance.FilterLength = HeuristicPrefix.Name.size();
2106 Relevance.FileProximityMatch = &*FileProximity;
2108 Relevance.ScopeProximityMatch = &*ScopeProximity;
2110 Relevance.HadContextType =
true;
2111 Relevance.ContextWords = &ContextWords;
2112 Relevance.MainFileSignals = Opts.MainFileSignals;
2114 auto &First = Bundle.front();
2115 if (
auto FuzzyScore = fuzzyScore(First))
2116 Relevance.NameMatch = *FuzzyScore;
2120 bool FromIndex =
false;
2121 for (
const auto &Candidate : Bundle) {
2122 if (Candidate.IndexResult) {
2123 Quality.merge(*Candidate.IndexResult);
2124 Relevance.merge(*Candidate.IndexResult);
2125 Origin |= Candidate.IndexResult->Origin;
2127 if (!Candidate.IndexResult->Type.empty())
2128 Relevance.HadSymbolType |=
true;
2129 if (PreferredType &&
2130 PreferredType->raw() == Candidate.IndexResult->Type) {
2131 Relevance.TypeMatchesPreferred =
true;
2134 if (Candidate.SemaResult) {
2135 Quality.merge(*Candidate.SemaResult);
2136 Relevance.merge(*Candidate.SemaResult);
2137 if (PreferredType) {
2139 Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
2140 Relevance.HadSymbolType |=
true;
2141 if (PreferredType == CompletionType)
2142 Relevance.TypeMatchesPreferred =
true;
2147 if (Candidate.IdentifierResult) {
2148 Quality.References = Candidate.IdentifierResult->References;
2154 CodeCompletion::Scores Scores = evaluateCompletion(Quality, Relevance);
2155 if (Opts.RecordCCResult)
2156 Opts.RecordCCResult(toCodeCompletion(Bundle), Quality, Relevance,
2159 dlog(
"CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
2160 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
2161 llvm::to_string(Relevance));
2164 NIndex += FromIndex;
2167 if (Candidates.push({std::move(Bundle), Scores}))
2171 CodeCompletion toCodeCompletion(
const CompletionCandidate::Bundle &Bundle) {
2172 std::optional<CodeCompletionBuilder> Builder;
2173 for (
const auto &Item : Bundle) {
2174 CodeCompletionString *SemaCCS =
2175 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
2178 Builder.emplace(Recorder ? &Recorder->CCSema->getASTContext() :
nullptr,
2179 Item, SemaCCS, AccessibleScopes, *Inserter, FileName,
2180 CCContextKind, Opts, IsUsingDeclaration, NextTokenKind);
2182 Builder->add(Item, SemaCCS, CCContextKind);
2184 return Builder->build();
2191 clang::CodeCompleteOptions
Result;
2192 Result.IncludeCodePatterns =
2194 Result.IncludeMacros =
true;
2195 Result.IncludeGlobals =
true;
2200 Result.IncludeBriefComments =
false;
2205 Result.LoadExternal = ForceLoadPreamble || !Index;
2206 Result.IncludeFixIts = IncludeFixIts;
2213 assert(Offset <= Content.size());
2214 StringRef Rest = Content.take_front(Offset);
2219 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2220 Rest = Rest.drop_back();
2221 Result.
Name = Content.slice(Rest.size(), Offset);
2224 while (Rest.consume_back(
"::") && !Rest.ends_with(
":"))
2225 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2226 Rest = Rest.drop_back();
2228 Content.slice(Rest.size(), Result.
Name.begin() - Content.begin());
2237 llvm::StringRef Prefix,
2241 return CodeCompleteResult();
2243 clang::CodeCompleteOptions Options;
2244 Options.IncludeGlobals =
false;
2245 Options.IncludeMacros =
false;
2246 Options.IncludeCodePatterns =
false;
2247 Options.IncludeBriefComments =
false;
2248 std::set<std::string> ParamNames;
2252 std::make_unique<ParamNameCollector>(Options, ParamNames), Options,
2256 if (ParamNames.empty())
2257 return CodeCompleteResult();
2259 CodeCompleteResult Result;
2260 Range CompletionRange;
2264 CompletionRange.
end =
2266 Result.CompletionRange = CompletionRange;
2267 Result.Context = CodeCompletionContext::CCC_NaturalLanguage;
2268 for (llvm::StringRef Name : ParamNames) {
2269 if (!Name.starts_with(Prefix))
2271 CodeCompletion Item;
2272 Item.Name = Name.str() +
"=*/";
2273 Item.FilterText = Item.Name;
2275 Item.CompletionTokenRange = CompletionRange;
2277 Result.Completions.push_back(Item);
2286std::optional<unsigned>
2288 while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
2289 Content = Content.drop_back();
2290 Content = Content.rtrim();
2291 if (Content.ends_with(
"/*"))
2292 return Content.size() - 2;
2293 return std::nullopt;
2300 SpeculativeFuzzyFind *SpecFuzzyFind) {
2303 elog(
"Code completion position was invalid {0}", Offset.takeError());
2304 return CodeCompleteResult();
2307 auto Content = llvm::StringRef(ParseInput.
Contents).take_front(*Offset);
2314 auto CommentPrefix = Content.substr(*OffsetBeforeComment + 2).trim();
2319 auto Flow = CodeCompleteFlow(
2321 SpecFuzzyFind, Opts);
2322 return (!
Preamble || Opts.RunParser == CodeCompleteOptions::NeverParse)
2323 ? std::move(Flow).runWithoutSema(ParseInput.
Contents, *Offset,
2325 : std::move(Flow).run({FileName, *Offset, *
Preamble,
2338 elog(
"Signature help position was invalid {0}", Offset.takeError());
2342 clang::CodeCompleteOptions Options;
2343 Options.IncludeGlobals =
false;
2344 Options.IncludeMacros =
false;
2345 Options.IncludeCodePatterns =
false;
2346 Options.IncludeBriefComments =
false;
2348 std::make_unique<SignatureHelpCollector>(Options, DocumentationFormat,
2349 ParseInput.
Index, Result),
2351 {FileName, *Offset, Preamble,
2352 PreamblePatch::createFullPatch(FileName, ParseInput, Preamble),
2358 auto InTopLevelScope = [](
const NamedDecl &ND) {
2359 switch (ND.getDeclContext()->getDeclKind()) {
2360 case Decl::TranslationUnit:
2361 case Decl::Namespace:
2362 case Decl::LinkageSpec:
2369 auto InClassScope = [](
const NamedDecl &ND) {
2370 return ND.getDeclContext()->getDeclKind() == Decl::CXXRecord;
2381 if (llvm::isa<ObjCCategoryDecl>(&ND) || llvm::isa<ObjCCategoryImplDecl>(&ND))
2384 if (InTopLevelScope(ND))
2390 if (
const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
2391 return (InTopLevelScope(*EnumDecl) || InClassScope(*EnumDecl));
2396CompletionItem CodeCompletion::render(
const CodeCompleteOptions &Opts)
const {
2398 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
2401 LSP.label = ((InsertInclude && InsertInclude->Insertion)
2402 ? Opts.IncludeIndicator.Insert
2403 : Opts.IncludeIndicator.NoInsert) +
2404 (Opts.ShowOrigins ?
"[" + llvm::to_string(Origin) +
"]" :
"") +
2405 RequiredQualifier + Name;
2406 LSP.labelDetails.emplace();
2407 LSP.labelDetails->detail = Signature;
2410 LSP.detail = BundleSize > 1
2411 ? std::string(llvm::formatv(
"[{0} overloads]", BundleSize))
2416 if (InsertInclude || Documentation) {
2417 markup::Document Doc;
2419 Doc.addParagraph().appendText(
"From ").appendCode(InsertInclude->Header);
2421 Doc.append(*Documentation);
2422 LSP.documentation = renderDoc(Doc, Opts.DocumentationFormat);
2424 LSP.sortText =
sortText(Score.Total, FilterText);
2425 LSP.filterText = FilterText;
2426 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name,
""};
2434 for (
const auto &FixIt : FixIts) {
2435 if (FixIt.range.end == LSP.textEdit->range.start) {
2436 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
2437 LSP.textEdit->range.start = FixIt.range.start;
2439 LSP.additionalTextEdits.push_back(FixIt);
2442 if (Opts.EnableSnippets)
2443 LSP.textEdit->newText += SnippetSuffix;
2447 LSP.insertText = LSP.textEdit->newText;
2451 LSP.insertTextFormat = (Opts.EnableSnippets && !SnippetSuffix.empty())
2454 if (InsertInclude && InsertInclude->Insertion)
2455 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
2457 LSP.score = Score.ExcludingName;
2462llvm::raw_ostream &
operator<<(llvm::raw_ostream &OS,
const CodeCompletion &C) {
2463 OS <<
"Signature: " <<
"\"" << C.Signature <<
"\", "
2464 <<
"SnippetSuffix: " <<
"\"" << C.SnippetSuffix <<
"\""
2471 const CodeCompleteResult &R) {
2472 OS <<
"CodeCompleteResult: " << R.Completions.size() << (R.HasMore ?
"+" :
"")
2473 <<
" (" << getCompletionKindString(R.Context) <<
")"
2475 for (
const auto &C : R.Completions)
2482 Line = Line.ltrim();
2483 if (!Line.consume_front(
"#"))
2485 Line = Line.ltrim();
2486 if (!(Line.consume_front(
"include_next") || Line.consume_front(
"include") ||
2487 Line.consume_front(
"import")))
2489 Line = Line.ltrim();
2490 if (Line.consume_front(
"<"))
2491 return Line.count(
'>') == 0;
2492 if (Line.consume_front(
"\""))
2493 return Line.count(
'"') == 0;
2499 Content = Content.take_front(Offset);
2500 auto Pos = Content.rfind(
'\n');
2501 if (Pos != llvm::StringRef::npos)
2502 Content = Content.substr(Pos + 1);
2505 if (Content.ends_with(
".") || Content.ends_with(
"->") ||
2506 Content.ends_with(
"::") || Content.ends_with(
"/*"))
2509 if ((Content.ends_with(
"<") || Content.ends_with(
"\"") ||
2510 Content.ends_with(
"/")) &&
2515 return !Content.empty() && (isAsciiIdentifierContinue(Content.back()) ||
2516 !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"