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