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