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