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