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