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