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