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