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