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