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     // For now we just use the Sema priority, mapping it onto a 0-1 interval.
233     if (!SemaResult) // FIXME(sammccall): better scoring for index results.
234       return 0.3f;   // fixed mediocre score for index-only results.
235 
236     // Priority 80 is a really bad score.
237     float Score = 1 - std::min<float>(80, SemaResult->Priority) / 80;
238 
239     switch (static_cast<CXAvailabilityKind>(SemaResult->Availability)) {
240     case CXAvailability_Available:
241       // No penalty.
242       break;
243     case CXAvailability_Deprecated:
244       Score *= 0.1f;
245       break;
246     case CXAvailability_NotAccessible:
247     case CXAvailability_NotAvailable:
248       Score = 0;
249       break;
250     }
251     return Score;
252   }
253 
254   // Builds an LSP completion item.
255   CompletionItem build(llvm::StringRef FileName,
256                        const CompletionItemScores &Scores,
257                        const CodeCompleteOptions &Opts,
258                        CodeCompletionString *SemaCCS) const {
259     assert(bool(SemaResult) == bool(SemaCCS));
260     CompletionItem I;
261     if (SemaResult) {
262       I.kind = toCompletionItemKind(SemaResult->Kind, SemaResult->CursorKind);
263       getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText,
264                             Opts.EnableSnippets);
265       I.filterText = getFilterText(*SemaCCS);
266       I.documentation = getDocumentation(*SemaCCS);
267       I.detail = getDetail(*SemaCCS);
268     }
269     if (IndexResult) {
270       if (I.kind == CompletionItemKind::Missing)
271         I.kind = toCompletionItemKind(IndexResult->SymInfo.Kind);
272       // FIXME: reintroduce a way to show the index source for debugging.
273       if (I.label.empty())
274         I.label = IndexResult->CompletionLabel;
275       if (I.filterText.empty())
276         I.filterText = IndexResult->Name;
277 
278       // FIXME(ioeric): support inserting/replacing scope qualifiers.
279       if (I.insertText.empty())
280         I.insertText = Opts.EnableSnippets
281                            ? IndexResult->CompletionSnippetInsertText
282                            : IndexResult->CompletionPlainInsertText;
283 
284       if (auto *D = IndexResult->Detail) {
285         if (I.documentation.empty())
286           I.documentation = D->Documentation;
287         if (I.detail.empty())
288           I.detail = D->CompletionDetail;
289         // FIXME: delay creating include insertion command to
290         // "completionItem/resolve", when it is supported
291         if (!D->IncludeHeader.empty()) {
292           // LSP favors additionalTextEdits over command. But we are still using
293           // command here because it would be expensive to calculate #include
294           // insertion edits for all candidates, and the include insertion edit
295           // is unlikely to conflict with the code completion edits.
296           Command Cmd;
297           // Command title is not added since this is not a user-facing command.
298           Cmd.command = ExecuteCommandParams::CLANGD_INSERT_HEADER_INCLUDE;
299           IncludeInsertion Insertion;
300           Insertion.header = D->IncludeHeader;
301           Insertion.textDocument.uri = URIForFile(FileName);
302           Cmd.includeInsertion = std::move(Insertion);
303           I.command = std::move(Cmd);
304         }
305       }
306     }
307     I.scoreInfo = Scores;
308     I.sortText = sortText(Scores.finalScore, Name);
309     I.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
310                                              : InsertTextFormat::PlainText;
311     return I;
312   }
313 };
314 
315 // Determine the symbol ID for a Sema code completion result, if possible.
316 llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
317   switch (R.Kind) {
318   case CodeCompletionResult::RK_Declaration:
319   case CodeCompletionResult::RK_Pattern: {
320     llvm::SmallString<128> USR;
321     if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
322       return None;
323     return SymbolID(USR);
324   }
325   case CodeCompletionResult::RK_Macro:
326     // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
327   case CodeCompletionResult::RK_Keyword:
328     return None;
329   }
330   llvm_unreachable("unknown CodeCompletionResult kind");
331 }
332 
333 // Scopes of the paritial identifier we're trying to complete.
334 // It is used when we query the index for more completion results.
335 struct SpecifiedScope {
336   // The scopes we should look in, determined by Sema.
337   //
338   // If the qualifier was fully resolved, we look for completions in these
339   // scopes; if there is an unresolved part of the qualifier, it should be
340   // resolved within these scopes.
341   //
342   // Examples of qualified completion:
343   //
344   //   "::vec"                                      => {""}
345   //   "using namespace std; ::vec^"                => {"", "std::"}
346   //   "namespace ns {using namespace std;} ns::^"  => {"ns::", "std::"}
347   //   "std::vec^"                                  => {""}  // "std" unresolved
348   //
349   // Examples of unqualified completion:
350   //
351   //   "vec^"                                       => {""}
352   //   "using namespace std; vec^"                  => {"", "std::"}
353   //   "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
354   //
355   // "" for global namespace, "ns::" for normal namespace.
356   std::vector<std::string> AccessibleScopes;
357   // The full scope qualifier as typed by the user (without the leading "::").
358   // Set if the qualifier is not fully resolved by Sema.
359   llvm::Optional<std::string> UnresolvedQualifier;
360 
361   // Construct scopes being queried in indexes.
362   // This method format the scopes to match the index request representation.
363   std::vector<std::string> scopesForIndexQuery() {
364     std::vector<std::string> Results;
365     for (llvm::StringRef AS : AccessibleScopes) {
366       Results.push_back(AS);
367       if (UnresolvedQualifier)
368         Results.back() += *UnresolvedQualifier;
369     }
370     return Results;
371   }
372 };
373 
374 // Get all scopes that will be queried in indexes.
375 std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
376                                         const SourceManager& SM) {
377   auto GetAllAccessibleScopes = [](CodeCompletionContext& CCContext) {
378     SpecifiedScope Info;
379     for (auto* Context : CCContext.getVisitedContexts()) {
380       if (isa<TranslationUnitDecl>(Context))
381         Info.AccessibleScopes.push_back(""); // global namespace
382       else if (const auto*NS = dyn_cast<NamespaceDecl>(Context))
383         Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
384     }
385     return Info;
386   };
387 
388   auto SS = CCContext.getCXXScopeSpecifier();
389 
390   // Unqualified completion (e.g. "vec^").
391   if (!SS) {
392     // FIXME: Once we can insert namespace qualifiers and use the in-scope
393     //        namespaces for scoring, search in all namespaces.
394     // FIXME: Capture scopes and use for scoring, for example,
395     //        "using namespace std; namespace foo {v^}" =>
396     //        foo::value > std::vector > boost::variant
397     return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
398   }
399 
400   // Qualified completion ("std::vec^"), we have two cases depending on whether
401   // the qualifier can be resolved by Sema.
402   if ((*SS)->isValid()) { // Resolved qualifier.
403     return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
404   }
405 
406   // Unresolved qualifier.
407   // FIXME: When Sema can resolve part of a scope chain (e.g.
408   // "known::unknown::id"), we should expand the known part ("known::") rather
409   // than treating the whole thing as unknown.
410   SpecifiedScope Info;
411   Info.AccessibleScopes.push_back(""); // global namespace
412 
413   Info.UnresolvedQualifier =
414       Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()),
415                            SM, clang::LangOptions()).ltrim("::");
416   // Sema excludes the trailing "::".
417   if (!Info.UnresolvedQualifier->empty())
418     *Info.UnresolvedQualifier += "::";
419 
420   return Info.scopesForIndexQuery();
421 }
422 
423 // The CompletionRecorder captures Sema code-complete output, including context.
424 // It filters out ignored results (but doesn't apply fuzzy-filtering yet).
425 // It doesn't do scoring or conversion to CompletionItem yet, as we want to
426 // merge with index results first.
427 struct CompletionRecorder : public CodeCompleteConsumer {
428   CompletionRecorder(const CodeCompleteOptions &Opts)
429       : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
430                              /*OutputIsBinary=*/false),
431         CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
432         CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
433         CCTUInfo(CCAllocator) {}
434   std::vector<CodeCompletionResult> Results;
435   CodeCompletionContext CCContext;
436   Sema *CCSema = nullptr; // Sema that created the results.
437   // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
438 
439   void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
440                                   CodeCompletionResult *InResults,
441                                   unsigned NumResults) override final {
442     // Record the completion context.
443     assert(!CCSema && "ProcessCodeCompleteResults called multiple times!");
444     CCSema = &S;
445     CCContext = Context;
446 
447     // Retain the results we might want.
448     for (unsigned I = 0; I < NumResults; ++I) {
449       auto &Result = InResults[I];
450       // Drop hidden items which cannot be found by lookup after completion.
451       // Exception: some items can be named by using a qualifier.
452       if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
453         continue;
454       if (!Opts.IncludeIneligibleResults &&
455           (Result.Availability == CXAvailability_NotAvailable ||
456            Result.Availability == CXAvailability_NotAccessible))
457         continue;
458       // Destructor completion is rarely useful, and works inconsistently.
459       // (s.^ completes ~string, but s.~st^ is an error).
460       if (dyn_cast_or_null<CXXDestructorDecl>(Result.Declaration))
461         continue;
462       Results.push_back(Result);
463     }
464   }
465 
466   CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
467   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
468 
469   // Returns the filtering/sorting name for Result, which must be from Results.
470   // Returned string is owned by this recorder (or the AST).
471   llvm::StringRef getName(const CodeCompletionResult &Result) {
472     switch (Result.Kind) {
473     case CodeCompletionResult::RK_Declaration:
474       if (auto *ID = Result.Declaration->getIdentifier())
475         return ID->getName();
476       break;
477     case CodeCompletionResult::RK_Keyword:
478       return Result.Keyword;
479     case CodeCompletionResult::RK_Macro:
480       return Result.Macro->getName();
481     case CodeCompletionResult::RK_Pattern:
482       return Result.Pattern->getTypedText();
483     }
484     auto *CCS = codeCompletionString(Result, /*IncludeBriefComments=*/false);
485     return CCS->getTypedText();
486   }
487 
488   // Build a CodeCompletion string for R, which must be from Results.
489   // The CCS will be owned by this recorder.
490   CodeCompletionString *codeCompletionString(const CodeCompletionResult &R,
491                                              bool IncludeBriefComments) {
492     // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
493     return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
494         *CCSema, CCContext, *CCAllocator, CCTUInfo, IncludeBriefComments);
495   }
496 
497 private:
498   CodeCompleteOptions Opts;
499   std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
500   CodeCompletionTUInfo CCTUInfo;
501 };
502 
503 // Tracks a bounded number of candidates with the best scores.
504 class TopN {
505 public:
506   using value_type = std::pair<CompletionCandidate, CompletionItemScores>;
507   static constexpr size_t Unbounded = std::numeric_limits<size_t>::max();
508 
509   TopN(size_t N) : N(N) {}
510 
511   // Adds a candidate to the set.
512   // Returns true if a candidate was dropped to get back under N.
513   bool push(value_type &&V) {
514     bool Dropped = false;
515     if (Heap.size() >= N) {
516       Dropped = true;
517       if (N > 0 && greater(V, Heap.front())) {
518         std::pop_heap(Heap.begin(), Heap.end(), greater);
519         Heap.back() = std::move(V);
520         std::push_heap(Heap.begin(), Heap.end(), greater);
521       }
522     } else {
523       Heap.push_back(std::move(V));
524       std::push_heap(Heap.begin(), Heap.end(), greater);
525     }
526     assert(Heap.size() <= N);
527     assert(std::is_heap(Heap.begin(), Heap.end(), greater));
528     return Dropped;
529   }
530 
531   // Returns candidates from best to worst.
532   std::vector<value_type> items() && {
533     std::sort_heap(Heap.begin(), Heap.end(), greater);
534     assert(Heap.size() <= N);
535     return std::move(Heap);
536   }
537 
538 private:
539   static bool greater(const value_type &L, const value_type &R) {
540     if (L.second.finalScore != R.second.finalScore)
541       return L.second.finalScore > R.second.finalScore;
542     return L.first.Name < R.first.Name; // Earlier name is better.
543   }
544 
545   const size_t N;
546   std::vector<value_type> Heap; // Min-heap, comparator is greater().
547 };
548 
549 class SignatureHelpCollector final : public CodeCompleteConsumer {
550 
551 public:
552   SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
553                          SignatureHelp &SigHelp)
554       : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
555         SigHelp(SigHelp),
556         Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
557         CCTUInfo(Allocator) {}
558 
559   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
560                                  OverloadCandidate *Candidates,
561                                  unsigned NumCandidates) override {
562     SigHelp.signatures.reserve(NumCandidates);
563     // FIXME(rwols): How can we determine the "active overload candidate"?
564     // Right now the overloaded candidates seem to be provided in a "best fit"
565     // order, so I'm not too worried about this.
566     SigHelp.activeSignature = 0;
567     assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
568            "too many arguments");
569     SigHelp.activeParameter = static_cast<int>(CurrentArg);
570     for (unsigned I = 0; I < NumCandidates; ++I) {
571       const auto &Candidate = Candidates[I];
572       const auto *CCS = Candidate.CreateSignatureString(
573           CurrentArg, S, *Allocator, CCTUInfo, true);
574       assert(CCS && "Expected the CodeCompletionString to be non-null");
575       SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS));
576     }
577   }
578 
579   GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
580 
581   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
582 
583 private:
584   // FIXME(ioeric): consider moving CodeCompletionString logic here to
585   // CompletionString.h.
586   SignatureInformation
587   ProcessOverloadCandidate(const OverloadCandidate &Candidate,
588                            const CodeCompletionString &CCS) const {
589     SignatureInformation Result;
590     const char *ReturnType = nullptr;
591 
592     Result.documentation = getDocumentation(CCS);
593 
594     for (const auto &Chunk : CCS) {
595       switch (Chunk.Kind) {
596       case CodeCompletionString::CK_ResultType:
597         // A piece of text that describes the type of an entity or,
598         // for functions and methods, the return type.
599         assert(!ReturnType && "Unexpected CK_ResultType");
600         ReturnType = Chunk.Text;
601         break;
602       case CodeCompletionString::CK_Placeholder:
603         // A string that acts as a placeholder for, e.g., a function call
604         // argument.
605         // Intentional fallthrough here.
606       case CodeCompletionString::CK_CurrentParameter: {
607         // A piece of text that describes the parameter that corresponds to
608         // the code-completion location within a function call, message send,
609         // macro invocation, etc.
610         Result.label += Chunk.Text;
611         ParameterInformation Info;
612         Info.label = Chunk.Text;
613         Result.parameters.push_back(std::move(Info));
614         break;
615       }
616       case CodeCompletionString::CK_Optional: {
617         // The rest of the parameters are defaulted/optional.
618         assert(Chunk.Optional &&
619                "Expected the optional code completion string to be non-null.");
620         Result.label +=
621             getOptionalParameters(*Chunk.Optional, Result.parameters);
622         break;
623       }
624       case CodeCompletionString::CK_VerticalSpace:
625         break;
626       default:
627         Result.label += Chunk.Text;
628         break;
629       }
630     }
631     if (ReturnType) {
632       Result.label += " -> ";
633       Result.label += ReturnType;
634     }
635     return Result;
636   }
637 
638   SignatureHelp &SigHelp;
639   std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
640   CodeCompletionTUInfo CCTUInfo;
641 
642 }; // SignatureHelpCollector
643 
644 struct SemaCompleteInput {
645   PathRef FileName;
646   const tooling::CompileCommand &Command;
647   PrecompiledPreamble const *Preamble;
648   StringRef Contents;
649   Position Pos;
650   IntrusiveRefCntPtr<vfs::FileSystem> VFS;
651   std::shared_ptr<PCHContainerOperations> PCHs;
652 };
653 
654 // Invokes Sema code completion on a file.
655 // Callback will be invoked once completion is done, but before cleaning up.
656 bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
657                       const clang::CodeCompleteOptions &Options,
658                       const SemaCompleteInput &Input,
659                       llvm::function_ref<void()> Callback = nullptr) {
660   auto Tracer = llvm::make_unique<trace::Span>("Sema completion");
661   std::vector<const char *> ArgStrs;
662   for (const auto &S : Input.Command.CommandLine)
663     ArgStrs.push_back(S.c_str());
664 
665   if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
666     log("Couldn't set working directory");
667     // We run parsing anyway, our lit-tests rely on results for non-existing
668     // working dirs.
669   }
670 
671   IgnoreDiagnostics DummyDiagsConsumer;
672   auto CI = createInvocationFromCommandLine(
673       ArgStrs,
674       CompilerInstance::createDiagnostics(new DiagnosticOptions,
675                                           &DummyDiagsConsumer, false),
676       Input.VFS);
677   if (!CI) {
678     log("Couldn't create CompilerInvocation");;
679     return false;
680   }
681   CI->getFrontendOpts().DisableFree = false;
682 
683   std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
684       llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
685 
686   // We reuse the preamble whether it's valid or not. This is a
687   // correctness/performance tradeoff: building without a preamble is slow, and
688   // completion is latency-sensitive.
689   if (Input.Preamble) {
690     auto Bounds =
691         ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
692     // FIXME(ibiryukov): Remove this call to CanReuse() after we'll fix
693     // clients relying on getting stats for preamble files during code
694     // completion.
695     // Note that results of CanReuse() are ignored, see the comment above.
696     Input.Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds,
697                              Input.VFS.get());
698   }
699   // The diagnostic options must be set before creating a CompilerInstance.
700   CI->getDiagnosticOpts().IgnoreWarnings = true;
701   auto Clang = prepareCompilerInstance(
702       std::move(CI), Input.Preamble, std::move(ContentsBuffer),
703       std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
704 
705   // Disable typo correction in Sema.
706   Clang->getLangOpts().SpellChecking = false;
707 
708   auto &FrontendOpts = Clang->getFrontendOpts();
709   FrontendOpts.SkipFunctionBodies = true;
710   FrontendOpts.CodeCompleteOpts = Options;
711   FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
712   FrontendOpts.CodeCompletionAt.Line = Input.Pos.line + 1;
713   FrontendOpts.CodeCompletionAt.Column = Input.Pos.character + 1;
714 
715   Clang->setCodeCompletionConsumer(Consumer.release());
716 
717   SyntaxOnlyAction Action;
718   if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
719     log("BeginSourceFile() failed when running codeComplete for " +
720         Input.FileName);
721     return false;
722   }
723   if (!Action.Execute()) {
724     log("Execute() failed when running codeComplete for " + Input.FileName);
725     return false;
726   }
727   Tracer.reset();
728 
729   if (Callback)
730     Callback();
731 
732   Tracer = llvm::make_unique<trace::Span>("Sema completion cleanup");
733   Action.EndSourceFile();
734 
735   return true;
736 }
737 
738 // Should we perform index-based completion in this context?
739 // FIXME: consider allowing completion, but restricting the result types.
740 bool allowIndex(enum CodeCompletionContext::Kind K) {
741   switch (K) {
742   case CodeCompletionContext::CCC_TopLevel:
743   case CodeCompletionContext::CCC_ObjCInterface:
744   case CodeCompletionContext::CCC_ObjCImplementation:
745   case CodeCompletionContext::CCC_ObjCIvarList:
746   case CodeCompletionContext::CCC_ClassStructUnion:
747   case CodeCompletionContext::CCC_Statement:
748   case CodeCompletionContext::CCC_Expression:
749   case CodeCompletionContext::CCC_ObjCMessageReceiver:
750   case CodeCompletionContext::CCC_EnumTag:
751   case CodeCompletionContext::CCC_UnionTag:
752   case CodeCompletionContext::CCC_ClassOrStructTag:
753   case CodeCompletionContext::CCC_ObjCProtocolName:
754   case CodeCompletionContext::CCC_Namespace:
755   case CodeCompletionContext::CCC_Type:
756   case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
757   case CodeCompletionContext::CCC_PotentiallyQualifiedName:
758   case CodeCompletionContext::CCC_ParenthesizedExpression:
759   case CodeCompletionContext::CCC_ObjCInterfaceName:
760   case CodeCompletionContext::CCC_ObjCCategoryName:
761     return true;
762   case CodeCompletionContext::CCC_Other: // Be conservative.
763   case CodeCompletionContext::CCC_OtherWithMacros:
764   case CodeCompletionContext::CCC_DotMemberAccess:
765   case CodeCompletionContext::CCC_ArrowMemberAccess:
766   case CodeCompletionContext::CCC_ObjCPropertyAccess:
767   case CodeCompletionContext::CCC_MacroName:
768   case CodeCompletionContext::CCC_MacroNameUse:
769   case CodeCompletionContext::CCC_PreprocessorExpression:
770   case CodeCompletionContext::CCC_PreprocessorDirective:
771   case CodeCompletionContext::CCC_NaturalLanguage:
772   case CodeCompletionContext::CCC_SelectorName:
773   case CodeCompletionContext::CCC_TypeQualifiers:
774   case CodeCompletionContext::CCC_ObjCInstanceMessage:
775   case CodeCompletionContext::CCC_ObjCClassMessage:
776   case CodeCompletionContext::CCC_Recovery:
777     return false;
778   }
779   llvm_unreachable("unknown code completion context");
780 }
781 
782 } // namespace
783 
784 clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
785   clang::CodeCompleteOptions Result;
786   Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
787   Result.IncludeMacros = IncludeMacros;
788   Result.IncludeGlobals = true;
789   Result.IncludeBriefComments = IncludeBriefComments;
790 
791   // When an is used, Sema is responsible for completing the main file,
792   // the index can provide results from the preamble.
793   // Tell Sema not to deserialize the preamble to look for results.
794   Result.LoadExternal = !Index;
795 
796   return Result;
797 }
798 
799 // Runs Sema-based (AST) and Index-based completion, returns merged results.
800 //
801 // There are a few tricky considerations:
802 //   - the AST provides information needed for the index query (e.g. which
803 //     namespaces to search in). So Sema must start first.
804 //   - we only want to return the top results (Opts.Limit).
805 //     Building CompletionItems for everything else is wasteful, so we want to
806 //     preserve the "native" format until we're done with scoring.
807 //   - the data underlying Sema completion items is owned by the AST and various
808 //     other arenas, which must stay alive for us to build CompletionItems.
809 //   - we may get duplicate results from Sema and the Index, we need to merge.
810 //
811 // So we start Sema completion first, but defer its cleanup until we're done.
812 // We use the Sema context information to query the index.
813 // Then we merge the two result sets, producing items that are Sema/Index/Both.
814 // These items are scored, and the top N are synthesized into the LSP response.
815 // Finally, we can clean up the data structures created by Sema completion.
816 //
817 // Main collaborators are:
818 //   - semaCodeComplete sets up the compiler machinery to run code completion.
819 //   - CompletionRecorder captures Sema completion results, including context.
820 //   - SymbolIndex (Opts.Index) provides index completion results as Symbols
821 //   - CompletionCandidates are the result of merging Sema and Index results.
822 //     Each candidate points to an underlying CodeCompletionResult (Sema), a
823 //     Symbol (Index), or both. It computes the result quality score.
824 //     CompletionCandidate also does conversion to CompletionItem (at the end).
825 //   - FuzzyMatcher scores how the candidate matches the partial identifier.
826 //     This score is combined with the result quality score for the final score.
827 //   - TopN determines the results with the best score.
828 class CodeCompleteFlow {
829   PathRef FileName;
830   const CodeCompleteOptions &Opts;
831   // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
832   std::unique_ptr<CompletionRecorder> RecorderOwner;
833   CompletionRecorder &Recorder;
834   int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
835   bool Incomplete = false; // Would more be available with a higher limit?
836   llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
837 
838 public:
839   // A CodeCompleteFlow object is only useful for calling run() exactly once.
840   CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
841       : FileName(FileName), Opts(Opts),
842         RecorderOwner(new CompletionRecorder(Opts)), Recorder(*RecorderOwner) {}
843 
844   CompletionList run(const SemaCompleteInput &SemaCCInput) && {
845     trace::Span Tracer("CodeCompleteFlow");
846     // We run Sema code completion first. It builds an AST and calculates:
847     //   - completion results based on the AST. These are saved for merging.
848     //   - partial identifier and context. We need these for the index query.
849     CompletionList Output;
850     semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
851                      SemaCCInput, [&] {
852                        if (Recorder.CCSema) {
853                          Output = runWithSema();
854                          SPAN_ATTACH(
855                              Tracer, "sema_completion_kind",
856                              getCompletionKindString(Recorder.CCContext.getKind()));
857                        } else
858                          log("Code complete: no Sema callback, 0 results");
859                      });
860 
861     SPAN_ATTACH(Tracer, "sema_results", NSema);
862     SPAN_ATTACH(Tracer, "index_results", NIndex);
863     SPAN_ATTACH(Tracer, "merged_results", NBoth);
864     SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
865     SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
866     log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
867                       "{2} matched, {3} returned{4}.",
868                       NSema, NIndex, NBoth, Output.items.size(),
869                       Output.isIncomplete ? " (incomplete)" : ""));
870     assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
871     // We don't assert that isIncomplete means we hit a limit.
872     // Indexes may choose to impose their own limits even if we don't have one.
873     return Output;
874   }
875 
876 private:
877   // This is called by run() once Sema code completion is done, but before the
878   // Sema data structures are torn down. It does all the real work.
879   CompletionList runWithSema() {
880     Filter = FuzzyMatcher(
881         Recorder.CCSema->getPreprocessor().getCodeCompletionFilter());
882     // Sema provides the needed context to query the index.
883     // FIXME: in addition to querying for extra/overlapping symbols, we should
884     //        explicitly request symbols corresponding to Sema results.
885     //        We can use their signals even if the index can't suggest them.
886     // We must copy index results to preserve them, but there are at most Limit.
887     auto IndexResults = queryIndex();
888     // Merge Sema and Index results, score them, and pick the winners.
889     auto Top = mergeResults(Recorder.Results, IndexResults);
890     // Convert the results to the desired LSP structs.
891     CompletionList Output;
892     for (auto &C : Top)
893       Output.items.push_back(toCompletionItem(C.first, C.second));
894     Output.isIncomplete = Incomplete;
895     return Output;
896   }
897 
898   SymbolSlab queryIndex() {
899     if (!Opts.Index || !allowIndex(Recorder.CCContext.getKind()))
900       return SymbolSlab();
901     trace::Span Tracer("Query index");
902     SPAN_ATTACH(Tracer, "limit", Opts.Limit);
903 
904     SymbolSlab::Builder ResultsBuilder;
905     // Build the query.
906     FuzzyFindRequest Req;
907     if (Opts.Limit)
908       Req.MaxCandidateCount = Opts.Limit;
909     Req.Query = Filter->pattern();
910     Req.Scopes =
911         getQueryScopes(Recorder.CCContext, Recorder.CCSema->getSourceManager());
912     log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
913                       Req.Query,
914                       llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
915     // Run the query against the index.
916     if (Opts.Index->fuzzyFind(
917             Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
918       Incomplete = true;
919     return std::move(ResultsBuilder).build();
920   }
921 
922   // Merges the Sema and Index results where possible, scores them, and
923   // returns the top results from best to worst.
924   std::vector<std::pair<CompletionCandidate, CompletionItemScores>>
925   mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
926                const SymbolSlab &IndexResults) {
927     trace::Span Tracer("Merge and score results");
928     // We only keep the best N results at any time, in "native" format.
929     TopN Top(Opts.Limit == 0 ? TopN::Unbounded : Opts.Limit);
930     llvm::DenseSet<const Symbol *> UsedIndexResults;
931     auto CorrespondingIndexResult =
932         [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
933       if (auto SymID = getSymbolID(SemaResult)) {
934         auto I = IndexResults.find(*SymID);
935         if (I != IndexResults.end()) {
936           UsedIndexResults.insert(&*I);
937           return &*I;
938         }
939       }
940       return nullptr;
941     };
942     // Emit all Sema results, merging them with Index results if possible.
943     for (auto &SemaResult : Recorder.Results)
944       addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult));
945     // Now emit any Index-only results.
946     for (const auto &IndexResult : IndexResults) {
947       if (UsedIndexResults.count(&IndexResult))
948         continue;
949       addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult);
950     }
951     return std::move(Top).items();
952   }
953 
954   // Scores a candidate and adds it to the TopN structure.
955   void addCandidate(TopN &Candidates, const CodeCompletionResult *SemaResult,
956                     const Symbol *IndexResult) {
957     CompletionCandidate C;
958     C.SemaResult = SemaResult;
959     C.IndexResult = IndexResult;
960     C.Name = IndexResult ? IndexResult->Name : Recorder.getName(*SemaResult);
961 
962     CompletionItemScores Scores;
963     if (auto FuzzyScore = Filter->match(C.Name))
964       Scores.filterScore = *FuzzyScore;
965     else
966       return;
967     Scores.symbolScore = C.score();
968     // We score candidates by multiplying symbolScore ("quality" of the result)
969     // with filterScore (how well it matched the query).
970     // This is sensitive to the distribution of both component scores!
971     Scores.finalScore = Scores.filterScore * Scores.symbolScore;
972 
973     NSema += bool(SemaResult);
974     NIndex += bool(IndexResult);
975     NBoth += SemaResult && IndexResult;
976     if (Candidates.push({C, Scores}))
977       Incomplete = true;
978   }
979 
980   CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
981                                   const CompletionItemScores &Scores) {
982     CodeCompletionString *SemaCCS = nullptr;
983     if (auto *SR = Candidate.SemaResult)
984       SemaCCS = Recorder.codeCompletionString(*SR, Opts.IncludeBriefComments);
985     return Candidate.build(FileName, Scores, Opts, SemaCCS);
986   }
987 };
988 
989 CompletionList codeComplete(PathRef FileName,
990                             const tooling::CompileCommand &Command,
991                             PrecompiledPreamble const *Preamble,
992                             StringRef Contents, Position Pos,
993                             IntrusiveRefCntPtr<vfs::FileSystem> VFS,
994                             std::shared_ptr<PCHContainerOperations> PCHs,
995                             CodeCompleteOptions Opts) {
996   return CodeCompleteFlow(FileName, Opts)
997       .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
998 }
999 
1000 SignatureHelp signatureHelp(PathRef FileName,
1001                             const tooling::CompileCommand &Command,
1002                             PrecompiledPreamble const *Preamble,
1003                             StringRef Contents, Position Pos,
1004                             IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1005                             std::shared_ptr<PCHContainerOperations> PCHs) {
1006   SignatureHelp Result;
1007   clang::CodeCompleteOptions Options;
1008   Options.IncludeGlobals = false;
1009   Options.IncludeMacros = false;
1010   Options.IncludeCodePatterns = false;
1011   Options.IncludeBriefComments = true;
1012   semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1013                    Options,
1014                    {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1015                     std::move(PCHs)});
1016   return Result;
1017 }
1018 
1019 } // namespace clangd
1020 } // namespace clang
1021