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