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