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