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 "ClangdUnit.h"
24 #include "CodeCompletionStrings.h"
25 #include "Compiler.h"
26 #include "Diagnostics.h"
27 #include "ExpectedTypes.h"
28 #include "FileDistance.h"
29 #include "FuzzyMatch.h"
30 #include "Headers.h"
31 #include "Logger.h"
32 #include "Quality.h"
33 #include "SourceCode.h"
34 #include "TUScheduler.h"
35 #include "Trace.h"
36 #include "URI.h"
37 #include "index/Index.h"
38 #include "clang/AST/Decl.h"
39 #include "clang/AST/DeclBase.h"
40 #include "clang/Basic/LangOptions.h"
41 #include "clang/Basic/SourceLocation.h"
42 #include "clang/Format/Format.h"
43 #include "clang/Frontend/CompilerInstance.h"
44 #include "clang/Frontend/FrontendActions.h"
45 #include "clang/Lex/PreprocessorOptions.h"
46 #include "clang/Sema/CodeCompleteConsumer.h"
47 #include "clang/Sema/Sema.h"
48 #include "llvm/ADT/ArrayRef.h"
49 #include "llvm/ADT/None.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/Support/Error.h"
53 #include "llvm/Support/Format.h"
54 #include "llvm/Support/FormatVariadic.h"
55 #include "llvm/Support/ScopedPrinter.h"
56 #include <algorithm>
57 #include <iterator>
58 
59 // We log detailed candidate here if you run with -debug-only=codecomplete.
60 #define DEBUG_TYPE "CodeComplete"
61 
62 using namespace llvm;
63 namespace clang {
64 namespace clangd {
65 namespace {
66 
67 CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
68   using SK = index::SymbolKind;
69   switch (Kind) {
70   case SK::Unknown:
71     return CompletionItemKind::Missing;
72   case SK::Module:
73   case SK::Namespace:
74   case SK::NamespaceAlias:
75     return CompletionItemKind::Module;
76   case SK::Macro:
77     return CompletionItemKind::Text;
78   case SK::Enum:
79     return CompletionItemKind::Enum;
80   // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
81   // protocol.
82   case SK::Struct:
83   case SK::Class:
84   case SK::Protocol:
85   case SK::Extension:
86   case SK::Union:
87     return CompletionItemKind::Class;
88   // FIXME(ioeric): figure out whether reference is the right type for aliases.
89   case SK::TypeAlias:
90   case SK::Using:
91     return CompletionItemKind::Reference;
92   case SK::Function:
93   // FIXME(ioeric): this should probably be an operator. This should be fixed
94   // when `Operator` is support type in the protocol.
95   case SK::ConversionFunction:
96     return CompletionItemKind::Function;
97   case SK::Variable:
98   case SK::Parameter:
99     return CompletionItemKind::Variable;
100   case SK::Field:
101     return CompletionItemKind::Field;
102   // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
103   case SK::EnumConstant:
104     return CompletionItemKind::Value;
105   case SK::InstanceMethod:
106   case SK::ClassMethod:
107   case SK::StaticMethod:
108   case SK::Destructor:
109     return CompletionItemKind::Method;
110   case SK::InstanceProperty:
111   case SK::ClassProperty:
112   case SK::StaticProperty:
113     return CompletionItemKind::Property;
114   case SK::Constructor:
115     return CompletionItemKind::Constructor;
116   }
117   llvm_unreachable("Unhandled clang::index::SymbolKind.");
118 }
119 
120 CompletionItemKind
121 toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
122                      const NamedDecl *Decl,
123                      CodeCompletionContext::Kind CtxKind) {
124   if (Decl)
125     return toCompletionItemKind(index::getSymbolInfo(Decl).Kind);
126   if (CtxKind == CodeCompletionContext::CCC_IncludedFile)
127     return CompletionItemKind::File;
128   switch (ResKind) {
129   case CodeCompletionResult::RK_Declaration:
130     llvm_unreachable("RK_Declaration without Decl");
131   case CodeCompletionResult::RK_Keyword:
132     return CompletionItemKind::Keyword;
133   case CodeCompletionResult::RK_Macro:
134     return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
135                                      // completion items in LSP.
136   case CodeCompletionResult::RK_Pattern:
137     return CompletionItemKind::Snippet;
138   }
139   llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
140 }
141 
142 /// Get the optional chunk as a string. This function is possibly recursive.
143 ///
144 /// The parameter info for each parameter is appended to the Parameters.
145 std::string getOptionalParameters(const CodeCompletionString &CCS,
146                                   std::vector<ParameterInformation> &Parameters,
147                                   SignatureQualitySignals &Signal) {
148   std::string Result;
149   for (const auto &Chunk : CCS) {
150     switch (Chunk.Kind) {
151     case CodeCompletionString::CK_Optional:
152       assert(Chunk.Optional &&
153              "Expected the optional code completion string to be non-null.");
154       Result += getOptionalParameters(*Chunk.Optional, Parameters, Signal);
155       break;
156     case CodeCompletionString::CK_VerticalSpace:
157       break;
158     case CodeCompletionString::CK_Placeholder:
159       // A string that acts as a placeholder for, e.g., a function call
160       // argument.
161       // Intentional fallthrough here.
162     case CodeCompletionString::CK_CurrentParameter: {
163       // A piece of text that describes the parameter that corresponds to
164       // the code-completion location within a function call, message send,
165       // macro invocation, etc.
166       Result += Chunk.Text;
167       ParameterInformation Info;
168       Info.label = Chunk.Text;
169       Parameters.push_back(std::move(Info));
170       Signal.ContainsActiveParameter = true;
171       Signal.NumberOfOptionalParameters++;
172       break;
173     }
174     default:
175       Result += Chunk.Text;
176       break;
177     }
178   }
179   return Result;
180 }
181 
182 /// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
183 /// include.
184 static Expected<HeaderFile> toHeaderFile(StringRef Header, StringRef HintPath) {
185   if (isLiteralInclude(Header))
186     return HeaderFile{Header.str(), /*Verbatim=*/true};
187   auto U = URI::parse(Header);
188   if (!U)
189     return U.takeError();
190 
191   auto IncludePath = URI::includeSpelling(*U);
192   if (!IncludePath)
193     return IncludePath.takeError();
194   if (!IncludePath->empty())
195     return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
196 
197   auto Resolved = URI::resolve(*U, HintPath);
198   if (!Resolved)
199     return Resolved.takeError();
200   return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
201 }
202 
203 /// A code completion result, in clang-native form.
204 /// It may be promoted to a CompletionItem if it's among the top-ranked results.
205 struct CompletionCandidate {
206   StringRef Name; // Used for filtering and sorting.
207   // We may have a result from Sema, from the index, or both.
208   const CodeCompletionResult *SemaResult = nullptr;
209   const Symbol *IndexResult = nullptr;
210   SmallVector<StringRef, 1> RankedIncludeHeaders;
211 
212   // Returns a token identifying the overload set this is part of.
213   // 0 indicates it's not part of any overload set.
214   size_t overloadSet() const {
215     SmallString<256> Scratch;
216     if (IndexResult) {
217       switch (IndexResult->SymInfo.Kind) {
218       case index::SymbolKind::ClassMethod:
219       case index::SymbolKind::InstanceMethod:
220       case index::SymbolKind::StaticMethod:
221 #ifndef NDEBUG
222         llvm_unreachable("Don't expect members from index in code completion");
223 #else
224         LLVM_FALLTHROUGH;
225 #endif
226       case index::SymbolKind::Function:
227         // We can't group overloads together that need different #includes.
228         // This could break #include insertion.
229         return hash_combine(
230             (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
231             headerToInsertIfAllowed().getValueOr(""));
232       default:
233         return 0;
234       }
235     }
236     assert(SemaResult);
237     // We need to make sure we're consistent with the IndexResult case!
238     const NamedDecl *D = SemaResult->Declaration;
239     if (!D || !D->isFunctionOrFunctionTemplate())
240       return 0;
241     {
242       raw_svector_ostream OS(Scratch);
243       D->printQualifiedName(OS);
244     }
245     return hash_combine(Scratch, headerToInsertIfAllowed().getValueOr(""));
246   }
247 
248   // The best header to include if include insertion is allowed.
249   Optional<StringRef> headerToInsertIfAllowed() const {
250     if (RankedIncludeHeaders.empty())
251       return None;
252     if (SemaResult && SemaResult->Declaration) {
253       // Avoid inserting new #include if the declaration is found in the current
254       // file e.g. the symbol is forward declared.
255       auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
256       for (const Decl *RD : SemaResult->Declaration->redecls())
257         if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
258           return None;
259     }
260     return RankedIncludeHeaders[0];
261   }
262 
263   using Bundle = SmallVector<CompletionCandidate, 4>;
264 };
265 using ScoredBundle =
266     std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
267 struct ScoredBundleGreater {
268   bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
269     if (L.second.Total != R.second.Total)
270       return L.second.Total > R.second.Total;
271     return L.first.front().Name <
272            R.first.front().Name; // Earlier name is better.
273   }
274 };
275 
276 // Assembles a code completion out of a bundle of >=1 completion candidates.
277 // Many of the expensive strings are only computed at this point, once we know
278 // the candidate bundle is going to be returned.
279 //
280 // Many fields are the same for all candidates in a bundle (e.g. name), and are
281 // computed from the first candidate, in the constructor.
282 // Others vary per candidate, so add() must be called for remaining candidates.
283 struct CodeCompletionBuilder {
284   CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
285                         CodeCompletionString *SemaCCS,
286                         ArrayRef<std::string> QueryScopes,
287                         const IncludeInserter &Includes, StringRef FileName,
288                         CodeCompletionContext::Kind ContextKind,
289                         const CodeCompleteOptions &Opts)
290       : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments),
291         EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets) {
292     add(C, SemaCCS);
293     if (C.SemaResult) {
294       Completion.Origin |= SymbolOrigin::AST;
295       Completion.Name = StringRef(SemaCCS->getTypedText());
296       if (Completion.Scope.empty()) {
297         if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
298             (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
299           if (const auto *D = C.SemaResult->getDeclaration())
300             if (const auto *ND = dyn_cast<NamedDecl>(D))
301               Completion.Scope =
302                   splitQualifiedName(printQualifiedName(*ND)).first;
303       }
304       Completion.Kind = toCompletionItemKind(
305           C.SemaResult->Kind, C.SemaResult->Declaration, ContextKind);
306       // Sema could provide more info on whether the completion was a file or
307       // folder.
308       if (Completion.Kind == CompletionItemKind::File &&
309           Completion.Name.back() == '/')
310         Completion.Kind = CompletionItemKind::Folder;
311       for (const auto &FixIt : C.SemaResult->FixIts) {
312         Completion.FixIts.push_back(
313             toTextEdit(FixIt, ASTCtx.getSourceManager(), ASTCtx.getLangOpts()));
314       }
315       llvm::sort(Completion.FixIts, [](const TextEdit &X, const TextEdit &Y) {
316         return std::tie(X.range.start.line, X.range.start.character) <
317                std::tie(Y.range.start.line, Y.range.start.character);
318       });
319       Completion.Deprecated |=
320           (C.SemaResult->Availability == CXAvailability_Deprecated);
321     }
322     if (C.IndexResult) {
323       Completion.Origin |= C.IndexResult->Origin;
324       if (Completion.Scope.empty())
325         Completion.Scope = C.IndexResult->Scope;
326       if (Completion.Kind == CompletionItemKind::Missing)
327         Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
328       if (Completion.Name.empty())
329         Completion.Name = C.IndexResult->Name;
330       // If the completion was visible to Sema, no qualifier is needed. This
331       // avoids unneeded qualifiers in cases like with `using ns::X`.
332       if (Completion.RequiredQualifier.empty() && !C.SemaResult) {
333         StringRef ShortestQualifier = C.IndexResult->Scope;
334         for (StringRef Scope : QueryScopes) {
335           StringRef Qualifier = C.IndexResult->Scope;
336           if (Qualifier.consume_front(Scope) &&
337               Qualifier.size() < ShortestQualifier.size())
338             ShortestQualifier = Qualifier;
339         }
340         Completion.RequiredQualifier = ShortestQualifier;
341       }
342       Completion.Deprecated |= (C.IndexResult->Flags & Symbol::Deprecated);
343     }
344 
345     // Turn absolute path into a literal string that can be #included.
346     auto Inserted =
347         [&](StringRef Header) -> Expected<std::pair<std::string, bool>> {
348       auto ResolvedDeclaring =
349           toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
350       if (!ResolvedDeclaring)
351         return ResolvedDeclaring.takeError();
352       auto ResolvedInserted = toHeaderFile(Header, FileName);
353       if (!ResolvedInserted)
354         return ResolvedInserted.takeError();
355       return std::make_pair(
356           Includes.calculateIncludePath(*ResolvedDeclaring, *ResolvedInserted),
357           Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
358     };
359     bool ShouldInsert = C.headerToInsertIfAllowed().hasValue();
360     // Calculate include paths and edits for all possible headers.
361     for (const auto &Inc : C.RankedIncludeHeaders) {
362       if (auto ToInclude = Inserted(Inc)) {
363         CodeCompletion::IncludeCandidate Include;
364         Include.Header = ToInclude->first;
365         if (ToInclude->second && ShouldInsert)
366           Include.Insertion = Includes.insert(ToInclude->first);
367         Completion.Includes.push_back(std::move(Include));
368       } else
369         log("Failed to generate include insertion edits for adding header "
370             "(FileURI='{0}', IncludeHeader='{1}') into {2}",
371             C.IndexResult->CanonicalDeclaration.FileURI, Inc, FileName);
372     }
373     // Prefer includes that do not need edits (i.e. already exist).
374     std::stable_partition(Completion.Includes.begin(),
375                           Completion.Includes.end(),
376                           [](const CodeCompletion::IncludeCandidate &I) {
377                             return !I.Insertion.hasValue();
378                           });
379   }
380 
381   void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {
382     assert(bool(C.SemaResult) == bool(SemaCCS));
383     Bundled.emplace_back();
384     BundledEntry &S = Bundled.back();
385     if (C.SemaResult) {
386       getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
387                    &Completion.RequiredQualifier);
388       S.ReturnType = getReturnType(*SemaCCS);
389     } else if (C.IndexResult) {
390       S.Signature = C.IndexResult->Signature;
391       S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix;
392       S.ReturnType = C.IndexResult->ReturnType;
393     }
394     if (ExtractDocumentation && Completion.Documentation.empty()) {
395       if (C.IndexResult)
396         Completion.Documentation = C.IndexResult->Documentation;
397       else if (C.SemaResult)
398         Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
399                                                  /*CommentsFromHeader=*/false);
400     }
401   }
402 
403   CodeCompletion build() {
404     Completion.ReturnType = summarizeReturnType();
405     Completion.Signature = summarizeSignature();
406     Completion.SnippetSuffix = summarizeSnippet();
407     Completion.BundleSize = Bundled.size();
408     return std::move(Completion);
409   }
410 
411 private:
412   struct BundledEntry {
413     std::string SnippetSuffix;
414     std::string Signature;
415     std::string ReturnType;
416   };
417 
418   // If all BundledEntrys have the same value for a property, return it.
419   template <std::string BundledEntry::*Member>
420   const std::string *onlyValue() const {
421     auto B = Bundled.begin(), E = Bundled.end();
422     for (auto I = B + 1; I != E; ++I)
423       if (I->*Member != B->*Member)
424         return nullptr;
425     return &(B->*Member);
426   }
427 
428   template <bool BundledEntry::*Member> const bool *onlyValue() const {
429     auto B = Bundled.begin(), E = Bundled.end();
430     for (auto I = B + 1; I != E; ++I)
431       if (I->*Member != B->*Member)
432         return nullptr;
433     return &(B->*Member);
434   }
435 
436   std::string summarizeReturnType() const {
437     if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
438       return *RT;
439     return "";
440   }
441 
442   std::string summarizeSnippet() const {
443     auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
444     if (!Snippet)
445       // All bundles are function calls.
446       // FIXME(ibiryukov): sometimes add template arguments to a snippet, e.g.
447       // we need to complete 'forward<$1>($0)'.
448       return "($0)";
449     if (EnableFunctionArgSnippets)
450       return *Snippet;
451 
452     // Replace argument snippets with a simplified pattern.
453     if (Snippet->empty())
454       return "";
455     if (Completion.Kind == CompletionItemKind::Function ||
456         Completion.Kind == CompletionItemKind::Method) {
457       // Functions snippets can be of 2 types:
458       // - containing only function arguments, e.g.
459       //   foo(${1:int p1}, ${2:int p2});
460       //   We transform this pattern to '($0)' or '()'.
461       // - template arguments and function arguments, e.g.
462       //   foo<${1:class}>(${2:int p1}).
463       //   We transform this pattern to '<$1>()$0' or '<$0>()'.
464 
465       bool EmptyArgs = StringRef(*Snippet).endswith("()");
466       if (Snippet->front() == '<')
467         return EmptyArgs ? "<$1>()$0" : "<$1>($0)";
468       if (Snippet->front() == '(')
469         return EmptyArgs ? "()" : "($0)";
470       return *Snippet; // Not an arg snippet?
471     }
472     if (Completion.Kind == CompletionItemKind::Reference ||
473         Completion.Kind == CompletionItemKind::Class) {
474       if (Snippet->front() != '<')
475         return *Snippet; // Not an arg snippet?
476 
477       // Classes and template using aliases can only have template arguments,
478       // e.g. Foo<${1:class}>.
479       if (StringRef(*Snippet).endswith("<>"))
480         return "<>"; // can happen with defaulted template arguments.
481       return "<$0>";
482     }
483     return *Snippet;
484   }
485 
486   std::string summarizeSignature() const {
487     if (auto *Signature = onlyValue<&BundledEntry::Signature>())
488       return *Signature;
489     // All bundles are function calls.
490     return "(…)";
491   }
492 
493   ASTContext &ASTCtx;
494   CodeCompletion Completion;
495   SmallVector<BundledEntry, 1> Bundled;
496   bool ExtractDocumentation;
497   bool EnableFunctionArgSnippets;
498 };
499 
500 // Determine the symbol ID for a Sema code completion result, if possible.
501 Optional<SymbolID> getSymbolID(const CodeCompletionResult &R,
502                                const SourceManager &SM) {
503   switch (R.Kind) {
504   case CodeCompletionResult::RK_Declaration:
505   case CodeCompletionResult::RK_Pattern: {
506     return clang::clangd::getSymbolID(R.Declaration);
507   }
508   case CodeCompletionResult::RK_Macro:
509     return clang::clangd::getSymbolID(*R.Macro, R.MacroDefInfo, SM);
510   case CodeCompletionResult::RK_Keyword:
511     return None;
512   }
513   llvm_unreachable("unknown CodeCompletionResult kind");
514 }
515 
516 // Scopes of the paritial identifier we're trying to complete.
517 // It is used when we query the index for more completion results.
518 struct SpecifiedScope {
519   // The scopes we should look in, determined by Sema.
520   //
521   // If the qualifier was fully resolved, we look for completions in these
522   // scopes; if there is an unresolved part of the qualifier, it should be
523   // resolved within these scopes.
524   //
525   // Examples of qualified completion:
526   //
527   //   "::vec"                                      => {""}
528   //   "using namespace std; ::vec^"                => {"", "std::"}
529   //   "namespace ns {using namespace std;} ns::^"  => {"ns::", "std::"}
530   //   "std::vec^"                                  => {""}  // "std" unresolved
531   //
532   // Examples of unqualified completion:
533   //
534   //   "vec^"                                       => {""}
535   //   "using namespace std; vec^"                  => {"", "std::"}
536   //   "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
537   //
538   // "" for global namespace, "ns::" for normal namespace.
539   std::vector<std::string> AccessibleScopes;
540   // The full scope qualifier as typed by the user (without the leading "::").
541   // Set if the qualifier is not fully resolved by Sema.
542   Optional<std::string> UnresolvedQualifier;
543 
544   // Construct scopes being queried in indexes. The results are deduplicated.
545   // This method format the scopes to match the index request representation.
546   std::vector<std::string> scopesForIndexQuery() {
547     std::set<std::string> Results;
548     for (StringRef AS : AccessibleScopes)
549       Results.insert(
550           ((UnresolvedQualifier ? *UnresolvedQualifier : "") + AS).str());
551     return {Results.begin(), Results.end()};
552   }
553 };
554 
555 // Get all scopes that will be queried in indexes and whether symbols from
556 // any scope is allowed. The first scope in the list is the preferred scope
557 // (e.g. enclosing namespace).
558 std::pair<std::vector<std::string>, bool>
559 getQueryScopes(CodeCompletionContext &CCContext, const Sema &CCSema,
560                const CodeCompleteOptions &Opts) {
561   auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
562     SpecifiedScope Info;
563     for (auto *Context : CCContext.getVisitedContexts()) {
564       if (isa<TranslationUnitDecl>(Context))
565         Info.AccessibleScopes.push_back(""); // global namespace
566       else if (isa<NamespaceDecl>(Context))
567         Info.AccessibleScopes.push_back(printNamespaceScope(*Context));
568     }
569     return Info;
570   };
571 
572   auto SS = CCContext.getCXXScopeSpecifier();
573 
574   // Unqualified completion (e.g. "vec^").
575   if (!SS) {
576     std::vector<std::string> Scopes;
577     std::string EnclosingScope = printNamespaceScope(*CCSema.CurContext);
578     Scopes.push_back(EnclosingScope);
579     for (auto &S : GetAllAccessibleScopes(CCContext).scopesForIndexQuery()) {
580       if (EnclosingScope != S)
581         Scopes.push_back(std::move(S));
582     }
583     // Allow AllScopes completion only for there is no explicit scope qualifier.
584     return {Scopes, Opts.AllScopes};
585   }
586 
587   // Qualified completion ("std::vec^"), we have two cases depending on whether
588   // the qualifier can be resolved by Sema.
589   if ((*SS)->isValid()) { // Resolved qualifier.
590     return {GetAllAccessibleScopes(CCContext).scopesForIndexQuery(), false};
591   }
592 
593   // Unresolved qualifier.
594   // FIXME: When Sema can resolve part of a scope chain (e.g.
595   // "known::unknown::id"), we should expand the known part ("known::") rather
596   // than treating the whole thing as unknown.
597   SpecifiedScope Info;
598   Info.AccessibleScopes.push_back(""); // global namespace
599 
600   Info.UnresolvedQualifier =
601       Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()),
602                            CCSema.SourceMgr, clang::LangOptions())
603           .ltrim("::");
604   // Sema excludes the trailing "::".
605   if (!Info.UnresolvedQualifier->empty())
606     *Info.UnresolvedQualifier += "::";
607 
608   return {Info.scopesForIndexQuery(), false};
609 }
610 
611 // Should we perform index-based completion in a context of the specified kind?
612 // FIXME: consider allowing completion, but restricting the result types.
613 bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
614   switch (K) {
615   case CodeCompletionContext::CCC_TopLevel:
616   case CodeCompletionContext::CCC_ObjCInterface:
617   case CodeCompletionContext::CCC_ObjCImplementation:
618   case CodeCompletionContext::CCC_ObjCIvarList:
619   case CodeCompletionContext::CCC_ClassStructUnion:
620   case CodeCompletionContext::CCC_Statement:
621   case CodeCompletionContext::CCC_Expression:
622   case CodeCompletionContext::CCC_ObjCMessageReceiver:
623   case CodeCompletionContext::CCC_EnumTag:
624   case CodeCompletionContext::CCC_UnionTag:
625   case CodeCompletionContext::CCC_ClassOrStructTag:
626   case CodeCompletionContext::CCC_ObjCProtocolName:
627   case CodeCompletionContext::CCC_Namespace:
628   case CodeCompletionContext::CCC_Type:
629   case CodeCompletionContext::CCC_ParenthesizedExpression:
630   case CodeCompletionContext::CCC_ObjCInterfaceName:
631   case CodeCompletionContext::CCC_ObjCCategoryName:
632   case CodeCompletionContext::CCC_Symbol:
633   case CodeCompletionContext::CCC_SymbolOrNewName:
634     return true;
635   case CodeCompletionContext::CCC_OtherWithMacros:
636   case CodeCompletionContext::CCC_DotMemberAccess:
637   case CodeCompletionContext::CCC_ArrowMemberAccess:
638   case CodeCompletionContext::CCC_ObjCPropertyAccess:
639   case CodeCompletionContext::CCC_MacroName:
640   case CodeCompletionContext::CCC_MacroNameUse:
641   case CodeCompletionContext::CCC_PreprocessorExpression:
642   case CodeCompletionContext::CCC_PreprocessorDirective:
643   case CodeCompletionContext::CCC_SelectorName:
644   case CodeCompletionContext::CCC_TypeQualifiers:
645   case CodeCompletionContext::CCC_ObjCInstanceMessage:
646   case CodeCompletionContext::CCC_ObjCClassMessage:
647   case CodeCompletionContext::CCC_IncludedFile:
648   // FIXME: Provide identifier based completions for the following contexts:
649   case CodeCompletionContext::CCC_Other: // Be conservative.
650   case CodeCompletionContext::CCC_NaturalLanguage:
651   case CodeCompletionContext::CCC_Recovery:
652   case CodeCompletionContext::CCC_NewName:
653     return false;
654   }
655   llvm_unreachable("unknown code completion context");
656 }
657 
658 static bool isInjectedClass(const NamedDecl &D) {
659   if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
660     if (R->isInjectedClassName())
661       return true;
662   return false;
663 }
664 
665 // Some member calls are blacklisted because they're so rarely useful.
666 static bool isBlacklistedMember(const NamedDecl &D) {
667   // Destructor completion is rarely useful, and works inconsistently.
668   // (s.^ completes ~string, but s.~st^ is an error).
669   if (D.getKind() == Decl::CXXDestructor)
670     return true;
671   // Injected name may be useful for A::foo(), but who writes A::A::foo()?
672   if (isInjectedClass(D))
673     return true;
674   // Explicit calls to operators are also rare.
675   auto NameKind = D.getDeclName().getNameKind();
676   if (NameKind == DeclarationName::CXXOperatorName ||
677       NameKind == DeclarationName::CXXLiteralOperatorName ||
678       NameKind == DeclarationName::CXXConversionFunctionName)
679     return true;
680   return false;
681 }
682 
683 // The CompletionRecorder captures Sema code-complete output, including context.
684 // It filters out ignored results (but doesn't apply fuzzy-filtering yet).
685 // It doesn't do scoring or conversion to CompletionItem yet, as we want to
686 // merge with index results first.
687 // Generally the fields and methods of this object should only be used from
688 // within the callback.
689 struct CompletionRecorder : public CodeCompleteConsumer {
690   CompletionRecorder(const CodeCompleteOptions &Opts,
691                      unique_function<void()> ResultsCallback)
692       : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
693                              /*OutputIsBinary=*/false),
694         CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
695         CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
696         CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
697     assert(this->ResultsCallback);
698   }
699 
700   std::vector<CodeCompletionResult> Results;
701   CodeCompletionContext CCContext;
702   Sema *CCSema = nullptr; // Sema that created the results.
703   // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
704 
705   void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
706                                   CodeCompletionResult *InResults,
707                                   unsigned NumResults) override final {
708     // Results from recovery mode are generally useless, and the callback after
709     // recovery (if any) is usually more interesting. To make sure we handle the
710     // future callback from sema, we just ignore all callbacks in recovery mode,
711     // as taking only results from recovery mode results in poor completion
712     // results.
713     // FIXME: in case there is no future sema completion callback after the
714     // recovery mode, we might still want to provide some results (e.g. trivial
715     // identifier-based completion).
716     if (Context.getKind() == CodeCompletionContext::CCC_Recovery) {
717       log("Code complete: Ignoring sema code complete callback with Recovery "
718           "context.");
719       return;
720     }
721     // If a callback is called without any sema result and the context does not
722     // support index-based completion, we simply skip it to give way to
723     // potential future callbacks with results.
724     if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
725       return;
726     if (CCSema) {
727       log("Multiple code complete callbacks (parser backtracked?). "
728           "Dropping results from context {0}, keeping results from {1}.",
729           getCompletionKindString(Context.getKind()),
730           getCompletionKindString(this->CCContext.getKind()));
731       return;
732     }
733     // Record the completion context.
734     CCSema = &S;
735     CCContext = Context;
736 
737     // Retain the results we might want.
738     for (unsigned I = 0; I < NumResults; ++I) {
739       auto &Result = InResults[I];
740       // Class members that are shadowed by subclasses are usually noise.
741       if (Result.Hidden && Result.Declaration &&
742           Result.Declaration->isCXXClassMember())
743         continue;
744       if (!Opts.IncludeIneligibleResults &&
745           (Result.Availability == CXAvailability_NotAvailable ||
746            Result.Availability == CXAvailability_NotAccessible))
747         continue;
748       if (Result.Declaration &&
749           !Context.getBaseType().isNull() // is this a member-access context?
750           && isBlacklistedMember(*Result.Declaration))
751         continue;
752       // Skip injected class name when no class scope is not explicitly set.
753       // E.g. show injected A::A in `using A::A^` but not in "A^".
754       if (Result.Declaration && !Context.getCXXScopeSpecifier().hasValue() &&
755           isInjectedClass(*Result.Declaration))
756         continue;
757       // We choose to never append '::' to completion results in clangd.
758       Result.StartsNestedNameSpecifier = false;
759       Results.push_back(Result);
760     }
761     ResultsCallback();
762   }
763 
764   CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
765   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
766 
767   // Returns the filtering/sorting name for Result, which must be from Results.
768   // Returned string is owned by this recorder (or the AST).
769   StringRef getName(const CodeCompletionResult &Result) {
770     switch (Result.Kind) {
771     case CodeCompletionResult::RK_Declaration:
772       if (auto *ID = Result.Declaration->getIdentifier())
773         return ID->getName();
774       break;
775     case CodeCompletionResult::RK_Keyword:
776       return Result.Keyword;
777     case CodeCompletionResult::RK_Macro:
778       return Result.Macro->getName();
779     case CodeCompletionResult::RK_Pattern:
780       return Result.Pattern->getTypedText();
781     }
782     auto *CCS = codeCompletionString(Result);
783     return CCS->getTypedText();
784   }
785 
786   // Build a CodeCompletion string for R, which must be from Results.
787   // The CCS will be owned by this recorder.
788   CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
789     // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
790     return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
791         *CCSema, CCContext, *CCAllocator, CCTUInfo,
792         /*IncludeBriefComments=*/false);
793   }
794 
795 private:
796   CodeCompleteOptions Opts;
797   std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
798   CodeCompletionTUInfo CCTUInfo;
799   unique_function<void()> ResultsCallback;
800 };
801 
802 struct ScoredSignature {
803   // When set, requires documentation to be requested from the index with this
804   // ID.
805   Optional<SymbolID> IDForDoc;
806   SignatureInformation Signature;
807   SignatureQualitySignals Quality;
808 };
809 
810 class SignatureHelpCollector final : public CodeCompleteConsumer {
811 public:
812   SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
813                          const SymbolIndex *Index, SignatureHelp &SigHelp)
814       : CodeCompleteConsumer(CodeCompleteOpts,
815                              /*OutputIsBinary=*/false),
816         SigHelp(SigHelp),
817         Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
818         CCTUInfo(Allocator), Index(Index) {}
819 
820   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
821                                  OverloadCandidate *Candidates,
822                                  unsigned NumCandidates,
823                                  SourceLocation OpenParLoc) override {
824     assert(!OpenParLoc.isInvalid());
825     SourceManager &SrcMgr = S.getSourceManager();
826     OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
827     if (SrcMgr.isInMainFile(OpenParLoc))
828       SigHelp.argListStart = sourceLocToPosition(SrcMgr, OpenParLoc);
829     else
830       elog("Location oustide main file in signature help: {0}",
831            OpenParLoc.printToString(SrcMgr));
832 
833     std::vector<ScoredSignature> ScoredSignatures;
834     SigHelp.signatures.reserve(NumCandidates);
835     ScoredSignatures.reserve(NumCandidates);
836     // FIXME(rwols): How can we determine the "active overload candidate"?
837     // Right now the overloaded candidates seem to be provided in a "best fit"
838     // order, so I'm not too worried about this.
839     SigHelp.activeSignature = 0;
840     assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
841            "too many arguments");
842     SigHelp.activeParameter = static_cast<int>(CurrentArg);
843     for (unsigned I = 0; I < NumCandidates; ++I) {
844       OverloadCandidate Candidate = Candidates[I];
845       // We want to avoid showing instantiated signatures, because they may be
846       // long in some cases (e.g. when 'T' is substituted with 'std::string', we
847       // would get 'std::basic_string<char>').
848       if (auto *Func = Candidate.getFunction()) {
849         if (auto *Pattern = Func->getTemplateInstantiationPattern())
850           Candidate = OverloadCandidate(Pattern);
851       }
852 
853       const auto *CCS = Candidate.CreateSignatureString(
854           CurrentArg, S, *Allocator, CCTUInfo, true);
855       assert(CCS && "Expected the CodeCompletionString to be non-null");
856       ScoredSignatures.push_back(processOverloadCandidate(
857           Candidate, *CCS,
858           Candidate.getFunction()
859               ? getDeclComment(S.getASTContext(), *Candidate.getFunction())
860               : ""));
861     }
862 
863     // Sema does not load the docs from the preamble, so we need to fetch extra
864     // docs from the index instead.
865     DenseMap<SymbolID, std::string> FetchedDocs;
866     if (Index) {
867       LookupRequest IndexRequest;
868       for (const auto &S : ScoredSignatures) {
869         if (!S.IDForDoc)
870           continue;
871         IndexRequest.IDs.insert(*S.IDForDoc);
872       }
873       Index->lookup(IndexRequest, [&](const Symbol &S) {
874         if (!S.Documentation.empty())
875           FetchedDocs[S.ID] = S.Documentation;
876       });
877       log("SigHelp: requested docs for {0} symbols from the index, got {1} "
878           "symbols with non-empty docs in the response",
879           IndexRequest.IDs.size(), FetchedDocs.size());
880     }
881 
882     llvm::sort(
883         ScoredSignatures,
884         [](const ScoredSignature &L, const ScoredSignature &R) {
885           // Ordering follows:
886           // - Less number of parameters is better.
887           // - Function is better than FunctionType which is better than
888           // Function Template.
889           // - High score is better.
890           // - Shorter signature is better.
891           // - Alphebatically smaller is better.
892           if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
893             return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
894           if (L.Quality.NumberOfOptionalParameters !=
895               R.Quality.NumberOfOptionalParameters)
896             return L.Quality.NumberOfOptionalParameters <
897                    R.Quality.NumberOfOptionalParameters;
898           if (L.Quality.Kind != R.Quality.Kind) {
899             using OC = CodeCompleteConsumer::OverloadCandidate;
900             switch (L.Quality.Kind) {
901             case OC::CK_Function:
902               return true;
903             case OC::CK_FunctionType:
904               return R.Quality.Kind != OC::CK_Function;
905             case OC::CK_FunctionTemplate:
906               return false;
907             }
908             llvm_unreachable("Unknown overload candidate type.");
909           }
910           if (L.Signature.label.size() != R.Signature.label.size())
911             return L.Signature.label.size() < R.Signature.label.size();
912           return L.Signature.label < R.Signature.label;
913         });
914 
915     for (auto &SS : ScoredSignatures) {
916       auto IndexDocIt =
917           SS.IDForDoc ? FetchedDocs.find(*SS.IDForDoc) : FetchedDocs.end();
918       if (IndexDocIt != FetchedDocs.end())
919         SS.Signature.documentation = IndexDocIt->second;
920 
921       SigHelp.signatures.push_back(std::move(SS.Signature));
922     }
923   }
924 
925   GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
926 
927   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
928 
929 private:
930   // FIXME(ioeric): consider moving CodeCompletionString logic here to
931   // CompletionString.h.
932   ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
933                                            const CodeCompletionString &CCS,
934                                            StringRef DocComment) const {
935     SignatureInformation Signature;
936     SignatureQualitySignals Signal;
937     const char *ReturnType = nullptr;
938 
939     Signature.documentation = formatDocumentation(CCS, DocComment);
940     Signal.Kind = Candidate.getKind();
941 
942     for (const auto &Chunk : CCS) {
943       switch (Chunk.Kind) {
944       case CodeCompletionString::CK_ResultType:
945         // A piece of text that describes the type of an entity or,
946         // for functions and methods, the return type.
947         assert(!ReturnType && "Unexpected CK_ResultType");
948         ReturnType = Chunk.Text;
949         break;
950       case CodeCompletionString::CK_Placeholder:
951         // A string that acts as a placeholder for, e.g., a function call
952         // argument.
953         // Intentional fallthrough here.
954       case CodeCompletionString::CK_CurrentParameter: {
955         // A piece of text that describes the parameter that corresponds to
956         // the code-completion location within a function call, message send,
957         // macro invocation, etc.
958         Signature.label += Chunk.Text;
959         ParameterInformation Info;
960         Info.label = Chunk.Text;
961         Signature.parameters.push_back(std::move(Info));
962         Signal.NumberOfParameters++;
963         Signal.ContainsActiveParameter = true;
964         break;
965       }
966       case CodeCompletionString::CK_Optional: {
967         // The rest of the parameters are defaulted/optional.
968         assert(Chunk.Optional &&
969                "Expected the optional code completion string to be non-null.");
970         Signature.label += getOptionalParameters(*Chunk.Optional,
971                                                  Signature.parameters, Signal);
972         break;
973       }
974       case CodeCompletionString::CK_VerticalSpace:
975         break;
976       default:
977         Signature.label += Chunk.Text;
978         break;
979       }
980     }
981     if (ReturnType) {
982       Signature.label += " -> ";
983       Signature.label += ReturnType;
984     }
985     dlog("Signal for {0}: {1}", Signature, Signal);
986     ScoredSignature Result;
987     Result.Signature = std::move(Signature);
988     Result.Quality = Signal;
989     Result.IDForDoc =
990         Result.Signature.documentation.empty() && Candidate.getFunction()
991             ? clangd::getSymbolID(Candidate.getFunction())
992             : None;
993     return Result;
994   }
995 
996   SignatureHelp &SigHelp;
997   std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
998   CodeCompletionTUInfo CCTUInfo;
999   const SymbolIndex *Index;
1000 }; // SignatureHelpCollector
1001 
1002 struct SemaCompleteInput {
1003   PathRef FileName;
1004   const tooling::CompileCommand &Command;
1005   const PreambleData *Preamble;
1006   StringRef Contents;
1007   Position Pos;
1008   IntrusiveRefCntPtr<vfs::FileSystem> VFS;
1009   std::shared_ptr<PCHContainerOperations> PCHs;
1010 };
1011 
1012 // Invokes Sema code completion on a file.
1013 // If \p Includes is set, it will be updated based on the compiler invocation.
1014 bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
1015                       const clang::CodeCompleteOptions &Options,
1016                       const SemaCompleteInput &Input,
1017                       IncludeStructure *Includes = nullptr) {
1018   trace::Span Tracer("Sema completion");
1019   std::vector<const char *> ArgStrs;
1020   for (const auto &S : Input.Command.CommandLine)
1021     ArgStrs.push_back(S.c_str());
1022 
1023   if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
1024     log("Couldn't set working directory");
1025     // We run parsing anyway, our lit-tests rely on results for non-existing
1026     // working dirs.
1027   }
1028 
1029   IntrusiveRefCntPtr<vfs::FileSystem> VFS = Input.VFS;
1030   if (Input.Preamble && Input.Preamble->StatCache)
1031     VFS = Input.Preamble->StatCache->getConsumingFS(std::move(VFS));
1032   IgnoreDiagnostics DummyDiagsConsumer;
1033   auto CI = createInvocationFromCommandLine(
1034       ArgStrs,
1035       CompilerInstance::createDiagnostics(new DiagnosticOptions,
1036                                           &DummyDiagsConsumer, false),
1037       VFS);
1038   if (!CI) {
1039     elog("Couldn't create CompilerInvocation");
1040     return false;
1041   }
1042   auto &FrontendOpts = CI->getFrontendOpts();
1043   FrontendOpts.DisableFree = false;
1044   FrontendOpts.SkipFunctionBodies = true;
1045   CI->getLangOpts()->CommentOpts.ParseAllComments = true;
1046   // Disable typo correction in Sema.
1047   CI->getLangOpts()->SpellChecking = false;
1048   // Setup code completion.
1049   FrontendOpts.CodeCompleteOpts = Options;
1050   FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
1051   auto Offset = positionToOffset(Input.Contents, Input.Pos);
1052   if (!Offset) {
1053     elog("Code completion position was invalid {0}", Offset.takeError());
1054     return false;
1055   }
1056   std::tie(FrontendOpts.CodeCompletionAt.Line,
1057            FrontendOpts.CodeCompletionAt.Column) =
1058       offsetToClangLineColumn(Input.Contents, *Offset);
1059 
1060   std::unique_ptr<MemoryBuffer> ContentsBuffer =
1061       MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
1062   // The diagnostic options must be set before creating a CompilerInstance.
1063   CI->getDiagnosticOpts().IgnoreWarnings = true;
1064   // We reuse the preamble whether it's valid or not. This is a
1065   // correctness/performance tradeoff: building without a preamble is slow, and
1066   // completion is latency-sensitive.
1067   // However, if we're completing *inside* the preamble section of the draft,
1068   // overriding the preamble will break sema completion. Fortunately we can just
1069   // skip all includes in this case; these completions are really simple.
1070   bool CompletingInPreamble =
1071       ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0).Size >
1072       *Offset;
1073   // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
1074   // the remapped buffers do not get freed.
1075   auto Clang = prepareCompilerInstance(
1076       std::move(CI),
1077       (Input.Preamble && !CompletingInPreamble) ? &Input.Preamble->Preamble
1078                                                 : nullptr,
1079       std::move(ContentsBuffer), std::move(Input.PCHs), std::move(VFS),
1080       DummyDiagsConsumer);
1081   Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
1082   Clang->setCodeCompletionConsumer(Consumer.release());
1083 
1084   SyntaxOnlyAction Action;
1085   if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1086     log("BeginSourceFile() failed when running codeComplete for {0}",
1087         Input.FileName);
1088     return false;
1089   }
1090   if (Includes)
1091     Clang->getPreprocessor().addPPCallbacks(
1092         collectIncludeStructureCallback(Clang->getSourceManager(), Includes));
1093   if (!Action.Execute()) {
1094     log("Execute() failed when running codeComplete for {0}", Input.FileName);
1095     return false;
1096   }
1097   Action.EndSourceFile();
1098 
1099   return true;
1100 }
1101 
1102 // Should we allow index completions in the specified context?
1103 bool allowIndex(CodeCompletionContext &CC) {
1104   if (!contextAllowsIndex(CC.getKind()))
1105     return false;
1106   // We also avoid ClassName::bar (but allow namespace::bar).
1107   auto Scope = CC.getCXXScopeSpecifier();
1108   if (!Scope)
1109     return true;
1110   NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
1111   if (!NameSpec)
1112     return true;
1113   // We only query the index when qualifier is a namespace.
1114   // If it's a class, we rely solely on sema completions.
1115   switch (NameSpec->getKind()) {
1116   case NestedNameSpecifier::Global:
1117   case NestedNameSpecifier::Namespace:
1118   case NestedNameSpecifier::NamespaceAlias:
1119     return true;
1120   case NestedNameSpecifier::Super:
1121   case NestedNameSpecifier::TypeSpec:
1122   case NestedNameSpecifier::TypeSpecWithTemplate:
1123   // Unresolved inside a template.
1124   case NestedNameSpecifier::Identifier:
1125     return false;
1126   }
1127   llvm_unreachable("invalid NestedNameSpecifier kind");
1128 }
1129 
1130 std::future<SymbolSlab> startAsyncFuzzyFind(const SymbolIndex &Index,
1131                                             const FuzzyFindRequest &Req) {
1132   return runAsync<SymbolSlab>([&Index, Req]() {
1133     trace::Span Tracer("Async fuzzyFind");
1134     SymbolSlab::Builder Syms;
1135     Index.fuzzyFind(Req, [&Syms](const Symbol &Sym) { Syms.insert(Sym); });
1136     return std::move(Syms).build();
1137   });
1138 }
1139 
1140 // Creates a `FuzzyFindRequest` based on the cached index request from the
1141 // last completion, if any, and the speculated completion filter text in the
1142 // source code.
1143 Optional<FuzzyFindRequest> speculativeFuzzyFindRequestForCompletion(
1144     FuzzyFindRequest CachedReq, PathRef File, StringRef Content, Position Pos) {
1145   auto Filter = speculateCompletionFilter(Content, Pos);
1146   if (!Filter) {
1147     elog("Failed to speculate filter text for code completion at Pos "
1148          "{0}:{1}: {2}",
1149          Pos.line, Pos.character, Filter.takeError());
1150     return None;
1151   }
1152   CachedReq.Query = *Filter;
1153   return CachedReq;
1154 }
1155 
1156 } // namespace
1157 
1158 clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
1159   clang::CodeCompleteOptions Result;
1160   Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
1161   Result.IncludeMacros = IncludeMacros;
1162   Result.IncludeGlobals = true;
1163   // We choose to include full comments and not do doxygen parsing in
1164   // completion.
1165   // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
1166   // formatting of the comments.
1167   Result.IncludeBriefComments = false;
1168 
1169   // When an is used, Sema is responsible for completing the main file,
1170   // the index can provide results from the preamble.
1171   // Tell Sema not to deserialize the preamble to look for results.
1172   Result.LoadExternal = !Index;
1173   Result.IncludeFixIts = IncludeFixIts;
1174 
1175   return Result;
1176 }
1177 
1178 // Returns the most popular include header for \p Sym. If two headers are
1179 // equally popular, prefer the shorter one. Returns empty string if \p Sym has
1180 // no include header.
1181 SmallVector<StringRef, 1> getRankedIncludes(const Symbol &Sym) {
1182   auto Includes = Sym.IncludeHeaders;
1183   // Sort in descending order by reference count and header length.
1184   llvm::sort(Includes, [](const Symbol::IncludeHeaderWithReferences &LHS,
1185                           const Symbol::IncludeHeaderWithReferences &RHS) {
1186     if (LHS.References == RHS.References)
1187       return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
1188     return LHS.References > RHS.References;
1189   });
1190   SmallVector<StringRef, 1> Headers;
1191   for (const auto &Include : Includes)
1192     Headers.push_back(Include.IncludeHeader);
1193   return Headers;
1194 }
1195 
1196 // Runs Sema-based (AST) and Index-based completion, returns merged results.
1197 //
1198 // There are a few tricky considerations:
1199 //   - the AST provides information needed for the index query (e.g. which
1200 //     namespaces to search in). So Sema must start first.
1201 //   - we only want to return the top results (Opts.Limit).
1202 //     Building CompletionItems for everything else is wasteful, so we want to
1203 //     preserve the "native" format until we're done with scoring.
1204 //   - the data underlying Sema completion items is owned by the AST and various
1205 //     other arenas, which must stay alive for us to build CompletionItems.
1206 //   - we may get duplicate results from Sema and the Index, we need to merge.
1207 //
1208 // So we start Sema completion first, and do all our work in its callback.
1209 // We use the Sema context information to query the index.
1210 // Then we merge the two result sets, producing items that are Sema/Index/Both.
1211 // These items are scored, and the top N are synthesized into the LSP response.
1212 // Finally, we can clean up the data structures created by Sema completion.
1213 //
1214 // Main collaborators are:
1215 //   - semaCodeComplete sets up the compiler machinery to run code completion.
1216 //   - CompletionRecorder captures Sema completion results, including context.
1217 //   - SymbolIndex (Opts.Index) provides index completion results as Symbols
1218 //   - CompletionCandidates are the result of merging Sema and Index results.
1219 //     Each candidate points to an underlying CodeCompletionResult (Sema), a
1220 //     Symbol (Index), or both. It computes the result quality score.
1221 //     CompletionCandidate also does conversion to CompletionItem (at the end).
1222 //   - FuzzyMatcher scores how the candidate matches the partial identifier.
1223 //     This score is combined with the result quality score for the final score.
1224 //   - TopN determines the results with the best score.
1225 class CodeCompleteFlow {
1226   PathRef FileName;
1227   IncludeStructure Includes; // Complete once the compiler runs.
1228   SpeculativeFuzzyFind *SpecFuzzyFind; // Can be nullptr.
1229   const CodeCompleteOptions &Opts;
1230 
1231   // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
1232   CompletionRecorder *Recorder = nullptr;
1233   int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
1234   bool Incomplete = false; // Would more be available with a higher limit?
1235   Optional<FuzzyMatcher> Filter;        // Initialized once Sema runs.
1236   std::vector<std::string> QueryScopes; // Initialized once Sema runs.
1237   // Initialized once QueryScopes is initialized, if there are scopes.
1238   Optional<ScopeDistance> ScopeProximity;
1239   llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs.
1240   // Whether to query symbols from any scope. Initialized once Sema runs.
1241   bool AllScopes = false;
1242   // Include-insertion and proximity scoring rely on the include structure.
1243   // This is available after Sema has run.
1244   Optional<IncludeInserter> Inserter;  // Available during runWithSema.
1245   Optional<URIDistance> FileProximity; // Initialized once Sema runs.
1246   /// Speculative request based on the cached request and the filter text before
1247   /// the cursor.
1248   /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
1249   /// set and contains a cached request.
1250   Optional<FuzzyFindRequest> SpecReq;
1251 
1252 public:
1253   // A CodeCompleteFlow object is only useful for calling run() exactly once.
1254   CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
1255                    SpeculativeFuzzyFind *SpecFuzzyFind,
1256                    const CodeCompleteOptions &Opts)
1257       : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1258         Opts(Opts) {}
1259 
1260   CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
1261     trace::Span Tracer("CodeCompleteFlow");
1262     if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq.hasValue()) {
1263       assert(!SpecFuzzyFind->Result.valid());
1264       if ((SpecReq = speculativeFuzzyFindRequestForCompletion(
1265                *SpecFuzzyFind->CachedReq, SemaCCInput.FileName,
1266                SemaCCInput.Contents, SemaCCInput.Pos)))
1267         SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1268     }
1269 
1270     // We run Sema code completion first. It builds an AST and calculates:
1271     //   - completion results based on the AST.
1272     //   - partial identifier and context. We need these for the index query.
1273     CodeCompleteResult Output;
1274     auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
1275       assert(Recorder && "Recorder is not set");
1276       auto Style =
1277           format::getStyle(format::DefaultFormatStyle, SemaCCInput.FileName,
1278                            format::DefaultFallbackStyle, SemaCCInput.Contents,
1279                            SemaCCInput.VFS.get());
1280       if (!Style) {
1281         log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.",
1282             SemaCCInput.FileName, Style.takeError());
1283         Style = format::getLLVMStyle();
1284       }
1285       // If preprocessor was run, inclusions from preprocessor callback should
1286       // already be added to Includes.
1287       Inserter.emplace(
1288           SemaCCInput.FileName, SemaCCInput.Contents, *Style,
1289           SemaCCInput.Command.Directory,
1290           Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
1291       for (const auto &Inc : Includes.MainFileIncludes)
1292         Inserter->addExisting(Inc);
1293 
1294       // Most of the cost of file proximity is in initializing the FileDistance
1295       // structures based on the observed includes, once per query. Conceptually
1296       // that happens here (though the per-URI-scheme initialization is lazy).
1297       // The per-result proximity scoring is (amortized) very cheap.
1298       FileDistanceOptions ProxOpts{}; // Use defaults.
1299       const auto &SM = Recorder->CCSema->getSourceManager();
1300       StringMap<SourceParams> ProxSources;
1301       for (auto &Entry : Includes.includeDepth(
1302                SM.getFileEntryForID(SM.getMainFileID())->getName())) {
1303         auto &Source = ProxSources[Entry.getKey()];
1304         Source.Cost = Entry.getValue() * ProxOpts.IncludeCost;
1305         // Symbols near our transitive includes are good, but only consider
1306         // things in the same directory or below it. Otherwise there can be
1307         // many false positives.
1308         if (Entry.getValue() > 0)
1309           Source.MaxUpTraversals = 1;
1310       }
1311       FileProximity.emplace(ProxSources, ProxOpts);
1312 
1313       Output = runWithSema();
1314       Inserter.reset(); // Make sure this doesn't out-live Clang.
1315       SPAN_ATTACH(Tracer, "sema_completion_kind",
1316                   getCompletionKindString(Recorder->CCContext.getKind()));
1317       log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1318           "expected type {3}",
1319           getCompletionKindString(Recorder->CCContext.getKind()),
1320           join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
1321           PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1322                         : "<none>");
1323     });
1324 
1325     Recorder = RecorderOwner.get();
1326 
1327     semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1328                      SemaCCInput, &Includes);
1329 
1330     SPAN_ATTACH(Tracer, "sema_results", NSema);
1331     SPAN_ATTACH(Tracer, "index_results", NIndex);
1332     SPAN_ATTACH(Tracer, "merged_results", NBoth);
1333     SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
1334     SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
1335     log("Code complete: {0} results from Sema, {1} from Index, "
1336         "{2} matched, {3} returned{4}.",
1337         NSema, NIndex, NBoth, Output.Completions.size(),
1338         Output.HasMore ? " (incomplete)" : "");
1339     assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1340     // We don't assert that isIncomplete means we hit a limit.
1341     // Indexes may choose to impose their own limits even if we don't have one.
1342     return Output;
1343   }
1344 
1345 private:
1346   // This is called by run() once Sema code completion is done, but before the
1347   // Sema data structures are torn down. It does all the real work.
1348   CodeCompleteResult runWithSema() {
1349     const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1350         Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1351     Range TextEditRange;
1352     // When we are getting completions with an empty identifier, for example
1353     //    std::vector<int> asdf;
1354     //    asdf.^;
1355     // Then the range will be invalid and we will be doing insertion, use
1356     // current cursor position in such cases as range.
1357     if (CodeCompletionRange.isValid()) {
1358       TextEditRange = halfOpenToRange(Recorder->CCSema->getSourceManager(),
1359                                       CodeCompletionRange);
1360     } else {
1361       const auto &Pos = sourceLocToPosition(
1362           Recorder->CCSema->getSourceManager(),
1363           Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1364       TextEditRange.start = TextEditRange.end = Pos;
1365     }
1366     Filter = FuzzyMatcher(
1367         Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1368     std::tie(QueryScopes, AllScopes) =
1369         getQueryScopes(Recorder->CCContext, *Recorder->CCSema, Opts);
1370     if (!QueryScopes.empty())
1371       ScopeProximity.emplace(QueryScopes);
1372     PreferredType =
1373         OpaqueType::fromType(Recorder->CCSema->getASTContext(),
1374                              Recorder->CCContext.getPreferredType());
1375     // Sema provides the needed context to query the index.
1376     // FIXME: in addition to querying for extra/overlapping symbols, we should
1377     //        explicitly request symbols corresponding to Sema results.
1378     //        We can use their signals even if the index can't suggest them.
1379     // We must copy index results to preserve them, but there are at most Limit.
1380     auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1381                             ? queryIndex()
1382                             : SymbolSlab();
1383     trace::Span Tracer("Populate CodeCompleteResult");
1384     // Merge Sema and Index results, score them, and pick the winners.
1385     auto Top = mergeResults(Recorder->Results, IndexResults);
1386     CodeCompleteResult Output;
1387 
1388     // Convert the results to final form, assembling the expensive strings.
1389     for (auto &C : Top) {
1390       Output.Completions.push_back(toCodeCompletion(C.first));
1391       Output.Completions.back().Score = C.second;
1392       Output.Completions.back().CompletionTokenRange = TextEditRange;
1393     }
1394     Output.HasMore = Incomplete;
1395     Output.Context = Recorder->CCContext.getKind();
1396 
1397     return Output;
1398   }
1399 
1400   SymbolSlab queryIndex() {
1401     trace::Span Tracer("Query index");
1402     SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
1403 
1404     // Build the query.
1405     FuzzyFindRequest Req;
1406     if (Opts.Limit)
1407       Req.Limit = Opts.Limit;
1408     Req.Query = Filter->pattern();
1409     Req.RestrictForCodeCompletion = true;
1410     Req.Scopes = QueryScopes;
1411     Req.AnyScope = AllScopes;
1412     // FIXME: we should send multiple weighted paths here.
1413     Req.ProximityPaths.push_back(FileName);
1414     vlog("Code complete: fuzzyFind({0:2})", toJSON(Req));
1415 
1416     if (SpecFuzzyFind)
1417       SpecFuzzyFind->NewReq = Req;
1418     if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1419       vlog("Code complete: speculative fuzzy request matches the actual index "
1420            "request. Waiting for the speculative index results.");
1421       SPAN_ATTACH(Tracer, "Speculative results", true);
1422 
1423       trace::Span WaitSpec("Wait speculative results");
1424       return SpecFuzzyFind->Result.get();
1425     }
1426 
1427     SPAN_ATTACH(Tracer, "Speculative results", false);
1428 
1429     // Run the query against the index.
1430     SymbolSlab::Builder ResultsBuilder;
1431     if (Opts.Index->fuzzyFind(
1432             Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1433       Incomplete = true;
1434     return std::move(ResultsBuilder).build();
1435   }
1436 
1437   // Merges Sema and Index results where possible, to form CompletionCandidates.
1438   // Groups overloads if desired, to form CompletionCandidate::Bundles. The
1439   // bundles are scored and top results are returned, best to worst.
1440   std::vector<ScoredBundle>
1441   mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1442                const SymbolSlab &IndexResults) {
1443     trace::Span Tracer("Merge and score results");
1444     std::vector<CompletionCandidate::Bundle> Bundles;
1445     DenseMap<size_t, size_t> BundleLookup;
1446     auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
1447                             const Symbol *IndexResult) {
1448       CompletionCandidate C;
1449       C.SemaResult = SemaResult;
1450       C.IndexResult = IndexResult;
1451       if (C.IndexResult)
1452         C.RankedIncludeHeaders = getRankedIncludes(*C.IndexResult);
1453       C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1454       if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1455         auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1456         if (Ret.second)
1457           Bundles.emplace_back();
1458         Bundles[Ret.first->second].push_back(std::move(C));
1459       } else {
1460         Bundles.emplace_back();
1461         Bundles.back().push_back(std::move(C));
1462       }
1463     };
1464     DenseSet<const Symbol *> UsedIndexResults;
1465     auto CorrespondingIndexResult =
1466         [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
1467       if (auto SymID =
1468               getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
1469         auto I = IndexResults.find(*SymID);
1470         if (I != IndexResults.end()) {
1471           UsedIndexResults.insert(&*I);
1472           return &*I;
1473         }
1474       }
1475       return nullptr;
1476     };
1477     // Emit all Sema results, merging them with Index results if possible.
1478     for (auto &SemaResult : Recorder->Results)
1479       AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
1480     // Now emit any Index-only results.
1481     for (const auto &IndexResult : IndexResults) {
1482       if (UsedIndexResults.count(&IndexResult))
1483         continue;
1484       AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
1485     }
1486     // We only keep the best N results at any time, in "native" format.
1487     TopN<ScoredBundle, ScoredBundleGreater> Top(
1488         Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1489     for (auto &Bundle : Bundles)
1490       addCandidate(Top, std::move(Bundle));
1491     return std::move(Top).items();
1492   }
1493 
1494   Optional<float> fuzzyScore(const CompletionCandidate &C) {
1495     // Macros can be very spammy, so we only support prefix completion.
1496     // We won't end up with underfull index results, as macros are sema-only.
1497     if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1498         !C.Name.startswith_lower(Filter->pattern()))
1499       return None;
1500     return Filter->match(C.Name);
1501   }
1502 
1503   // Scores a candidate and adds it to the TopN structure.
1504   void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1505                     CompletionCandidate::Bundle Bundle) {
1506     SymbolQualitySignals Quality;
1507     SymbolRelevanceSignals Relevance;
1508     Relevance.Context = Recorder->CCContext.getKind();
1509     Relevance.Query = SymbolRelevanceSignals::CodeComplete;
1510     Relevance.FileProximityMatch = FileProximity.getPointer();
1511     if (ScopeProximity)
1512       Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
1513     if (PreferredType)
1514       Relevance.HadContextType = true;
1515 
1516     auto &First = Bundle.front();
1517     if (auto FuzzyScore = fuzzyScore(First))
1518       Relevance.NameMatch = *FuzzyScore;
1519     else
1520       return;
1521     SymbolOrigin Origin = SymbolOrigin::Unknown;
1522     bool FromIndex = false;
1523     for (const auto &Candidate : Bundle) {
1524       if (Candidate.IndexResult) {
1525         Quality.merge(*Candidate.IndexResult);
1526         Relevance.merge(*Candidate.IndexResult);
1527         Origin |= Candidate.IndexResult->Origin;
1528         FromIndex = true;
1529         if (!Candidate.IndexResult->Type.empty())
1530           Relevance.HadSymbolType |= true;
1531         if (PreferredType &&
1532             PreferredType->raw() == Candidate.IndexResult->Type) {
1533           Relevance.TypeMatchesPreferred = true;
1534         }
1535       }
1536       if (Candidate.SemaResult) {
1537         Quality.merge(*Candidate.SemaResult);
1538         Relevance.merge(*Candidate.SemaResult);
1539         if (PreferredType) {
1540           if (auto CompletionType = OpaqueType::fromCompletionResult(
1541                   Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
1542             Relevance.HadSymbolType |= true;
1543             if (PreferredType == CompletionType)
1544               Relevance.TypeMatchesPreferred = true;
1545           }
1546         }
1547         Origin |= SymbolOrigin::AST;
1548       }
1549     }
1550 
1551     CodeCompletion::Scores Scores;
1552     Scores.Quality = Quality.evaluate();
1553     Scores.Relevance = Relevance.evaluate();
1554     Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1555     // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1556     Scores.ExcludingName = Relevance.NameMatch
1557                                ? Scores.Total / Relevance.NameMatch
1558                                : Scores.Quality;
1559 
1560     dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
1561          to_string(Origin), Scores.Total, to_string(Quality),
1562          to_string(Relevance));
1563 
1564     NSema += bool(Origin & SymbolOrigin::AST);
1565     NIndex += FromIndex;
1566     NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
1567     if (Candidates.push({std::move(Bundle), Scores}))
1568       Incomplete = true;
1569   }
1570 
1571   CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
1572     Optional<CodeCompletionBuilder> Builder;
1573     for (const auto &Item : Bundle) {
1574       CodeCompletionString *SemaCCS =
1575           Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1576                           : nullptr;
1577       if (!Builder)
1578         Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
1579                         QueryScopes, *Inserter, FileName,
1580                         Recorder->CCContext.getKind(), Opts);
1581       else
1582         Builder->add(Item, SemaCCS);
1583     }
1584     return Builder->build();
1585   }
1586 };
1587 
1588 Expected<StringRef> speculateCompletionFilter(StringRef Content, Position Pos) {
1589   auto Offset = positionToOffset(Content, Pos);
1590   if (!Offset)
1591     return make_error<StringError>(
1592         "Failed to convert position to offset in content.",
1593         inconvertibleErrorCode());
1594   if (*Offset == 0)
1595     return "";
1596 
1597   // Start from the character before the cursor.
1598   int St = *Offset - 1;
1599   // FIXME(ioeric): consider UTF characters?
1600   auto IsValidIdentifierChar = [](char c) {
1601     return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
1602             (c >= '0' && c <= '9') || (c == '_'));
1603   };
1604   size_t Len = 0;
1605   for (; (St >= 0) && IsValidIdentifierChar(Content[St]); --St, ++Len) {
1606   }
1607   if (Len > 0)
1608     St++; // Shift to the first valid character.
1609   return Content.substr(St, Len);
1610 }
1611 
1612 CodeCompleteResult
1613 codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
1614              const PreambleData *Preamble, StringRef Contents, Position Pos,
1615              IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1616              std::shared_ptr<PCHContainerOperations> PCHs,
1617              CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind) {
1618   return CodeCompleteFlow(FileName,
1619                           Preamble ? Preamble->Includes : IncludeStructure(),
1620                           SpecFuzzyFind, Opts)
1621       .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
1622 }
1623 
1624 SignatureHelp signatureHelp(PathRef FileName,
1625                             const tooling::CompileCommand &Command,
1626                             const PreambleData *Preamble, StringRef Contents,
1627                             Position Pos,
1628                             IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1629                             std::shared_ptr<PCHContainerOperations> PCHs,
1630                             const SymbolIndex *Index) {
1631   SignatureHelp Result;
1632   clang::CodeCompleteOptions Options;
1633   Options.IncludeGlobals = false;
1634   Options.IncludeMacros = false;
1635   Options.IncludeCodePatterns = false;
1636   Options.IncludeBriefComments = false;
1637   IncludeStructure PreambleInclusions; // Unused for signatureHelp
1638   semaCodeComplete(
1639       llvm::make_unique<SignatureHelpCollector>(Options, Index, Result),
1640       Options,
1641       {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1642        std::move(PCHs)});
1643   return Result;
1644 }
1645 
1646 bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1647   auto InTopLevelScope = [](const NamedDecl &ND) {
1648     switch (ND.getDeclContext()->getDeclKind()) {
1649     case Decl::TranslationUnit:
1650     case Decl::Namespace:
1651     case Decl::LinkageSpec:
1652       return true;
1653     default:
1654       break;
1655     };
1656     return false;
1657   };
1658   if (InTopLevelScope(ND))
1659     return true;
1660 
1661   if (const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
1662     return InTopLevelScope(*EnumDecl) && !EnumDecl->isScoped();
1663 
1664   return false;
1665 }
1666 
1667 CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1668   CompletionItem LSP;
1669   const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
1670   LSP.label = ((InsertInclude && InsertInclude->Insertion)
1671                    ? Opts.IncludeIndicator.Insert
1672                    : Opts.IncludeIndicator.NoInsert) +
1673               (Opts.ShowOrigins ? "[" + to_string(Origin) + "]" : "") +
1674               RequiredQualifier + Name + Signature;
1675 
1676   LSP.kind = Kind;
1677   LSP.detail =
1678       BundleSize > 1 ? formatv("[{0} overloads]", BundleSize) : ReturnType;
1679   LSP.deprecated = Deprecated;
1680   if (InsertInclude)
1681     LSP.detail += "\n" + InsertInclude->Header;
1682   LSP.documentation = Documentation;
1683   LSP.sortText = sortText(Score.Total, Name);
1684   LSP.filterText = Name;
1685   LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name};
1686   // Merge continuous additionalTextEdits into main edit. The main motivation
1687   // behind this is to help LSP clients, it seems most of them are confused when
1688   // they are provided with additionalTextEdits that are consecutive to main
1689   // edit.
1690   // Note that we store additional text edits from back to front in a line. That
1691   // is mainly to help LSP clients again, so that changes do not effect each
1692   // other.
1693   for (const auto &FixIt : FixIts) {
1694     if (IsRangeConsecutive(FixIt.range, LSP.textEdit->range)) {
1695       LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
1696       LSP.textEdit->range.start = FixIt.range.start;
1697     } else {
1698       LSP.additionalTextEdits.push_back(FixIt);
1699     }
1700   }
1701   if (Opts.EnableSnippets)
1702     LSP.textEdit->newText += SnippetSuffix;
1703 
1704   // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
1705   // compatible with most of the editors.
1706   LSP.insertText = LSP.textEdit->newText;
1707   LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1708                                              : InsertTextFormat::PlainText;
1709   if (InsertInclude && InsertInclude->Insertion)
1710     LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
1711 
1712   return LSP;
1713 }
1714 
1715 raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) {
1716   // For now just lean on CompletionItem.
1717   return OS << C.render(CodeCompleteOptions());
1718 }
1719 
1720 raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) {
1721   OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
1722      << " (" << getCompletionKindString(R.Context) << ")"
1723      << " items:\n";
1724   for (const auto &C : R.Completions)
1725     OS << C << "\n";
1726   return OS;
1727 }
1728 
1729 } // namespace clangd
1730 } // namespace clang
1731