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