1 //===--- CodeComplete.cpp ---------------------------------------*- C++-*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===---------------------------------------------------------------------===//
9 //
10 // Code completion has several moving parts:
11 //  - AST-based completions are provided using the completion hooks in Sema.
12 //  - external completions are retrieved from the index (using hints from Sema)
13 //  - the two sources overlap, and must be merged and overloads bundled
14 //  - results must be scored and ranked (see Quality.h) before rendering
15 //
16 // Signature help works in a similar way as code completion, but it is simpler:
17 // it's purely AST-based, and there are few candidates.
18 //
19 //===---------------------------------------------------------------------===//
20 
21 #include "CodeComplete.h"
22 #include "AST.h"
23 #include "CodeCompletionStrings.h"
24 #include "Compiler.h"
25 #include "FuzzyMatch.h"
26 #include "Headers.h"
27 #include "Logger.h"
28 #include "Quality.h"
29 #include "SourceCode.h"
30 #include "Trace.h"
31 #include "URI.h"
32 #include "index/Index.h"
33 #include "clang/ASTMatchers/ASTMatchFinder.h"
34 #include "clang/Basic/LangOptions.h"
35 #include "clang/Format/Format.h"
36 #include "clang/Frontend/CompilerInstance.h"
37 #include "clang/Frontend/FrontendActions.h"
38 #include "clang/Index/USRGeneration.h"
39 #include "clang/Sema/CodeCompleteConsumer.h"
40 #include "clang/Sema/Sema.h"
41 #include "clang/Tooling/Core/Replacement.h"
42 #include "llvm/Support/Format.h"
43 #include <queue>
44 
45 // We log detailed candidate here if you run with -debug-only=codecomplete.
46 #define DEBUG_TYPE "CodeComplete"
47 
48 namespace clang {
49 namespace clangd {
50 namespace {
51 
52 CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
53   using SK = index::SymbolKind;
54   switch (Kind) {
55   case SK::Unknown:
56     return CompletionItemKind::Missing;
57   case SK::Module:
58   case SK::Namespace:
59   case SK::NamespaceAlias:
60     return CompletionItemKind::Module;
61   case SK::Macro:
62     return CompletionItemKind::Text;
63   case SK::Enum:
64     return CompletionItemKind::Enum;
65   // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
66   // protocol.
67   case SK::Struct:
68   case SK::Class:
69   case SK::Protocol:
70   case SK::Extension:
71   case SK::Union:
72     return CompletionItemKind::Class;
73   // FIXME(ioeric): figure out whether reference is the right type for aliases.
74   case SK::TypeAlias:
75   case SK::Using:
76     return CompletionItemKind::Reference;
77   case SK::Function:
78   // FIXME(ioeric): this should probably be an operator. This should be fixed
79   // when `Operator` is support type in the protocol.
80   case SK::ConversionFunction:
81     return CompletionItemKind::Function;
82   case SK::Variable:
83   case SK::Parameter:
84     return CompletionItemKind::Variable;
85   case SK::Field:
86     return CompletionItemKind::Field;
87   // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
88   case SK::EnumConstant:
89     return CompletionItemKind::Value;
90   case SK::InstanceMethod:
91   case SK::ClassMethod:
92   case SK::StaticMethod:
93   case SK::Destructor:
94     return CompletionItemKind::Method;
95   case SK::InstanceProperty:
96   case SK::ClassProperty:
97   case SK::StaticProperty:
98     return CompletionItemKind::Property;
99   case SK::Constructor:
100     return CompletionItemKind::Constructor;
101   }
102   llvm_unreachable("Unhandled clang::index::SymbolKind.");
103 }
104 
105 CompletionItemKind
106 toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
107                      const NamedDecl *Decl) {
108   if (Decl)
109     return toCompletionItemKind(index::getSymbolInfo(Decl).Kind);
110   switch (ResKind) {
111   case CodeCompletionResult::RK_Declaration:
112     llvm_unreachable("RK_Declaration without Decl");
113   case CodeCompletionResult::RK_Keyword:
114     return CompletionItemKind::Keyword;
115   case CodeCompletionResult::RK_Macro:
116     return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
117                                      // completion items in LSP.
118   case CodeCompletionResult::RK_Pattern:
119     return CompletionItemKind::Snippet;
120   }
121   llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
122 }
123 
124 /// Get the optional chunk as a string. This function is possibly recursive.
125 ///
126 /// The parameter info for each parameter is appended to the Parameters.
127 std::string
128 getOptionalParameters(const CodeCompletionString &CCS,
129                       std::vector<ParameterInformation> &Parameters) {
130   std::string Result;
131   for (const auto &Chunk : CCS) {
132     switch (Chunk.Kind) {
133     case CodeCompletionString::CK_Optional:
134       assert(Chunk.Optional &&
135              "Expected the optional code completion string to be non-null.");
136       Result += getOptionalParameters(*Chunk.Optional, Parameters);
137       break;
138     case CodeCompletionString::CK_VerticalSpace:
139       break;
140     case CodeCompletionString::CK_Placeholder:
141       // A string that acts as a placeholder for, e.g., a function call
142       // argument.
143       // Intentional fallthrough here.
144     case CodeCompletionString::CK_CurrentParameter: {
145       // A piece of text that describes the parameter that corresponds to
146       // the code-completion location within a function call, message send,
147       // macro invocation, etc.
148       Result += Chunk.Text;
149       ParameterInformation Info;
150       Info.label = Chunk.Text;
151       Parameters.push_back(std::move(Info));
152       break;
153     }
154     default:
155       Result += Chunk.Text;
156       break;
157     }
158   }
159   return Result;
160 }
161 
162 /// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
163 /// include.
164 static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
165                                                llvm::StringRef HintPath) {
166   if (isLiteralInclude(Header))
167     return HeaderFile{Header.str(), /*Verbatim=*/true};
168   auto U = URI::parse(Header);
169   if (!U)
170     return U.takeError();
171 
172   auto IncludePath = URI::includeSpelling(*U);
173   if (!IncludePath)
174     return IncludePath.takeError();
175   if (!IncludePath->empty())
176     return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
177 
178   auto Resolved = URI::resolve(*U, HintPath);
179   if (!Resolved)
180     return Resolved.takeError();
181   return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
182 }
183 
184 /// A code completion result, in clang-native form.
185 /// It may be promoted to a CompletionItem if it's among the top-ranked results.
186 struct CompletionCandidate {
187   llvm::StringRef Name; // Used for filtering and sorting.
188   // We may have a result from Sema, from the index, or both.
189   const CodeCompletionResult *SemaResult = nullptr;
190   const Symbol *IndexResult = nullptr;
191 
192   // Returns a token identifying the overload set this is part of.
193   // 0 indicates it's not part of any overload set.
194   size_t overloadSet() const {
195     SmallString<256> Scratch;
196     if (IndexResult) {
197       switch (IndexResult->SymInfo.Kind) {
198       case index::SymbolKind::ClassMethod:
199       case index::SymbolKind::InstanceMethod:
200       case index::SymbolKind::StaticMethod:
201         assert(false && "Don't expect members from index in code completion");
202         // fall through
203       case index::SymbolKind::Function:
204         // We can't group overloads together that need different #includes.
205         // This could break #include insertion.
206         return hash_combine(
207             (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
208             headerToInsertIfNotPresent().getValueOr(""));
209       default:
210         return 0;
211       }
212     }
213     assert(SemaResult);
214     // We need to make sure we're consistent with the IndexResult case!
215     const NamedDecl *D = SemaResult->Declaration;
216     if (!D || !D->isFunctionOrFunctionTemplate())
217       return 0;
218     {
219       llvm::raw_svector_ostream OS(Scratch);
220       D->printQualifiedName(OS);
221     }
222     return hash_combine(Scratch, headerToInsertIfNotPresent().getValueOr(""));
223   }
224 
225   llvm::Optional<llvm::StringRef> headerToInsertIfNotPresent() const {
226     if (!IndexResult || !IndexResult->Detail ||
227         IndexResult->Detail->IncludeHeader.empty())
228       return llvm::None;
229     if (SemaResult && SemaResult->Declaration) {
230       // Avoid inserting new #include if the declaration is found in the current
231       // file e.g. the symbol is forward declared.
232       auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
233       for (const Decl *RD : SemaResult->Declaration->redecls())
234         if (SM.isInMainFile(SM.getExpansionLoc(RD->getLocStart())))
235           return llvm::None;
236     }
237     return IndexResult->Detail->IncludeHeader;
238   }
239 
240   using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
241 };
242 using ScoredBundle =
243     std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
244 struct ScoredBundleGreater {
245   bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
246     if (L.second.Total != R.second.Total)
247       return L.second.Total > R.second.Total;
248     return L.first.front().Name <
249            R.first.front().Name; // Earlier name is better.
250   }
251 };
252 
253 // Assembles a code completion out of a bundle of >=1 completion candidates.
254 // Many of the expensive strings are only computed at this point, once we know
255 // the candidate bundle is going to be returned.
256 //
257 // Many fields are the same for all candidates in a bundle (e.g. name), and are
258 // computed from the first candidate, in the constructor.
259 // Others vary per candidate, so add() must be called for remaining candidates.
260 struct CodeCompletionBuilder {
261   CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
262                         CodeCompletionString *SemaCCS,
263                         const IncludeInserter &Includes, StringRef FileName,
264                         const CodeCompleteOptions &Opts)
265       : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments) {
266     add(C, SemaCCS);
267     if (C.SemaResult) {
268       Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
269       if (Completion.Scope.empty())
270         if (C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
271           if (const auto *D = C.SemaResult->getDeclaration())
272             if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
273               Completion.Scope =
274                   splitQualifiedName(printQualifiedName(*ND)).first;
275       Completion.Kind =
276           toCompletionItemKind(C.SemaResult->Kind, C.SemaResult->Declaration);
277     }
278     if (C.IndexResult) {
279       if (Completion.Scope.empty())
280         Completion.Scope = C.IndexResult->Scope;
281       if (Completion.Kind == CompletionItemKind::Missing)
282         Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
283       if (Completion.Name.empty())
284         Completion.Name = C.IndexResult->Name;
285     }
286     if (auto Inserted = C.headerToInsertIfNotPresent()) {
287       // Turn absolute path into a literal string that can be #included.
288       auto Include = [&]() -> Expected<std::pair<std::string, bool>> {
289         auto ResolvedDeclaring =
290             toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
291         if (!ResolvedDeclaring)
292           return ResolvedDeclaring.takeError();
293         auto ResolvedInserted = toHeaderFile(*Inserted, FileName);
294         if (!ResolvedInserted)
295           return ResolvedInserted.takeError();
296         return std::make_pair(Includes.calculateIncludePath(*ResolvedDeclaring,
297                                                             *ResolvedInserted),
298                               Includes.shouldInsertInclude(*ResolvedDeclaring,
299                                                            *ResolvedInserted));
300       }();
301       if (Include) {
302         Completion.Header = Include->first;
303         if (Include->second)
304           Completion.HeaderInsertion = Includes.insert(Include->first);
305       } else
306         log(llvm::formatv(
307             "Failed to generate include insertion edits for adding header "
308             "(FileURI='{0}', IncludeHeader='{1}') into {2}",
309             C.IndexResult->CanonicalDeclaration.FileURI,
310             C.IndexResult->Detail->IncludeHeader, FileName));
311     }
312   }
313 
314   void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {
315     assert(bool(C.SemaResult) == bool(SemaCCS));
316     Bundled.emplace_back();
317     BundledEntry &S = Bundled.back();
318     if (C.SemaResult) {
319       getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
320                    &Completion.RequiredQualifier);
321       S.ReturnType = getReturnType(*SemaCCS);
322     } else if (C.IndexResult) {
323       S.Signature = C.IndexResult->Signature;
324       S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix;
325       if (auto *D = C.IndexResult->Detail)
326         S.ReturnType = D->ReturnType;
327     }
328     if (ExtractDocumentation && Completion.Documentation.empty()) {
329       if (C.IndexResult && C.IndexResult->Detail)
330         Completion.Documentation = C.IndexResult->Detail->Documentation;
331       else if (C.SemaResult)
332         Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
333                                                  /*CommentsFromHeader=*/false);
334     }
335   }
336 
337   CodeCompletion build() {
338     Completion.ReturnType = summarizeReturnType();
339     Completion.Signature = summarizeSignature();
340     Completion.SnippetSuffix = summarizeSnippet();
341     Completion.BundleSize = Bundled.size();
342     return std::move(Completion);
343   }
344 
345 private:
346   struct BundledEntry {
347     std::string SnippetSuffix;
348     std::string Signature;
349     std::string ReturnType;
350   };
351 
352   // If all BundledEntrys have the same value for a property, return it.
353   template <std::string BundledEntry::*Member>
354   const std::string *onlyValue() const {
355     auto B = Bundled.begin(), E = Bundled.end();
356     for (auto I = B + 1; I != E; ++I)
357       if (I->*Member != B->*Member)
358         return nullptr;
359     return &(B->*Member);
360   }
361 
362   std::string summarizeReturnType() const {
363     if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
364       return *RT;
365     return "";
366   }
367 
368   std::string summarizeSnippet() const {
369     if (auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>())
370       return *Snippet;
371     // All bundles are function calls.
372     return "(${0})";
373   }
374 
375   std::string summarizeSignature() const {
376     if (auto *Signature = onlyValue<&BundledEntry::Signature>())
377       return *Signature;
378     // All bundles are function calls.
379     return "(…)";
380   }
381 
382   ASTContext &ASTCtx;
383   CodeCompletion Completion;
384   SmallVector<BundledEntry, 1> Bundled;
385   bool ExtractDocumentation;
386 };
387 
388 // Determine the symbol ID for a Sema code completion result, if possible.
389 llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
390   switch (R.Kind) {
391   case CodeCompletionResult::RK_Declaration:
392   case CodeCompletionResult::RK_Pattern: {
393     llvm::SmallString<128> USR;
394     if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
395       return None;
396     return SymbolID(USR);
397   }
398   case CodeCompletionResult::RK_Macro:
399     // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
400   case CodeCompletionResult::RK_Keyword:
401     return None;
402   }
403   llvm_unreachable("unknown CodeCompletionResult kind");
404 }
405 
406 // Scopes of the paritial identifier we're trying to complete.
407 // It is used when we query the index for more completion results.
408 struct SpecifiedScope {
409   // The scopes we should look in, determined by Sema.
410   //
411   // If the qualifier was fully resolved, we look for completions in these
412   // scopes; if there is an unresolved part of the qualifier, it should be
413   // resolved within these scopes.
414   //
415   // Examples of qualified completion:
416   //
417   //   "::vec"                                      => {""}
418   //   "using namespace std; ::vec^"                => {"", "std::"}
419   //   "namespace ns {using namespace std;} ns::^"  => {"ns::", "std::"}
420   //   "std::vec^"                                  => {""}  // "std" unresolved
421   //
422   // Examples of unqualified completion:
423   //
424   //   "vec^"                                       => {""}
425   //   "using namespace std; vec^"                  => {"", "std::"}
426   //   "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
427   //
428   // "" for global namespace, "ns::" for normal namespace.
429   std::vector<std::string> AccessibleScopes;
430   // The full scope qualifier as typed by the user (without the leading "::").
431   // Set if the qualifier is not fully resolved by Sema.
432   llvm::Optional<std::string> UnresolvedQualifier;
433 
434   // Construct scopes being queried in indexes.
435   // This method format the scopes to match the index request representation.
436   std::vector<std::string> scopesForIndexQuery() {
437     std::vector<std::string> Results;
438     for (llvm::StringRef AS : AccessibleScopes) {
439       Results.push_back(AS);
440       if (UnresolvedQualifier)
441         Results.back() += *UnresolvedQualifier;
442     }
443     return Results;
444   }
445 };
446 
447 // Get all scopes that will be queried in indexes.
448 std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
449                                         const SourceManager &SM) {
450   auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
451     SpecifiedScope Info;
452     for (auto *Context : CCContext.getVisitedContexts()) {
453       if (isa<TranslationUnitDecl>(Context))
454         Info.AccessibleScopes.push_back(""); // global namespace
455       else if (const auto *NS = dyn_cast<NamespaceDecl>(Context))
456         Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
457     }
458     return Info;
459   };
460 
461   auto SS = CCContext.getCXXScopeSpecifier();
462 
463   // Unqualified completion (e.g. "vec^").
464   if (!SS) {
465     // FIXME: Once we can insert namespace qualifiers and use the in-scope
466     //        namespaces for scoring, search in all namespaces.
467     // FIXME: Capture scopes and use for scoring, for example,
468     //        "using namespace std; namespace foo {v^}" =>
469     //        foo::value > std::vector > boost::variant
470     return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
471   }
472 
473   // Qualified completion ("std::vec^"), we have two cases depending on whether
474   // the qualifier can be resolved by Sema.
475   if ((*SS)->isValid()) { // Resolved qualifier.
476     return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
477   }
478 
479   // Unresolved qualifier.
480   // FIXME: When Sema can resolve part of a scope chain (e.g.
481   // "known::unknown::id"), we should expand the known part ("known::") rather
482   // than treating the whole thing as unknown.
483   SpecifiedScope Info;
484   Info.AccessibleScopes.push_back(""); // global namespace
485 
486   Info.UnresolvedQualifier =
487       Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM,
488                            clang::LangOptions())
489           .ltrim("::");
490   // Sema excludes the trailing "::".
491   if (!Info.UnresolvedQualifier->empty())
492     *Info.UnresolvedQualifier += "::";
493 
494   return Info.scopesForIndexQuery();
495 }
496 
497 // Should we perform index-based completion in a context of the specified kind?
498 // FIXME: consider allowing completion, but restricting the result types.
499 bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
500   switch (K) {
501   case CodeCompletionContext::CCC_TopLevel:
502   case CodeCompletionContext::CCC_ObjCInterface:
503   case CodeCompletionContext::CCC_ObjCImplementation:
504   case CodeCompletionContext::CCC_ObjCIvarList:
505   case CodeCompletionContext::CCC_ClassStructUnion:
506   case CodeCompletionContext::CCC_Statement:
507   case CodeCompletionContext::CCC_Expression:
508   case CodeCompletionContext::CCC_ObjCMessageReceiver:
509   case CodeCompletionContext::CCC_EnumTag:
510   case CodeCompletionContext::CCC_UnionTag:
511   case CodeCompletionContext::CCC_ClassOrStructTag:
512   case CodeCompletionContext::CCC_ObjCProtocolName:
513   case CodeCompletionContext::CCC_Namespace:
514   case CodeCompletionContext::CCC_Type:
515   case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
516   case CodeCompletionContext::CCC_PotentiallyQualifiedName:
517   case CodeCompletionContext::CCC_ParenthesizedExpression:
518   case CodeCompletionContext::CCC_ObjCInterfaceName:
519   case CodeCompletionContext::CCC_ObjCCategoryName:
520     return true;
521   case CodeCompletionContext::CCC_Other: // Be conservative.
522   case CodeCompletionContext::CCC_OtherWithMacros:
523   case CodeCompletionContext::CCC_DotMemberAccess:
524   case CodeCompletionContext::CCC_ArrowMemberAccess:
525   case CodeCompletionContext::CCC_ObjCPropertyAccess:
526   case CodeCompletionContext::CCC_MacroName:
527   case CodeCompletionContext::CCC_MacroNameUse:
528   case CodeCompletionContext::CCC_PreprocessorExpression:
529   case CodeCompletionContext::CCC_PreprocessorDirective:
530   case CodeCompletionContext::CCC_NaturalLanguage:
531   case CodeCompletionContext::CCC_SelectorName:
532   case CodeCompletionContext::CCC_TypeQualifiers:
533   case CodeCompletionContext::CCC_ObjCInstanceMessage:
534   case CodeCompletionContext::CCC_ObjCClassMessage:
535   case CodeCompletionContext::CCC_Recovery:
536     return false;
537   }
538   llvm_unreachable("unknown code completion context");
539 }
540 
541 // Some member calls are blacklisted because they're so rarely useful.
542 static bool isBlacklistedMember(const NamedDecl &D) {
543   // Destructor completion is rarely useful, and works inconsistently.
544   // (s.^ completes ~string, but s.~st^ is an error).
545   if (D.getKind() == Decl::CXXDestructor)
546     return true;
547   // Injected name may be useful for A::foo(), but who writes A::A::foo()?
548   if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
549     if (R->isInjectedClassName())
550       return true;
551   // Explicit calls to operators are also rare.
552   auto NameKind = D.getDeclName().getNameKind();
553   if (NameKind == DeclarationName::CXXOperatorName ||
554       NameKind == DeclarationName::CXXLiteralOperatorName ||
555       NameKind == DeclarationName::CXXConversionFunctionName)
556     return true;
557   return false;
558 }
559 
560 // The CompletionRecorder captures Sema code-complete output, including context.
561 // It filters out ignored results (but doesn't apply fuzzy-filtering yet).
562 // It doesn't do scoring or conversion to CompletionItem yet, as we want to
563 // merge with index results first.
564 // Generally the fields and methods of this object should only be used from
565 // within the callback.
566 struct CompletionRecorder : public CodeCompleteConsumer {
567   CompletionRecorder(const CodeCompleteOptions &Opts,
568                      UniqueFunction<void()> ResultsCallback)
569       : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
570                              /*OutputIsBinary=*/false),
571         CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
572         CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
573         CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
574     assert(this->ResultsCallback);
575   }
576 
577   std::vector<CodeCompletionResult> Results;
578   CodeCompletionContext CCContext;
579   Sema *CCSema = nullptr; // Sema that created the results.
580   // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
581 
582   void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
583                                   CodeCompletionResult *InResults,
584                                   unsigned NumResults) override final {
585     // If a callback is called without any sema result and the context does not
586     // support index-based completion, we simply skip it to give way to
587     // potential future callbacks with results.
588     if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
589       return;
590     if (CCSema) {
591       log(llvm::formatv(
592           "Multiple code complete callbacks (parser backtracked?). "
593           "Dropping results from context {0}, keeping results from {1}.",
594           getCompletionKindString(Context.getKind()),
595           getCompletionKindString(this->CCContext.getKind())));
596       return;
597     }
598     // Record the completion context.
599     CCSema = &S;
600     CCContext = Context;
601 
602     // Retain the results we might want.
603     for (unsigned I = 0; I < NumResults; ++I) {
604       auto &Result = InResults[I];
605       // Drop hidden items which cannot be found by lookup after completion.
606       // Exception: some items can be named by using a qualifier.
607       if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
608         continue;
609       if (!Opts.IncludeIneligibleResults &&
610           (Result.Availability == CXAvailability_NotAvailable ||
611            Result.Availability == CXAvailability_NotAccessible))
612         continue;
613       if (Result.Declaration &&
614           !Context.getBaseType().isNull() // is this a member-access context?
615           && isBlacklistedMember(*Result.Declaration))
616         continue;
617       // We choose to never append '::' to completion results in clangd.
618       Result.StartsNestedNameSpecifier = false;
619       Results.push_back(Result);
620     }
621     ResultsCallback();
622   }
623 
624   CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
625   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
626 
627   // Returns the filtering/sorting name for Result, which must be from Results.
628   // Returned string is owned by this recorder (or the AST).
629   llvm::StringRef getName(const CodeCompletionResult &Result) {
630     switch (Result.Kind) {
631     case CodeCompletionResult::RK_Declaration:
632       if (auto *ID = Result.Declaration->getIdentifier())
633         return ID->getName();
634       break;
635     case CodeCompletionResult::RK_Keyword:
636       return Result.Keyword;
637     case CodeCompletionResult::RK_Macro:
638       return Result.Macro->getName();
639     case CodeCompletionResult::RK_Pattern:
640       return Result.Pattern->getTypedText();
641     }
642     auto *CCS = codeCompletionString(Result);
643     return CCS->getTypedText();
644   }
645 
646   // Build a CodeCompletion string for R, which must be from Results.
647   // The CCS will be owned by this recorder.
648   CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
649     // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
650     return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
651         *CCSema, CCContext, *CCAllocator, CCTUInfo,
652         /*IncludeBriefComments=*/false);
653   }
654 
655 private:
656   CodeCompleteOptions Opts;
657   std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
658   CodeCompletionTUInfo CCTUInfo;
659   UniqueFunction<void()> ResultsCallback;
660 };
661 
662 class SignatureHelpCollector final : public CodeCompleteConsumer {
663 
664 public:
665   SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
666                          SignatureHelp &SigHelp)
667       : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
668         SigHelp(SigHelp),
669         Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
670         CCTUInfo(Allocator) {}
671 
672   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
673                                  OverloadCandidate *Candidates,
674                                  unsigned NumCandidates) override {
675     SigHelp.signatures.reserve(NumCandidates);
676     // FIXME(rwols): How can we determine the "active overload candidate"?
677     // Right now the overloaded candidates seem to be provided in a "best fit"
678     // order, so I'm not too worried about this.
679     SigHelp.activeSignature = 0;
680     assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
681            "too many arguments");
682     SigHelp.activeParameter = static_cast<int>(CurrentArg);
683     for (unsigned I = 0; I < NumCandidates; ++I) {
684       const auto &Candidate = Candidates[I];
685       const auto *CCS = Candidate.CreateSignatureString(
686           CurrentArg, S, *Allocator, CCTUInfo, true);
687       assert(CCS && "Expected the CodeCompletionString to be non-null");
688       // FIXME: for headers, we need to get a comment from the index.
689       SigHelp.signatures.push_back(ProcessOverloadCandidate(
690           Candidate, *CCS,
691           getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
692                                  /*CommentsFromHeaders=*/false)));
693     }
694   }
695 
696   GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
697 
698   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
699 
700 private:
701   // FIXME(ioeric): consider moving CodeCompletionString logic here to
702   // CompletionString.h.
703   SignatureInformation
704   ProcessOverloadCandidate(const OverloadCandidate &Candidate,
705                            const CodeCompletionString &CCS,
706                            llvm::StringRef DocComment) const {
707     SignatureInformation Result;
708     const char *ReturnType = nullptr;
709 
710     Result.documentation = formatDocumentation(CCS, DocComment);
711 
712     for (const auto &Chunk : CCS) {
713       switch (Chunk.Kind) {
714       case CodeCompletionString::CK_ResultType:
715         // A piece of text that describes the type of an entity or,
716         // for functions and methods, the return type.
717         assert(!ReturnType && "Unexpected CK_ResultType");
718         ReturnType = Chunk.Text;
719         break;
720       case CodeCompletionString::CK_Placeholder:
721         // A string that acts as a placeholder for, e.g., a function call
722         // argument.
723         // Intentional fallthrough here.
724       case CodeCompletionString::CK_CurrentParameter: {
725         // A piece of text that describes the parameter that corresponds to
726         // the code-completion location within a function call, message send,
727         // macro invocation, etc.
728         Result.label += Chunk.Text;
729         ParameterInformation Info;
730         Info.label = Chunk.Text;
731         Result.parameters.push_back(std::move(Info));
732         break;
733       }
734       case CodeCompletionString::CK_Optional: {
735         // The rest of the parameters are defaulted/optional.
736         assert(Chunk.Optional &&
737                "Expected the optional code completion string to be non-null.");
738         Result.label +=
739             getOptionalParameters(*Chunk.Optional, Result.parameters);
740         break;
741       }
742       case CodeCompletionString::CK_VerticalSpace:
743         break;
744       default:
745         Result.label += Chunk.Text;
746         break;
747       }
748     }
749     if (ReturnType) {
750       Result.label += " -> ";
751       Result.label += ReturnType;
752     }
753     return Result;
754   }
755 
756   SignatureHelp &SigHelp;
757   std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
758   CodeCompletionTUInfo CCTUInfo;
759 
760 }; // SignatureHelpCollector
761 
762 struct SemaCompleteInput {
763   PathRef FileName;
764   const tooling::CompileCommand &Command;
765   PrecompiledPreamble const *Preamble;
766   const std::vector<Inclusion> &PreambleInclusions;
767   StringRef Contents;
768   Position Pos;
769   IntrusiveRefCntPtr<vfs::FileSystem> VFS;
770   std::shared_ptr<PCHContainerOperations> PCHs;
771 };
772 
773 // Invokes Sema code completion on a file.
774 // If \p Includes is set, it will be initialized after a compiler instance has
775 // been set up.
776 bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
777                       const clang::CodeCompleteOptions &Options,
778                       const SemaCompleteInput &Input,
779                       std::unique_ptr<IncludeInserter> *Includes = nullptr) {
780   trace::Span Tracer("Sema completion");
781   std::vector<const char *> ArgStrs;
782   for (const auto &S : Input.Command.CommandLine)
783     ArgStrs.push_back(S.c_str());
784 
785   if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
786     log("Couldn't set working directory");
787     // We run parsing anyway, our lit-tests rely on results for non-existing
788     // working dirs.
789   }
790 
791   IgnoreDiagnostics DummyDiagsConsumer;
792   auto CI = createInvocationFromCommandLine(
793       ArgStrs,
794       CompilerInstance::createDiagnostics(new DiagnosticOptions,
795                                           &DummyDiagsConsumer, false),
796       Input.VFS);
797   if (!CI) {
798     log("Couldn't create CompilerInvocation");
799     return false;
800   }
801   auto &FrontendOpts = CI->getFrontendOpts();
802   FrontendOpts.DisableFree = false;
803   FrontendOpts.SkipFunctionBodies = true;
804   CI->getLangOpts()->CommentOpts.ParseAllComments = true;
805   // Disable typo correction in Sema.
806   CI->getLangOpts()->SpellChecking = false;
807   // Setup code completion.
808   FrontendOpts.CodeCompleteOpts = Options;
809   FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
810   auto Offset = positionToOffset(Input.Contents, Input.Pos);
811   if (!Offset) {
812     log("Code completion position was invalid " +
813         llvm::toString(Offset.takeError()));
814     return false;
815   }
816   std::tie(FrontendOpts.CodeCompletionAt.Line,
817            FrontendOpts.CodeCompletionAt.Column) =
818       offsetToClangLineColumn(Input.Contents, *Offset);
819 
820   std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
821       llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
822   // The diagnostic options must be set before creating a CompilerInstance.
823   CI->getDiagnosticOpts().IgnoreWarnings = true;
824   // We reuse the preamble whether it's valid or not. This is a
825   // correctness/performance tradeoff: building without a preamble is slow, and
826   // completion is latency-sensitive.
827   // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
828   // the remapped buffers do not get freed.
829   auto Clang = prepareCompilerInstance(
830       std::move(CI), Input.Preamble, std::move(ContentsBuffer),
831       std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
832   Clang->setCodeCompletionConsumer(Consumer.release());
833 
834   SyntaxOnlyAction Action;
835   if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
836     log("BeginSourceFile() failed when running codeComplete for " +
837         Input.FileName);
838     return false;
839   }
840   if (Includes) {
841     // Initialize Includes if provided.
842 
843     // FIXME(ioeric): needs more consistent style support in clangd server.
844     auto Style = format::getStyle(format::DefaultFormatStyle, Input.FileName,
845                                   format::DefaultFallbackStyle, Input.Contents,
846                                   Input.VFS.get());
847     if (!Style) {
848       log("ERROR: failed to get FormatStyle for file " + Input.FileName +
849           ". Fall back to use LLVM style. Error: " +
850           llvm::toString(Style.takeError()));
851       Style = format::getLLVMStyle();
852     }
853     *Includes = llvm::make_unique<IncludeInserter>(
854         Input.FileName, Input.Contents, *Style, Input.Command.Directory,
855         Clang->getPreprocessor().getHeaderSearchInfo());
856     for (const auto &Inc : Input.PreambleInclusions)
857       Includes->get()->addExisting(Inc);
858     Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
859         Clang->getSourceManager(), [Includes](Inclusion Inc) {
860           Includes->get()->addExisting(std::move(Inc));
861         }));
862   }
863   if (!Action.Execute()) {
864     log("Execute() failed when running codeComplete for " + Input.FileName);
865     return false;
866   }
867   Action.EndSourceFile();
868 
869   return true;
870 }
871 
872 // Should we allow index completions in the specified context?
873 bool allowIndex(CodeCompletionContext &CC) {
874   if (!contextAllowsIndex(CC.getKind()))
875     return false;
876   // We also avoid ClassName::bar (but allow namespace::bar).
877   auto Scope = CC.getCXXScopeSpecifier();
878   if (!Scope)
879     return true;
880   NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
881   if (!NameSpec)
882     return true;
883   // We only query the index when qualifier is a namespace.
884   // If it's a class, we rely solely on sema completions.
885   switch (NameSpec->getKind()) {
886   case NestedNameSpecifier::Global:
887   case NestedNameSpecifier::Namespace:
888   case NestedNameSpecifier::NamespaceAlias:
889     return true;
890   case NestedNameSpecifier::Super:
891   case NestedNameSpecifier::TypeSpec:
892   case NestedNameSpecifier::TypeSpecWithTemplate:
893   // Unresolved inside a template.
894   case NestedNameSpecifier::Identifier:
895     return false;
896   }
897   llvm_unreachable("invalid NestedNameSpecifier kind");
898 }
899 
900 } // namespace
901 
902 clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
903   clang::CodeCompleteOptions Result;
904   Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
905   Result.IncludeMacros = IncludeMacros;
906   Result.IncludeGlobals = true;
907   // We choose to include full comments and not do doxygen parsing in
908   // completion.
909   // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
910   // formatting of the comments.
911   Result.IncludeBriefComments = false;
912 
913   // When an is used, Sema is responsible for completing the main file,
914   // the index can provide results from the preamble.
915   // Tell Sema not to deserialize the preamble to look for results.
916   Result.LoadExternal = !Index;
917 
918   return Result;
919 }
920 
921 // Runs Sema-based (AST) and Index-based completion, returns merged results.
922 //
923 // There are a few tricky considerations:
924 //   - the AST provides information needed for the index query (e.g. which
925 //     namespaces to search in). So Sema must start first.
926 //   - we only want to return the top results (Opts.Limit).
927 //     Building CompletionItems for everything else is wasteful, so we want to
928 //     preserve the "native" format until we're done with scoring.
929 //   - the data underlying Sema completion items is owned by the AST and various
930 //     other arenas, which must stay alive for us to build CompletionItems.
931 //   - we may get duplicate results from Sema and the Index, we need to merge.
932 //
933 // So we start Sema completion first, and do all our work in its callback.
934 // We use the Sema context information to query the index.
935 // Then we merge the two result sets, producing items that are Sema/Index/Both.
936 // These items are scored, and the top N are synthesized into the LSP response.
937 // Finally, we can clean up the data structures created by Sema completion.
938 //
939 // Main collaborators are:
940 //   - semaCodeComplete sets up the compiler machinery to run code completion.
941 //   - CompletionRecorder captures Sema completion results, including context.
942 //   - SymbolIndex (Opts.Index) provides index completion results as Symbols
943 //   - CompletionCandidates are the result of merging Sema and Index results.
944 //     Each candidate points to an underlying CodeCompletionResult (Sema), a
945 //     Symbol (Index), or both. It computes the result quality score.
946 //     CompletionCandidate also does conversion to CompletionItem (at the end).
947 //   - FuzzyMatcher scores how the candidate matches the partial identifier.
948 //     This score is combined with the result quality score for the final score.
949 //   - TopN determines the results with the best score.
950 class CodeCompleteFlow {
951   PathRef FileName;
952   const CodeCompleteOptions &Opts;
953   // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
954   CompletionRecorder *Recorder = nullptr;
955   int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
956   bool Incomplete = false; // Would more be available with a higher limit?
957   llvm::Optional<FuzzyMatcher> Filter;       // Initialized once Sema runs.
958   std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs.
959   FileProximityMatcher FileProximityMatch;
960 
961 public:
962   // A CodeCompleteFlow object is only useful for calling run() exactly once.
963   CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
964       : FileName(FileName), Opts(Opts),
965         // FIXME: also use path of the main header corresponding to FileName to
966         // calculate the file proximity, which would capture include/ and src/
967         // project setup where headers and implementations are not in the same
968         // directory.
969         FileProximityMatch(ArrayRef<StringRef>({FileName})) {}
970 
971   CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
972     trace::Span Tracer("CodeCompleteFlow");
973 
974     // We run Sema code completion first. It builds an AST and calculates:
975     //   - completion results based on the AST.
976     //   - partial identifier and context. We need these for the index query.
977     CodeCompleteResult Output;
978     auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
979       assert(Recorder && "Recorder is not set");
980       assert(Includes && "Includes is not set");
981       // If preprocessor was run, inclusions from preprocessor callback should
982       // already be added to Inclusions.
983       Output = runWithSema();
984       Includes.reset(); // Make sure this doesn't out-live Clang.
985       SPAN_ATTACH(Tracer, "sema_completion_kind",
986                   getCompletionKindString(Recorder->CCContext.getKind()));
987     });
988 
989     Recorder = RecorderOwner.get();
990     semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
991                      SemaCCInput, &Includes);
992 
993     SPAN_ATTACH(Tracer, "sema_results", NSema);
994     SPAN_ATTACH(Tracer, "index_results", NIndex);
995     SPAN_ATTACH(Tracer, "merged_results", NBoth);
996     SPAN_ATTACH(Tracer, "returned_results", Output.Completions.size());
997     SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
998     log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
999                       "{2} matched, {3} returned{4}.",
1000                       NSema, NIndex, NBoth, Output.Completions.size(),
1001                       Output.HasMore ? " (incomplete)" : ""));
1002     assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1003     // We don't assert that isIncomplete means we hit a limit.
1004     // Indexes may choose to impose their own limits even if we don't have one.
1005     return Output;
1006   }
1007 
1008 private:
1009   // This is called by run() once Sema code completion is done, but before the
1010   // Sema data structures are torn down. It does all the real work.
1011   CodeCompleteResult runWithSema() {
1012     Filter = FuzzyMatcher(
1013         Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1014     // Sema provides the needed context to query the index.
1015     // FIXME: in addition to querying for extra/overlapping symbols, we should
1016     //        explicitly request symbols corresponding to Sema results.
1017     //        We can use their signals even if the index can't suggest them.
1018     // We must copy index results to preserve them, but there are at most Limit.
1019     auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1020                             ? queryIndex()
1021                             : SymbolSlab();
1022     // Merge Sema and Index results, score them, and pick the winners.
1023     auto Top = mergeResults(Recorder->Results, IndexResults);
1024     // Convert the results to final form, assembling the expensive strings.
1025     CodeCompleteResult Output;
1026     for (auto &C : Top) {
1027       Output.Completions.push_back(toCodeCompletion(C.first));
1028       Output.Completions.back().Score = C.second;
1029     }
1030     Output.HasMore = Incomplete;
1031     return Output;
1032   }
1033 
1034   SymbolSlab queryIndex() {
1035     trace::Span Tracer("Query index");
1036     SPAN_ATTACH(Tracer, "limit", Opts.Limit);
1037 
1038     SymbolSlab::Builder ResultsBuilder;
1039     // Build the query.
1040     FuzzyFindRequest Req;
1041     if (Opts.Limit)
1042       Req.MaxCandidateCount = Opts.Limit;
1043     Req.Query = Filter->pattern();
1044     Req.RestrictForCodeCompletion = true;
1045     Req.Scopes = getQueryScopes(Recorder->CCContext,
1046                                 Recorder->CCSema->getSourceManager());
1047     Req.ProximityPaths.push_back(FileName);
1048     log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
1049                       Req.Query,
1050                       llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
1051     // Run the query against the index.
1052     if (Opts.Index->fuzzyFind(
1053             Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1054       Incomplete = true;
1055     return std::move(ResultsBuilder).build();
1056   }
1057 
1058   // Merges Sema and Index results where possible, to form CompletionCandidates.
1059   // Groups overloads if desired, to form CompletionCandidate::Bundles.
1060   // The bundles are scored and top results are returned, best to worst.
1061   std::vector<ScoredBundle>
1062   mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1063                const SymbolSlab &IndexResults) {
1064     trace::Span Tracer("Merge and score results");
1065     std::vector<CompletionCandidate::Bundle> Bundles;
1066     llvm::DenseMap<size_t, size_t> BundleLookup;
1067     auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
1068                             const Symbol *IndexResult) {
1069       CompletionCandidate C;
1070       C.SemaResult = SemaResult;
1071       C.IndexResult = IndexResult;
1072       C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1073       if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1074         auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1075         if (Ret.second)
1076           Bundles.emplace_back();
1077         Bundles[Ret.first->second].push_back(std::move(C));
1078       } else {
1079         Bundles.emplace_back();
1080         Bundles.back().push_back(std::move(C));
1081       }
1082     };
1083     llvm::DenseSet<const Symbol *> UsedIndexResults;
1084     auto CorrespondingIndexResult =
1085         [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
1086       if (auto SymID = getSymbolID(SemaResult)) {
1087         auto I = IndexResults.find(*SymID);
1088         if (I != IndexResults.end()) {
1089           UsedIndexResults.insert(&*I);
1090           return &*I;
1091         }
1092       }
1093       return nullptr;
1094     };
1095     // Emit all Sema results, merging them with Index results if possible.
1096     for (auto &SemaResult : Recorder->Results)
1097       AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
1098     // Now emit any Index-only results.
1099     for (const auto &IndexResult : IndexResults) {
1100       if (UsedIndexResults.count(&IndexResult))
1101         continue;
1102       AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
1103     }
1104     // We only keep the best N results at any time, in "native" format.
1105     TopN<ScoredBundle, ScoredBundleGreater> Top(
1106         Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1107     for (auto &Bundle : Bundles)
1108       addCandidate(Top, std::move(Bundle));
1109     return std::move(Top).items();
1110   }
1111 
1112   Optional<float> fuzzyScore(const CompletionCandidate &C) {
1113     // Macros can be very spammy, so we only support prefix completion.
1114     // We won't end up with underfull index results, as macros are sema-only.
1115     if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1116         !C.Name.startswith_lower(Filter->pattern()))
1117       return None;
1118     return Filter->match(C.Name);
1119   }
1120 
1121   // Scores a candidate and adds it to the TopN structure.
1122   void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1123                     CompletionCandidate::Bundle Bundle) {
1124     SymbolQualitySignals Quality;
1125     SymbolRelevanceSignals Relevance;
1126     Relevance.Query = SymbolRelevanceSignals::CodeComplete;
1127     Relevance.FileProximityMatch = &FileProximityMatch;
1128     auto &First = Bundle.front();
1129     if (auto FuzzyScore = fuzzyScore(First))
1130       Relevance.NameMatch = *FuzzyScore;
1131     else
1132       return;
1133     unsigned SemaResult = 0, IndexResult = 0;
1134     for (const auto &Candidate : Bundle) {
1135       if (Candidate.IndexResult) {
1136         Quality.merge(*Candidate.IndexResult);
1137         Relevance.merge(*Candidate.IndexResult);
1138         ++IndexResult;
1139       }
1140       if (Candidate.SemaResult) {
1141         Quality.merge(*Candidate.SemaResult);
1142         Relevance.merge(*Candidate.SemaResult);
1143         ++SemaResult;
1144       }
1145     }
1146 
1147     CodeCompletion::Scores Scores;
1148     Scores.Quality = Quality.evaluate();
1149     Scores.Relevance = Relevance.evaluate();
1150     Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1151     // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1152     Scores.ExcludingName = Relevance.NameMatch
1153                                ? Scores.Total / Relevance.NameMatch
1154                                : Scores.Quality;
1155 
1156     LLVM_DEBUG(llvm::dbgs() << "CodeComplete: " << First.Name << "("
1157                             << IndexResult << " index) "
1158                             << "(" << SemaResult << " sema)"
1159                             << " = " << Scores.Total << "\n"
1160                             << Quality << Relevance << "\n");
1161 
1162     NSema += bool(SemaResult);
1163     NIndex += bool(IndexResult);
1164     NBoth += SemaResult && IndexResult;
1165     if (Candidates.push({std::move(Bundle), Scores}))
1166       Incomplete = true;
1167   }
1168 
1169   CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
1170     llvm::Optional<CodeCompletionBuilder> Builder;
1171     for (const auto &Item : Bundle) {
1172       CodeCompletionString *SemaCCS =
1173           Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1174                           : nullptr;
1175       if (!Builder)
1176         Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
1177                         *Includes, FileName, Opts);
1178       else
1179         Builder->add(Item, SemaCCS);
1180     }
1181     return Builder->build();
1182   }
1183 };
1184 
1185 CodeCompleteResult codeComplete(
1186     PathRef FileName, const tooling::CompileCommand &Command,
1187     PrecompiledPreamble const *Preamble,
1188     const std::vector<Inclusion> &PreambleInclusions, StringRef Contents,
1189     Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1190     std::shared_ptr<PCHContainerOperations> PCHs, CodeCompleteOptions Opts) {
1191   return CodeCompleteFlow(FileName, Opts)
1192       .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS,
1193             PCHs});
1194 }
1195 
1196 SignatureHelp signatureHelp(PathRef FileName,
1197                             const tooling::CompileCommand &Command,
1198                             PrecompiledPreamble const *Preamble,
1199                             StringRef Contents, Position Pos,
1200                             IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1201                             std::shared_ptr<PCHContainerOperations> PCHs) {
1202   SignatureHelp Result;
1203   clang::CodeCompleteOptions Options;
1204   Options.IncludeGlobals = false;
1205   Options.IncludeMacros = false;
1206   Options.IncludeCodePatterns = false;
1207   Options.IncludeBriefComments = false;
1208   std::vector<Inclusion> PreambleInclusions = {}; // Unused for signatureHelp
1209   semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1210                    Options,
1211                    {FileName, Command, Preamble, PreambleInclusions, Contents,
1212                     Pos, std::move(VFS), std::move(PCHs)});
1213   return Result;
1214 }
1215 
1216 bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1217   using namespace clang::ast_matchers;
1218   auto InTopLevelScope = hasDeclContext(
1219       anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1220   return !match(decl(anyOf(InTopLevelScope,
1221                            hasDeclContext(
1222                                enumDecl(InTopLevelScope, unless(isScoped()))))),
1223                 ND, ASTCtx)
1224               .empty();
1225 }
1226 
1227 CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1228   CompletionItem LSP;
1229   LSP.label = (HeaderInsertion ? Opts.IncludeIndicator.Insert
1230                                : Opts.IncludeIndicator.NoInsert) +
1231               RequiredQualifier + Name + Signature;
1232   LSP.kind = Kind;
1233   LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
1234                               : ReturnType;
1235   if (!Header.empty())
1236     LSP.detail += "\n" + Header;
1237   LSP.documentation = Documentation;
1238   LSP.sortText = sortText(Score.Total, Name);
1239   LSP.filterText = Name;
1240   LSP.insertText = RequiredQualifier + Name;
1241   if (Opts.EnableSnippets)
1242     LSP.insertText += SnippetSuffix;
1243   LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1244                                              : InsertTextFormat::PlainText;
1245   if (HeaderInsertion)
1246     LSP.additionalTextEdits = {*HeaderInsertion};
1247   LSP.SymbolScope = Scope;
1248   return LSP;
1249 }
1250 
1251 } // namespace clangd
1252 } // namespace clang
1253