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