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