44#include "clang/AST/Decl.h"
45#include "clang/AST/DeclBase.h"
46#include "clang/AST/DeclTemplate.h"
47#include "clang/Basic/CharInfo.h"
48#include "clang/Basic/LangOptions.h"
49#include "clang/Basic/SourceLocation.h"
50#include "clang/Basic/TokenKinds.h"
51#include "clang/Format/Format.h"
52#include "clang/Frontend/CompilerInstance.h"
53#include "clang/Frontend/FrontendActions.h"
54#include "clang/Lex/ExternalPreprocessorSource.h"
55#include "clang/Lex/Lexer.h"
56#include "clang/Lex/Preprocessor.h"
57#include "clang/Lex/PreprocessorOptions.h"
58#include "clang/Sema/CodeCompleteConsumer.h"
59#include "clang/Sema/DeclSpec.h"
60#include "clang/Sema/Sema.h"
61#include "llvm/ADT/ArrayRef.h"
62#include "llvm/ADT/SmallVector.h"
63#include "llvm/ADT/StringExtras.h"
64#include "llvm/ADT/StringRef.h"
65#include "llvm/Support/Casting.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/Debug.h"
68#include "llvm/Support/Error.h"
69#include "llvm/Support/FormatVariadic.h"
70#include "llvm/Support/ScopedPrinter.h"
78#define DEBUG_TYPE "CodeComplete"
83#if CLANGD_DECISION_FOREST
84const CodeCompleteOptions::CodeCompletionRankingModel
85 CodeCompleteOptions::DefaultRankingModel =
86 CodeCompleteOptions::DecisionForest;
88const CodeCompleteOptions::CodeCompletionRankingModel
89 CodeCompleteOptions::DefaultRankingModel = CodeCompleteOptions::Heuristics;
97toCompletionItemKind(index::SymbolKind Kind,
98 const llvm::StringRef *Signature =
nullptr) {
99 using SK = index::SymbolKind;
103 case SK::IncludeDirective:
108 case SK::NamespaceAlias:
135 case SK::ConversionFunction:
139 case SK::NonTypeTemplateParm:
143 case SK::EnumConstant:
145 case SK::InstanceMethod:
146 case SK::ClassMethod:
147 case SK::StaticMethod:
150 case SK::InstanceProperty:
151 case SK::ClassProperty:
152 case SK::StaticProperty:
154 case SK::Constructor:
156 case SK::TemplateTypeParm:
157 case SK::TemplateTemplateParm:
162 llvm_unreachable(
"Unhandled clang::index::SymbolKind.");
167CompletionItemKind toCompletionItemKind(
const CodeCompletionResult &Res,
168 CodeCompletionContext::Kind CtxKind) {
170 return toCompletionItemKind(index::getSymbolInfo(Res.Declaration).Kind);
171 if (CtxKind == CodeCompletionContext::CCC_IncludedFile)
174 case CodeCompletionResult::RK_Declaration:
175 llvm_unreachable(
"RK_Declaration without Decl");
176 case CodeCompletionResult::RK_Keyword:
178 case CodeCompletionResult::RK_Macro:
182 return Res.MacroDefInfo && Res.MacroDefInfo->isFunctionLike()
185 case CodeCompletionResult::RK_Pattern:
188 llvm_unreachable(
"Unhandled CodeCompletionResult::ResultKind.");
192MarkupContent renderDoc(
const markup::Document &Doc, MarkupKind Kind) {
193 MarkupContent Result;
197 Result.value.append(Doc.asPlainText());
202 Result.value.append(Doc.asEscapedMarkdown());
204 Result.value.append(Doc.asMarkdown());
211 if (!Opts.ImportInsertions || !Opts.MainFileSignals)
213 return Opts.MainFileSignals->InsertionDirective;
217struct RawIdentifier {
218 llvm::StringRef Name;
224struct CompletionCandidate {
225 llvm::StringRef Name;
227 const CodeCompletionResult *SemaResult =
nullptr;
228 const Symbol *IndexResult =
nullptr;
229 const RawIdentifier *IdentifierResult =
nullptr;
230 llvm::SmallVector<SymbolInclude, 1> RankedIncludeHeaders;
234 size_t overloadSet(
const CodeCompleteOptions &Opts, llvm::StringRef FileName,
235 IncludeInserter *Inserter,
236 CodeCompletionContext::Kind CCContextKind)
const {
237 if (!Opts.BundleOverloads)
243 std::string HeaderForHash;
245 if (
auto Header = headerToInsertIfAllowed(Opts, CCContextKind)) {
246 if (
auto HeaderFile =
toHeaderFile(*Header, FileName)) {
248 Inserter->calculateIncludePath(*HeaderFile, FileName))
251 vlog(
"Code completion header path manipulation failed {0}",
252 HeaderFile.takeError());
257 llvm::SmallString<256> Scratch;
259 switch (IndexResult->SymInfo.Kind) {
260 case index::SymbolKind::ClassMethod:
261 case index::SymbolKind::InstanceMethod:
262 case index::SymbolKind::StaticMethod:
264 llvm_unreachable(
"Don't expect members from index in code completion");
268 case index::SymbolKind::Function:
271 return llvm::hash_combine(
272 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
280 const NamedDecl *D = SemaResult->Declaration;
281 if (!D || !D->isFunctionOrFunctionTemplate())
284 llvm::raw_svector_ostream OS(Scratch);
285 D->printQualifiedName(OS);
287 return llvm::hash_combine(Scratch, HeaderForHash);
289 assert(IdentifierResult);
293 bool contextAllowsHeaderInsertion(CodeCompletionContext::Kind Kind)
const {
296 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
302 std::optional<llvm::StringRef>
303 headerToInsertIfAllowed(
const CodeCompleteOptions &Opts,
304 CodeCompletionContext::Kind ContextKind)
const {
306 RankedIncludeHeaders.empty() ||
307 !contextAllowsHeaderInsertion(ContextKind))
309 if (SemaResult && SemaResult->Declaration) {
312 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
313 for (
const Decl *RD : SemaResult->Declaration->redecls())
314 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
318 for (
const auto &Inc : RankedIncludeHeaders)
319 if ((Inc.Directive & Directive) != 0)
324 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
327 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
328struct ScoredBundleGreater {
329 bool operator()(
const ScoredBundle &L,
const ScoredBundle &R) {
330 if (L.second.Total != R.second.Total)
331 return L.second.Total > R.second.Total;
332 return L.first.front().Name <
333 R.first.front().Name;
339std::string removeFirstTemplateArg(llvm::StringRef Signature) {
340 auto Rest = Signature.split(
",").second;
343 return (
"<" + Rest.ltrim()).str();
353struct CodeCompletionBuilder {
354 CodeCompletionBuilder(ASTContext *ASTCtx,
const CompletionCandidate &C,
355 CodeCompletionString *SemaCCS,
356 llvm::ArrayRef<std::string> AccessibleScopes,
357 const IncludeInserter &Includes,
358 llvm::StringRef FileName,
359 CodeCompletionContext::Kind ContextKind,
360 const CodeCompleteOptions &Opts,
361 bool IsUsingDeclaration, tok::TokenKind NextTokenKind)
362 : ASTCtx(ASTCtx), ArgumentLists(Opts.ArgumentLists),
363 IsUsingDeclaration(IsUsingDeclaration), NextTokenKind(NextTokenKind) {
364 Completion.Deprecated =
true;
365 add(C, SemaCCS, ContextKind);
369 Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText()));
370 Completion.FilterText = SemaCCS->getAllTypedText();
371 if (Completion.Scope.empty()) {
372 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
373 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
374 if (
const auto *D = C.SemaResult->getDeclaration())
375 if (
const auto *ND = dyn_cast<NamedDecl>(D))
376 Completion.Scope = std::string(
379 Completion.Kind = toCompletionItemKind(*C.SemaResult, ContextKind);
383 Completion.Name.back() ==
'/')
385 for (
const auto &FixIt : C.SemaResult->FixIts) {
387 FixIt, ASTCtx->getSourceManager(), ASTCtx->getLangOpts()));
389 llvm::sort(Completion.FixIts, [](
const TextEdit &
X,
const TextEdit &Y) {
390 return std::tie(X.range.start.line, X.range.start.character) <
391 std::tie(Y.range.start.line, Y.range.start.character);
395 Completion.Origin |= C.IndexResult->Origin;
396 if (Completion.Scope.empty())
397 Completion.Scope = std::string(C.IndexResult->Scope);
399 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind,
400 &C.IndexResult->Signature);
401 if (Completion.Name.empty())
402 Completion.Name = std::string(C.IndexResult->Name);
403 if (Completion.FilterText.empty())
404 Completion.FilterText = Completion.Name;
407 if (Completion.RequiredQualifier.empty() && !C.SemaResult) {
408 llvm::StringRef ShortestQualifier = C.IndexResult->Scope;
409 for (llvm::StringRef Scope : AccessibleScopes) {
410 llvm::StringRef Qualifier = C.IndexResult->Scope;
411 if (Qualifier.consume_front(Scope) &&
412 Qualifier.size() < ShortestQualifier.size())
413 ShortestQualifier = Qualifier;
415 Completion.RequiredQualifier = std::string(ShortestQualifier);
418 if (C.IdentifierResult) {
421 Completion.Name = std::string(C.IdentifierResult->Name);
422 Completion.FilterText = Completion.Name;
426 auto Inserted = [&](llvm::StringRef Header)
427 -> llvm::Expected<std::pair<std::string, bool>> {
428 auto ResolvedDeclaring =
429 URI::resolve(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
430 if (!ResolvedDeclaring)
431 return ResolvedDeclaring.takeError();
433 if (!ResolvedInserted)
434 return ResolvedInserted.takeError();
435 auto Spelled = Includes.calculateIncludePath(*ResolvedInserted, FileName);
437 return error(
"Header not on include path");
438 return std::make_pair(
440 Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
443 C.headerToInsertIfAllowed(Opts, ContextKind).has_value();
446 for (
const auto &Inc : C.RankedIncludeHeaders) {
447 if ((Inc.Directive & Directive) == 0)
450 if (
auto ToInclude = Inserted(Inc.Header)) {
451 CodeCompletion::IncludeCandidate Include;
452 Include.Header = ToInclude->first;
453 if (ToInclude->second && ShouldInsert)
454 Include.Insertion = Includes.insert(
456 ? tooling::IncludeDirective::Import
457 : tooling::IncludeDirective::Include);
458 Completion.Includes.push_back(std::move(Include));
460 log(
"Failed to generate include insertion edits for adding header "
461 "(FileURI='{0}', IncludeHeader='{1}') into {2}: {3}",
462 C.IndexResult->CanonicalDeclaration.FileURI, Inc.Header, FileName,
463 ToInclude.takeError());
466 std::stable_partition(Completion.Includes.begin(),
467 Completion.Includes.end(),
468 [](
const CodeCompletion::IncludeCandidate &I) {
469 return !I.Insertion.has_value();
473 void add(
const CompletionCandidate &C, CodeCompletionString *SemaCCS,
474 CodeCompletionContext::Kind ContextKind) {
475 assert(
bool(C.SemaResult) ==
bool(SemaCCS));
476 Bundled.emplace_back();
477 BundledEntry &S = Bundled.back();
478 bool IsConcept =
false;
481 *SemaCCS, &S.Signature, &S.SnippetSuffix, C.SemaResult->Kind,
482 C.SemaResult->CursorKind,
483 C.SemaResult->FunctionCanBeCall ||
484 C.SemaResult->DeclaringEntity,
485 &Completion.RequiredQualifier);
487 if (C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
488 if (
const auto *D = C.SemaResult->getDeclaration())
489 if (isa<ConceptDecl>(D))
491 }
else if (C.IndexResult) {
492 S.Signature = std::string(C.IndexResult->Signature);
493 S.SnippetSuffix = std::string(C.IndexResult->CompletionSnippetSuffix);
494 S.ReturnType = std::string(C.IndexResult->ReturnType);
495 if (C.IndexResult->SymInfo.Kind == index::SymbolKind::Concept)
502 if (IsConcept && ContextKind == CodeCompletionContext::CCC_TopLevel) {
503 S.Signature = removeFirstTemplateArg(S.Signature);
506 S.SnippetSuffix = removeFirstTemplateArg(S.SnippetSuffix);
509 if (!Completion.Documentation) {
510 auto SetDoc = [&](llvm::StringRef Doc) {
512 Completion.Documentation.emplace();
517 SetDoc(C.IndexResult->Documentation);
518 }
else if (C.SemaResult) {
519 const auto DocComment =
getDocComment(*ASTCtx, *C.SemaResult,
524 if (Completion.Deprecated) {
526 Completion.Deprecated &=
527 C.SemaResult->Availability == CXAvailability_Deprecated;
529 Completion.Deprecated &=
534 CodeCompletion build() {
535 Completion.ReturnType = summarizeReturnType();
536 Completion.Signature = summarizeSignature();
537 Completion.SnippetSuffix = summarizeSnippet();
538 Completion.BundleSize = Bundled.size();
539 return std::move(Completion);
543 struct BundledEntry {
544 std::string SnippetSuffix;
545 std::string Signature;
546 std::string ReturnType;
550 template <std::
string BundledEntry::*Member>
551 const std::string *onlyValue()
const {
552 auto B = Bundled.begin(), E = Bundled.end();
553 for (
auto *I = B + 1; I != E; ++I)
554 if (I->*Member != B->*Member)
556 return &(B->*Member);
559 std::string summarizeReturnType()
const {
560 if (
auto *RT = onlyValue<&BundledEntry::ReturnType>())
565 std::string summarizeSnippet()
const {
575 if (IsUsingDeclaration)
577 auto *
Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
582 return None ?
"" : (
Open ?
"(" :
"($0)");
587 bool MayHaveArgList =
597 if (MayHaveArgList) {
601 if (NextTokenKind == tok::less &&
Snippet->front() ==
'<')
604 if (NextTokenKind == tok::l_paren) {
614 else if (
Snippet->at(I) ==
'<')
617 }
while (Balance > 0);
627 if (MayHaveArgList && llvm::StringRef(*Snippet).contains(
"(")) {
636 bool EmptyArgs = llvm::StringRef(*Snippet).ends_with(
"()");
638 return None ?
"" : (
Open ?
"<" : (EmptyArgs ?
"<$1>()$0" :
"<$1>($0)"));
640 return None ?
"" : (
Open ?
"(" : (EmptyArgs ?
"()" :
"($0)"));
652 if (llvm::StringRef(*Snippet).ends_with(
"<>"))
654 return None ?
"" : (
Open ?
"<" :
"<$0>");
659 std::string summarizeSignature()
const {
660 if (
auto *Signature = onlyValue<&BundledEntry::Signature>())
668 CodeCompletion Completion;
669 llvm::SmallVector<BundledEntry, 1> Bundled;
674 bool IsUsingDeclaration;
675 tok::TokenKind NextTokenKind;
679SymbolID
getSymbolID(
const CodeCompletionResult &R,
const SourceManager &SM) {
681 case CodeCompletionResult::RK_Declaration:
682 case CodeCompletionResult::RK_Pattern: {
688 case CodeCompletionResult::RK_Macro:
690 case CodeCompletionResult::RK_Keyword:
693 llvm_unreachable(
"unknown CodeCompletionResult kind");
698struct SpecifiedScope {
721 std::vector<std::string> AccessibleScopes;
724 std::vector<std::string> QueryScopes;
727 std::optional<std::string> UnresolvedQualifier;
729 std::optional<std::string> EnclosingNamespace;
731 bool AllowAllScopes =
false;
735 std::vector<std::string> scopesForQualification() {
736 std::set<std::string> Results;
737 for (llvm::StringRef AS : AccessibleScopes)
739 (AS + (UnresolvedQualifier ? *UnresolvedQualifier :
"")).str());
740 return {Results.begin(), Results.end()};
745 std::vector<std::string> scopesForIndexQuery() {
747 std::vector<std::string> EnclosingAtFront;
748 if (EnclosingNamespace.has_value())
749 EnclosingAtFront.push_back(*EnclosingNamespace);
750 std::set<std::string> Deduplicated;
751 for (llvm::StringRef S : QueryScopes)
752 if (S != EnclosingNamespace)
753 Deduplicated.insert((S + UnresolvedQualifier.value_or(
"")).str());
755 EnclosingAtFront.reserve(EnclosingAtFront.size() + Deduplicated.size());
756 llvm::copy(Deduplicated, std::back_inserter(EnclosingAtFront));
758 return EnclosingAtFront;
765SpecifiedScope getQueryScopes(CodeCompletionContext &CCContext,
767 const CompletionPrefix &HeuristicPrefix,
768 const CodeCompleteOptions &Opts) {
769 SpecifiedScope Scopes;
770 for (
auto *Context : CCContext.getVisitedContexts()) {
771 if (isa<TranslationUnitDecl>(Context)) {
772 Scopes.QueryScopes.push_back(
"");
773 Scopes.AccessibleScopes.push_back(
"");
774 }
else if (
const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
780 const CXXScopeSpec *SemaSpecifier =
781 CCContext.getCXXScopeSpecifier().value_or(
nullptr);
783 if (!SemaSpecifier) {
786 if (!HeuristicPrefix.Qualifier.empty()) {
787 vlog(
"Sema said no scope specifier, but we saw {0} in the source code",
788 HeuristicPrefix.Qualifier);
789 StringRef SpelledSpecifier = HeuristicPrefix.Qualifier;
790 if (SpelledSpecifier.consume_front(
"::")) {
791 Scopes.AccessibleScopes = {
""};
792 Scopes.QueryScopes = {
""};
794 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
802 Scopes.AllowAllScopes = Opts.AllScopes;
806 if (SemaSpecifier && SemaSpecifier->isValid())
810 Scopes.QueryScopes.push_back(
"");
811 llvm::StringRef SpelledSpecifier = Lexer::getSourceText(
812 CharSourceRange::getCharRange(SemaSpecifier->getRange()),
813 CCSema.SourceMgr, clang::LangOptions());
814 if (SpelledSpecifier.consume_front(
"::"))
815 Scopes.QueryScopes = {
""};
816 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
818 if (!Scopes.UnresolvedQualifier->empty())
819 *Scopes.UnresolvedQualifier +=
"::";
821 Scopes.AccessibleScopes = Scopes.QueryScopes;
828bool contextAllowsIndex(
enum CodeCompletionContext::Kind K) {
830 case CodeCompletionContext::CCC_TopLevel:
831 case CodeCompletionContext::CCC_ObjCInterface:
832 case CodeCompletionContext::CCC_ObjCImplementation:
833 case CodeCompletionContext::CCC_ObjCIvarList:
834 case CodeCompletionContext::CCC_ClassStructUnion:
835 case CodeCompletionContext::CCC_Statement:
836 case CodeCompletionContext::CCC_Expression:
837 case CodeCompletionContext::CCC_ObjCMessageReceiver:
838 case CodeCompletionContext::CCC_EnumTag:
839 case CodeCompletionContext::CCC_UnionTag:
840 case CodeCompletionContext::CCC_ClassOrStructTag:
841 case CodeCompletionContext::CCC_ObjCProtocolName:
842 case CodeCompletionContext::CCC_Namespace:
843 case CodeCompletionContext::CCC_Type:
844 case CodeCompletionContext::CCC_ParenthesizedExpression:
845 case CodeCompletionContext::CCC_ObjCInterfaceName:
846 case CodeCompletionContext::CCC_Symbol:
847 case CodeCompletionContext::CCC_SymbolOrNewName:
848 case CodeCompletionContext::CCC_ObjCClassForwardDecl:
849 case CodeCompletionContext::CCC_TopLevelOrExpression:
851 case CodeCompletionContext::CCC_OtherWithMacros:
852 case CodeCompletionContext::CCC_DotMemberAccess:
853 case CodeCompletionContext::CCC_ArrowMemberAccess:
854 case CodeCompletionContext::CCC_ObjCCategoryName:
855 case CodeCompletionContext::CCC_ObjCPropertyAccess:
856 case CodeCompletionContext::CCC_MacroName:
857 case CodeCompletionContext::CCC_MacroNameUse:
858 case CodeCompletionContext::CCC_PreprocessorExpression:
859 case CodeCompletionContext::CCC_PreprocessorDirective:
860 case CodeCompletionContext::CCC_SelectorName:
861 case CodeCompletionContext::CCC_TypeQualifiers:
862 case CodeCompletionContext::CCC_ObjCInstanceMessage:
863 case CodeCompletionContext::CCC_ObjCClassMessage:
864 case CodeCompletionContext::CCC_IncludedFile:
865 case CodeCompletionContext::CCC_Attribute:
867 case CodeCompletionContext::CCC_Other:
868 case CodeCompletionContext::CCC_NaturalLanguage:
869 case CodeCompletionContext::CCC_Recovery:
870 case CodeCompletionContext::CCC_NewName:
873 llvm_unreachable(
"unknown code completion context");
876static bool isInjectedClass(
const NamedDecl &D) {
877 if (
auto *R = dyn_cast_or_null<CXXRecordDecl>(&D))
878 if (R->isInjectedClassName())
884static bool isExcludedMember(
const NamedDecl &D) {
887 if (D.getKind() == Decl::CXXDestructor)
890 if (isInjectedClass(D))
893 auto NameKind = D.getDeclName().getNameKind();
894 if (NameKind == DeclarationName::CXXOperatorName ||
895 NameKind == DeclarationName::CXXLiteralOperatorName ||
896 NameKind == DeclarationName::CXXConversionFunctionName)
907struct CompletionRecorder :
public CodeCompleteConsumer {
908 CompletionRecorder(
const CodeCompleteOptions &Opts,
909 llvm::unique_function<
void()> ResultsCallback)
910 : CodeCompleteConsumer(Opts.getClangCompleteOpts()),
911 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
912 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
913 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
914 assert(this->ResultsCallback);
917 std::vector<CodeCompletionResult> Results;
918 CodeCompletionContext CCContext;
919 Sema *CCSema =
nullptr;
922 void ProcessCodeCompleteResults(
class Sema &S, CodeCompletionContext Context,
923 CodeCompletionResult *InResults,
924 unsigned NumResults)
final {
933 CodeCompletionContext::Kind ContextKind = Context.getKind();
934 if (ContextKind == CodeCompletionContext::CCC_Recovery) {
935 log(
"Code complete: Ignoring sema code complete callback with Recovery "
942 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
945 log(
"Multiple code complete callbacks (parser backtracked?). "
946 "Dropping results from context {0}, keeping results from {1}.",
947 getCompletionKindString(Context.getKind()),
948 getCompletionKindString(this->CCContext.getKind()));
956 for (
unsigned I = 0; I < NumResults; ++I) {
957 auto &Result = InResults[I];
960 Result.Kind == CodeCompletionResult::RK_Pattern &&
962 ContextKind != CodeCompletionContext::CCC_IncludedFile)
965 if (Result.Hidden && Result.Declaration &&
966 Result.Declaration->isCXXClassMember())
968 if (!Opts.IncludeIneligibleResults &&
969 (Result.Availability == CXAvailability_NotAvailable ||
970 Result.Availability == CXAvailability_NotAccessible))
972 if (Result.Declaration &&
973 !Context.getBaseType().isNull()
974 && isExcludedMember(*Result.Declaration))
978 if (Result.Declaration && !Context.getCXXScopeSpecifier() &&
979 isInjectedClass(*Result.Declaration))
982 Result.StartsNestedNameSpecifier =
false;
983 Results.push_back(Result);
988 CodeCompletionAllocator &getAllocator()
override {
return *CCAllocator; }
989 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
993 llvm::StringRef getName(
const CodeCompletionResult &Result) {
994 switch (Result.Kind) {
995 case CodeCompletionResult::RK_Declaration:
996 if (
auto *ID = Result.Declaration->getIdentifier())
997 return ID->getName();
999 case CodeCompletionResult::RK_Keyword:
1000 return Result.Keyword;
1001 case CodeCompletionResult::RK_Macro:
1002 return Result.Macro->getName();
1003 case CodeCompletionResult::RK_Pattern:
1006 auto *CCS = codeCompletionString(Result);
1007 const CodeCompletionString::Chunk *OnlyText =
nullptr;
1008 for (
auto &C : *CCS) {
1009 if (C.Kind != CodeCompletionString::CK_TypedText)
1012 return CCAllocator->CopyString(CCS->getAllTypedText());
1015 return OnlyText ? OnlyText->Text : llvm::StringRef();
1020 CodeCompletionString *codeCompletionString(
const CodeCompletionResult &R) {
1022 return const_cast<CodeCompletionResult &
>(R).CreateCodeCompletionString(
1023 *CCSema, CCContext, *CCAllocator, CCTUInfo,
1028 CodeCompleteOptions Opts;
1029 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
1030 CodeCompletionTUInfo CCTUInfo;
1031 llvm::unique_function<void()> ResultsCallback;
1034struct ScoredSignature {
1038 SignatureInformation Signature;
1039 SignatureQualitySignals Quality;
1047int paramIndexForArg(
const CodeCompleteConsumer::OverloadCandidate &Candidate,
1049 int NumParams = Candidate.getNumParams();
1050 if (
auto *T = Candidate.getFunctionType()) {
1051 if (
auto *Proto = T->getAs<FunctionProtoType>()) {
1052 if (Proto->isVariadic())
1056 return std::min(Arg, std::max(NumParams - 1, 0));
1059class SignatureHelpCollector final :
public CodeCompleteConsumer {
1061 SignatureHelpCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1062 MarkupKind DocumentationFormat,
1063 const SymbolIndex *Index, SignatureHelp &SigHelp)
1064 : CodeCompleteConsumer(CodeCompleteOpts), SigHelp(SigHelp),
1065 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1066 CCTUInfo(Allocator), Index(Index),
1067 DocumentationFormat(DocumentationFormat) {}
1069 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1070 OverloadCandidate *Candidates,
1071 unsigned NumCandidates,
1072 SourceLocation OpenParLoc,
1073 bool Braced)
override {
1074 assert(!OpenParLoc.isInvalid());
1075 SourceManager &SrcMgr = S.getSourceManager();
1076 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
1077 if (SrcMgr.isInMainFile(OpenParLoc))
1080 elog(
"Location oustide main file in signature help: {0}",
1081 OpenParLoc.printToString(SrcMgr));
1083 std::vector<ScoredSignature> ScoredSignatures;
1084 SigHelp.signatures.reserve(NumCandidates);
1085 ScoredSignatures.reserve(NumCandidates);
1089 SigHelp.activeSignature = 0;
1090 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1091 "too many arguments");
1093 SigHelp.activeParameter =
static_cast<int>(CurrentArg);
1095 for (
unsigned I = 0; I < NumCandidates; ++I) {
1096 OverloadCandidate Candidate = Candidates[I];
1100 if (
auto *Func = Candidate.getFunction()) {
1101 if (
auto *Pattern = Func->getTemplateInstantiationPattern())
1102 Candidate = OverloadCandidate(Pattern);
1104 if (
static_cast<int>(I) == SigHelp.activeSignature) {
1109 SigHelp.activeParameter =
1110 paramIndexForArg(Candidate, SigHelp.activeParameter);
1113 const auto *CCS = Candidate.CreateSignatureString(
1114 CurrentArg, S, *Allocator, CCTUInfo,
1116 assert(CCS &&
"Expected the CodeCompletionString to be non-null");
1117 ScoredSignatures.push_back(processOverloadCandidate(
1119 Candidate.getFunction()
1126 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
1128 LookupRequest IndexRequest;
1129 for (
const auto &S : ScoredSignatures) {
1132 IndexRequest.IDs.insert(S.IDForDoc);
1134 Index->lookup(IndexRequest, [&](
const Symbol &S) {
1135 if (!S.Documentation.empty())
1136 FetchedDocs[S.ID] = std::string(S.Documentation);
1138 vlog(
"SigHelp: requested docs for {0} symbols from the index, got {1} "
1139 "symbols with non-empty docs in the response",
1140 IndexRequest.IDs.size(), FetchedDocs.size());
1143 llvm::sort(ScoredSignatures, [](
const ScoredSignature &L,
1144 const ScoredSignature &R) {
1151 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
1152 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
1153 if (L.Quality.NumberOfOptionalParameters !=
1154 R.Quality.NumberOfOptionalParameters)
1155 return L.Quality.NumberOfOptionalParameters <
1156 R.Quality.NumberOfOptionalParameters;
1157 if (L.Quality.Kind != R.Quality.Kind) {
1158 using OC = CodeCompleteConsumer::OverloadCandidate;
1159 auto KindPriority = [&](OC::CandidateKind K) {
1161 case OC::CK_Aggregate:
1163 case OC::CK_Function:
1165 case OC::CK_FunctionType:
1167 case OC::CK_FunctionProtoTypeLoc:
1169 case OC::CK_FunctionTemplate:
1171 case OC::CK_Template:
1174 llvm_unreachable(
"Unknown overload candidate type.");
1176 return KindPriority(L.Quality.Kind) < KindPriority(R.Quality.Kind);
1178 if (L.Signature.label.size() != R.Signature.label.size())
1179 return L.Signature.label.size() < R.Signature.label.size();
1180 return L.Signature.label < R.Signature.label;
1183 for (
auto &SS : ScoredSignatures) {
1185 SS.IDForDoc ? FetchedDocs.find(SS.IDForDoc) : FetchedDocs.end();
1186 if (IndexDocIt != FetchedDocs.end()) {
1187 markup::Document SignatureComment;
1189 SS.Signature.documentation =
1190 renderDoc(SignatureComment, DocumentationFormat);
1193 SigHelp.signatures.push_back(std::move(SS.Signature));
1197 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1199 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1202 void processParameterChunk(llvm::StringRef ChunkText,
1203 SignatureInformation &Signature)
const {
1205 unsigned ParamStartOffset =
lspLength(Signature.label);
1206 unsigned ParamEndOffset = ParamStartOffset +
lspLength(ChunkText);
1210 Signature.label += ChunkText;
1211 ParameterInformation
Info;
1212 Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset);
1214 Info.labelString = std::string(ChunkText);
1216 Signature.parameters.push_back(std::move(
Info));
1219 void processOptionalChunk(
const CodeCompletionString &CCS,
1220 SignatureInformation &Signature,
1221 SignatureQualitySignals &Signal)
const {
1222 for (
const auto &Chunk : CCS) {
1223 switch (Chunk.Kind) {
1224 case CodeCompletionString::CK_Optional:
1225 assert(Chunk.Optional &&
1226 "Expected the optional code completion string to be non-null.");
1227 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1229 case CodeCompletionString::CK_VerticalSpace:
1231 case CodeCompletionString::CK_CurrentParameter:
1232 case CodeCompletionString::CK_Placeholder:
1233 processParameterChunk(Chunk.Text, Signature);
1234 Signal.NumberOfOptionalParameters++;
1237 Signature.label += Chunk.Text;
1245 ScoredSignature processOverloadCandidate(
const OverloadCandidate &Candidate,
1246 const CodeCompletionString &CCS,
1247 llvm::StringRef DocComment)
const {
1248 SignatureInformation Signature;
1249 SignatureQualitySignals Signal;
1250 const char *ReturnType =
nullptr;
1252 markup::Document OverloadComment;
1254 Signature.documentation = renderDoc(OverloadComment, DocumentationFormat);
1255 Signal.Kind = Candidate.getKind();
1257 for (
const auto &Chunk : CCS) {
1258 switch (Chunk.Kind) {
1259 case CodeCompletionString::CK_ResultType:
1262 assert(!ReturnType &&
"Unexpected CK_ResultType");
1263 ReturnType = Chunk.Text;
1265 case CodeCompletionString::CK_CurrentParameter:
1266 case CodeCompletionString::CK_Placeholder:
1267 processParameterChunk(Chunk.Text, Signature);
1268 Signal.NumberOfParameters++;
1270 case CodeCompletionString::CK_Optional: {
1272 assert(Chunk.Optional &&
1273 "Expected the optional code completion string to be non-null.");
1274 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1277 case CodeCompletionString::CK_VerticalSpace:
1280 Signature.label += Chunk.Text;
1285 Signature.label +=
" -> ";
1286 Signature.label += ReturnType;
1288 dlog(
"Signal for {0}: {1}", Signature, Signal);
1289 ScoredSignature Result;
1290 Result.Signature = std::move(Signature);
1291 Result.Quality = Signal;
1292 const FunctionDecl *Func = Candidate.getFunction();
1293 if (Func && Result.Signature.documentation.value.empty()) {
1301 SignatureHelp &SigHelp;
1302 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1303 CodeCompletionTUInfo CCTUInfo;
1304 const SymbolIndex *Index;
1305 MarkupKind DocumentationFormat;
1310class ParamNameCollector final :
public CodeCompleteConsumer {
1312 ParamNameCollector(
const clang::CodeCompleteOptions &CodeCompleteOpts,
1313 std::set<std::string> &ParamNames)
1314 : CodeCompleteConsumer(CodeCompleteOpts),
1315 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1316 CCTUInfo(Allocator), ParamNames(ParamNames) {}
1318 void ProcessOverloadCandidates(Sema &S,
unsigned CurrentArg,
1319 OverloadCandidate *Candidates,
1320 unsigned NumCandidates,
1321 SourceLocation OpenParLoc,
1322 bool Braced)
override {
1323 assert(CurrentArg <= (
unsigned)std::numeric_limits<int>::max() &&
1324 "too many arguments");
1326 for (
unsigned I = 0; I < NumCandidates; ++I) {
1327 if (
const NamedDecl *ND = Candidates[I].getParamDecl(CurrentArg))
1328 if (
const auto *II = ND->getIdentifier())
1329 ParamNames.emplace(II->getName());
1334 GlobalCodeCompletionAllocator &getAllocator()
override {
return *Allocator; }
1336 CodeCompletionTUInfo &getCodeCompletionTUInfo()
override {
return CCTUInfo; }
1338 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1339 CodeCompletionTUInfo CCTUInfo;
1340 std::set<std::string> &ParamNames;
1343struct SemaCompleteInput {
1347 const std::optional<PreamblePatch> Patch;
1348 const ParseInputs &ParseInput;
1351void loadMainFilePreambleMacros(
const Preprocessor &PP,
1356 ExternalPreprocessorSource *PreambleMacros = PP.getExternalSource();
1359 const auto &ITable = PP.getIdentifierTable();
1360 IdentifierInfoLookup *PreambleIdentifiers =
1361 ITable.getExternalIdentifierLookup();
1363 if (!PreambleIdentifiers || !PreambleMacros)
1365 for (
const auto &MacroName :
Preamble.Macros.Names) {
1366 if (ITable.find(MacroName.getKey()) != ITable.end())
1368 if (
auto *II = PreambleIdentifiers->get(MacroName.getKey()))
1369 if (II->isOutOfDate())
1370 PreambleMacros->updateOutOfDateIdentifier(*II);
1376bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
1377 const clang::CodeCompleteOptions &Options,
1378 const SemaCompleteInput &Input,
1379 IncludeStructure *Includes =
nullptr,
1380 std::unique_ptr<CompilerInvocation> CI =
nullptr) {
1381 trace::Span Tracer(
"Sema completion");
1383 IgnoreDiagnostics IgnoreDiags;
1387 elog(
"Couldn't create CompilerInvocation");
1391 auto &FrontendOpts = CI->getFrontendOpts();
1392 FrontendOpts.SkipFunctionBodies =
true;
1394 CI->getLangOpts().SpellChecking =
false;
1398 CI->getLangOpts().DelayedTemplateParsing =
false;
1400 FrontendOpts.CodeCompleteOpts = Options;
1401 FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName);
1402 std::tie(FrontendOpts.CodeCompletionAt.Line,
1403 FrontendOpts.CodeCompletionAt.Column) =
1406 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1407 llvm::MemoryBuffer::getMemBuffer(Input.ParseInput.Contents,
1410 CI->getDiagnosticOpts().IgnoreWarnings =
true;
1417 PreambleBounds PreambleRegion =
1419 Input.ParseInput.Opts.SkipPreambleBuild);
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));
1433 (!CompletingInPreamble && !Input.ParseInput.Opts.SkipPreambleBuild)
1434 ? &Input.Preamble.Preamble
1436 std::move(ContentsBuffer), std::move(VFS), IgnoreDiags);
1437 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
1438 Clang->setCodeCompletionConsumer(Consumer.release());
1440 if (Input.Preamble.RequiredModules)
1441 Input.Preamble.RequiredModules->adjustHeaderSearchOptions(
1442 Clang->getHeaderSearchOpts());
1445 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1446 log(
"BeginSourceFile() failed when running codeComplete for {0}",
1456 loadMainFilePreambleMacros(Clang->getPreprocessor(), Input.Preamble);
1458 Includes->collect(*Clang);
1459 if (llvm::Error Err = Action.Execute()) {
1460 log(
"Execute() failed when running codeComplete for {0}: {1}",
1461 Input.FileName,
toString(std::move(Err)));
1464 Action.EndSourceFile();
1470bool allowIndex(CodeCompletionContext &CC) {
1471 if (!contextAllowsIndex(CC.getKind()))
1474 auto Scope = CC.getCXXScopeSpecifier();
1479 switch ((*Scope)->getScopeRep().getKind()) {
1480 case NestedNameSpecifier::Kind::Null:
1481 case NestedNameSpecifier::Kind::Global:
1482 case NestedNameSpecifier::Kind::Namespace:
1484 case NestedNameSpecifier::Kind::MicrosoftSuper:
1485 case NestedNameSpecifier::Kind::Type:
1488 llvm_unreachable(
"invalid NestedNameSpecifier kind");
1493bool includeSymbolFromIndex(CodeCompletionContext::Kind Kind,
1494 const Symbol &Sym) {
1498 if (Sym.SymInfo.Kind == index::SymbolKind::Protocol &&
1499 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC)
1500 return Kind == CodeCompletionContext::CCC_ObjCProtocolName;
1501 else if (Kind == CodeCompletionContext::CCC_ObjCProtocolName)
1505 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
1506 return Sym.SymInfo.Kind == index::SymbolKind::Class &&
1507 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC;
1511std::future<std::pair<bool, SymbolSlab>>
1512startAsyncFuzzyFind(
const SymbolIndex &Index,
const FuzzyFindRequest &Req) {
1514 trace::Span Tracer(
"Async fuzzyFind");
1515 SymbolSlab::Builder Syms;
1517 Index.fuzzyFind(Req, [&Syms](
const Symbol &Sym) { Syms.insert(Sym); });
1518 return std::make_pair(Incomplete, std::move(Syms).build());
1525FuzzyFindRequest speculativeFuzzyFindRequestForCompletion(
1526 FuzzyFindRequest CachedReq,
const CompletionPrefix &HeuristicPrefix) {
1527 CachedReq.Query = std::string(HeuristicPrefix.Name);
1560class CodeCompleteFlow {
1562 IncludeStructure Includes;
1563 SpeculativeFuzzyFind *SpecFuzzyFind;
1564 const CodeCompleteOptions &Opts;
1567 CompletionRecorder *Recorder =
nullptr;
1568 CodeCompletionContext::Kind CCContextKind = CodeCompletionContext::CCC_Other;
1569 bool IsUsingDeclaration =
false;
1573 tok::TokenKind NextTokenKind = tok::eof;
1576 SourceLocation IdentifierSuffixEnd;
1578 int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
1579 bool Incomplete =
false;
1580 CompletionPrefix HeuristicPrefix;
1581 std::optional<FuzzyMatcher> Filter;
1583 std::optional<Range> ReplaceRange;
1584 std::vector<std::string> QueryScopes;
1585 std::vector<std::string> AccessibleScopes;
1587 std::optional<ScopeDistance> ScopeProximity;
1588 std::optional<OpaqueType> PreferredType;
1590 bool AllScopes =
false;
1591 llvm::StringSet<> ContextWords;
1594 std::optional<IncludeInserter> Inserter;
1595 std::optional<URIDistance> FileProximity;
1600 std::optional<FuzzyFindRequest> SpecReq;
1604 CodeCompleteFlow(
PathRef FileName,
const IncludeStructure &Includes,
1605 SpeculativeFuzzyFind *SpecFuzzyFind,
1606 const CodeCompleteOptions &Opts)
1607 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1610 CodeCompleteResult
run(
const SemaCompleteInput &SemaCCInput) && {
1611 trace::Span Tracer(
"CodeCompleteFlow");
1613 SemaCCInput.Offset);
1614 populateContextWords(SemaCCInput.ParseInput.Contents);
1615 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq) {
1616 assert(!SpecFuzzyFind->Result.valid());
1617 SpecReq = speculativeFuzzyFindRequestForCompletion(
1618 *SpecFuzzyFind->CachedReq, HeuristicPrefix);
1619 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1625 CodeCompleteResult Output;
1626 auto RecorderOwner = std::make_unique<CompletionRecorder>(Opts, [&]() {
1627 assert(Recorder &&
"Recorder is not set");
1628 CCContextKind = Recorder->CCContext.getKind();
1629 IsUsingDeclaration = Recorder->CCContext.isUsingDeclaration();
1631 SemaCCInput.ParseInput.Contents,
1632 *SemaCCInput.ParseInput.TFS,
false);
1633 const auto &SM = Recorder->CCSema->getSourceManager();
1634 const LangOptions &LangOpts = Recorder->CCSema->getLangOpts();
1637 IdentifierSuffixEnd = Lexer::findEndOfIdentifierContinuation(
1638 Recorder->CCSema->getPreprocessor()
1639 .getCodeCompletionLoc()
1640 .getLocWithOffset(1),
1643 if (Token NextToken;
1644 !Lexer::getRawToken(IdentifierSuffixEnd, NextToken, SM, LangOpts,
1646 NextTokenKind = NextToken.getKind();
1650 SemaCCInput.FileName, SemaCCInput.ParseInput.Contents, Style,
1651 SemaCCInput.ParseInput.CompileCommand.Directory,
1652 &Recorder->CCSema->getPreprocessor().getHeaderSearchInfo(),
1655 for (
const auto &Inc : Includes.MainFileIncludes)
1656 Inserter->addExisting(Inc);
1662 FileDistanceOptions ProxOpts{};
1663 llvm::StringMap<SourceParams> ProxSources;
1665 Includes.getID(SM.getFileEntryForID(SM.getMainFileID()));
1667 for (
auto &HeaderIDAndDepth : Includes.includeDepth(*MainFileID)) {
1669 ProxSources[Includes.getRealPath(HeaderIDAndDepth.getFirst())];
1670 Source.Cost = HeaderIDAndDepth.getSecond() * ProxOpts.IncludeCost;
1674 if (HeaderIDAndDepth.getSecond() > 0)
1675 Source.MaxUpTraversals = 1;
1677 FileProximity.emplace(ProxSources, ProxOpts);
1679 Output = runWithSema();
1682 getCompletionKindString(CCContextKind));
1683 log(
"Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1684 "expected type {3}{4}",
1685 getCompletionKindString(CCContextKind),
1686 llvm::join(QueryScopes.begin(), QueryScopes.end(),
","), AllScopes,
1687 PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1689 IsUsingDeclaration ?
", inside using declaration" :
"");
1692 Recorder = RecorderOwner.get();
1694 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1695 SemaCCInput, &Includes);
1696 logResults(Output, Tracer);
1700 void logResults(
const CodeCompleteResult &Output,
const trace::Span &Tracer) {
1703 SPAN_ATTACH(Tracer,
"merged_results", NSemaAndIndex);
1704 SPAN_ATTACH(Tracer,
"identifier_results", NIdent);
1705 SPAN_ATTACH(Tracer,
"returned_results", int64_t(Output.Completions.size()));
1706 SPAN_ATTACH(Tracer,
"incomplete", Output.HasMore);
1707 log(
"Code complete: {0} results from Sema, {1} from Index, "
1708 "{2} matched, {3} from identifiers, {4} returned{5}.",
1709 NSema, NIndex, NSemaAndIndex, NIdent, Output.Completions.size(),
1710 Output.HasMore ?
" (incomplete)" :
"");
1711 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1716 CodeCompleteResult runWithoutSema(llvm::StringRef Content,
size_t Offset,
1717 const ThreadsafeFS &TFS) && {
1718 trace::Span Tracer(
"CodeCompleteWithoutSema");
1721 populateContextWords(Content);
1722 CCContextKind = CodeCompletionContext::CCC_Recovery;
1723 IsUsingDeclaration =
false;
1724 Filter = FuzzyMatcher(HeuristicPrefix.Name);
1726 InsertRange.start = InsertRange.end = Pos;
1727 InsertRange.start.character -= HeuristicPrefix.Name.size();
1729 if (Opts.EnableInsertReplace) {
1730 ReplaceRange.emplace();
1731 ReplaceRange->start = InsertRange.start;
1733 size_t ReplaceEnd = Offset;
1734 while (ReplaceEnd < Content.size() &&
1735 isAsciiIdentifierContinue(Content[ReplaceEnd]))
1740 llvm::StringMap<SourceParams> ProxSources;
1741 ProxSources[FileName].Cost = 0;
1742 FileProximity.emplace(ProxSources);
1746 Inserter.emplace(FileName, Content, Style,
1752 std::vector<RawIdentifier> IdentifierResults;
1753 for (
const auto &IDAndCount : Identifiers) {
1755 ID.Name = IDAndCount.first();
1756 ID.References = IDAndCount.second;
1758 if (ID.Name == HeuristicPrefix.Name)
1760 if (ID.References > 0)
1761 IdentifierResults.push_back(std::move(ID));
1767 SpecifiedScope Scopes;
1769 Content.take_front(Offset), format::getFormattingLangOpts(Style));
1770 for (std::string &S : Scopes.QueryScopes)
1773 if (HeuristicPrefix.Qualifier.empty())
1774 AllScopes = Opts.AllScopes;
1775 else if (HeuristicPrefix.Qualifier.starts_with(
"::")) {
1776 Scopes.QueryScopes = {
""};
1777 Scopes.UnresolvedQualifier =
1778 std::string(HeuristicPrefix.Qualifier.drop_front(2));
1780 Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier);
1782 QueryScopes = Scopes.scopesForIndexQuery();
1783 AccessibleScopes = QueryScopes;
1784 ScopeProximity.emplace(QueryScopes);
1786 SymbolSlab IndexResults = Opts.Index ? queryIndex() : SymbolSlab();
1788 CodeCompleteResult Output = toCodeCompleteResult(mergeResults(
1789 {}, IndexResults, IdentifierResults));
1790 Output.RanParser =
false;
1791 logResults(Output, Tracer);
1796 void populateContextWords(llvm::StringRef Content) {
1798 unsigned RangeEnd = HeuristicPrefix.Qualifier.begin() - Content.data(),
1799 RangeBegin = RangeEnd;
1800 for (
size_t I = 0; I < 3 && RangeBegin > 0; ++I) {
1801 auto PrevNL = Content.rfind(
'\n', RangeBegin);
1802 if (PrevNL == StringRef::npos) {
1806 RangeBegin = PrevNL;
1809 ContextWords =
collectWords(Content.slice(RangeBegin, RangeEnd));
1810 dlog(
"Completion context words: {0}",
1811 llvm::join(ContextWords.keys(),
", "));
1816 CodeCompleteResult runWithSema() {
1817 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1818 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1820 const SourceManager &SM = Recorder->CCSema->getSourceManager();
1827 if (CodeCompletionRange.isValid()) {
1831 SM, Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1832 InsertRange.start = InsertRange.end = Pos;
1835 if (Opts.EnableInsertReplace) {
1836 ReplaceRange.emplace();
1837 ReplaceRange->start = InsertRange.start;
1838 ReplaceRange->end = getEndOfCodeCompletionReplace(SM);
1840 Filter = FuzzyMatcher(
1841 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1842 auto SpecifiedScopes = getQueryScopes(
1843 Recorder->CCContext, *Recorder->CCSema, HeuristicPrefix, Opts);
1845 QueryScopes = SpecifiedScopes.scopesForIndexQuery();
1846 AccessibleScopes = SpecifiedScopes.scopesForQualification();
1847 AllScopes = SpecifiedScopes.AllowAllScopes;
1848 if (!QueryScopes.empty())
1849 ScopeProximity.emplace(QueryScopes);
1852 Recorder->CCContext.getPreferredType());
1858 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1861 trace::Span Tracer(
"Populate CodeCompleteResult");
1864 mergeResults(Recorder->Results, IndexResults, {});
1865 return toCodeCompleteResult(Top);
1870 Position getEndOfCodeCompletionReplace(
const SourceManager &SM) {
1879 toCodeCompleteResult(
const std::vector<ScoredBundle> &Scored) {
1880 CodeCompleteResult Output;
1885 llvm::DenseMap<SymbolID, uint32_t> SymbolToCompletion;
1886 for (
auto &C : Scored) {
1887 Output.Completions.push_back(toCodeCompletion(C.first));
1888 Output.Completions.back().Score = C.second;
1889 Output.Completions.back().CompletionInsertRange = InsertRange;
1890 Output.Completions.back().CompletionReplaceRange = ReplaceRange;
1891 if (Opts.Index && !Output.Completions.back().Documentation) {
1892 for (
auto &Cand : C.first) {
1893 if (Cand.SemaResult &&
1894 Cand.SemaResult->Kind == CodeCompletionResult::RK_Declaration) {
1895 const NamedDecl *DeclToLookup = Cand.SemaResult->getDeclaration();
1899 if (
const NamedDecl *Adjusted =
1900 dyn_cast<NamedDecl>(&adjustDeclToTemplate(*DeclToLookup))) {
1901 DeclToLookup = Adjusted;
1907 SymbolToCompletion[ID] = Output.Completions.size() - 1;
1912 Output.HasMore = Incomplete;
1913 Output.Context = CCContextKind;
1914 Output.InsertRange = InsertRange;
1915 Output.ReplaceRange = ReplaceRange;
1919 Opts.Index->lookup(Req, [&](
const Symbol &S) {
1920 if (S.Documentation.empty())
1922 auto &C = Output.Completions[SymbolToCompletion.at(S.ID)];
1923 C.Documentation.emplace();
1931 SymbolSlab queryIndex() {
1932 trace::Span Tracer(
"Query index");
1933 SPAN_ATTACH(Tracer,
"limit", int64_t(Opts.Limit));
1936 FuzzyFindRequest Req;
1938 Req.Limit = Opts.Limit;
1939 Req.Query = std::string(Filter->pattern());
1940 Req.RestrictForCodeCompletion =
true;
1941 Req.Scopes = QueryScopes;
1942 Req.AnyScope = AllScopes;
1944 Req.ProximityPaths.push_back(std::string(FileName));
1946 Req.PreferredTypes.push_back(std::string(PreferredType->raw()));
1947 vlog(
"Code complete: fuzzyFind({0:2})",
toJSON(Req));
1950 SpecFuzzyFind->NewReq = Req;
1951 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1952 vlog(
"Code complete: speculative fuzzy request matches the actual index "
1953 "request. Waiting for the speculative index results.");
1956 trace::Span WaitSpec(
"Wait speculative results");
1957 auto SpecRes = SpecFuzzyFind->Result.get();
1958 Incomplete |= SpecRes.first;
1959 return std::move(SpecRes.second);
1962 SPAN_ATTACH(Tracer,
"Speculative results",
false);
1965 SymbolSlab::Builder ResultsBuilder;
1966 Incomplete |= Opts.Index->fuzzyFind(
1967 Req, [&](
const Symbol &Sym) { ResultsBuilder.insert(Sym); });
1968 return std::move(ResultsBuilder).build();
1976 std::vector<ScoredBundle>
1977 mergeResults(
const std::vector<CodeCompletionResult> &SemaResults,
1978 const SymbolSlab &IndexResults,
1979 const std::vector<RawIdentifier> &IdentifierResults) {
1980 trace::Span Tracer(
"Merge and score results");
1981 std::vector<CompletionCandidate::Bundle> Bundles;
1982 llvm::DenseMap<size_t, size_t> BundleLookup;
1983 auto AddToBundles = [&](
const CodeCompletionResult *SemaResult,
1984 const Symbol *IndexResult,
1985 const RawIdentifier *IdentifierResult) {
1986 CompletionCandidate C;
1987 C.SemaResult = SemaResult;
1988 C.IndexResult = IndexResult;
1989 C.IdentifierResult = IdentifierResult;
1990 if (C.IndexResult) {
1991 C.Name = IndexResult->Name;
1993 }
else if (C.SemaResult) {
1994 C.Name = Recorder->getName(*SemaResult);
1996 assert(IdentifierResult);
1997 C.Name = IdentifierResult->Name;
1999 if (
auto OverloadSet = C.overloadSet(
2000 Opts, FileName, Inserter ? &*Inserter :
nullptr, CCContextKind)) {
2001 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
2003 Bundles.emplace_back();
2004 Bundles[Ret.first->second].push_back(std::move(C));
2006 Bundles.emplace_back();
2007 Bundles.back().push_back(std::move(C));
2010 llvm::DenseSet<const Symbol *> UsedIndexResults;
2011 auto CorrespondingIndexResult =
2012 [&](
const CodeCompletionResult &SemaResult) ->
const Symbol * {
2014 getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
2015 auto I = IndexResults.find(SymID);
2016 if (I != IndexResults.end()) {
2017 UsedIndexResults.insert(&*I);
2024 for (
auto &SemaResult : SemaResults)
2025 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult),
nullptr);
2027 for (
const auto &IndexResult : IndexResults) {
2028 if (UsedIndexResults.count(&IndexResult))
2030 if (!includeSymbolFromIndex(CCContextKind, IndexResult))
2032 AddToBundles(
nullptr, &IndexResult,
nullptr);
2035 for (
const auto &Ident : IdentifierResults)
2036 AddToBundles(
nullptr,
nullptr, &Ident);
2038 TopN<ScoredBundle, ScoredBundleGreater> Top(
2039 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
2040 for (
auto &Bundle : Bundles)
2041 addCandidate(Top, std::move(Bundle));
2042 return std::move(Top).items();
2045 std::optional<float> fuzzyScore(
const CompletionCandidate &C) {
2048 const auto IsMacroResult =
2050 C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
2052 C.IndexResult->SymInfo.Kind == index::SymbolKind::Macro));
2055 return Filter->match(C.Name);
2058 bool RequireExactPrefix =
2059 Opts.MacroFilter == MacroFilterPolicy::ExactPrefix ||
2060 C.Name.starts_with_insensitive(
"_") ||
2061 C.Name.ends_with_insensitive(
"_");
2063 if (RequireExactPrefix &&
2064 !C.Name.starts_with_insensitive(Filter->pattern())) {
2065 return std::nullopt;
2068 return Filter->match(C.Name);
2071 CodeCompletion::Scores
2072 evaluateCompletion(
const SymbolQualitySignals &Quality,
2073 const SymbolRelevanceSignals &Relevance) {
2074 using RM = CodeCompleteOptions::CodeCompletionRankingModel;
2075 CodeCompletion::Scores Scores;
2076 switch (Opts.RankingModel) {
2077 case RM::Heuristics:
2078 Scores.Quality = Quality.evaluateHeuristics();
2079 Scores.Relevance = Relevance.evaluateHeuristics();
2084 Scores.ExcludingName =
2085 Relevance.NameMatch > std::numeric_limits<float>::epsilon()
2086 ? Scores.Total / Relevance.NameMatch
2090 case RM::DecisionForest:
2091 DecisionForestScores DFScores = Opts.DecisionForestScorer(
2092 Quality, Relevance, Opts.DecisionForestBase);
2093 Scores.ExcludingName = DFScores.ExcludingName;
2094 Scores.Total = DFScores.Total;
2097 llvm_unreachable(
"Unhandled CodeCompletion ranking model.");
2101 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
2102 CompletionCandidate::Bundle Bundle) {
2103 SymbolQualitySignals Quality;
2104 SymbolRelevanceSignals Relevance;
2105 Relevance.Context = CCContextKind;
2106 Relevance.Name = Bundle.front().Name;
2107 Relevance.FilterLength = HeuristicPrefix.Name.size();
2109 Relevance.FileProximityMatch = &*FileProximity;
2111 Relevance.ScopeProximityMatch = &*ScopeProximity;
2113 Relevance.HadContextType =
true;
2114 Relevance.ContextWords = &ContextWords;
2115 Relevance.MainFileSignals = Opts.MainFileSignals;
2117 auto &First = Bundle.front();
2118 if (
auto FuzzyScore = fuzzyScore(First))
2119 Relevance.NameMatch = *FuzzyScore;
2123 bool FromIndex =
false;
2124 for (
const auto &Candidate : Bundle) {
2125 if (Candidate.IndexResult) {
2126 Quality.merge(*Candidate.IndexResult);
2127 Relevance.merge(*Candidate.IndexResult);
2128 Origin |= Candidate.IndexResult->Origin;
2130 if (!Candidate.IndexResult->Type.empty())
2131 Relevance.HadSymbolType |=
true;
2132 if (PreferredType &&
2133 PreferredType->raw() == Candidate.IndexResult->Type) {
2134 Relevance.TypeMatchesPreferred =
true;
2137 if (Candidate.SemaResult) {
2138 Quality.merge(*Candidate.SemaResult);
2139 Relevance.merge(*Candidate.SemaResult);
2140 if (PreferredType) {
2142 Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
2143 Relevance.HadSymbolType |=
true;
2144 if (PreferredType == CompletionType)
2145 Relevance.TypeMatchesPreferred =
true;
2150 if (Candidate.IdentifierResult) {
2151 Quality.References = Candidate.IdentifierResult->References;
2157 CodeCompletion::Scores Scores = evaluateCompletion(Quality, Relevance);
2158 if (Opts.RecordCCResult)
2159 Opts.RecordCCResult(toCodeCompletion(Bundle), Quality, Relevance,
2162 dlog(
"CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
2163 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
2164 llvm::to_string(Relevance));
2167 NIndex += FromIndex;
2170 if (Candidates.push({std::move(Bundle), Scores}))
2174 CodeCompletion toCodeCompletion(
const CompletionCandidate::Bundle &Bundle) {
2175 std::optional<CodeCompletionBuilder> Builder;
2176 for (
const auto &Item : Bundle) {
2177 CodeCompletionString *SemaCCS =
2178 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
2181 Builder.emplace(Recorder ? &Recorder->CCSema->getASTContext() :
nullptr,
2182 Item, SemaCCS, AccessibleScopes, *Inserter, FileName,
2183 CCContextKind, Opts, IsUsingDeclaration, NextTokenKind);
2185 Builder->add(Item, SemaCCS, CCContextKind);
2187 return Builder->build();
2194 clang::CodeCompleteOptions
Result;
2195 Result.IncludeCodePatterns =
2197 Result.IncludeMacros =
true;
2198 Result.IncludeGlobals =
true;
2203 Result.IncludeBriefComments =
false;
2208 Result.LoadExternal = ForceLoadPreamble || !Index;
2209 Result.IncludeFixIts = IncludeFixIts;
2216 assert(Offset <= Content.size());
2217 StringRef Rest = Content.take_front(Offset);
2222 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2223 Rest = Rest.drop_back();
2224 Result.
Name = Content.slice(Rest.size(), Offset);
2227 while (Rest.consume_back(
"::") && !Rest.ends_with(
":"))
2228 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2229 Rest = Rest.drop_back();
2231 Content.slice(Rest.size(), Result.
Name.begin() - Content.begin());
2239static std::optional<unsigned>
2241 const llvm::StringRef Content,
2242 const LangOptions &LangOpts) {
2243 if (Offset > Content.size())
2244 return std::nullopt;
2246 SourceManagerForFile FileSM(FileName, Content);
2247 const SourceManager &SM = FileSM.get();
2248 const SourceLocation Cursor = SM.getComposedLoc(SM.getMainFileID(), Offset);
2249 const SourceLocation EndOfSuffix =
2250 Lexer::findEndOfIdentifierContinuation(Cursor, SM, LangOpts);
2251 const unsigned EndOfSuffixOffset = SM.getFileOffset(EndOfSuffix);
2253 const llvm::StringRef Rest = Content.drop_front(EndOfSuffixOffset);
2254 llvm::StringRef RestTrimmed = Rest.ltrim();
2256 if (RestTrimmed.starts_with(
"="))
2257 RestTrimmed = RestTrimmed.drop_front(1).ltrim();
2258 if (RestTrimmed.starts_with(
"*/"))
2259 return EndOfSuffixOffset + (Rest.size() - RestTrimmed.size()) + 2;
2260 return std::nullopt;
2268 unsigned OutsideStartOffset, llvm::StringRef Prefix,
2272 return CodeCompleteResult();
2277 return CodeCompleteResult();
2279 std::optional<unsigned> OutsideEndOffset;
2280 if (Opts.EnableInsertReplace)
2282 FileName, CursorOffset, ParseInput.
Contents, CI->getLangOpts());
2284 clang::CodeCompleteOptions Options;
2285 Options.IncludeGlobals =
false;
2286 Options.IncludeMacros =
false;
2287 Options.IncludeCodePatterns =
false;
2288 Options.IncludeBriefComments =
false;
2289 std::set<std::string> ParamNames;
2293 std::make_unique<ParamNameCollector>(Options, ParamNames), Options,
2294 {FileName, OutsideStartOffset, *
Preamble,
2297 nullptr, std::move(CI));
2298 if (ParamNames.empty())
2299 return CodeCompleteResult();
2301 CodeCompleteResult Result;
2304 const unsigned InsideStartOffset = OutsideStartOffset + 2;
2308 Result.InsertRange = InsertRange;
2310 if (Opts.EnableInsertReplace) {
2316 Result.ReplaceRange = ReplaceRange;
2319 Result.Context = CodeCompletionContext::CCC_NaturalLanguage;
2320 for (llvm::StringRef Name : ParamNames) {
2321 if (!Name.starts_with(Prefix))
2323 CodeCompletion Item;
2324 Item.Name = Name.str() +
"=*/";
2325 Item.FilterText = Item.Name;
2327 Item.CompletionInsertRange = InsertRange;
2328 Item.CompletionReplaceRange = Result.ReplaceRange;
2330 Result.Completions.push_back(Item);
2339std::optional<unsigned>
2341 while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
2342 Content = Content.drop_back();
2343 Content = Content.rtrim();
2344 if (Content.ends_with(
"/*"))
2345 return Content.size() - 2;
2346 return std::nullopt;
2353 SpeculativeFuzzyFind *SpecFuzzyFind) {
2356 elog(
"Code completion position was invalid {0}", Offset.takeError());
2357 return CodeCompleteResult();
2360 auto Content = llvm::StringRef(ParseInput.
Contents).take_front(*Offset);
2367 auto CommentPrefix = Content.substr(*OffsetBeforeComment + 2).trim();
2369 CommentPrefix,
Preamble, ParseInput, Opts);
2372 auto Flow = CodeCompleteFlow(
2374 SpecFuzzyFind, Opts);
2375 return (!
Preamble || Opts.RunParser == CodeCompleteOptions::NeverParse)
2376 ? std::move(Flow).runWithoutSema(ParseInput.
Contents, *Offset,
2378 : std::move(Flow).run({FileName, *Offset, *
Preamble,
2391 elog(
"Signature help position was invalid {0}", Offset.takeError());
2395 clang::CodeCompleteOptions Options;
2396 Options.IncludeGlobals =
false;
2397 Options.IncludeMacros =
false;
2398 Options.IncludeCodePatterns =
false;
2399 Options.IncludeBriefComments =
false;
2401 std::make_unique<SignatureHelpCollector>(Options, DocumentationFormat,
2402 ParseInput.
Index, Result),
2404 {FileName, *Offset, Preamble,
2405 PreamblePatch::createFullPatch(FileName, ParseInput, Preamble),
2411 auto InTopLevelScope = [](
const NamedDecl &ND) {
2412 switch (ND.getDeclContext()->getDeclKind()) {
2413 case Decl::TranslationUnit:
2414 case Decl::Namespace:
2415 case Decl::LinkageSpec:
2422 auto InClassScope = [](
const NamedDecl &ND) {
2423 return ND.getDeclContext()->getDeclKind() == Decl::CXXRecord;
2434 if (llvm::isa<ObjCCategoryDecl>(&ND) || llvm::isa<ObjCCategoryImplDecl>(&ND))
2437 if (InTopLevelScope(ND))
2443 if (
const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
2444 return (InTopLevelScope(*EnumDecl) || InClassScope(*EnumDecl));
2449CompletionItem CodeCompletion::render(
const CodeCompleteOptions &Opts)
const {
2451 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
2454 LSP.label = ((InsertInclude && InsertInclude->Insertion)
2455 ? Opts.IncludeIndicator.Insert
2456 : Opts.IncludeIndicator.NoInsert) +
2457 (Opts.ShowOrigins ?
"[" + llvm::to_string(Origin) +
"]" :
"") +
2458 RequiredQualifier + Name;
2459 LSP.labelDetails.emplace();
2460 LSP.labelDetails->detail = Signature;
2463 LSP.detail = BundleSize > 1
2464 ? std::string(llvm::formatv(
"[{0} overloads]", BundleSize))
2469 if (InsertInclude || Documentation) {
2470 markup::Document Doc;
2472 Doc.addParagraph().appendText(
"From ").appendCode(InsertInclude->Header);
2474 Doc.append(*Documentation);
2475 LSP.documentation = renderDoc(Doc, Opts.DocumentationFormat);
2477 LSP.sortText =
sortText(Score.Total, FilterText);
2478 LSP.filterText = FilterText;
2480 Edit.range = CompletionInsertRange;
2481 Edit.newText = RequiredQualifier + Name;
2489 for (
const auto &FixIt : FixIts) {
2490 if (FixIt.range.end == Edit.range.start) {
2491 Edit.newText = FixIt.newText + Edit.newText;
2492 Edit.range.start = FixIt.range.start;
2494 LSP.additionalTextEdits.push_back(FixIt);
2497 if (Opts.EnableSnippets)
2498 Edit.newText += SnippetSuffix;
2502 LSP.insertText =
Edit.newText;
2503 if (Opts.EnableInsertReplace) {
2504 assert(CompletionReplaceRange &&
2505 "CompletionReplaceRange must be already set before render() "
2506 "when EnableInsertReplace is on");
2509 IRE.insert =
Edit.range;
2510 IRE.replace = *CompletionReplaceRange;
2513 IRE.replace.start = IRE.insert.start;
2514 LSP.textEdit = std::move(IRE);
2516 LSP.textEdit = std::move(
Edit);
2521 LSP.insertTextFormat = (Opts.EnableSnippets && !SnippetSuffix.empty())
2524 if (InsertInclude && InsertInclude->Insertion)
2525 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
2527 LSP.score = Score.ExcludingName;
2532llvm::raw_ostream &
operator<<(llvm::raw_ostream &OS,
const CodeCompletion &C) {
2533 OS <<
"Signature: " <<
"\"" << C.Signature <<
"\", "
2534 <<
"SnippetSuffix: " <<
"\"" << C.SnippetSuffix <<
"\""
2541 const CodeCompleteResult &R) {
2542 OS <<
"CodeCompleteResult: " << R.Completions.size() << (R.HasMore ?
"+" :
"")
2543 <<
" (" << getCompletionKindString(R.Context) <<
")"
2545 for (
const auto &C : R.Completions)
2552 Line = Line.ltrim();
2553 if (!Line.consume_front(
"#"))
2555 Line = Line.ltrim();
2556 if (!(Line.consume_front(
"include_next") || Line.consume_front(
"include") ||
2557 Line.consume_front(
"import")))
2559 Line = Line.ltrim();
2560 if (Line.consume_front(
"<"))
2561 return Line.count(
'>') == 0;
2562 if (Line.consume_front(
"\""))
2563 return Line.count(
'"') == 0;
2569 Content = Content.take_front(Offset);
2570 auto Pos = Content.rfind(
'\n');
2571 if (Pos != llvm::StringRef::npos)
2572 Content = Content.substr(Pos + 1);
2575 if (Content.ends_with(
".") || Content.ends_with(
"->") ||
2576 Content.ends_with(
"::") || Content.ends_with(
"/*"))
2579 if ((Content.ends_with(
"<") || Content.ends_with(
"\"") ||
2580 Content.ends_with(
"/")) &&
2585 return !Content.empty() && (isAsciiIdentifierContinue(Content.back()) ||
2586 !llvm::isASCII(Content.back()));
static clang::FrontendPluginRegistry::Add< clang::tidy::ClangTidyPluginAction > X("clang-tidy", "clang-tidy")
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
static std::optional< OpaqueType > fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R)
Create a type from a code completion result.
static std::optional< OpaqueType > fromType(ASTContext &Ctx, QualType Type)
Construct an instance from a clang::QualType.
static PreamblePatch createMacroPatch(llvm::StringRef FileName, const ParseInputs &Modified, const PreambleData &Baseline)
static PreamblePatch createFullPatch(llvm::StringRef FileName, const ParseInputs &Modified, const PreambleData &Baseline)
Builds a patch that contains new PP directives introduced to the preamble section of Modified compare...
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
@ Info
An information message.
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
std::string formatDocumentation(const CodeCompletionString &CCS, llvm::StringRef DocComment)
Assembles formatted documentation for a completion result.
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
std::string sortText(float Score, llvm::StringRef Name)
Returns a string that sorts in the same order as (-Score, Tiebreak), for LSP.
std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl)
Similar to getDocComment, but returns the comment for a NamedDecl.
bool isIncludeFile(llvm::StringRef Line)
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, const LangOptions &L)
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
size_t lspLength(llvm::StringRef Code)
CompletionPrefix guessCompletionPrefix(llvm::StringRef Content, unsigned Offset)
std::unique_ptr< CompilerInvocation > buildCompilerInvocation(const ParseInputs &Inputs, clang::DiagnosticConsumer &D, std::vector< std::string > *CC1Args)
Builds compiler invocation that could be used to build AST or preamble.
bool isExplicitTemplateSpecialization(const NamedDecl *D)
Indicates if D is an explicit template specialization, e.g.
bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset)
void vlog(const char *Fmt, Ts &&... Vals)
static const char * toString(OffsetEncoding OE)
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
std::string getReturnType(const CodeCompletionString &CCS)
Gets detail to be used as the detail field in an LSP completion item.
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
llvm::StringMap< unsigned > collectIdentifiers(llvm::StringRef Content, const format::FormatStyle &Style)
Collects identifiers with counts in the source code.
bool hasUnstableLinkage(const Decl *D)
Whether we must avoid computing linkage for D during code completion.
llvm::json::Value toJSON(const FuzzyFindRequest &Request)
std::vector< std::string > visibleNamespaces(llvm::StringRef Code, const LangOptions &LangOpts)
Heuristically determine namespaces visible at a point, without parsing Code.
llvm::Expected< HeaderFile > toHeaderFile(llvm::StringRef Header, llvm::StringRef HintPath)
Creates a HeaderFile from Header which can be either a URI or a literal include.
std::unique_ptr< CompilerInstance > prepareCompilerInstance(std::unique_ptr< clang::CompilerInvocation > CI, const PrecompiledPreamble *Preamble, std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, DiagnosticConsumer &DiagsClient)
std::future< T > runAsync(llvm::unique_function< T()> Action)
Runs Action asynchronously with a new std::thread.
void log(const char *Fmt, Ts &&... Vals)
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
std::optional< unsigned > maybeFunctionArgumentCommentStart(llvm::StringRef Content)
llvm::StringSet collectWords(llvm::StringRef Content)
Collects words from the source code.
void getSignature(const CodeCompletionString &CCS, std::string *Signature, std::string *Snippet, CodeCompletionResult::ResultKind ResultKind, CXCursorKind CursorKind, bool IncludeFunctionArguments, std::string *RequiredQualifiers)
Formats the signature for an item, as a display string and snippet.
llvm::StringRef PathRef
A typedef to represent a ref to file path.
CodeCompleteResult codeCompleteComment(PathRef FileName, const unsigned CursorOffset, unsigned OutsideStartOffset, llvm::StringRef Prefix, const PreambleData *Preamble, const ParseInputs &ParseInput, const CodeCompleteOptions &Opts)
llvm::SmallVector< SymbolInclude, 1 > getRankedIncludes(const Symbol &Sym)
std::pair< size_t, size_t > offsetToClangLineColumn(llvm::StringRef Code, size_t Offset)
@ Deprecated
Deprecated or obsolete code.
@ Full
Documents are synced by always sending the full content of the document.
void parseDocumentation(llvm::StringRef Input, markup::Document &Output)
float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance)
Combine symbol quality and relevance into a single score.
CodeCompleteResult codeComplete(PathRef FileName, Position Pos, const PreambleData *Preamble, const ParseInputs &ParseInput, CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind)
Gets code completions at a specified Pos in FileName.
@ PlainText
The primary text to be inserted is treated as a plain string.
@ Snippet
The primary text to be inserted is treated as a snippet.
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
SignatureHelp signatureHelp(PathRef FileName, Position Pos, const PreambleData &Preamble, const ParseInputs &ParseInput, MarkupKind DocumentationFormat)
Get signature help at a specified Pos in FileName.
void elog(const char *Fmt, Ts &&... Vals)
std::string getDocComment(const ASTContext &Ctx, const CodeCompletionResult &Result, bool CommentsFromHeaders)
Gets a minimally formatted documentation comment of Result, with comment markers stripped.
static std::optional< unsigned > maybeFunctionArgumentCommentEnd(const PathRef FileName, const unsigned Offset, const llvm::StringRef Content, const LangOptions &LangOpts)
std::string printNamespaceScope(const DeclContext &DC)
Returns the first enclosing namespace scope starting from DC.
bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx)
PreambleBounds computePreambleBounds(const LangOptions &LangOpts, const llvm::MemoryBufferRef &Buffer, bool SkipPreambleBuild)
format::FormatStyle getFormatStyleForFile(llvm::StringRef File, llvm::StringRef Content, const ThreadsafeFS &TFS, bool FormatFile)
Choose the clang-format style we should apply to a certain file.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
clang::CodeCompleteOptions getClangCompleteOpts() const
Returns options that can be passed to clang's completion engine.
llvm::StringRef Qualifier
struct clang::clangd::Config::@314053012031341203055315320366267371313202370174 Style
Style of the codebase.
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
ArgumentListsPolicy
controls the completion options for argument lists.
@ None
nothing, no argument list and also NO Delimiters "()" or "<>".
@ Delimiters
empty pair of delimiters "()" or "<>".
@ OpenDelimiter
open, only opening delimiter "(" or "<".
@ FullPlaceholders
full name of both type and variable.
@ PlainText
Treat comments as plain text.
std::vector< std::function< bool(llvm::StringRef)> > QuotedHeaders
CodePatternsPolicy CodePatterns
Enables code patterns & snippets suggestions.
CommentFormatPolicy CommentFormat
std::vector< std::function< bool(llvm::StringRef)> > AngledHeaders
A set of edits generated for a single file.
std::string newText
The string to be inserted.
The parsed preamble and associated data.
Position start
The range's start position.
Position end
The range's end position.
Represents the signature of a callable.
@ Deprecated
Indicates if the symbol is deprecated.
@ Include
#include "header.h"
@ Import
#import "header.h"