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