1 //===--- CodeComplete.cpp ---------------------------------------*- C++-*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===---------------------------------------------------------------------===//
9 //
10 // AST-based completions are provided using the completion hooks in Sema.
11 //
12 // Signature help works in a similar way as code completion, but it is simpler
13 // as there are typically fewer candidates.
14 //
15 //===---------------------------------------------------------------------===//
16 
17 #include "CodeComplete.h"
18 #include "CodeCompletionStrings.h"
19 #include "Compiler.h"
20 #include "FuzzyMatch.h"
21 #include "Logger.h"
22 #include "SourceCode.h"
23 #include "Trace.h"
24 #include "index/Index.h"
25 #include "clang/Format/Format.h"
26 #include "clang/Frontend/CompilerInstance.h"
27 #include "clang/Frontend/FrontendActions.h"
28 #include "clang/Index/USRGeneration.h"
29 #include "clang/Sema/CodeCompleteConsumer.h"
30 #include "clang/Sema/Sema.h"
31 #include "clang/Tooling/Core/Replacement.h"
32 #include "llvm/Support/Format.h"
33 #include <queue>
34 
35 namespace clang {
36 namespace clangd {
37 namespace {
38 
39 CompletionItemKind toCompletionItemKind(CXCursorKind CursorKind) {
40   switch (CursorKind) {
41   case CXCursor_MacroInstantiation:
42   case CXCursor_MacroDefinition:
43     return CompletionItemKind::Text;
44   case CXCursor_CXXMethod:
45   case CXCursor_Destructor:
46     return CompletionItemKind::Method;
47   case CXCursor_FunctionDecl:
48   case CXCursor_FunctionTemplate:
49     return CompletionItemKind::Function;
50   case CXCursor_Constructor:
51     return CompletionItemKind::Constructor;
52   case CXCursor_FieldDecl:
53     return CompletionItemKind::Field;
54   case CXCursor_VarDecl:
55   case CXCursor_ParmDecl:
56     return CompletionItemKind::Variable;
57   // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
58   // protocol.
59   case CXCursor_StructDecl:
60   case CXCursor_ClassDecl:
61   case CXCursor_UnionDecl:
62   case CXCursor_ClassTemplate:
63   case CXCursor_ClassTemplatePartialSpecialization:
64     return CompletionItemKind::Class;
65   case CXCursor_Namespace:
66   case CXCursor_NamespaceAlias:
67   case CXCursor_NamespaceRef:
68     return CompletionItemKind::Module;
69   case CXCursor_EnumConstantDecl:
70     return CompletionItemKind::Value;
71   case CXCursor_EnumDecl:
72     return CompletionItemKind::Enum;
73   // FIXME(ioeric): figure out whether reference is the right type for aliases.
74   case CXCursor_TypeAliasDecl:
75   case CXCursor_TypeAliasTemplateDecl:
76   case CXCursor_TypedefDecl:
77   case CXCursor_MemberRef:
78   case CXCursor_TypeRef:
79     return CompletionItemKind::Reference;
80   default:
81     return CompletionItemKind::Missing;
82   }
83 }
84 
85 CompletionItemKind
86 toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
87                      CXCursorKind CursorKind) {
88   switch (ResKind) {
89   case CodeCompletionResult::RK_Declaration:
90     return toCompletionItemKind(CursorKind);
91   case CodeCompletionResult::RK_Keyword:
92     return CompletionItemKind::Keyword;
93   case CodeCompletionResult::RK_Macro:
94     return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
95                                      // completion items in LSP.
96   case CodeCompletionResult::RK_Pattern:
97     return CompletionItemKind::Snippet;
98   }
99   llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
100 }
101 
102 CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
103   using SK = index::SymbolKind;
104   switch (Kind) {
105   case SK::Unknown:
106     return CompletionItemKind::Missing;
107   case SK::Module:
108   case SK::Namespace:
109   case SK::NamespaceAlias:
110     return CompletionItemKind::Module;
111   case SK::Macro:
112     return CompletionItemKind::Text;
113   case SK::Enum:
114     return CompletionItemKind::Enum;
115   // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
116   // protocol.
117   case SK::Struct:
118   case SK::Class:
119   case SK::Protocol:
120   case SK::Extension:
121   case SK::Union:
122     return CompletionItemKind::Class;
123   // FIXME(ioeric): figure out whether reference is the right type for aliases.
124   case SK::TypeAlias:
125   case SK::Using:
126     return CompletionItemKind::Reference;
127   case SK::Function:
128   // FIXME(ioeric): this should probably be an operator. This should be fixed
129   // when `Operator` is support type in the protocol.
130   case SK::ConversionFunction:
131     return CompletionItemKind::Function;
132   case SK::Variable:
133   case SK::Parameter:
134     return CompletionItemKind::Variable;
135   case SK::Field:
136     return CompletionItemKind::Field;
137   // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
138   case SK::EnumConstant:
139     return CompletionItemKind::Value;
140   case SK::InstanceMethod:
141   case SK::ClassMethod:
142   case SK::StaticMethod:
143   case SK::Destructor:
144     return CompletionItemKind::Method;
145   case SK::InstanceProperty:
146   case SK::ClassProperty:
147   case SK::StaticProperty:
148     return CompletionItemKind::Property;
149   case SK::Constructor:
150     return CompletionItemKind::Constructor;
151   }
152   llvm_unreachable("Unhandled clang::index::SymbolKind.");
153 }
154 
155 /// Get the optional chunk as a string. This function is possibly recursive.
156 ///
157 /// The parameter info for each parameter is appended to the Parameters.
158 std::string
159 getOptionalParameters(const CodeCompletionString &CCS,
160                       std::vector<ParameterInformation> &Parameters) {
161   std::string Result;
162   for (const auto &Chunk : CCS) {
163     switch (Chunk.Kind) {
164     case CodeCompletionString::CK_Optional:
165       assert(Chunk.Optional &&
166              "Expected the optional code completion string to be non-null.");
167       Result += getOptionalParameters(*Chunk.Optional, Parameters);
168       break;
169     case CodeCompletionString::CK_VerticalSpace:
170       break;
171     case CodeCompletionString::CK_Placeholder:
172       // A string that acts as a placeholder for, e.g., a function call
173       // argument.
174       // Intentional fallthrough here.
175     case CodeCompletionString::CK_CurrentParameter: {
176       // A piece of text that describes the parameter that corresponds to
177       // the code-completion location within a function call, message send,
178       // macro invocation, etc.
179       Result += Chunk.Text;
180       ParameterInformation Info;
181       Info.label = Chunk.Text;
182       Parameters.push_back(std::move(Info));
183       break;
184     }
185     default:
186       Result += Chunk.Text;
187       break;
188     }
189   }
190   return Result;
191 }
192 
193 // Produces an integer that sorts in the same order as F.
194 // That is: a < b <==> encodeFloat(a) < encodeFloat(b).
195 uint32_t encodeFloat(float F) {
196   static_assert(std::numeric_limits<float>::is_iec559, "");
197   static_assert(sizeof(float) == sizeof(uint32_t), "");
198   constexpr uint32_t TopBit = ~(~uint32_t{0} >> 1);
199 
200   // Get the bits of the float. Endianness is the same as for integers.
201   uint32_t U;
202   memcpy(&U, &F, sizeof(float));
203   // IEEE 754 floats compare like sign-magnitude integers.
204   if (U & TopBit)    // Negative float.
205     return 0 - U;    // Map onto the low half of integers, order reversed.
206   return U + TopBit; // Positive floats map onto the high half of integers.
207 }
208 
209 // Returns a string that sorts in the same order as (-Score, Name), for LSP.
210 std::string sortText(float Score, llvm::StringRef Name) {
211   // We convert -Score to an integer, and hex-encode for readability.
212   // Example: [0.5, "foo"] -> "41000000foo"
213   std::string S;
214   llvm::raw_string_ostream OS(S);
215   write_hex(OS, encodeFloat(-Score), llvm::HexPrintStyle::Lower,
216             /*Width=*/2 * sizeof(Score));
217   OS << Name;
218   OS.flush();
219   return S;
220 }
221 
222 /// A code completion result, in clang-native form.
223 /// It may be promoted to a CompletionItem if it's among the top-ranked results.
224 struct CompletionCandidate {
225   llvm::StringRef Name; // Used for filtering and sorting.
226   // We may have a result from Sema, from the index, or both.
227   const CodeCompletionResult *SemaResult = nullptr;
228   const Symbol *IndexResult = nullptr;
229 
230   // Computes the "symbol quality" score for this completion. Higher is better.
231   float score() const {
232     float Score = 1;
233     if (IndexResult)
234       Score *= quality(*IndexResult);
235     if (SemaResult) {
236       // For now we just use the Sema priority, mapping it onto a 0-2 interval.
237       // That makes 1 neutral-ish, so we don't reward/penalize non-Sema results.
238       // Priority 80 is a really bad score.
239       Score *= 2 - std::min<float>(80, SemaResult->Priority) / 40;
240 
241       switch (static_cast<CXAvailabilityKind>(SemaResult->Availability)) {
242       case CXAvailability_Available:
243         // No penalty.
244         break;
245       case CXAvailability_Deprecated:
246         Score *= 0.1f;
247         break;
248       case CXAvailability_NotAccessible:
249       case CXAvailability_NotAvailable:
250         Score = 0;
251         break;
252       }
253     }
254     return Score;
255   }
256 
257   // Builds an LSP completion item.
258   CompletionItem build(llvm::StringRef FileName,
259                        const CompletionItemScores &Scores,
260                        const CodeCompleteOptions &Opts,
261                        CodeCompletionString *SemaCCS) const {
262     assert(bool(SemaResult) == bool(SemaCCS));
263     CompletionItem I;
264     if (SemaResult) {
265       I.kind = toCompletionItemKind(SemaResult->Kind, SemaResult->CursorKind);
266       getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText,
267                             Opts.EnableSnippets);
268       I.filterText = getFilterText(*SemaCCS);
269       I.documentation = getDocumentation(*SemaCCS);
270       I.detail = getDetail(*SemaCCS);
271     }
272     if (IndexResult) {
273       if (I.kind == CompletionItemKind::Missing)
274         I.kind = toCompletionItemKind(IndexResult->SymInfo.Kind);
275       // FIXME: reintroduce a way to show the index source for debugging.
276       if (I.label.empty())
277         I.label = IndexResult->CompletionLabel;
278       if (I.filterText.empty())
279         I.filterText = IndexResult->Name;
280 
281       // FIXME(ioeric): support inserting/replacing scope qualifiers.
282       if (I.insertText.empty())
283         I.insertText = Opts.EnableSnippets
284                            ? IndexResult->CompletionSnippetInsertText
285                            : IndexResult->CompletionPlainInsertText;
286 
287       if (auto *D = IndexResult->Detail) {
288         if (I.documentation.empty())
289           I.documentation = D->Documentation;
290         if (I.detail.empty())
291           I.detail = D->CompletionDetail;
292         // FIXME: delay creating include insertion command to
293         // "completionItem/resolve", when it is supported
294         if (!D->IncludeHeader.empty()) {
295           // LSP favors additionalTextEdits over command. But we are still using
296           // command here because it would be expensive to calculate #include
297           // insertion edits for all candidates, and the include insertion edit
298           // is unlikely to conflict with the code completion edits.
299           Command Cmd;
300           // Command title is not added since this is not a user-facing command.
301           Cmd.command = ExecuteCommandParams::CLANGD_INSERT_HEADER_INCLUDE;
302           IncludeInsertion Insertion;
303           // Fallback to canonical header if declaration location is invalid.
304           Insertion.declaringHeader =
305               IndexResult->CanonicalDeclaration.FileURI.empty()
306                   ? D->IncludeHeader
307                   : IndexResult->CanonicalDeclaration.FileURI;
308           Insertion.preferredHeader = D->IncludeHeader;
309           Insertion.textDocument.uri = URIForFile(FileName);
310           Cmd.includeInsertion = std::move(Insertion);
311           I.command = std::move(Cmd);
312         }
313       }
314     }
315     I.scoreInfo = Scores;
316     I.sortText = sortText(Scores.finalScore, Name);
317     I.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
318                                              : InsertTextFormat::PlainText;
319     return I;
320   }
321 };
322 
323 // Determine the symbol ID for a Sema code completion result, if possible.
324 llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
325   switch (R.Kind) {
326   case CodeCompletionResult::RK_Declaration:
327   case CodeCompletionResult::RK_Pattern: {
328     llvm::SmallString<128> USR;
329     if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
330       return None;
331     return SymbolID(USR);
332   }
333   case CodeCompletionResult::RK_Macro:
334     // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
335   case CodeCompletionResult::RK_Keyword:
336     return None;
337   }
338   llvm_unreachable("unknown CodeCompletionResult kind");
339 }
340 
341 // Scopes of the paritial identifier we're trying to complete.
342 // It is used when we query the index for more completion results.
343 struct SpecifiedScope {
344   // The scopes we should look in, determined by Sema.
345   //
346   // If the qualifier was fully resolved, we look for completions in these
347   // scopes; if there is an unresolved part of the qualifier, it should be
348   // resolved within these scopes.
349   //
350   // Examples of qualified completion:
351   //
352   //   "::vec"                                      => {""}
353   //   "using namespace std; ::vec^"                => {"", "std::"}
354   //   "namespace ns {using namespace std;} ns::^"  => {"ns::", "std::"}
355   //   "std::vec^"                                  => {""}  // "std" unresolved
356   //
357   // Examples of unqualified completion:
358   //
359   //   "vec^"                                       => {""}
360   //   "using namespace std; vec^"                  => {"", "std::"}
361   //   "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
362   //
363   // "" for global namespace, "ns::" for normal namespace.
364   std::vector<std::string> AccessibleScopes;
365   // The full scope qualifier as typed by the user (without the leading "::").
366   // Set if the qualifier is not fully resolved by Sema.
367   llvm::Optional<std::string> UnresolvedQualifier;
368 
369   // Construct scopes being queried in indexes.
370   // This method format the scopes to match the index request representation.
371   std::vector<std::string> scopesForIndexQuery() {
372     std::vector<std::string> Results;
373     for (llvm::StringRef AS : AccessibleScopes) {
374       Results.push_back(AS);
375       if (UnresolvedQualifier)
376         Results.back() += *UnresolvedQualifier;
377     }
378     return Results;
379   }
380 };
381 
382 // Get all scopes that will be queried in indexes.
383 std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
384                                         const SourceManager& SM) {
385   auto GetAllAccessibleScopes = [](CodeCompletionContext& CCContext) {
386     SpecifiedScope Info;
387     for (auto* Context : CCContext.getVisitedContexts()) {
388       if (isa<TranslationUnitDecl>(Context))
389         Info.AccessibleScopes.push_back(""); // global namespace
390       else if (const auto*NS = dyn_cast<NamespaceDecl>(Context))
391         Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
392     }
393     return Info;
394   };
395 
396   auto SS = CCContext.getCXXScopeSpecifier();
397 
398   // Unqualified completion (e.g. "vec^").
399   if (!SS) {
400     // FIXME: Once we can insert namespace qualifiers and use the in-scope
401     //        namespaces for scoring, search in all namespaces.
402     // FIXME: Capture scopes and use for scoring, for example,
403     //        "using namespace std; namespace foo {v^}" =>
404     //        foo::value > std::vector > boost::variant
405     return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
406   }
407 
408   // Qualified completion ("std::vec^"), we have two cases depending on whether
409   // the qualifier can be resolved by Sema.
410   if ((*SS)->isValid()) { // Resolved qualifier.
411     return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
412   }
413 
414   // Unresolved qualifier.
415   // FIXME: When Sema can resolve part of a scope chain (e.g.
416   // "known::unknown::id"), we should expand the known part ("known::") rather
417   // than treating the whole thing as unknown.
418   SpecifiedScope Info;
419   Info.AccessibleScopes.push_back(""); // global namespace
420 
421   Info.UnresolvedQualifier =
422       Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()),
423                            SM, clang::LangOptions()).ltrim("::");
424   // Sema excludes the trailing "::".
425   if (!Info.UnresolvedQualifier->empty())
426     *Info.UnresolvedQualifier += "::";
427 
428   return Info.scopesForIndexQuery();
429 }
430 
431 // The CompletionRecorder captures Sema code-complete output, including context.
432 // It filters out ignored results (but doesn't apply fuzzy-filtering yet).
433 // It doesn't do scoring or conversion to CompletionItem yet, as we want to
434 // merge with index results first.
435 // Generally the fields and methods of this object should only be used from
436 // within the callback.
437 struct CompletionRecorder : public CodeCompleteConsumer {
438   CompletionRecorder(const CodeCompleteOptions &Opts,
439                      UniqueFunction<void()> ResultsCallback)
440       : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
441                              /*OutputIsBinary=*/false),
442         CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
443         CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
444         CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
445     assert(this->ResultsCallback);
446   }
447 
448   std::vector<CodeCompletionResult> Results;
449   CodeCompletionContext CCContext;
450   Sema *CCSema = nullptr; // Sema that created the results.
451   // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
452 
453   void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
454                                   CodeCompletionResult *InResults,
455                                   unsigned NumResults) override final {
456     if (CCSema) {
457       log(llvm::formatv(
458           "Multiple code complete callbacks (parser backtracked?). "
459           "Dropping results from context {0}, keeping results from {1}.",
460           getCompletionKindString(this->CCContext.getKind()),
461           getCompletionKindString(Context.getKind())));
462       return;
463     }
464     // Record the completion context.
465     CCSema = &S;
466     CCContext = Context;
467 
468     // Retain the results we might want.
469     for (unsigned I = 0; I < NumResults; ++I) {
470       auto &Result = InResults[I];
471       // Drop hidden items which cannot be found by lookup after completion.
472       // Exception: some items can be named by using a qualifier.
473       if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
474         continue;
475       if (!Opts.IncludeIneligibleResults &&
476           (Result.Availability == CXAvailability_NotAvailable ||
477            Result.Availability == CXAvailability_NotAccessible))
478         continue;
479       // Destructor completion is rarely useful, and works inconsistently.
480       // (s.^ completes ~string, but s.~st^ is an error).
481       if (dyn_cast_or_null<CXXDestructorDecl>(Result.Declaration))
482         continue;
483       // We choose to never append '::' to completion results in clangd.
484       Result.StartsNestedNameSpecifier = false;
485       Results.push_back(Result);
486     }
487     ResultsCallback();
488   }
489 
490   CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
491   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
492 
493   // Returns the filtering/sorting name for Result, which must be from Results.
494   // Returned string is owned by this recorder (or the AST).
495   llvm::StringRef getName(const CodeCompletionResult &Result) {
496     switch (Result.Kind) {
497     case CodeCompletionResult::RK_Declaration:
498       if (auto *ID = Result.Declaration->getIdentifier())
499         return ID->getName();
500       break;
501     case CodeCompletionResult::RK_Keyword:
502       return Result.Keyword;
503     case CodeCompletionResult::RK_Macro:
504       return Result.Macro->getName();
505     case CodeCompletionResult::RK_Pattern:
506       return Result.Pattern->getTypedText();
507     }
508     auto *CCS = codeCompletionString(Result, /*IncludeBriefComments=*/false);
509     return CCS->getTypedText();
510   }
511 
512   // Build a CodeCompletion string for R, which must be from Results.
513   // The CCS will be owned by this recorder.
514   CodeCompletionString *codeCompletionString(const CodeCompletionResult &R,
515                                              bool IncludeBriefComments) {
516     // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
517     return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
518         *CCSema, CCContext, *CCAllocator, CCTUInfo, IncludeBriefComments);
519   }
520 
521 private:
522   CodeCompleteOptions Opts;
523   std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
524   CodeCompletionTUInfo CCTUInfo;
525   UniqueFunction<void()> ResultsCallback;
526 };
527 
528 // Tracks a bounded number of candidates with the best scores.
529 class TopN {
530 public:
531   using value_type = std::pair<CompletionCandidate, CompletionItemScores>;
532   static constexpr size_t Unbounded = std::numeric_limits<size_t>::max();
533 
534   TopN(size_t N) : N(N) {}
535 
536   // Adds a candidate to the set.
537   // Returns true if a candidate was dropped to get back under N.
538   bool push(value_type &&V) {
539     bool Dropped = false;
540     if (Heap.size() >= N) {
541       Dropped = true;
542       if (N > 0 && greater(V, Heap.front())) {
543         std::pop_heap(Heap.begin(), Heap.end(), greater);
544         Heap.back() = std::move(V);
545         std::push_heap(Heap.begin(), Heap.end(), greater);
546       }
547     } else {
548       Heap.push_back(std::move(V));
549       std::push_heap(Heap.begin(), Heap.end(), greater);
550     }
551     assert(Heap.size() <= N);
552     assert(std::is_heap(Heap.begin(), Heap.end(), greater));
553     return Dropped;
554   }
555 
556   // Returns candidates from best to worst.
557   std::vector<value_type> items() && {
558     std::sort_heap(Heap.begin(), Heap.end(), greater);
559     assert(Heap.size() <= N);
560     return std::move(Heap);
561   }
562 
563 private:
564   static bool greater(const value_type &L, const value_type &R) {
565     if (L.second.finalScore != R.second.finalScore)
566       return L.second.finalScore > R.second.finalScore;
567     return L.first.Name < R.first.Name; // Earlier name is better.
568   }
569 
570   const size_t N;
571   std::vector<value_type> Heap; // Min-heap, comparator is greater().
572 };
573 
574 class SignatureHelpCollector final : public CodeCompleteConsumer {
575 
576 public:
577   SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
578                          SignatureHelp &SigHelp)
579       : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
580         SigHelp(SigHelp),
581         Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
582         CCTUInfo(Allocator) {}
583 
584   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
585                                  OverloadCandidate *Candidates,
586                                  unsigned NumCandidates) override {
587     SigHelp.signatures.reserve(NumCandidates);
588     // FIXME(rwols): How can we determine the "active overload candidate"?
589     // Right now the overloaded candidates seem to be provided in a "best fit"
590     // order, so I'm not too worried about this.
591     SigHelp.activeSignature = 0;
592     assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
593            "too many arguments");
594     SigHelp.activeParameter = static_cast<int>(CurrentArg);
595     for (unsigned I = 0; I < NumCandidates; ++I) {
596       const auto &Candidate = Candidates[I];
597       const auto *CCS = Candidate.CreateSignatureString(
598           CurrentArg, S, *Allocator, CCTUInfo, true);
599       assert(CCS && "Expected the CodeCompletionString to be non-null");
600       SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS));
601     }
602   }
603 
604   GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
605 
606   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
607 
608 private:
609   // FIXME(ioeric): consider moving CodeCompletionString logic here to
610   // CompletionString.h.
611   SignatureInformation
612   ProcessOverloadCandidate(const OverloadCandidate &Candidate,
613                            const CodeCompletionString &CCS) const {
614     SignatureInformation Result;
615     const char *ReturnType = nullptr;
616 
617     Result.documentation = getDocumentation(CCS);
618 
619     for (const auto &Chunk : CCS) {
620       switch (Chunk.Kind) {
621       case CodeCompletionString::CK_ResultType:
622         // A piece of text that describes the type of an entity or,
623         // for functions and methods, the return type.
624         assert(!ReturnType && "Unexpected CK_ResultType");
625         ReturnType = Chunk.Text;
626         break;
627       case CodeCompletionString::CK_Placeholder:
628         // A string that acts as a placeholder for, e.g., a function call
629         // argument.
630         // Intentional fallthrough here.
631       case CodeCompletionString::CK_CurrentParameter: {
632         // A piece of text that describes the parameter that corresponds to
633         // the code-completion location within a function call, message send,
634         // macro invocation, etc.
635         Result.label += Chunk.Text;
636         ParameterInformation Info;
637         Info.label = Chunk.Text;
638         Result.parameters.push_back(std::move(Info));
639         break;
640       }
641       case CodeCompletionString::CK_Optional: {
642         // The rest of the parameters are defaulted/optional.
643         assert(Chunk.Optional &&
644                "Expected the optional code completion string to be non-null.");
645         Result.label +=
646             getOptionalParameters(*Chunk.Optional, Result.parameters);
647         break;
648       }
649       case CodeCompletionString::CK_VerticalSpace:
650         break;
651       default:
652         Result.label += Chunk.Text;
653         break;
654       }
655     }
656     if (ReturnType) {
657       Result.label += " -> ";
658       Result.label += ReturnType;
659     }
660     return Result;
661   }
662 
663   SignatureHelp &SigHelp;
664   std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
665   CodeCompletionTUInfo CCTUInfo;
666 
667 }; // SignatureHelpCollector
668 
669 struct SemaCompleteInput {
670   PathRef FileName;
671   const tooling::CompileCommand &Command;
672   PrecompiledPreamble const *Preamble;
673   StringRef Contents;
674   Position Pos;
675   IntrusiveRefCntPtr<vfs::FileSystem> VFS;
676   std::shared_ptr<PCHContainerOperations> PCHs;
677 };
678 
679 // Invokes Sema code completion on a file.
680 bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
681                       const clang::CodeCompleteOptions &Options,
682                       const SemaCompleteInput &Input) {
683   trace::Span Tracer("Sema completion");
684   std::vector<const char *> ArgStrs;
685   for (const auto &S : Input.Command.CommandLine)
686     ArgStrs.push_back(S.c_str());
687 
688   if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
689     log("Couldn't set working directory");
690     // We run parsing anyway, our lit-tests rely on results for non-existing
691     // working dirs.
692   }
693 
694   IgnoreDiagnostics DummyDiagsConsumer;
695   auto CI = createInvocationFromCommandLine(
696       ArgStrs,
697       CompilerInstance::createDiagnostics(new DiagnosticOptions,
698                                           &DummyDiagsConsumer, false),
699       Input.VFS);
700   if (!CI) {
701     log("Couldn't create CompilerInvocation");;
702     return false;
703   }
704   CI->getFrontendOpts().DisableFree = false;
705 
706   std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
707       llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
708 
709   // We reuse the preamble whether it's valid or not. This is a
710   // correctness/performance tradeoff: building without a preamble is slow, and
711   // completion is latency-sensitive.
712   if (Input.Preamble) {
713     auto Bounds =
714         ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
715     // FIXME(ibiryukov): Remove this call to CanReuse() after we'll fix
716     // clients relying on getting stats for preamble files during code
717     // completion.
718     // Note that results of CanReuse() are ignored, see the comment above.
719     Input.Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds,
720                              Input.VFS.get());
721   }
722   // The diagnostic options must be set before creating a CompilerInstance.
723   CI->getDiagnosticOpts().IgnoreWarnings = true;
724   auto Clang = prepareCompilerInstance(
725       std::move(CI), Input.Preamble, std::move(ContentsBuffer),
726       std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
727 
728   // Disable typo correction in Sema.
729   Clang->getLangOpts().SpellChecking = false;
730 
731   auto &FrontendOpts = Clang->getFrontendOpts();
732   FrontendOpts.SkipFunctionBodies = true;
733   FrontendOpts.CodeCompleteOpts = Options;
734   FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
735   auto Offset = positionToOffset(Input.Contents, Input.Pos);
736   if (!Offset) {
737     log("Code completion position was invalid " +
738         llvm::toString(Offset.takeError()));
739     return false;
740   }
741   std::tie(FrontendOpts.CodeCompletionAt.Line,
742            FrontendOpts.CodeCompletionAt.Column) =
743       offsetToClangLineColumn(Input.Contents, *Offset);
744 
745   Clang->setCodeCompletionConsumer(Consumer.release());
746 
747   SyntaxOnlyAction Action;
748   if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
749     log("BeginSourceFile() failed when running codeComplete for " +
750         Input.FileName);
751     return false;
752   }
753   if (!Action.Execute()) {
754     log("Execute() failed when running codeComplete for " + Input.FileName);
755     return false;
756   }
757   Action.EndSourceFile();
758 
759   return true;
760 }
761 
762 // Should we perform index-based completion in this context?
763 // FIXME: consider allowing completion, but restricting the result types.
764 bool allowIndex(enum CodeCompletionContext::Kind K) {
765   switch (K) {
766   case CodeCompletionContext::CCC_TopLevel:
767   case CodeCompletionContext::CCC_ObjCInterface:
768   case CodeCompletionContext::CCC_ObjCImplementation:
769   case CodeCompletionContext::CCC_ObjCIvarList:
770   case CodeCompletionContext::CCC_ClassStructUnion:
771   case CodeCompletionContext::CCC_Statement:
772   case CodeCompletionContext::CCC_Expression:
773   case CodeCompletionContext::CCC_ObjCMessageReceiver:
774   case CodeCompletionContext::CCC_EnumTag:
775   case CodeCompletionContext::CCC_UnionTag:
776   case CodeCompletionContext::CCC_ClassOrStructTag:
777   case CodeCompletionContext::CCC_ObjCProtocolName:
778   case CodeCompletionContext::CCC_Namespace:
779   case CodeCompletionContext::CCC_Type:
780   case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
781   case CodeCompletionContext::CCC_PotentiallyQualifiedName:
782   case CodeCompletionContext::CCC_ParenthesizedExpression:
783   case CodeCompletionContext::CCC_ObjCInterfaceName:
784   case CodeCompletionContext::CCC_ObjCCategoryName:
785     return true;
786   case CodeCompletionContext::CCC_Other: // Be conservative.
787   case CodeCompletionContext::CCC_OtherWithMacros:
788   case CodeCompletionContext::CCC_DotMemberAccess:
789   case CodeCompletionContext::CCC_ArrowMemberAccess:
790   case CodeCompletionContext::CCC_ObjCPropertyAccess:
791   case CodeCompletionContext::CCC_MacroName:
792   case CodeCompletionContext::CCC_MacroNameUse:
793   case CodeCompletionContext::CCC_PreprocessorExpression:
794   case CodeCompletionContext::CCC_PreprocessorDirective:
795   case CodeCompletionContext::CCC_NaturalLanguage:
796   case CodeCompletionContext::CCC_SelectorName:
797   case CodeCompletionContext::CCC_TypeQualifiers:
798   case CodeCompletionContext::CCC_ObjCInstanceMessage:
799   case CodeCompletionContext::CCC_ObjCClassMessage:
800   case CodeCompletionContext::CCC_Recovery:
801     return false;
802   }
803   llvm_unreachable("unknown code completion context");
804 }
805 
806 } // namespace
807 
808 clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
809   clang::CodeCompleteOptions Result;
810   Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
811   Result.IncludeMacros = IncludeMacros;
812   Result.IncludeGlobals = true;
813   Result.IncludeBriefComments = IncludeBriefComments;
814 
815   // When an is used, Sema is responsible for completing the main file,
816   // the index can provide results from the preamble.
817   // Tell Sema not to deserialize the preamble to look for results.
818   Result.LoadExternal = !Index;
819 
820   return Result;
821 }
822 
823 // Runs Sema-based (AST) and Index-based completion, returns merged results.
824 //
825 // There are a few tricky considerations:
826 //   - the AST provides information needed for the index query (e.g. which
827 //     namespaces to search in). So Sema must start first.
828 //   - we only want to return the top results (Opts.Limit).
829 //     Building CompletionItems for everything else is wasteful, so we want to
830 //     preserve the "native" format until we're done with scoring.
831 //   - the data underlying Sema completion items is owned by the AST and various
832 //     other arenas, which must stay alive for us to build CompletionItems.
833 //   - we may get duplicate results from Sema and the Index, we need to merge.
834 //
835 // So we start Sema completion first, and do all our work in its callback.
836 // We use the Sema context information to query the index.
837 // Then we merge the two result sets, producing items that are Sema/Index/Both.
838 // These items are scored, and the top N are synthesized into the LSP response.
839 // Finally, we can clean up the data structures created by Sema completion.
840 //
841 // Main collaborators are:
842 //   - semaCodeComplete sets up the compiler machinery to run code completion.
843 //   - CompletionRecorder captures Sema completion results, including context.
844 //   - SymbolIndex (Opts.Index) provides index completion results as Symbols
845 //   - CompletionCandidates are the result of merging Sema and Index results.
846 //     Each candidate points to an underlying CodeCompletionResult (Sema), a
847 //     Symbol (Index), or both. It computes the result quality score.
848 //     CompletionCandidate also does conversion to CompletionItem (at the end).
849 //   - FuzzyMatcher scores how the candidate matches the partial identifier.
850 //     This score is combined with the result quality score for the final score.
851 //   - TopN determines the results with the best score.
852 class CodeCompleteFlow {
853   PathRef FileName;
854   const CodeCompleteOptions &Opts;
855   // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
856   CompletionRecorder *Recorder = nullptr;
857   int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
858   bool Incomplete = false; // Would more be available with a higher limit?
859   llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
860 
861 public:
862   // A CodeCompleteFlow object is only useful for calling run() exactly once.
863   CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
864       : FileName(FileName), Opts(Opts) {}
865 
866   CompletionList run(const SemaCompleteInput &SemaCCInput) && {
867     trace::Span Tracer("CodeCompleteFlow");
868     // We run Sema code completion first. It builds an AST and calculates:
869     //   - completion results based on the AST.
870     //   - partial identifier and context. We need these for the index query.
871     CompletionList Output;
872     auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
873       assert(Recorder && "Recorder is not set");
874       Output = runWithSema();
875       SPAN_ATTACH(Tracer, "sema_completion_kind",
876                   getCompletionKindString(Recorder->CCContext.getKind()));
877     });
878 
879     Recorder = RecorderOwner.get();
880     semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
881                      SemaCCInput);
882 
883     SPAN_ATTACH(Tracer, "sema_results", NSema);
884     SPAN_ATTACH(Tracer, "index_results", NIndex);
885     SPAN_ATTACH(Tracer, "merged_results", NBoth);
886     SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
887     SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
888     log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
889                       "{2} matched, {3} returned{4}.",
890                       NSema, NIndex, NBoth, Output.items.size(),
891                       Output.isIncomplete ? " (incomplete)" : ""));
892     assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
893     // We don't assert that isIncomplete means we hit a limit.
894     // Indexes may choose to impose their own limits even if we don't have one.
895     return Output;
896   }
897 
898 private:
899   // This is called by run() once Sema code completion is done, but before the
900   // Sema data structures are torn down. It does all the real work.
901   CompletionList runWithSema() {
902     Filter = FuzzyMatcher(
903         Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
904     // Sema provides the needed context to query the index.
905     // FIXME: in addition to querying for extra/overlapping symbols, we should
906     //        explicitly request symbols corresponding to Sema results.
907     //        We can use their signals even if the index can't suggest them.
908     // We must copy index results to preserve them, but there are at most Limit.
909     auto IndexResults = queryIndex();
910     // Merge Sema and Index results, score them, and pick the winners.
911     auto Top = mergeResults(Recorder->Results, IndexResults);
912     // Convert the results to the desired LSP structs.
913     CompletionList Output;
914     for (auto &C : Top)
915       Output.items.push_back(toCompletionItem(C.first, C.second));
916     Output.isIncomplete = Incomplete;
917     return Output;
918   }
919 
920   SymbolSlab queryIndex() {
921     if (!Opts.Index || !allowIndex(Recorder->CCContext.getKind()))
922       return SymbolSlab();
923     trace::Span Tracer("Query index");
924     SPAN_ATTACH(Tracer, "limit", Opts.Limit);
925 
926     SymbolSlab::Builder ResultsBuilder;
927     // Build the query.
928     FuzzyFindRequest Req;
929     if (Opts.Limit)
930       Req.MaxCandidateCount = Opts.Limit;
931     Req.Query = Filter->pattern();
932     Req.Scopes = getQueryScopes(Recorder->CCContext,
933                                 Recorder->CCSema->getSourceManager());
934     log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
935                       Req.Query,
936                       llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
937     // Run the query against the index.
938     if (Opts.Index->fuzzyFind(
939             Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
940       Incomplete = true;
941     return std::move(ResultsBuilder).build();
942   }
943 
944   // Merges the Sema and Index results where possible, scores them, and
945   // returns the top results from best to worst.
946   std::vector<std::pair<CompletionCandidate, CompletionItemScores>>
947   mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
948                const SymbolSlab &IndexResults) {
949     trace::Span Tracer("Merge and score results");
950     // We only keep the best N results at any time, in "native" format.
951     TopN Top(Opts.Limit == 0 ? TopN::Unbounded : Opts.Limit);
952     llvm::DenseSet<const Symbol *> UsedIndexResults;
953     auto CorrespondingIndexResult =
954         [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
955       if (auto SymID = getSymbolID(SemaResult)) {
956         auto I = IndexResults.find(*SymID);
957         if (I != IndexResults.end()) {
958           UsedIndexResults.insert(&*I);
959           return &*I;
960         }
961       }
962       return nullptr;
963     };
964     // Emit all Sema results, merging them with Index results if possible.
965     for (auto &SemaResult : Recorder->Results)
966       addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult));
967     // Now emit any Index-only results.
968     for (const auto &IndexResult : IndexResults) {
969       if (UsedIndexResults.count(&IndexResult))
970         continue;
971       addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult);
972     }
973     return std::move(Top).items();
974   }
975 
976   // Scores a candidate and adds it to the TopN structure.
977   void addCandidate(TopN &Candidates, const CodeCompletionResult *SemaResult,
978                     const Symbol *IndexResult) {
979     CompletionCandidate C;
980     C.SemaResult = SemaResult;
981     C.IndexResult = IndexResult;
982     C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
983 
984     CompletionItemScores Scores;
985     if (auto FuzzyScore = Filter->match(C.Name))
986       Scores.filterScore = *FuzzyScore;
987     else
988       return;
989     Scores.symbolScore = C.score();
990     // We score candidates by multiplying symbolScore ("quality" of the result)
991     // with filterScore (how well it matched the query).
992     // This is sensitive to the distribution of both component scores!
993     Scores.finalScore = Scores.filterScore * Scores.symbolScore;
994 
995     NSema += bool(SemaResult);
996     NIndex += bool(IndexResult);
997     NBoth += SemaResult && IndexResult;
998     if (Candidates.push({C, Scores}))
999       Incomplete = true;
1000   }
1001 
1002   CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
1003                                   const CompletionItemScores &Scores) {
1004     CodeCompletionString *SemaCCS = nullptr;
1005     if (auto *SR = Candidate.SemaResult)
1006       SemaCCS = Recorder->codeCompletionString(*SR, Opts.IncludeBriefComments);
1007     return Candidate.build(FileName, Scores, Opts, SemaCCS);
1008   }
1009 };
1010 
1011 CompletionList codeComplete(PathRef FileName,
1012                             const tooling::CompileCommand &Command,
1013                             PrecompiledPreamble const *Preamble,
1014                             StringRef Contents, Position Pos,
1015                             IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1016                             std::shared_ptr<PCHContainerOperations> PCHs,
1017                             CodeCompleteOptions Opts) {
1018   return CodeCompleteFlow(FileName, Opts)
1019       .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
1020 }
1021 
1022 SignatureHelp signatureHelp(PathRef FileName,
1023                             const tooling::CompileCommand &Command,
1024                             PrecompiledPreamble const *Preamble,
1025                             StringRef Contents, Position Pos,
1026                             IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1027                             std::shared_ptr<PCHContainerOperations> PCHs) {
1028   SignatureHelp Result;
1029   clang::CodeCompleteOptions Options;
1030   Options.IncludeGlobals = false;
1031   Options.IncludeMacros = false;
1032   Options.IncludeCodePatterns = false;
1033   Options.IncludeBriefComments = true;
1034   semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1035                    Options,
1036                    {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1037                     std::move(PCHs)});
1038   return Result;
1039 }
1040 
1041 } // namespace clangd
1042 } // namespace clang
1043