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 = 0;
899   if (const auto *F = Candidate.getFunction()) {
900     NumParams = F->getNumParams();
901     if (F->isVariadic())
902       ++NumParams;
903   } else if (auto *T = Candidate.getFunctionType()) {
904     if (auto *Proto = T->getAs<FunctionProtoType>()) {
905       NumParams = Proto->getNumParams();
906       if (Proto->isVariadic())
907         ++NumParams;
908     }
909   }
910   return std::min(Arg, std::max(NumParams - 1, 0));
911 }
912 
913 class SignatureHelpCollector final : public CodeCompleteConsumer {
914 public:
915   SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
916                          MarkupKind DocumentationFormat,
917                          const SymbolIndex *Index, SignatureHelp &SigHelp)
918       : CodeCompleteConsumer(CodeCompleteOpts), SigHelp(SigHelp),
919         Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
920         CCTUInfo(Allocator), Index(Index),
921         DocumentationFormat(DocumentationFormat) {}
922 
923   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
924                                  OverloadCandidate *Candidates,
925                                  unsigned NumCandidates,
926                                  SourceLocation OpenParLoc) override {
927     assert(!OpenParLoc.isInvalid());
928     SourceManager &SrcMgr = S.getSourceManager();
929     OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
930     if (SrcMgr.isInMainFile(OpenParLoc))
931       SigHelp.argListStart = sourceLocToPosition(SrcMgr, OpenParLoc);
932     else
933       elog("Location oustide main file in signature help: {0}",
934            OpenParLoc.printToString(SrcMgr));
935 
936     std::vector<ScoredSignature> ScoredSignatures;
937     SigHelp.signatures.reserve(NumCandidates);
938     ScoredSignatures.reserve(NumCandidates);
939     // FIXME(rwols): How can we determine the "active overload candidate"?
940     // Right now the overloaded candidates seem to be provided in a "best fit"
941     // order, so I'm not too worried about this.
942     SigHelp.activeSignature = 0;
943     assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
944            "too many arguments");
945 
946     SigHelp.activeParameter = static_cast<int>(CurrentArg);
947 
948     for (unsigned I = 0; I < NumCandidates; ++I) {
949       OverloadCandidate Candidate = Candidates[I];
950       // We want to avoid showing instantiated signatures, because they may be
951       // long in some cases (e.g. when 'T' is substituted with 'std::string', we
952       // would get 'std::basic_string<char>').
953       if (auto *Func = Candidate.getFunction()) {
954         if (auto *Pattern = Func->getTemplateInstantiationPattern())
955           Candidate = OverloadCandidate(Pattern);
956       }
957       if (static_cast<int>(I) == SigHelp.activeSignature) {
958         // The activeParameter in LSP relates to the activeSignature. There is
959         // another, per-signature field, but we currently do not use it and not
960         // all clients might support it.
961         // FIXME: Add support for per-signature activeParameter field.
962         SigHelp.activeParameter =
963             paramIndexForArg(Candidate, SigHelp.activeParameter);
964       }
965 
966       const auto *CCS = Candidate.CreateSignatureString(
967           CurrentArg, S, *Allocator, CCTUInfo, true);
968       assert(CCS && "Expected the CodeCompletionString to be non-null");
969       ScoredSignatures.push_back(processOverloadCandidate(
970           Candidate, *CCS,
971           Candidate.getFunction()
972               ? getDeclComment(S.getASTContext(), *Candidate.getFunction())
973               : ""));
974     }
975 
976     // Sema does not load the docs from the preamble, so we need to fetch extra
977     // docs from the index instead.
978     llvm::DenseMap<SymbolID, std::string> FetchedDocs;
979     if (Index) {
980       LookupRequest IndexRequest;
981       for (const auto &S : ScoredSignatures) {
982         if (!S.IDForDoc)
983           continue;
984         IndexRequest.IDs.insert(S.IDForDoc);
985       }
986       Index->lookup(IndexRequest, [&](const Symbol &S) {
987         if (!S.Documentation.empty())
988           FetchedDocs[S.ID] = std::string(S.Documentation);
989       });
990       vlog("SigHelp: requested docs for {0} symbols from the index, got {1} "
991            "symbols with non-empty docs in the response",
992            IndexRequest.IDs.size(), FetchedDocs.size());
993     }
994 
995     llvm::sort(ScoredSignatures, [](const ScoredSignature &L,
996                                     const ScoredSignature &R) {
997       // Ordering follows:
998       // - Less number of parameters is better.
999       // - Function is better than FunctionType which is better than
1000       // Function Template.
1001       // - High score is better.
1002       // - Shorter signature is better.
1003       // - Alphabetically smaller is better.
1004       if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
1005         return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
1006       if (L.Quality.NumberOfOptionalParameters !=
1007           R.Quality.NumberOfOptionalParameters)
1008         return L.Quality.NumberOfOptionalParameters <
1009                R.Quality.NumberOfOptionalParameters;
1010       if (L.Quality.Kind != R.Quality.Kind) {
1011         using OC = CodeCompleteConsumer::OverloadCandidate;
1012         switch (L.Quality.Kind) {
1013         case OC::CK_Function:
1014           return true;
1015         case OC::CK_FunctionType:
1016           return R.Quality.Kind != OC::CK_Function;
1017         case OC::CK_FunctionTemplate:
1018           return false;
1019         }
1020         llvm_unreachable("Unknown overload candidate type.");
1021       }
1022       if (L.Signature.label.size() != R.Signature.label.size())
1023         return L.Signature.label.size() < R.Signature.label.size();
1024       return L.Signature.label < R.Signature.label;
1025     });
1026 
1027     for (auto &SS : ScoredSignatures) {
1028       auto IndexDocIt =
1029           SS.IDForDoc ? FetchedDocs.find(SS.IDForDoc) : FetchedDocs.end();
1030       if (IndexDocIt != FetchedDocs.end()) {
1031         markup::Document SignatureComment;
1032         parseDocumentation(IndexDocIt->second, SignatureComment);
1033         SS.Signature.documentation =
1034             renderDoc(SignatureComment, DocumentationFormat);
1035       }
1036 
1037       SigHelp.signatures.push_back(std::move(SS.Signature));
1038     }
1039   }
1040 
1041   GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
1042 
1043   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1044 
1045 private:
1046   void processParameterChunk(llvm::StringRef ChunkText,
1047                              SignatureInformation &Signature) const {
1048     // (!) this is O(n), should still be fast compared to building ASTs.
1049     unsigned ParamStartOffset = lspLength(Signature.label);
1050     unsigned ParamEndOffset = ParamStartOffset + lspLength(ChunkText);
1051     // A piece of text that describes the parameter that corresponds to
1052     // the code-completion location within a function call, message send,
1053     // macro invocation, etc.
1054     Signature.label += ChunkText;
1055     ParameterInformation Info;
1056     Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset);
1057     // FIXME: only set 'labelOffsets' when all clients migrate out of it.
1058     Info.labelString = std::string(ChunkText);
1059 
1060     Signature.parameters.push_back(std::move(Info));
1061   }
1062 
1063   void processOptionalChunk(const CodeCompletionString &CCS,
1064                             SignatureInformation &Signature,
1065                             SignatureQualitySignals &Signal) const {
1066     for (const auto &Chunk : CCS) {
1067       switch (Chunk.Kind) {
1068       case CodeCompletionString::CK_Optional:
1069         assert(Chunk.Optional &&
1070                "Expected the optional code completion string to be non-null.");
1071         processOptionalChunk(*Chunk.Optional, Signature, Signal);
1072         break;
1073       case CodeCompletionString::CK_VerticalSpace:
1074         break;
1075       case CodeCompletionString::CK_CurrentParameter:
1076       case CodeCompletionString::CK_Placeholder:
1077         processParameterChunk(Chunk.Text, Signature);
1078         Signal.NumberOfOptionalParameters++;
1079         break;
1080       default:
1081         Signature.label += Chunk.Text;
1082         break;
1083       }
1084     }
1085   }
1086 
1087   // FIXME(ioeric): consider moving CodeCompletionString logic here to
1088   // CompletionString.h.
1089   ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
1090                                            const CodeCompletionString &CCS,
1091                                            llvm::StringRef DocComment) const {
1092     SignatureInformation Signature;
1093     SignatureQualitySignals Signal;
1094     const char *ReturnType = nullptr;
1095 
1096     markup::Document OverloadComment;
1097     parseDocumentation(formatDocumentation(CCS, DocComment), OverloadComment);
1098     Signature.documentation = renderDoc(OverloadComment, DocumentationFormat);
1099     Signal.Kind = Candidate.getKind();
1100 
1101     for (const auto &Chunk : CCS) {
1102       switch (Chunk.Kind) {
1103       case CodeCompletionString::CK_ResultType:
1104         // A piece of text that describes the type of an entity or,
1105         // for functions and methods, the return type.
1106         assert(!ReturnType && "Unexpected CK_ResultType");
1107         ReturnType = Chunk.Text;
1108         break;
1109       case CodeCompletionString::CK_CurrentParameter:
1110       case CodeCompletionString::CK_Placeholder:
1111         processParameterChunk(Chunk.Text, Signature);
1112         Signal.NumberOfParameters++;
1113         break;
1114       case CodeCompletionString::CK_Optional: {
1115         // The rest of the parameters are defaulted/optional.
1116         assert(Chunk.Optional &&
1117                "Expected the optional code completion string to be non-null.");
1118         processOptionalChunk(*Chunk.Optional, Signature, Signal);
1119         break;
1120       }
1121       case CodeCompletionString::CK_VerticalSpace:
1122         break;
1123       default:
1124         Signature.label += Chunk.Text;
1125         break;
1126       }
1127     }
1128     if (ReturnType) {
1129       Signature.label += " -> ";
1130       Signature.label += ReturnType;
1131     }
1132     dlog("Signal for {0}: {1}", Signature, Signal);
1133     ScoredSignature Result;
1134     Result.Signature = std::move(Signature);
1135     Result.Quality = Signal;
1136     const FunctionDecl *Func = Candidate.getFunction();
1137     if (Func && Result.Signature.documentation.value.empty()) {
1138       // Computing USR caches linkage, which may change after code completion.
1139       if (!hasUnstableLinkage(Func))
1140         Result.IDForDoc = clangd::getSymbolID(Func);
1141     }
1142     return Result;
1143   }
1144 
1145   SignatureHelp &SigHelp;
1146   std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1147   CodeCompletionTUInfo CCTUInfo;
1148   const SymbolIndex *Index;
1149   MarkupKind DocumentationFormat;
1150 }; // SignatureHelpCollector
1151 
1152 // Used only for completion of C-style comments in function call (i.e.
1153 // /*foo=*/7). Similar to SignatureHelpCollector, but needs to do less work.
1154 class ParamNameCollector final : public CodeCompleteConsumer {
1155 public:
1156   ParamNameCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
1157                      std::set<std::string> &ParamNames)
1158       : CodeCompleteConsumer(CodeCompleteOpts),
1159         Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1160         CCTUInfo(Allocator), ParamNames(ParamNames) {}
1161 
1162   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1163                                  OverloadCandidate *Candidates,
1164                                  unsigned NumCandidates,
1165                                  SourceLocation OpenParLoc) override {
1166     assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
1167            "too many arguments");
1168 
1169     for (unsigned I = 0; I < NumCandidates; ++I) {
1170       OverloadCandidate Candidate = Candidates[I];
1171       auto *Func = Candidate.getFunction();
1172       if (!Func || Func->getNumParams() <= CurrentArg)
1173         continue;
1174       auto *PVD = Func->getParamDecl(CurrentArg);
1175       if (!PVD)
1176         continue;
1177       auto *Ident = PVD->getIdentifier();
1178       if (!Ident)
1179         continue;
1180       auto Name = Ident->getName();
1181       if (!Name.empty())
1182         ParamNames.insert(Name.str());
1183     }
1184   }
1185 
1186 private:
1187   GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
1188 
1189   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1190 
1191   std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1192   CodeCompletionTUInfo CCTUInfo;
1193   std::set<std::string> &ParamNames;
1194 };
1195 
1196 struct SemaCompleteInput {
1197   PathRef FileName;
1198   size_t Offset;
1199   const PreambleData &Preamble;
1200   const llvm::Optional<PreamblePatch> Patch;
1201   const ParseInputs &ParseInput;
1202 };
1203 
1204 void loadMainFilePreambleMacros(const Preprocessor &PP,
1205                                 const PreambleData &Preamble) {
1206   // The ExternalPreprocessorSource has our macros, if we know where to look.
1207   // We can read all the macros using PreambleMacros->ReadDefinedMacros(),
1208   // but this includes transitively included files, so may deserialize a lot.
1209   ExternalPreprocessorSource *PreambleMacros = PP.getExternalSource();
1210   // As we have the names of the macros, we can look up their IdentifierInfo
1211   // and then use this to load just the macros we want.
1212   const auto &ITable = PP.getIdentifierTable();
1213   IdentifierInfoLookup *PreambleIdentifiers =
1214       ITable.getExternalIdentifierLookup();
1215 
1216   if (!PreambleIdentifiers || !PreambleMacros)
1217     return;
1218   for (const auto &MacroName : Preamble.Macros.Names) {
1219     if (ITable.find(MacroName.getKey()) != ITable.end())
1220       continue;
1221     if (auto *II = PreambleIdentifiers->get(MacroName.getKey()))
1222       if (II->isOutOfDate())
1223         PreambleMacros->updateOutOfDateIdentifier(*II);
1224   }
1225 }
1226 
1227 // Invokes Sema code completion on a file.
1228 // If \p Includes is set, it will be updated based on the compiler invocation.
1229 bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
1230                       const clang::CodeCompleteOptions &Options,
1231                       const SemaCompleteInput &Input,
1232                       IncludeStructure *Includes = nullptr) {
1233   trace::Span Tracer("Sema completion");
1234 
1235   IgnoreDiagnostics IgnoreDiags;
1236   auto CI = buildCompilerInvocation(Input.ParseInput, IgnoreDiags);
1237   if (!CI) {
1238     elog("Couldn't create CompilerInvocation");
1239     return false;
1240   }
1241   auto &FrontendOpts = CI->getFrontendOpts();
1242   FrontendOpts.SkipFunctionBodies = true;
1243   // Disable typo correction in Sema.
1244   CI->getLangOpts()->SpellChecking = false;
1245   // Code completion won't trigger in delayed template bodies.
1246   // This is on-by-default in windows to allow parsing SDK headers; we're only
1247   // disabling it for the main-file (not preamble).
1248   CI->getLangOpts()->DelayedTemplateParsing = false;
1249   // Setup code completion.
1250   FrontendOpts.CodeCompleteOpts = Options;
1251   FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName);
1252   std::tie(FrontendOpts.CodeCompletionAt.Line,
1253            FrontendOpts.CodeCompletionAt.Column) =
1254       offsetToClangLineColumn(Input.ParseInput.Contents, Input.Offset);
1255 
1256   std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1257       llvm::MemoryBuffer::getMemBuffer(Input.ParseInput.Contents,
1258                                        Input.FileName);
1259   // The diagnostic options must be set before creating a CompilerInstance.
1260   CI->getDiagnosticOpts().IgnoreWarnings = true;
1261   // We reuse the preamble whether it's valid or not. This is a
1262   // correctness/performance tradeoff: building without a preamble is slow, and
1263   // completion is latency-sensitive.
1264   // However, if we're completing *inside* the preamble section of the draft,
1265   // overriding the preamble will break sema completion. Fortunately we can just
1266   // skip all includes in this case; these completions are really simple.
1267   PreambleBounds PreambleRegion =
1268       ComputePreambleBounds(*CI->getLangOpts(), *ContentsBuffer, 0);
1269   bool CompletingInPreamble = Input.Offset < PreambleRegion.Size ||
1270                               (!PreambleRegion.PreambleEndsAtStartOfLine &&
1271                                Input.Offset == PreambleRegion.Size);
1272   if (Input.Patch)
1273     Input.Patch->apply(*CI);
1274   // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
1275   // the remapped buffers do not get freed.
1276   llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1277       Input.ParseInput.TFS->view(Input.ParseInput.CompileCommand.Directory);
1278   if (Input.Preamble.StatCache)
1279     VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS));
1280   auto Clang = prepareCompilerInstance(
1281       std::move(CI), !CompletingInPreamble ? &Input.Preamble.Preamble : nullptr,
1282       std::move(ContentsBuffer), std::move(VFS), IgnoreDiags);
1283   Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
1284   Clang->setCodeCompletionConsumer(Consumer.release());
1285 
1286   SyntaxOnlyAction Action;
1287   if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1288     log("BeginSourceFile() failed when running codeComplete for {0}",
1289         Input.FileName);
1290     return false;
1291   }
1292   // Macros can be defined within the preamble region of the main file.
1293   // They don't fall nicely into our index/Sema dichotomy:
1294   //  - they're not indexed for completion (they're not available across files)
1295   //  - but Sema code complete won't see them: as part of the preamble, they're
1296   //    deserialized only when mentioned.
1297   // Force them to be deserialized so SemaCodeComplete sees them.
1298   loadMainFilePreambleMacros(Clang->getPreprocessor(), Input.Preamble);
1299   if (Includes)
1300     Includes->collect(*Clang);
1301   if (llvm::Error Err = Action.Execute()) {
1302     log("Execute() failed when running codeComplete for {0}: {1}",
1303         Input.FileName, toString(std::move(Err)));
1304     return false;
1305   }
1306   Action.EndSourceFile();
1307 
1308   return true;
1309 }
1310 
1311 // Should we allow index completions in the specified context?
1312 bool allowIndex(CodeCompletionContext &CC) {
1313   if (!contextAllowsIndex(CC.getKind()))
1314     return false;
1315   // We also avoid ClassName::bar (but allow namespace::bar).
1316   auto Scope = CC.getCXXScopeSpecifier();
1317   if (!Scope)
1318     return true;
1319   NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
1320   if (!NameSpec)
1321     return true;
1322   // We only query the index when qualifier is a namespace.
1323   // If it's a class, we rely solely on sema completions.
1324   switch (NameSpec->getKind()) {
1325   case NestedNameSpecifier::Global:
1326   case NestedNameSpecifier::Namespace:
1327   case NestedNameSpecifier::NamespaceAlias:
1328     return true;
1329   case NestedNameSpecifier::Super:
1330   case NestedNameSpecifier::TypeSpec:
1331   case NestedNameSpecifier::TypeSpecWithTemplate:
1332   // Unresolved inside a template.
1333   case NestedNameSpecifier::Identifier:
1334     return false;
1335   }
1336   llvm_unreachable("invalid NestedNameSpecifier kind");
1337 }
1338 
1339 std::future<SymbolSlab> startAsyncFuzzyFind(const SymbolIndex &Index,
1340                                             const FuzzyFindRequest &Req) {
1341   return runAsync<SymbolSlab>([&Index, Req]() {
1342     trace::Span Tracer("Async fuzzyFind");
1343     SymbolSlab::Builder Syms;
1344     Index.fuzzyFind(Req, [&Syms](const Symbol &Sym) { Syms.insert(Sym); });
1345     return std::move(Syms).build();
1346   });
1347 }
1348 
1349 // Creates a `FuzzyFindRequest` based on the cached index request from the
1350 // last completion, if any, and the speculated completion filter text in the
1351 // source code.
1352 FuzzyFindRequest speculativeFuzzyFindRequestForCompletion(
1353     FuzzyFindRequest CachedReq, const CompletionPrefix &HeuristicPrefix) {
1354   CachedReq.Query = std::string(HeuristicPrefix.Name);
1355   return CachedReq;
1356 }
1357 
1358 // Runs Sema-based (AST) and Index-based completion, returns merged results.
1359 //
1360 // There are a few tricky considerations:
1361 //   - the AST provides information needed for the index query (e.g. which
1362 //     namespaces to search in). So Sema must start first.
1363 //   - we only want to return the top results (Opts.Limit).
1364 //     Building CompletionItems for everything else is wasteful, so we want to
1365 //     preserve the "native" format until we're done with scoring.
1366 //   - the data underlying Sema completion items is owned by the AST and various
1367 //     other arenas, which must stay alive for us to build CompletionItems.
1368 //   - we may get duplicate results from Sema and the Index, we need to merge.
1369 //
1370 // So we start Sema completion first, and do all our work in its callback.
1371 // We use the Sema context information to query the index.
1372 // Then we merge the two result sets, producing items that are Sema/Index/Both.
1373 // These items are scored, and the top N are synthesized into the LSP response.
1374 // Finally, we can clean up the data structures created by Sema completion.
1375 //
1376 // Main collaborators are:
1377 //   - semaCodeComplete sets up the compiler machinery to run code completion.
1378 //   - CompletionRecorder captures Sema completion results, including context.
1379 //   - SymbolIndex (Opts.Index) provides index completion results as Symbols
1380 //   - CompletionCandidates are the result of merging Sema and Index results.
1381 //     Each candidate points to an underlying CodeCompletionResult (Sema), a
1382 //     Symbol (Index), or both. It computes the result quality score.
1383 //     CompletionCandidate also does conversion to CompletionItem (at the end).
1384 //   - FuzzyMatcher scores how the candidate matches the partial identifier.
1385 //     This score is combined with the result quality score for the final score.
1386 //   - TopN determines the results with the best score.
1387 class CodeCompleteFlow {
1388   PathRef FileName;
1389   IncludeStructure Includes;           // Complete once the compiler runs.
1390   SpeculativeFuzzyFind *SpecFuzzyFind; // Can be nullptr.
1391   const CodeCompleteOptions &Opts;
1392 
1393   // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
1394   CompletionRecorder *Recorder = nullptr;
1395   CodeCompletionContext::Kind CCContextKind = CodeCompletionContext::CCC_Other;
1396   bool IsUsingDeclaration = false;
1397   // The snippets will not be generated if the token following completion
1398   // location is an opening parenthesis (tok::l_paren) because this would add
1399   // extra parenthesis.
1400   tok::TokenKind NextTokenKind = tok::eof;
1401   // Counters for logging.
1402   int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
1403   bool Incomplete = false; // Would more be available with a higher limit?
1404   CompletionPrefix HeuristicPrefix;
1405   llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
1406   Range ReplacedRange;
1407   std::vector<std::string> QueryScopes; // Initialized once Sema runs.
1408   // Initialized once QueryScopes is initialized, if there are scopes.
1409   llvm::Optional<ScopeDistance> ScopeProximity;
1410   llvm::Optional<OpaqueType> PreferredType; // Initialized once Sema runs.
1411   // Whether to query symbols from any scope. Initialized once Sema runs.
1412   bool AllScopes = false;
1413   llvm::StringSet<> ContextWords;
1414   // Include-insertion and proximity scoring rely on the include structure.
1415   // This is available after Sema has run.
1416   llvm::Optional<IncludeInserter> Inserter;  // Available during runWithSema.
1417   llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
1418   /// Speculative request based on the cached request and the filter text before
1419   /// the cursor.
1420   /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
1421   /// set and contains a cached request.
1422   llvm::Optional<FuzzyFindRequest> SpecReq;
1423 
1424 public:
1425   // A CodeCompleteFlow object is only useful for calling run() exactly once.
1426   CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
1427                    SpeculativeFuzzyFind *SpecFuzzyFind,
1428                    const CodeCompleteOptions &Opts)
1429       : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1430         Opts(Opts) {}
1431 
1432   CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
1433     trace::Span Tracer("CodeCompleteFlow");
1434     HeuristicPrefix = guessCompletionPrefix(SemaCCInput.ParseInput.Contents,
1435                                             SemaCCInput.Offset);
1436     populateContextWords(SemaCCInput.ParseInput.Contents);
1437     if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq.hasValue()) {
1438       assert(!SpecFuzzyFind->Result.valid());
1439       SpecReq = speculativeFuzzyFindRequestForCompletion(
1440           *SpecFuzzyFind->CachedReq, HeuristicPrefix);
1441       SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1442     }
1443 
1444     // We run Sema code completion first. It builds an AST and calculates:
1445     //   - completion results based on the AST.
1446     //   - partial identifier and context. We need these for the index query.
1447     CodeCompleteResult Output;
1448     auto RecorderOwner = std::make_unique<CompletionRecorder>(Opts, [&]() {
1449       assert(Recorder && "Recorder is not set");
1450       CCContextKind = Recorder->CCContext.getKind();
1451       IsUsingDeclaration = Recorder->CCContext.isUsingDeclaration();
1452       auto Style = getFormatStyleForFile(SemaCCInput.FileName,
1453                                          SemaCCInput.ParseInput.Contents,
1454                                          *SemaCCInput.ParseInput.TFS);
1455       const auto NextToken = Lexer::findNextToken(
1456           Recorder->CCSema->getPreprocessor().getCodeCompletionLoc(),
1457           Recorder->CCSema->getSourceManager(), Recorder->CCSema->LangOpts);
1458       if (NextToken)
1459         NextTokenKind = NextToken->getKind();
1460       // If preprocessor was run, inclusions from preprocessor callback should
1461       // already be added to Includes.
1462       Inserter.emplace(
1463           SemaCCInput.FileName, SemaCCInput.ParseInput.Contents, Style,
1464           SemaCCInput.ParseInput.CompileCommand.Directory,
1465           &Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
1466       for (const auto &Inc : Includes.MainFileIncludes)
1467         Inserter->addExisting(Inc);
1468 
1469       // Most of the cost of file proximity is in initializing the FileDistance
1470       // structures based on the observed includes, once per query. Conceptually
1471       // that happens here (though the per-URI-scheme initialization is lazy).
1472       // The per-result proximity scoring is (amortized) very cheap.
1473       FileDistanceOptions ProxOpts{}; // Use defaults.
1474       const auto &SM = Recorder->CCSema->getSourceManager();
1475       llvm::StringMap<SourceParams> ProxSources;
1476       auto MainFileID =
1477           Includes.getID(SM.getFileEntryForID(SM.getMainFileID()));
1478       assert(MainFileID);
1479       for (auto &HeaderIDAndDepth : Includes.includeDepth(*MainFileID)) {
1480         auto &Source =
1481             ProxSources[Includes.getRealPath(HeaderIDAndDepth.getFirst())];
1482         Source.Cost = HeaderIDAndDepth.getSecond() * ProxOpts.IncludeCost;
1483         // Symbols near our transitive includes are good, but only consider
1484         // things in the same directory or below it. Otherwise there can be
1485         // many false positives.
1486         if (HeaderIDAndDepth.getSecond() > 0)
1487           Source.MaxUpTraversals = 1;
1488       }
1489       FileProximity.emplace(ProxSources, ProxOpts);
1490 
1491       Output = runWithSema();
1492       Inserter.reset(); // Make sure this doesn't out-live Clang.
1493       SPAN_ATTACH(Tracer, "sema_completion_kind",
1494                   getCompletionKindString(CCContextKind));
1495       log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1496           "expected type {3}{4}",
1497           getCompletionKindString(CCContextKind),
1498           llvm::join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
1499           PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1500                         : "<none>",
1501           IsUsingDeclaration ? ", inside using declaration" : "");
1502     });
1503 
1504     Recorder = RecorderOwner.get();
1505 
1506     semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1507                      SemaCCInput, &Includes);
1508     logResults(Output, Tracer);
1509     return Output;
1510   }
1511 
1512   void logResults(const CodeCompleteResult &Output, const trace::Span &Tracer) {
1513     SPAN_ATTACH(Tracer, "sema_results", NSema);
1514     SPAN_ATTACH(Tracer, "index_results", NIndex);
1515     SPAN_ATTACH(Tracer, "merged_results", NSemaAndIndex);
1516     SPAN_ATTACH(Tracer, "identifier_results", NIdent);
1517     SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
1518     SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
1519     log("Code complete: {0} results from Sema, {1} from Index, "
1520         "{2} matched, {3} from identifiers, {4} returned{5}.",
1521         NSema, NIndex, NSemaAndIndex, NIdent, Output.Completions.size(),
1522         Output.HasMore ? " (incomplete)" : "");
1523     assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1524     // We don't assert that isIncomplete means we hit a limit.
1525     // Indexes may choose to impose their own limits even if we don't have one.
1526   }
1527 
1528   CodeCompleteResult runWithoutSema(llvm::StringRef Content, size_t Offset,
1529                                     const ThreadsafeFS &TFS) && {
1530     trace::Span Tracer("CodeCompleteWithoutSema");
1531     // Fill in fields normally set by runWithSema()
1532     HeuristicPrefix = guessCompletionPrefix(Content, Offset);
1533     populateContextWords(Content);
1534     CCContextKind = CodeCompletionContext::CCC_Recovery;
1535     IsUsingDeclaration = false;
1536     Filter = FuzzyMatcher(HeuristicPrefix.Name);
1537     auto Pos = offsetToPosition(Content, Offset);
1538     ReplacedRange.start = ReplacedRange.end = Pos;
1539     ReplacedRange.start.character -= HeuristicPrefix.Name.size();
1540 
1541     llvm::StringMap<SourceParams> ProxSources;
1542     ProxSources[FileName].Cost = 0;
1543     FileProximity.emplace(ProxSources);
1544 
1545     auto Style = getFormatStyleForFile(FileName, Content, TFS);
1546     // This will only insert verbatim headers.
1547     Inserter.emplace(FileName, Content, Style,
1548                      /*BuildDir=*/"", /*HeaderSearchInfo=*/nullptr);
1549 
1550     auto Identifiers = collectIdentifiers(Content, Style);
1551     std::vector<RawIdentifier> IdentifierResults;
1552     for (const auto &IDAndCount : Identifiers) {
1553       RawIdentifier ID;
1554       ID.Name = IDAndCount.first();
1555       ID.References = IDAndCount.second;
1556       // Avoid treating typed filter as an identifier.
1557       if (ID.Name == HeuristicPrefix.Name)
1558         --ID.References;
1559       if (ID.References > 0)
1560         IdentifierResults.push_back(std::move(ID));
1561     }
1562 
1563     // Simplified version of getQueryScopes():
1564     //  - accessible scopes are determined heuristically.
1565     //  - all-scopes query if no qualifier was typed (and it's allowed).
1566     SpecifiedScope Scopes;
1567     Scopes.AccessibleScopes = visibleNamespaces(
1568         Content.take_front(Offset), format::getFormattingLangOpts(Style));
1569     for (std::string &S : Scopes.AccessibleScopes)
1570       if (!S.empty())
1571         S.append("::"); // visibleNamespaces doesn't include trailing ::.
1572     if (HeuristicPrefix.Qualifier.empty())
1573       AllScopes = Opts.AllScopes;
1574     else if (HeuristicPrefix.Qualifier.startswith("::")) {
1575       Scopes.AccessibleScopes = {""};
1576       Scopes.UnresolvedQualifier =
1577           std::string(HeuristicPrefix.Qualifier.drop_front(2));
1578     } else
1579       Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier);
1580     // First scope is the (modified) enclosing scope.
1581     QueryScopes = Scopes.scopesForIndexQuery();
1582     ScopeProximity.emplace(QueryScopes);
1583 
1584     SymbolSlab IndexResults = Opts.Index ? queryIndex() : SymbolSlab();
1585 
1586     CodeCompleteResult Output = toCodeCompleteResult(mergeResults(
1587         /*SemaResults=*/{}, IndexResults, IdentifierResults));
1588     Output.RanParser = false;
1589     logResults(Output, Tracer);
1590     return Output;
1591   }
1592 
1593 private:
1594   void populateContextWords(llvm::StringRef Content) {
1595     // Take last 3 lines before the completion point.
1596     unsigned RangeEnd = HeuristicPrefix.Qualifier.begin() - Content.data(),
1597              RangeBegin = RangeEnd;
1598     for (size_t I = 0; I < 3 && RangeBegin > 0; ++I) {
1599       auto PrevNL = Content.rfind('\n', RangeBegin);
1600       if (PrevNL == StringRef::npos) {
1601         RangeBegin = 0;
1602         break;
1603       }
1604       RangeBegin = PrevNL;
1605     }
1606 
1607     ContextWords = collectWords(Content.slice(RangeBegin, RangeEnd));
1608     dlog("Completion context words: {0}",
1609          llvm::join(ContextWords.keys(), ", "));
1610   }
1611 
1612   // This is called by run() once Sema code completion is done, but before the
1613   // Sema data structures are torn down. It does all the real work.
1614   CodeCompleteResult runWithSema() {
1615     const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1616         Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1617     // When we are getting completions with an empty identifier, for example
1618     //    std::vector<int> asdf;
1619     //    asdf.^;
1620     // Then the range will be invalid and we will be doing insertion, use
1621     // current cursor position in such cases as range.
1622     if (CodeCompletionRange.isValid()) {
1623       ReplacedRange = halfOpenToRange(Recorder->CCSema->getSourceManager(),
1624                                       CodeCompletionRange);
1625     } else {
1626       const auto &Pos = sourceLocToPosition(
1627           Recorder->CCSema->getSourceManager(),
1628           Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1629       ReplacedRange.start = ReplacedRange.end = Pos;
1630     }
1631     Filter = FuzzyMatcher(
1632         Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1633     std::tie(QueryScopes, AllScopes) = getQueryScopes(
1634         Recorder->CCContext, *Recorder->CCSema, HeuristicPrefix, Opts);
1635     if (!QueryScopes.empty())
1636       ScopeProximity.emplace(QueryScopes);
1637     PreferredType =
1638         OpaqueType::fromType(Recorder->CCSema->getASTContext(),
1639                              Recorder->CCContext.getPreferredType());
1640     // Sema provides the needed context to query the index.
1641     // FIXME: in addition to querying for extra/overlapping symbols, we should
1642     //        explicitly request symbols corresponding to Sema results.
1643     //        We can use their signals even if the index can't suggest them.
1644     // We must copy index results to preserve them, but there are at most Limit.
1645     auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1646                             ? queryIndex()
1647                             : SymbolSlab();
1648     trace::Span Tracer("Populate CodeCompleteResult");
1649     // Merge Sema and Index results, score them, and pick the winners.
1650     auto Top =
1651         mergeResults(Recorder->Results, IndexResults, /*Identifiers*/ {});
1652     return toCodeCompleteResult(Top);
1653   }
1654 
1655   CodeCompleteResult
1656   toCodeCompleteResult(const std::vector<ScoredBundle> &Scored) {
1657     CodeCompleteResult Output;
1658 
1659     // Convert the results to final form, assembling the expensive strings.
1660     for (auto &C : Scored) {
1661       Output.Completions.push_back(toCodeCompletion(C.first));
1662       Output.Completions.back().Score = C.second;
1663       Output.Completions.back().CompletionTokenRange = ReplacedRange;
1664     }
1665     Output.HasMore = Incomplete;
1666     Output.Context = CCContextKind;
1667     Output.CompletionRange = ReplacedRange;
1668     return Output;
1669   }
1670 
1671   SymbolSlab queryIndex() {
1672     trace::Span Tracer("Query index");
1673     SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
1674 
1675     // Build the query.
1676     FuzzyFindRequest Req;
1677     if (Opts.Limit)
1678       Req.Limit = Opts.Limit;
1679     Req.Query = std::string(Filter->pattern());
1680     Req.RestrictForCodeCompletion = true;
1681     Req.Scopes = QueryScopes;
1682     Req.AnyScope = AllScopes;
1683     // FIXME: we should send multiple weighted paths here.
1684     Req.ProximityPaths.push_back(std::string(FileName));
1685     if (PreferredType)
1686       Req.PreferredTypes.push_back(std::string(PreferredType->raw()));
1687     vlog("Code complete: fuzzyFind({0:2})", toJSON(Req));
1688 
1689     if (SpecFuzzyFind)
1690       SpecFuzzyFind->NewReq = Req;
1691     if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1692       vlog("Code complete: speculative fuzzy request matches the actual index "
1693            "request. Waiting for the speculative index results.");
1694       SPAN_ATTACH(Tracer, "Speculative results", true);
1695 
1696       trace::Span WaitSpec("Wait speculative results");
1697       return SpecFuzzyFind->Result.get();
1698     }
1699 
1700     SPAN_ATTACH(Tracer, "Speculative results", false);
1701 
1702     // Run the query against the index.
1703     SymbolSlab::Builder ResultsBuilder;
1704     if (Opts.Index->fuzzyFind(
1705             Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1706       Incomplete = true;
1707     return std::move(ResultsBuilder).build();
1708   }
1709 
1710   // Merges Sema and Index results where possible, to form CompletionCandidates.
1711   // \p Identifiers is raw identifiers that can also be completion candidates.
1712   // Identifiers are not merged with results from index or sema.
1713   // Groups overloads if desired, to form CompletionCandidate::Bundles. The
1714   // bundles are scored and top results are returned, best to worst.
1715   std::vector<ScoredBundle>
1716   mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1717                const SymbolSlab &IndexResults,
1718                const std::vector<RawIdentifier> &IdentifierResults) {
1719     trace::Span Tracer("Merge and score results");
1720     std::vector<CompletionCandidate::Bundle> Bundles;
1721     llvm::DenseMap<size_t, size_t> BundleLookup;
1722     auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
1723                             const Symbol *IndexResult,
1724                             const RawIdentifier *IdentifierResult) {
1725       CompletionCandidate C;
1726       C.SemaResult = SemaResult;
1727       C.IndexResult = IndexResult;
1728       C.IdentifierResult = IdentifierResult;
1729       if (C.IndexResult) {
1730         C.Name = IndexResult->Name;
1731         C.RankedIncludeHeaders = getRankedIncludes(*C.IndexResult);
1732       } else if (C.SemaResult) {
1733         C.Name = Recorder->getName(*SemaResult);
1734       } else {
1735         assert(IdentifierResult);
1736         C.Name = IdentifierResult->Name;
1737       }
1738       if (auto OverloadSet = C.overloadSet(
1739               Opts, FileName, Inserter ? Inserter.getPointer() : nullptr)) {
1740         auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1741         if (Ret.second)
1742           Bundles.emplace_back();
1743         Bundles[Ret.first->second].push_back(std::move(C));
1744       } else {
1745         Bundles.emplace_back();
1746         Bundles.back().push_back(std::move(C));
1747       }
1748     };
1749     llvm::DenseSet<const Symbol *> UsedIndexResults;
1750     auto CorrespondingIndexResult =
1751         [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
1752       if (auto SymID =
1753               getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
1754         auto I = IndexResults.find(SymID);
1755         if (I != IndexResults.end()) {
1756           UsedIndexResults.insert(&*I);
1757           return &*I;
1758         }
1759       }
1760       return nullptr;
1761     };
1762     // Emit all Sema results, merging them with Index results if possible.
1763     for (auto &SemaResult : SemaResults)
1764       AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult), nullptr);
1765     // Now emit any Index-only results.
1766     for (const auto &IndexResult : IndexResults) {
1767       if (UsedIndexResults.count(&IndexResult))
1768         continue;
1769       AddToBundles(/*SemaResult=*/nullptr, &IndexResult, nullptr);
1770     }
1771     // Emit identifier results.
1772     for (const auto &Ident : IdentifierResults)
1773       AddToBundles(/*SemaResult=*/nullptr, /*IndexResult=*/nullptr, &Ident);
1774     // We only keep the best N results at any time, in "native" format.
1775     TopN<ScoredBundle, ScoredBundleGreater> Top(
1776         Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1777     for (auto &Bundle : Bundles)
1778       addCandidate(Top, std::move(Bundle));
1779     return std::move(Top).items();
1780   }
1781 
1782   llvm::Optional<float> fuzzyScore(const CompletionCandidate &C) {
1783     // Macros can be very spammy, so we only support prefix completion.
1784     if (((C.SemaResult &&
1785           C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
1786          (C.IndexResult &&
1787           C.IndexResult->SymInfo.Kind == index::SymbolKind::Macro)) &&
1788         !C.Name.startswith_insensitive(Filter->pattern()))
1789       return None;
1790     return Filter->match(C.Name);
1791   }
1792 
1793   CodeCompletion::Scores
1794   evaluateCompletion(const SymbolQualitySignals &Quality,
1795                      const SymbolRelevanceSignals &Relevance) {
1796     using RM = CodeCompleteOptions::CodeCompletionRankingModel;
1797     CodeCompletion::Scores Scores;
1798     switch (Opts.RankingModel) {
1799     case RM::Heuristics:
1800       Scores.Quality = Quality.evaluateHeuristics();
1801       Scores.Relevance = Relevance.evaluateHeuristics();
1802       Scores.Total =
1803           evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1804       // NameMatch is in fact a multiplier on total score, so rescoring is
1805       // sound.
1806       Scores.ExcludingName =
1807           Relevance.NameMatch > std::numeric_limits<float>::epsilon()
1808               ? Scores.Total / Relevance.NameMatch
1809               : Scores.Quality;
1810       return Scores;
1811 
1812     case RM::DecisionForest:
1813       DecisionForestScores DFScores = Opts.DecisionForestScorer(
1814           Quality, Relevance, Opts.DecisionForestBase);
1815       Scores.ExcludingName = DFScores.ExcludingName;
1816       Scores.Total = DFScores.Total;
1817       return Scores;
1818     }
1819     llvm_unreachable("Unhandled CodeCompletion ranking model.");
1820   }
1821 
1822   // Scores a candidate and adds it to the TopN structure.
1823   void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1824                     CompletionCandidate::Bundle Bundle) {
1825     SymbolQualitySignals Quality;
1826     SymbolRelevanceSignals Relevance;
1827     Relevance.Context = CCContextKind;
1828     Relevance.Name = Bundle.front().Name;
1829     Relevance.FilterLength = HeuristicPrefix.Name.size();
1830     Relevance.Query = SymbolRelevanceSignals::CodeComplete;
1831     Relevance.FileProximityMatch = FileProximity.getPointer();
1832     if (ScopeProximity)
1833       Relevance.ScopeProximityMatch = ScopeProximity.getPointer();
1834     if (PreferredType)
1835       Relevance.HadContextType = true;
1836     Relevance.ContextWords = &ContextWords;
1837     Relevance.MainFileSignals = Opts.MainFileSignals;
1838 
1839     auto &First = Bundle.front();
1840     if (auto FuzzyScore = fuzzyScore(First))
1841       Relevance.NameMatch = *FuzzyScore;
1842     else
1843       return;
1844     SymbolOrigin Origin = SymbolOrigin::Unknown;
1845     bool FromIndex = false;
1846     for (const auto &Candidate : Bundle) {
1847       if (Candidate.IndexResult) {
1848         Quality.merge(*Candidate.IndexResult);
1849         Relevance.merge(*Candidate.IndexResult);
1850         Origin |= Candidate.IndexResult->Origin;
1851         FromIndex = true;
1852         if (!Candidate.IndexResult->Type.empty())
1853           Relevance.HadSymbolType |= true;
1854         if (PreferredType &&
1855             PreferredType->raw() == Candidate.IndexResult->Type) {
1856           Relevance.TypeMatchesPreferred = true;
1857         }
1858       }
1859       if (Candidate.SemaResult) {
1860         Quality.merge(*Candidate.SemaResult);
1861         Relevance.merge(*Candidate.SemaResult);
1862         if (PreferredType) {
1863           if (auto CompletionType = OpaqueType::fromCompletionResult(
1864                   Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
1865             Relevance.HadSymbolType |= true;
1866             if (PreferredType == CompletionType)
1867               Relevance.TypeMatchesPreferred = true;
1868           }
1869         }
1870         Origin |= SymbolOrigin::AST;
1871       }
1872       if (Candidate.IdentifierResult) {
1873         Quality.References = Candidate.IdentifierResult->References;
1874         Relevance.Scope = SymbolRelevanceSignals::FileScope;
1875         Origin |= SymbolOrigin::Identifier;
1876       }
1877     }
1878 
1879     CodeCompletion::Scores Scores = evaluateCompletion(Quality, Relevance);
1880     if (Opts.RecordCCResult)
1881       Opts.RecordCCResult(toCodeCompletion(Bundle), Quality, Relevance,
1882                           Scores.Total);
1883 
1884     dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
1885          llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
1886          llvm::to_string(Relevance));
1887 
1888     NSema += bool(Origin & SymbolOrigin::AST);
1889     NIndex += FromIndex;
1890     NSemaAndIndex += bool(Origin & SymbolOrigin::AST) && FromIndex;
1891     NIdent += bool(Origin & SymbolOrigin::Identifier);
1892     if (Candidates.push({std::move(Bundle), Scores}))
1893       Incomplete = true;
1894   }
1895 
1896   CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
1897     llvm::Optional<CodeCompletionBuilder> Builder;
1898     for (const auto &Item : Bundle) {
1899       CodeCompletionString *SemaCCS =
1900           Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1901                           : nullptr;
1902       if (!Builder)
1903         Builder.emplace(Recorder ? &Recorder->CCSema->getASTContext() : nullptr,
1904                         Item, SemaCCS, QueryScopes, *Inserter, FileName,
1905                         CCContextKind, Opts, IsUsingDeclaration, NextTokenKind);
1906       else
1907         Builder->add(Item, SemaCCS);
1908     }
1909     return Builder->build();
1910   }
1911 };
1912 
1913 } // namespace
1914 
1915 clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
1916   clang::CodeCompleteOptions Result;
1917   Result.IncludeCodePatterns = EnableSnippets;
1918   Result.IncludeMacros = true;
1919   Result.IncludeGlobals = true;
1920   // We choose to include full comments and not do doxygen parsing in
1921   // completion.
1922   // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
1923   // formatting of the comments.
1924   Result.IncludeBriefComments = false;
1925 
1926   // When an is used, Sema is responsible for completing the main file,
1927   // the index can provide results from the preamble.
1928   // Tell Sema not to deserialize the preamble to look for results.
1929   Result.LoadExternal = !Index;
1930   Result.IncludeFixIts = IncludeFixIts;
1931 
1932   return Result;
1933 }
1934 
1935 CompletionPrefix guessCompletionPrefix(llvm::StringRef Content,
1936                                        unsigned Offset) {
1937   assert(Offset <= Content.size());
1938   StringRef Rest = Content.take_front(Offset);
1939   CompletionPrefix Result;
1940 
1941   // Consume the unqualified name. We only handle ASCII characters.
1942   // isAsciiIdentifierContinue will let us match "0invalid", but we don't mind.
1943   while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
1944     Rest = Rest.drop_back();
1945   Result.Name = Content.slice(Rest.size(), Offset);
1946 
1947   // Consume qualifiers.
1948   while (Rest.consume_back("::") && !Rest.endswith(":")) // reject ::::
1949     while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
1950       Rest = Rest.drop_back();
1951   Result.Qualifier =
1952       Content.slice(Rest.size(), Result.Name.begin() - Content.begin());
1953 
1954   return Result;
1955 }
1956 
1957 // Code complete the argument name on "/*" inside function call.
1958 // Offset should be pointing to the start of the comment, i.e.:
1959 // foo(^/*, rather than foo(/*^) where the cursor probably is.
1960 CodeCompleteResult codeCompleteComment(PathRef FileName, unsigned Offset,
1961                                        llvm::StringRef Prefix,
1962                                        const PreambleData *Preamble,
1963                                        const ParseInputs &ParseInput) {
1964   if (Preamble == nullptr) // Can't run without Sema.
1965     return CodeCompleteResult();
1966 
1967   clang::CodeCompleteOptions Options;
1968   Options.IncludeGlobals = false;
1969   Options.IncludeMacros = false;
1970   Options.IncludeCodePatterns = false;
1971   Options.IncludeBriefComments = false;
1972   std::set<std::string> ParamNames;
1973   // We want to see signatures coming from newly introduced includes, hence a
1974   // full patch.
1975   semaCodeComplete(
1976       std::make_unique<ParamNameCollector>(Options, ParamNames), Options,
1977       {FileName, Offset, *Preamble,
1978        PreamblePatch::createFullPatch(FileName, ParseInput, *Preamble),
1979        ParseInput});
1980   if (ParamNames.empty())
1981     return CodeCompleteResult();
1982 
1983   CodeCompleteResult Result;
1984   Result.Context = CodeCompletionContext::CCC_NaturalLanguage;
1985   for (llvm::StringRef Name : ParamNames) {
1986     if (!Name.startswith(Prefix))
1987       continue;
1988     CodeCompletion Item;
1989     Item.Name = Name.str() + "=";
1990     Item.Kind = CompletionItemKind::Text;
1991     Result.Completions.push_back(Item);
1992   }
1993 
1994   return Result;
1995 }
1996 
1997 // If Offset is inside what looks like argument comment (e.g.
1998 // "/*^" or "/* foo^"), returns new offset pointing to the start of the /*
1999 // (place where semaCodeComplete should run).
2000 llvm::Optional<unsigned>
2001 maybeFunctionArgumentCommentStart(llvm::StringRef Content) {
2002   while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
2003     Content = Content.drop_back();
2004   Content = Content.rtrim();
2005   if (Content.endswith("/*"))
2006     return Content.size() - 2;
2007   return None;
2008 }
2009 
2010 CodeCompleteResult codeComplete(PathRef FileName, Position Pos,
2011                                 const PreambleData *Preamble,
2012                                 const ParseInputs &ParseInput,
2013                                 CodeCompleteOptions Opts,
2014                                 SpeculativeFuzzyFind *SpecFuzzyFind) {
2015   auto Offset = positionToOffset(ParseInput.Contents, Pos);
2016   if (!Offset) {
2017     elog("Code completion position was invalid {0}", Offset.takeError());
2018     return CodeCompleteResult();
2019   }
2020 
2021   auto Content = llvm::StringRef(ParseInput.Contents).take_front(*Offset);
2022   if (auto OffsetBeforeComment = maybeFunctionArgumentCommentStart(Content)) {
2023     // We are doing code completion of a comment, where we currently only
2024     // support completing param names in function calls. To do this, we
2025     // require information from Sema, but Sema's comment completion stops at
2026     // parsing, so we must move back the position before running it, extract
2027     // information we need and construct completion items ourselves.
2028     auto CommentPrefix = Content.substr(*OffsetBeforeComment + 2).trim();
2029     return codeCompleteComment(FileName, *OffsetBeforeComment, CommentPrefix,
2030                                Preamble, ParseInput);
2031   }
2032 
2033   auto Flow = CodeCompleteFlow(
2034       FileName, Preamble ? Preamble->Includes : IncludeStructure(),
2035       SpecFuzzyFind, Opts);
2036   return (!Preamble || Opts.RunParser == CodeCompleteOptions::NeverParse)
2037              ? std::move(Flow).runWithoutSema(ParseInput.Contents, *Offset,
2038                                               *ParseInput.TFS)
2039              : std::move(Flow).run({FileName, *Offset, *Preamble,
2040                                     /*PreamblePatch=*/
2041                                     PreamblePatch::createMacroPatch(
2042                                         FileName, ParseInput, *Preamble),
2043                                     ParseInput});
2044 }
2045 
2046 SignatureHelp signatureHelp(PathRef FileName, Position Pos,
2047                             const PreambleData &Preamble,
2048                             const ParseInputs &ParseInput,
2049                             MarkupKind DocumentationFormat) {
2050   auto Offset = positionToOffset(ParseInput.Contents, Pos);
2051   if (!Offset) {
2052     elog("Signature help position was invalid {0}", Offset.takeError());
2053     return SignatureHelp();
2054   }
2055   SignatureHelp Result;
2056   clang::CodeCompleteOptions Options;
2057   Options.IncludeGlobals = false;
2058   Options.IncludeMacros = false;
2059   Options.IncludeCodePatterns = false;
2060   Options.IncludeBriefComments = false;
2061   semaCodeComplete(
2062       std::make_unique<SignatureHelpCollector>(Options, DocumentationFormat,
2063                                                ParseInput.Index, Result),
2064       Options,
2065       {FileName, *Offset, Preamble,
2066        PreamblePatch::createFullPatch(FileName, ParseInput, Preamble),
2067        ParseInput});
2068   return Result;
2069 }
2070 
2071 bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
2072   auto InTopLevelScope = [](const NamedDecl &ND) {
2073     switch (ND.getDeclContext()->getDeclKind()) {
2074     case Decl::TranslationUnit:
2075     case Decl::Namespace:
2076     case Decl::LinkageSpec:
2077       return true;
2078     default:
2079       break;
2080     };
2081     return false;
2082   };
2083   // We only complete symbol's name, which is the same as the name of the
2084   // *primary* template in case of template specializations.
2085   if (isExplicitTemplateSpecialization(&ND))
2086     return false;
2087 
2088   // Category decls are not useful on their own outside the interface or
2089   // implementation blocks. Moreover, sema already provides completion for
2090   // these, even if it requires preamble deserialization. So by excluding them
2091   // from the index, we reduce the noise in all the other completion scopes.
2092   if (llvm::isa<ObjCCategoryDecl>(&ND) || llvm::isa<ObjCCategoryImplDecl>(&ND))
2093     return false;
2094 
2095   if (InTopLevelScope(ND))
2096     return true;
2097 
2098   if (const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
2099     return InTopLevelScope(*EnumDecl) && !EnumDecl->isScoped();
2100 
2101   return false;
2102 }
2103 
2104 CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
2105   CompletionItem LSP;
2106   const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
2107   LSP.label = ((InsertInclude && InsertInclude->Insertion)
2108                    ? Opts.IncludeIndicator.Insert
2109                    : Opts.IncludeIndicator.NoInsert) +
2110               (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
2111               RequiredQualifier + Name + Signature;
2112 
2113   LSP.kind = Kind;
2114   LSP.detail = BundleSize > 1
2115                    ? std::string(llvm::formatv("[{0} overloads]", BundleSize))
2116                    : ReturnType;
2117   LSP.deprecated = Deprecated;
2118   // Combine header information and documentation in LSP `documentation` field.
2119   // This is not quite right semantically, but tends to display well in editors.
2120   if (InsertInclude || Documentation) {
2121     markup::Document Doc;
2122     if (InsertInclude)
2123       Doc.addParagraph().appendText("From ").appendCode(InsertInclude->Header);
2124     if (Documentation)
2125       Doc.append(*Documentation);
2126     LSP.documentation = renderDoc(Doc, Opts.DocumentationFormat);
2127   }
2128   LSP.sortText = sortText(Score.Total, Name);
2129   LSP.filterText = Name;
2130   LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name};
2131   // Merge continuous additionalTextEdits into main edit. The main motivation
2132   // behind this is to help LSP clients, it seems most of them are confused when
2133   // they are provided with additionalTextEdits that are consecutive to main
2134   // edit.
2135   // Note that we store additional text edits from back to front in a line. That
2136   // is mainly to help LSP clients again, so that changes do not effect each
2137   // other.
2138   for (const auto &FixIt : FixIts) {
2139     if (FixIt.range.end == LSP.textEdit->range.start) {
2140       LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
2141       LSP.textEdit->range.start = FixIt.range.start;
2142     } else {
2143       LSP.additionalTextEdits.push_back(FixIt);
2144     }
2145   }
2146   if (Opts.EnableSnippets)
2147     LSP.textEdit->newText += SnippetSuffix;
2148 
2149   // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
2150   // compatible with most of the editors.
2151   LSP.insertText = LSP.textEdit->newText;
2152   // Some clients support snippets but work better with plaintext.
2153   // So if the snippet is trivial, let the client know.
2154   // https://github.com/clangd/clangd/issues/922
2155   LSP.insertTextFormat = (Opts.EnableSnippets && !SnippetSuffix.empty())
2156                              ? InsertTextFormat::Snippet
2157                              : InsertTextFormat::PlainText;
2158   if (InsertInclude && InsertInclude->Insertion)
2159     LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
2160 
2161   LSP.score = Score.ExcludingName;
2162 
2163   return LSP;
2164 }
2165 
2166 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CodeCompletion &C) {
2167   // For now just lean on CompletionItem.
2168   return OS << C.render(CodeCompleteOptions());
2169 }
2170 
2171 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
2172                               const CodeCompleteResult &R) {
2173   OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
2174      << " (" << getCompletionKindString(R.Context) << ")"
2175      << " items:\n";
2176   for (const auto &C : R.Completions)
2177     OS << C << "\n";
2178   return OS;
2179 }
2180 
2181 // Heuristically detect whether the `Line` is an unterminated include filename.
2182 bool isIncludeFile(llvm::StringRef Line) {
2183   Line = Line.ltrim();
2184   if (!Line.consume_front("#"))
2185     return false;
2186   Line = Line.ltrim();
2187   if (!(Line.consume_front("include_next") || Line.consume_front("include") ||
2188         Line.consume_front("import")))
2189     return false;
2190   Line = Line.ltrim();
2191   if (Line.consume_front("<"))
2192     return Line.count('>') == 0;
2193   if (Line.consume_front("\""))
2194     return Line.count('"') == 0;
2195   return false;
2196 }
2197 
2198 bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset) {
2199   // Look at last line before completion point only.
2200   Content = Content.take_front(Offset);
2201   auto Pos = Content.rfind('\n');
2202   if (Pos != llvm::StringRef::npos)
2203     Content = Content.substr(Pos + 1);
2204 
2205   // Complete after scope operators.
2206   if (Content.endswith(".") || Content.endswith("->") ||
2207       Content.endswith("::") || Content.endswith("/*"))
2208     return true;
2209   // Complete after `#include <` and #include `<foo/`.
2210   if ((Content.endswith("<") || Content.endswith("\"") ||
2211        Content.endswith("/")) &&
2212       isIncludeFile(Content))
2213     return true;
2214 
2215   // Complete words. Give non-ascii characters the benefit of the doubt.
2216   return !Content.empty() && (isAsciiIdentifierContinue(Content.back()) ||
2217                               !llvm::isASCII(Content.back()));
2218 }
2219 
2220 } // namespace clangd
2221 } // namespace clang
2222