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