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