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 // Code completion has several moving parts:
11 //  - AST-based completions are provided using the completion hooks in Sema.
12 //  - external completions are retrieved from the index (using hints from Sema)
13 //  - the two sources overlap, and must be merged and overloads bundled
14 //  - results must be scored and ranked (see Quality.h) before rendering
15 //
16 // Signature help works in a similar way as code completion, but it is simpler:
17 // it's purely AST-based, and there are few candidates.
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "CodeComplete.h"
22 #include "AST.h"
23 #include "CodeCompletionStrings.h"
24 #include "Compiler.h"
25 #include "Diagnostics.h"
26 #include "FileDistance.h"
27 #include "FuzzyMatch.h"
28 #include "Headers.h"
29 #include "Logger.h"
30 #include "Quality.h"
31 #include "SourceCode.h"
32 #include "Trace.h"
33 #include "URI.h"
34 #include "index/Index.h"
35 #include "clang/ASTMatchers/ASTMatchFinder.h"
36 #include "clang/Basic/LangOptions.h"
37 #include "clang/Basic/SourceLocation.h"
38 #include "clang/Format/Format.h"
39 #include "clang/Frontend/CompilerInstance.h"
40 #include "clang/Frontend/FrontendActions.h"
41 #include "clang/Index/USRGeneration.h"
42 #include "clang/Sema/CodeCompleteConsumer.h"
43 #include "clang/Sema/Sema.h"
44 #include "clang/Tooling/Core/Replacement.h"
45 #include "llvm/Support/Format.h"
46 #include "llvm/Support/FormatVariadic.h"
47 #include "llvm/Support/ScopedPrinter.h"
48 #include <queue>
49 
50 // We log detailed candidate here if you run with -debug-only=codecomplete.
51 #define DEBUG_TYPE "CodeComplete"
52 
53 namespace clang {
54 namespace clangd {
55 namespace {
56 
57 CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
58   using SK = index::SymbolKind;
59   switch (Kind) {
60   case SK::Unknown:
61     return CompletionItemKind::Missing;
62   case SK::Module:
63   case SK::Namespace:
64   case SK::NamespaceAlias:
65     return CompletionItemKind::Module;
66   case SK::Macro:
67     return CompletionItemKind::Text;
68   case SK::Enum:
69     return CompletionItemKind::Enum;
70   // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
71   // protocol.
72   case SK::Struct:
73   case SK::Class:
74   case SK::Protocol:
75   case SK::Extension:
76   case SK::Union:
77     return CompletionItemKind::Class;
78   // FIXME(ioeric): figure out whether reference is the right type for aliases.
79   case SK::TypeAlias:
80   case SK::Using:
81     return CompletionItemKind::Reference;
82   case SK::Function:
83   // FIXME(ioeric): this should probably be an operator. This should be fixed
84   // when `Operator` is support type in the protocol.
85   case SK::ConversionFunction:
86     return CompletionItemKind::Function;
87   case SK::Variable:
88   case SK::Parameter:
89     return CompletionItemKind::Variable;
90   case SK::Field:
91     return CompletionItemKind::Field;
92   // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
93   case SK::EnumConstant:
94     return CompletionItemKind::Value;
95   case SK::InstanceMethod:
96   case SK::ClassMethod:
97   case SK::StaticMethod:
98   case SK::Destructor:
99     return CompletionItemKind::Method;
100   case SK::InstanceProperty:
101   case SK::ClassProperty:
102   case SK::StaticProperty:
103     return CompletionItemKind::Property;
104   case SK::Constructor:
105     return CompletionItemKind::Constructor;
106   }
107   llvm_unreachable("Unhandled clang::index::SymbolKind.");
108 }
109 
110 CompletionItemKind
111 toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
112                      const NamedDecl *Decl) {
113   if (Decl)
114     return toCompletionItemKind(index::getSymbolInfo(Decl).Kind);
115   switch (ResKind) {
116   case CodeCompletionResult::RK_Declaration:
117     llvm_unreachable("RK_Declaration without Decl");
118   case CodeCompletionResult::RK_Keyword:
119     return CompletionItemKind::Keyword;
120   case CodeCompletionResult::RK_Macro:
121     return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
122                                      // completion items in LSP.
123   case CodeCompletionResult::RK_Pattern:
124     return CompletionItemKind::Snippet;
125   }
126   llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
127 }
128 
129 /// Get the optional chunk as a string. This function is possibly recursive.
130 ///
131 /// The parameter info for each parameter is appended to the Parameters.
132 std::string getOptionalParameters(const CodeCompletionString &CCS,
133                                   std::vector<ParameterInformation> &Parameters,
134                                   SignatureQualitySignals &Signal) {
135   std::string Result;
136   for (const auto &Chunk : CCS) {
137     switch (Chunk.Kind) {
138     case CodeCompletionString::CK_Optional:
139       assert(Chunk.Optional &&
140              "Expected the optional code completion string to be non-null.");
141       Result += getOptionalParameters(*Chunk.Optional, Parameters, Signal);
142       break;
143     case CodeCompletionString::CK_VerticalSpace:
144       break;
145     case CodeCompletionString::CK_Placeholder:
146       // A string that acts as a placeholder for, e.g., a function call
147       // argument.
148       // Intentional fallthrough here.
149     case CodeCompletionString::CK_CurrentParameter: {
150       // A piece of text that describes the parameter that corresponds to
151       // the code-completion location within a function call, message send,
152       // macro invocation, etc.
153       Result += Chunk.Text;
154       ParameterInformation Info;
155       Info.label = Chunk.Text;
156       Parameters.push_back(std::move(Info));
157       Signal.ContainsActiveParameter = true;
158       Signal.NumberOfOptionalParameters++;
159       break;
160     }
161     default:
162       Result += Chunk.Text;
163       break;
164     }
165   }
166   return Result;
167 }
168 
169 /// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
170 /// include.
171 static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
172                                                llvm::StringRef HintPath) {
173   if (isLiteralInclude(Header))
174     return HeaderFile{Header.str(), /*Verbatim=*/true};
175   auto U = URI::parse(Header);
176   if (!U)
177     return U.takeError();
178 
179   auto IncludePath = URI::includeSpelling(*U);
180   if (!IncludePath)
181     return IncludePath.takeError();
182   if (!IncludePath->empty())
183     return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
184 
185   auto Resolved = URI::resolve(*U, HintPath);
186   if (!Resolved)
187     return Resolved.takeError();
188   return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
189 }
190 
191 /// A code completion result, in clang-native form.
192 /// It may be promoted to a CompletionItem if it's among the top-ranked results.
193 struct CompletionCandidate {
194   llvm::StringRef Name; // Used for filtering and sorting.
195   // We may have a result from Sema, from the index, or both.
196   const CodeCompletionResult *SemaResult = nullptr;
197   const Symbol *IndexResult = nullptr;
198 
199   // Returns a token identifying the overload set this is part of.
200   // 0 indicates it's not part of any overload set.
201   size_t overloadSet() const {
202     SmallString<256> Scratch;
203     if (IndexResult) {
204       switch (IndexResult->SymInfo.Kind) {
205       case index::SymbolKind::ClassMethod:
206       case index::SymbolKind::InstanceMethod:
207       case index::SymbolKind::StaticMethod:
208         assert(false && "Don't expect members from index in code completion");
209         // fall through
210       case index::SymbolKind::Function:
211         // We can't group overloads together that need different #includes.
212         // This could break #include insertion.
213         return hash_combine(
214             (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
215             headerToInsertIfNotPresent().getValueOr(""));
216       default:
217         return 0;
218       }
219     }
220     assert(SemaResult);
221     // We need to make sure we're consistent with the IndexResult case!
222     const NamedDecl *D = SemaResult->Declaration;
223     if (!D || !D->isFunctionOrFunctionTemplate())
224       return 0;
225     {
226       llvm::raw_svector_ostream OS(Scratch);
227       D->printQualifiedName(OS);
228     }
229     return hash_combine(Scratch, headerToInsertIfNotPresent().getValueOr(""));
230   }
231 
232   llvm::Optional<llvm::StringRef> headerToInsertIfNotPresent() const {
233     if (!IndexResult || !IndexResult->Detail ||
234         IndexResult->Detail->IncludeHeader.empty())
235       return llvm::None;
236     if (SemaResult && SemaResult->Declaration) {
237       // Avoid inserting new #include if the declaration is found in the current
238       // file e.g. the symbol is forward declared.
239       auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
240       for (const Decl *RD : SemaResult->Declaration->redecls())
241         if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
242           return llvm::None;
243     }
244     return IndexResult->Detail->IncludeHeader;
245   }
246 
247   using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
248 };
249 using ScoredBundle =
250     std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
251 struct ScoredBundleGreater {
252   bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
253     if (L.second.Total != R.second.Total)
254       return L.second.Total > R.second.Total;
255     return L.first.front().Name <
256            R.first.front().Name; // Earlier name is better.
257   }
258 };
259 
260 // Assembles a code completion out of a bundle of >=1 completion candidates.
261 // Many of the expensive strings are only computed at this point, once we know
262 // the candidate bundle is going to be returned.
263 //
264 // Many fields are the same for all candidates in a bundle (e.g. name), and are
265 // computed from the first candidate, in the constructor.
266 // Others vary per candidate, so add() must be called for remaining candidates.
267 struct CodeCompletionBuilder {
268   CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
269                         CodeCompletionString *SemaCCS,
270                         const IncludeInserter &Includes, StringRef FileName,
271                         const CodeCompleteOptions &Opts)
272       : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments) {
273     add(C, SemaCCS);
274     if (C.SemaResult) {
275       Completion.Origin |= SymbolOrigin::AST;
276       Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
277       if (Completion.Scope.empty()) {
278         if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
279             (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
280           if (const auto *D = C.SemaResult->getDeclaration())
281             if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
282               Completion.Scope =
283                   splitQualifiedName(printQualifiedName(*ND)).first;
284       }
285       Completion.Kind =
286           toCompletionItemKind(C.SemaResult->Kind, C.SemaResult->Declaration);
287       for (const auto &FixIt : C.SemaResult->FixIts) {
288         Completion.FixIts.push_back(
289             toTextEdit(FixIt, ASTCtx.getSourceManager(), ASTCtx.getLangOpts()));
290       }
291       std::sort(Completion.FixIts.begin(), Completion.FixIts.end(),
292                 [](const TextEdit &X, const TextEdit &Y) {
293                   return std::tie(X.range.start.line, X.range.start.character) <
294                          std::tie(Y.range.start.line, Y.range.start.character);
295                 });
296     }
297     if (C.IndexResult) {
298       Completion.Origin |= C.IndexResult->Origin;
299       if (Completion.Scope.empty())
300         Completion.Scope = C.IndexResult->Scope;
301       if (Completion.Kind == CompletionItemKind::Missing)
302         Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
303       if (Completion.Name.empty())
304         Completion.Name = C.IndexResult->Name;
305     }
306     if (auto Inserted = C.headerToInsertIfNotPresent()) {
307       // Turn absolute path into a literal string that can be #included.
308       auto Include = [&]() -> Expected<std::pair<std::string, bool>> {
309         auto ResolvedDeclaring =
310             toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
311         if (!ResolvedDeclaring)
312           return ResolvedDeclaring.takeError();
313         auto ResolvedInserted = toHeaderFile(*Inserted, FileName);
314         if (!ResolvedInserted)
315           return ResolvedInserted.takeError();
316         return std::make_pair(Includes.calculateIncludePath(*ResolvedDeclaring,
317                                                             *ResolvedInserted),
318                               Includes.shouldInsertInclude(*ResolvedDeclaring,
319                                                            *ResolvedInserted));
320       }();
321       if (Include) {
322         Completion.Header = Include->first;
323         if (Include->second)
324           Completion.HeaderInsertion = Includes.insert(Include->first);
325       } else
326         log("Failed to generate include insertion edits for adding header "
327             "(FileURI='{0}', IncludeHeader='{1}') into {2}",
328             C.IndexResult->CanonicalDeclaration.FileURI,
329             C.IndexResult->Detail->IncludeHeader, FileName);
330     }
331   }
332 
333   void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {
334     assert(bool(C.SemaResult) == bool(SemaCCS));
335     Bundled.emplace_back();
336     BundledEntry &S = Bundled.back();
337     if (C.SemaResult) {
338       getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
339                    &Completion.RequiredQualifier);
340       S.ReturnType = getReturnType(*SemaCCS);
341     } else if (C.IndexResult) {
342       S.Signature = C.IndexResult->Signature;
343       S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix;
344       if (auto *D = C.IndexResult->Detail)
345         S.ReturnType = D->ReturnType;
346     }
347     if (ExtractDocumentation && Completion.Documentation.empty()) {
348       if (C.IndexResult && C.IndexResult->Detail)
349         Completion.Documentation = C.IndexResult->Detail->Documentation;
350       else if (C.SemaResult)
351         Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
352                                                  /*CommentsFromHeader=*/false);
353     }
354   }
355 
356   CodeCompletion build() {
357     Completion.ReturnType = summarizeReturnType();
358     Completion.Signature = summarizeSignature();
359     Completion.SnippetSuffix = summarizeSnippet();
360     Completion.BundleSize = Bundled.size();
361     return std::move(Completion);
362   }
363 
364 private:
365   struct BundledEntry {
366     std::string SnippetSuffix;
367     std::string Signature;
368     std::string ReturnType;
369   };
370 
371   // If all BundledEntrys have the same value for a property, return it.
372   template <std::string BundledEntry::*Member>
373   const std::string *onlyValue() const {
374     auto B = Bundled.begin(), E = Bundled.end();
375     for (auto I = B + 1; I != E; ++I)
376       if (I->*Member != B->*Member)
377         return nullptr;
378     return &(B->*Member);
379   }
380 
381   std::string summarizeReturnType() const {
382     if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
383       return *RT;
384     return "";
385   }
386 
387   std::string summarizeSnippet() const {
388     if (auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>())
389       return *Snippet;
390     // All bundles are function calls.
391     return "(${0})";
392   }
393 
394   std::string summarizeSignature() const {
395     if (auto *Signature = onlyValue<&BundledEntry::Signature>())
396       return *Signature;
397     // All bundles are function calls.
398     return "(…)";
399   }
400 
401   ASTContext &ASTCtx;
402   CodeCompletion Completion;
403   SmallVector<BundledEntry, 1> Bundled;
404   bool ExtractDocumentation;
405 };
406 
407 // Determine the symbol ID for a Sema code completion result, if possible.
408 llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
409   switch (R.Kind) {
410   case CodeCompletionResult::RK_Declaration:
411   case CodeCompletionResult::RK_Pattern: {
412     return clang::clangd::getSymbolID(R.Declaration);
413   }
414   case CodeCompletionResult::RK_Macro:
415     // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
416   case CodeCompletionResult::RK_Keyword:
417     return None;
418   }
419   llvm_unreachable("unknown CodeCompletionResult kind");
420 }
421 
422 // Scopes of the paritial identifier we're trying to complete.
423 // It is used when we query the index for more completion results.
424 struct SpecifiedScope {
425   // The scopes we should look in, determined by Sema.
426   //
427   // If the qualifier was fully resolved, we look for completions in these
428   // scopes; if there is an unresolved part of the qualifier, it should be
429   // resolved within these scopes.
430   //
431   // Examples of qualified completion:
432   //
433   //   "::vec"                                      => {""}
434   //   "using namespace std; ::vec^"                => {"", "std::"}
435   //   "namespace ns {using namespace std;} ns::^"  => {"ns::", "std::"}
436   //   "std::vec^"                                  => {""}  // "std" unresolved
437   //
438   // Examples of unqualified completion:
439   //
440   //   "vec^"                                       => {""}
441   //   "using namespace std; vec^"                  => {"", "std::"}
442   //   "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
443   //
444   // "" for global namespace, "ns::" for normal namespace.
445   std::vector<std::string> AccessibleScopes;
446   // The full scope qualifier as typed by the user (without the leading "::").
447   // Set if the qualifier is not fully resolved by Sema.
448   llvm::Optional<std::string> UnresolvedQualifier;
449 
450   // Construct scopes being queried in indexes.
451   // This method format the scopes to match the index request representation.
452   std::vector<std::string> scopesForIndexQuery() {
453     std::vector<std::string> Results;
454     for (llvm::StringRef AS : AccessibleScopes) {
455       Results.push_back(AS);
456       if (UnresolvedQualifier)
457         Results.back() += *UnresolvedQualifier;
458     }
459     return Results;
460   }
461 };
462 
463 // Get all scopes that will be queried in indexes.
464 std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
465                                         const SourceManager &SM) {
466   auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
467     SpecifiedScope Info;
468     for (auto *Context : CCContext.getVisitedContexts()) {
469       if (isa<TranslationUnitDecl>(Context))
470         Info.AccessibleScopes.push_back(""); // global namespace
471       else if (const auto *NS = dyn_cast<NamespaceDecl>(Context))
472         Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
473     }
474     return Info;
475   };
476 
477   auto SS = CCContext.getCXXScopeSpecifier();
478 
479   // Unqualified completion (e.g. "vec^").
480   if (!SS) {
481     // FIXME: Once we can insert namespace qualifiers and use the in-scope
482     //        namespaces for scoring, search in all namespaces.
483     // FIXME: Capture scopes and use for scoring, for example,
484     //        "using namespace std; namespace foo {v^}" =>
485     //        foo::value > std::vector > boost::variant
486     return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
487   }
488 
489   // Qualified completion ("std::vec^"), we have two cases depending on whether
490   // the qualifier can be resolved by Sema.
491   if ((*SS)->isValid()) { // Resolved qualifier.
492     return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
493   }
494 
495   // Unresolved qualifier.
496   // FIXME: When Sema can resolve part of a scope chain (e.g.
497   // "known::unknown::id"), we should expand the known part ("known::") rather
498   // than treating the whole thing as unknown.
499   SpecifiedScope Info;
500   Info.AccessibleScopes.push_back(""); // global namespace
501 
502   Info.UnresolvedQualifier =
503       Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM,
504                            clang::LangOptions())
505           .ltrim("::");
506   // Sema excludes the trailing "::".
507   if (!Info.UnresolvedQualifier->empty())
508     *Info.UnresolvedQualifier += "::";
509 
510   return Info.scopesForIndexQuery();
511 }
512 
513 // Should we perform index-based completion in a context of the specified kind?
514 // FIXME: consider allowing completion, but restricting the result types.
515 bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
516   switch (K) {
517   case CodeCompletionContext::CCC_TopLevel:
518   case CodeCompletionContext::CCC_ObjCInterface:
519   case CodeCompletionContext::CCC_ObjCImplementation:
520   case CodeCompletionContext::CCC_ObjCIvarList:
521   case CodeCompletionContext::CCC_ClassStructUnion:
522   case CodeCompletionContext::CCC_Statement:
523   case CodeCompletionContext::CCC_Expression:
524   case CodeCompletionContext::CCC_ObjCMessageReceiver:
525   case CodeCompletionContext::CCC_EnumTag:
526   case CodeCompletionContext::CCC_UnionTag:
527   case CodeCompletionContext::CCC_ClassOrStructTag:
528   case CodeCompletionContext::CCC_ObjCProtocolName:
529   case CodeCompletionContext::CCC_Namespace:
530   case CodeCompletionContext::CCC_Type:
531   case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
532   case CodeCompletionContext::CCC_PotentiallyQualifiedName:
533   case CodeCompletionContext::CCC_ParenthesizedExpression:
534   case CodeCompletionContext::CCC_ObjCInterfaceName:
535   case CodeCompletionContext::CCC_ObjCCategoryName:
536     return true;
537   case CodeCompletionContext::CCC_Other: // Be conservative.
538   case CodeCompletionContext::CCC_OtherWithMacros:
539   case CodeCompletionContext::CCC_DotMemberAccess:
540   case CodeCompletionContext::CCC_ArrowMemberAccess:
541   case CodeCompletionContext::CCC_ObjCPropertyAccess:
542   case CodeCompletionContext::CCC_MacroName:
543   case CodeCompletionContext::CCC_MacroNameUse:
544   case CodeCompletionContext::CCC_PreprocessorExpression:
545   case CodeCompletionContext::CCC_PreprocessorDirective:
546   case CodeCompletionContext::CCC_NaturalLanguage:
547   case CodeCompletionContext::CCC_SelectorName:
548   case CodeCompletionContext::CCC_TypeQualifiers:
549   case CodeCompletionContext::CCC_ObjCInstanceMessage:
550   case CodeCompletionContext::CCC_ObjCClassMessage:
551   case CodeCompletionContext::CCC_Recovery:
552     return false;
553   }
554   llvm_unreachable("unknown code completion context");
555 }
556 
557 // Some member calls are blacklisted because they're so rarely useful.
558 static bool isBlacklistedMember(const NamedDecl &D) {
559   // Destructor completion is rarely useful, and works inconsistently.
560   // (s.^ completes ~string, but s.~st^ is an error).
561   if (D.getKind() == Decl::CXXDestructor)
562     return true;
563   // Injected name may be useful for A::foo(), but who writes A::A::foo()?
564   if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
565     if (R->isInjectedClassName())
566       return true;
567   // Explicit calls to operators are also rare.
568   auto NameKind = D.getDeclName().getNameKind();
569   if (NameKind == DeclarationName::CXXOperatorName ||
570       NameKind == DeclarationName::CXXLiteralOperatorName ||
571       NameKind == DeclarationName::CXXConversionFunctionName)
572     return true;
573   return false;
574 }
575 
576 // The CompletionRecorder captures Sema code-complete output, including context.
577 // It filters out ignored results (but doesn't apply fuzzy-filtering yet).
578 // It doesn't do scoring or conversion to CompletionItem yet, as we want to
579 // merge with index results first.
580 // Generally the fields and methods of this object should only be used from
581 // within the callback.
582 struct CompletionRecorder : public CodeCompleteConsumer {
583   CompletionRecorder(const CodeCompleteOptions &Opts,
584                      llvm::unique_function<void()> ResultsCallback)
585       : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
586                              /*OutputIsBinary=*/false),
587         CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
588         CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
589         CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
590     assert(this->ResultsCallback);
591   }
592 
593   std::vector<CodeCompletionResult> Results;
594   CodeCompletionContext CCContext;
595   Sema *CCSema = nullptr; // Sema that created the results.
596   // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
597 
598   void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
599                                   CodeCompletionResult *InResults,
600                                   unsigned NumResults) override final {
601     // Results from recovery mode are generally useless, and the callback after
602     // recovery (if any) is usually more interesting. To make sure we handle the
603     // future callback from sema, we just ignore all callbacks in recovery mode,
604     // as taking only results from recovery mode results in poor completion
605     // results.
606     // FIXME: in case there is no future sema completion callback after the
607     // recovery mode, we might still want to provide some results (e.g. trivial
608     // identifier-based completion).
609     if (Context.getKind() == CodeCompletionContext::CCC_Recovery) {
610       log("Code complete: Ignoring sema code complete callback with Recovery "
611           "context.");
612       return;
613     }
614     // If a callback is called without any sema result and the context does not
615     // support index-based completion, we simply skip it to give way to
616     // potential future callbacks with results.
617     if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
618       return;
619     if (CCSema) {
620       log("Multiple code complete callbacks (parser backtracked?). "
621           "Dropping results from context {0}, keeping results from {1}.",
622           getCompletionKindString(Context.getKind()),
623           getCompletionKindString(this->CCContext.getKind()));
624       return;
625     }
626     // Record the completion context.
627     CCSema = &S;
628     CCContext = Context;
629 
630     // Retain the results we might want.
631     for (unsigned I = 0; I < NumResults; ++I) {
632       auto &Result = InResults[I];
633       // Drop hidden items which cannot be found by lookup after completion.
634       // Exception: some items can be named by using a qualifier.
635       if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
636         continue;
637       if (!Opts.IncludeIneligibleResults &&
638           (Result.Availability == CXAvailability_NotAvailable ||
639            Result.Availability == CXAvailability_NotAccessible))
640         continue;
641       if (Result.Declaration &&
642           !Context.getBaseType().isNull() // is this a member-access context?
643           && isBlacklistedMember(*Result.Declaration))
644         continue;
645       // We choose to never append '::' to completion results in clangd.
646       Result.StartsNestedNameSpecifier = false;
647       Results.push_back(Result);
648     }
649     ResultsCallback();
650   }
651 
652   CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
653   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
654 
655   // Returns the filtering/sorting name for Result, which must be from Results.
656   // Returned string is owned by this recorder (or the AST).
657   llvm::StringRef getName(const CodeCompletionResult &Result) {
658     switch (Result.Kind) {
659     case CodeCompletionResult::RK_Declaration:
660       if (auto *ID = Result.Declaration->getIdentifier())
661         return ID->getName();
662       break;
663     case CodeCompletionResult::RK_Keyword:
664       return Result.Keyword;
665     case CodeCompletionResult::RK_Macro:
666       return Result.Macro->getName();
667     case CodeCompletionResult::RK_Pattern:
668       return Result.Pattern->getTypedText();
669     }
670     auto *CCS = codeCompletionString(Result);
671     return CCS->getTypedText();
672   }
673 
674   // Build a CodeCompletion string for R, which must be from Results.
675   // The CCS will be owned by this recorder.
676   CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
677     // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
678     return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
679         *CCSema, CCContext, *CCAllocator, CCTUInfo,
680         /*IncludeBriefComments=*/false);
681   }
682 
683 private:
684   CodeCompleteOptions Opts;
685   std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
686   CodeCompletionTUInfo CCTUInfo;
687   llvm::unique_function<void()> ResultsCallback;
688 };
689 
690 struct ScoredSignature {
691   // When set, requires documentation to be requested from the index with this
692   // ID.
693   llvm::Optional<SymbolID> IDForDoc;
694   SignatureInformation Signature;
695   SignatureQualitySignals Quality;
696 };
697 
698 class SignatureHelpCollector final : public CodeCompleteConsumer {
699 public:
700   SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
701                          SymbolIndex *Index, SignatureHelp &SigHelp)
702       : CodeCompleteConsumer(CodeCompleteOpts,
703                              /*OutputIsBinary=*/false),
704         SigHelp(SigHelp),
705         Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
706         CCTUInfo(Allocator), Index(Index) {}
707 
708   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
709                                  OverloadCandidate *Candidates,
710                                  unsigned NumCandidates) override {
711     std::vector<ScoredSignature> ScoredSignatures;
712     SigHelp.signatures.reserve(NumCandidates);
713     ScoredSignatures.reserve(NumCandidates);
714     // FIXME(rwols): How can we determine the "active overload candidate"?
715     // Right now the overloaded candidates seem to be provided in a "best fit"
716     // order, so I'm not too worried about this.
717     SigHelp.activeSignature = 0;
718     assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
719            "too many arguments");
720     SigHelp.activeParameter = static_cast<int>(CurrentArg);
721     for (unsigned I = 0; I < NumCandidates; ++I) {
722       OverloadCandidate Candidate = Candidates[I];
723       // We want to avoid showing instantiated signatures, because they may be
724       // long in some cases (e.g. when 'T' is substituted with 'std::string', we
725       // would get 'std::basic_string<char>').
726       if (auto *Func = Candidate.getFunction()) {
727         if (auto *Pattern = Func->getTemplateInstantiationPattern())
728           Candidate = OverloadCandidate(Pattern);
729       }
730 
731       const auto *CCS = Candidate.CreateSignatureString(
732           CurrentArg, S, *Allocator, CCTUInfo, true);
733       assert(CCS && "Expected the CodeCompletionString to be non-null");
734       ScoredSignatures.push_back(processOverloadCandidate(
735           Candidate, *CCS,
736           Candidate.getFunction()
737               ? getDeclComment(S.getASTContext(), *Candidate.getFunction())
738               : ""));
739     }
740 
741     // Sema does not load the docs from the preamble, so we need to fetch extra
742     // docs from the index instead.
743     llvm::DenseMap<SymbolID, std::string> FetchedDocs;
744     if (Index) {
745       LookupRequest IndexRequest;
746       for (const auto &S : ScoredSignatures) {
747         if (!S.IDForDoc)
748           continue;
749         IndexRequest.IDs.insert(*S.IDForDoc);
750       }
751       Index->lookup(IndexRequest, [&](const Symbol &S) {
752         if (!S.Detail || S.Detail->Documentation.empty())
753           return;
754         FetchedDocs[S.ID] = S.Detail->Documentation;
755       });
756       log("SigHelp: requested docs for {0} symbols from the index, got {1} "
757           "symbols with non-empty docs in the response",
758           IndexRequest.IDs.size(), FetchedDocs.size());
759     }
760 
761     std::sort(
762         ScoredSignatures.begin(), ScoredSignatures.end(),
763         [](const ScoredSignature &L, const ScoredSignature &R) {
764           // Ordering follows:
765           // - Less number of parameters is better.
766           // - Function is better than FunctionType which is better than
767           // Function Template.
768           // - High score is better.
769           // - Shorter signature is better.
770           // - Alphebatically smaller is better.
771           if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
772             return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
773           if (L.Quality.NumberOfOptionalParameters !=
774               R.Quality.NumberOfOptionalParameters)
775             return L.Quality.NumberOfOptionalParameters <
776                    R.Quality.NumberOfOptionalParameters;
777           if (L.Quality.Kind != R.Quality.Kind) {
778             using OC = CodeCompleteConsumer::OverloadCandidate;
779             switch (L.Quality.Kind) {
780             case OC::CK_Function:
781               return true;
782             case OC::CK_FunctionType:
783               return R.Quality.Kind != OC::CK_Function;
784             case OC::CK_FunctionTemplate:
785               return false;
786             }
787             llvm_unreachable("Unknown overload candidate type.");
788           }
789           if (L.Signature.label.size() != R.Signature.label.size())
790             return L.Signature.label.size() < R.Signature.label.size();
791           return L.Signature.label < R.Signature.label;
792         });
793 
794     for (auto &SS : ScoredSignatures) {
795       auto IndexDocIt =
796           SS.IDForDoc ? FetchedDocs.find(*SS.IDForDoc) : FetchedDocs.end();
797       if (IndexDocIt != FetchedDocs.end())
798         SS.Signature.documentation = IndexDocIt->second;
799 
800       SigHelp.signatures.push_back(std::move(SS.Signature));
801     }
802   }
803 
804   GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
805 
806   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
807 
808 private:
809   // FIXME(ioeric): consider moving CodeCompletionString logic here to
810   // CompletionString.h.
811   ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
812                                            const CodeCompletionString &CCS,
813                                            llvm::StringRef DocComment) const {
814     SignatureInformation Signature;
815     SignatureQualitySignals Signal;
816     const char *ReturnType = nullptr;
817 
818     Signature.documentation = formatDocumentation(CCS, DocComment);
819     Signal.Kind = Candidate.getKind();
820 
821     for (const auto &Chunk : CCS) {
822       switch (Chunk.Kind) {
823       case CodeCompletionString::CK_ResultType:
824         // A piece of text that describes the type of an entity or,
825         // for functions and methods, the return type.
826         assert(!ReturnType && "Unexpected CK_ResultType");
827         ReturnType = Chunk.Text;
828         break;
829       case CodeCompletionString::CK_Placeholder:
830         // A string that acts as a placeholder for, e.g., a function call
831         // argument.
832         // Intentional fallthrough here.
833       case CodeCompletionString::CK_CurrentParameter: {
834         // A piece of text that describes the parameter that corresponds to
835         // the code-completion location within a function call, message send,
836         // macro invocation, etc.
837         Signature.label += Chunk.Text;
838         ParameterInformation Info;
839         Info.label = Chunk.Text;
840         Signature.parameters.push_back(std::move(Info));
841         Signal.NumberOfParameters++;
842         Signal.ContainsActiveParameter = true;
843         break;
844       }
845       case CodeCompletionString::CK_Optional: {
846         // The rest of the parameters are defaulted/optional.
847         assert(Chunk.Optional &&
848                "Expected the optional code completion string to be non-null.");
849         Signature.label += getOptionalParameters(*Chunk.Optional,
850                                                  Signature.parameters, Signal);
851         break;
852       }
853       case CodeCompletionString::CK_VerticalSpace:
854         break;
855       default:
856         Signature.label += Chunk.Text;
857         break;
858       }
859     }
860     if (ReturnType) {
861       Signature.label += " -> ";
862       Signature.label += ReturnType;
863     }
864     dlog("Signal for {0}: {1}", Signature, Signal);
865     ScoredSignature Result;
866     Result.Signature = std::move(Signature);
867     Result.Quality = Signal;
868     Result.IDForDoc =
869         Result.Signature.documentation.empty() && Candidate.getFunction()
870             ? clangd::getSymbolID(Candidate.getFunction())
871             : llvm::None;
872     return Result;
873   }
874 
875   SignatureHelp &SigHelp;
876   std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
877   CodeCompletionTUInfo CCTUInfo;
878   const SymbolIndex *Index;
879 }; // SignatureHelpCollector
880 
881 struct SemaCompleteInput {
882   PathRef FileName;
883   const tooling::CompileCommand &Command;
884   PrecompiledPreamble const *Preamble;
885   StringRef Contents;
886   Position Pos;
887   IntrusiveRefCntPtr<vfs::FileSystem> VFS;
888   std::shared_ptr<PCHContainerOperations> PCHs;
889 };
890 
891 // Invokes Sema code completion on a file.
892 // If \p Includes is set, it will be updated based on the compiler invocation.
893 bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
894                       const clang::CodeCompleteOptions &Options,
895                       const SemaCompleteInput &Input,
896                       IncludeStructure *Includes = nullptr) {
897   trace::Span Tracer("Sema completion");
898   std::vector<const char *> ArgStrs;
899   for (const auto &S : Input.Command.CommandLine)
900     ArgStrs.push_back(S.c_str());
901 
902   if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
903     log("Couldn't set working directory");
904     // We run parsing anyway, our lit-tests rely on results for non-existing
905     // working dirs.
906   }
907 
908   IgnoreDiagnostics DummyDiagsConsumer;
909   auto CI = createInvocationFromCommandLine(
910       ArgStrs,
911       CompilerInstance::createDiagnostics(new DiagnosticOptions,
912                                           &DummyDiagsConsumer, false),
913       Input.VFS);
914   if (!CI) {
915     elog("Couldn't create CompilerInvocation");
916     return false;
917   }
918   auto &FrontendOpts = CI->getFrontendOpts();
919   FrontendOpts.DisableFree = false;
920   FrontendOpts.SkipFunctionBodies = true;
921   CI->getLangOpts()->CommentOpts.ParseAllComments = true;
922   // Disable typo correction in Sema.
923   CI->getLangOpts()->SpellChecking = false;
924   // Setup code completion.
925   FrontendOpts.CodeCompleteOpts = Options;
926   FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
927   auto Offset = positionToOffset(Input.Contents, Input.Pos);
928   if (!Offset) {
929     elog("Code completion position was invalid {0}", Offset.takeError());
930     return false;
931   }
932   std::tie(FrontendOpts.CodeCompletionAt.Line,
933            FrontendOpts.CodeCompletionAt.Column) =
934       offsetToClangLineColumn(Input.Contents, *Offset);
935 
936   std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
937       llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
938   // The diagnostic options must be set before creating a CompilerInstance.
939   CI->getDiagnosticOpts().IgnoreWarnings = true;
940   // We reuse the preamble whether it's valid or not. This is a
941   // correctness/performance tradeoff: building without a preamble is slow, and
942   // completion is latency-sensitive.
943   // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
944   // the remapped buffers do not get freed.
945   auto Clang = prepareCompilerInstance(
946       std::move(CI), Input.Preamble, std::move(ContentsBuffer),
947       std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
948   Clang->setCodeCompletionConsumer(Consumer.release());
949 
950   SyntaxOnlyAction Action;
951   if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
952     log("BeginSourceFile() failed when running codeComplete for {0}",
953         Input.FileName);
954     return false;
955   }
956   if (Includes)
957     Clang->getPreprocessor().addPPCallbacks(
958         collectIncludeStructureCallback(Clang->getSourceManager(), Includes));
959   if (!Action.Execute()) {
960     log("Execute() failed when running codeComplete for {0}", Input.FileName);
961     return false;
962   }
963   Action.EndSourceFile();
964 
965   return true;
966 }
967 
968 // Should we allow index completions in the specified context?
969 bool allowIndex(CodeCompletionContext &CC) {
970   if (!contextAllowsIndex(CC.getKind()))
971     return false;
972   // We also avoid ClassName::bar (but allow namespace::bar).
973   auto Scope = CC.getCXXScopeSpecifier();
974   if (!Scope)
975     return true;
976   NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
977   if (!NameSpec)
978     return true;
979   // We only query the index when qualifier is a namespace.
980   // If it's a class, we rely solely on sema completions.
981   switch (NameSpec->getKind()) {
982   case NestedNameSpecifier::Global:
983   case NestedNameSpecifier::Namespace:
984   case NestedNameSpecifier::NamespaceAlias:
985     return true;
986   case NestedNameSpecifier::Super:
987   case NestedNameSpecifier::TypeSpec:
988   case NestedNameSpecifier::TypeSpecWithTemplate:
989   // Unresolved inside a template.
990   case NestedNameSpecifier::Identifier:
991     return false;
992   }
993   llvm_unreachable("invalid NestedNameSpecifier kind");
994 }
995 
996 } // namespace
997 
998 clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
999   clang::CodeCompleteOptions Result;
1000   Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
1001   Result.IncludeMacros = IncludeMacros;
1002   Result.IncludeGlobals = true;
1003   // We choose to include full comments and not do doxygen parsing in
1004   // completion.
1005   // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
1006   // formatting of the comments.
1007   Result.IncludeBriefComments = false;
1008 
1009   // When an is used, Sema is responsible for completing the main file,
1010   // the index can provide results from the preamble.
1011   // Tell Sema not to deserialize the preamble to look for results.
1012   Result.LoadExternal = !Index;
1013   Result.IncludeFixIts = IncludeFixIts;
1014 
1015   return Result;
1016 }
1017 
1018 // Runs Sema-based (AST) and Index-based completion, returns merged results.
1019 //
1020 // There are a few tricky considerations:
1021 //   - the AST provides information needed for the index query (e.g. which
1022 //     namespaces to search in). So Sema must start first.
1023 //   - we only want to return the top results (Opts.Limit).
1024 //     Building CompletionItems for everything else is wasteful, so we want to
1025 //     preserve the "native" format until we're done with scoring.
1026 //   - the data underlying Sema completion items is owned by the AST and various
1027 //     other arenas, which must stay alive for us to build CompletionItems.
1028 //   - we may get duplicate results from Sema and the Index, we need to merge.
1029 //
1030 // So we start Sema completion first, and do all our work in its callback.
1031 // We use the Sema context information to query the index.
1032 // Then we merge the two result sets, producing items that are Sema/Index/Both.
1033 // These items are scored, and the top N are synthesized into the LSP response.
1034 // Finally, we can clean up the data structures created by Sema completion.
1035 //
1036 // Main collaborators are:
1037 //   - semaCodeComplete sets up the compiler machinery to run code completion.
1038 //   - CompletionRecorder captures Sema completion results, including context.
1039 //   - SymbolIndex (Opts.Index) provides index completion results as Symbols
1040 //   - CompletionCandidates are the result of merging Sema and Index results.
1041 //     Each candidate points to an underlying CodeCompletionResult (Sema), a
1042 //     Symbol (Index), or both. It computes the result quality score.
1043 //     CompletionCandidate also does conversion to CompletionItem (at the end).
1044 //   - FuzzyMatcher scores how the candidate matches the partial identifier.
1045 //     This score is combined with the result quality score for the final score.
1046 //   - TopN determines the results with the best score.
1047 class CodeCompleteFlow {
1048   PathRef FileName;
1049   IncludeStructure Includes; // Complete once the compiler runs.
1050   const CodeCompleteOptions &Opts;
1051   // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
1052   CompletionRecorder *Recorder = nullptr;
1053   int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
1054   bool Incomplete = false; // Would more be available with a higher limit?
1055   llvm::Optional<FuzzyMatcher> Filter;       // Initialized once Sema runs.
1056   std::vector<std::string> QueryScopes;      // Initialized once Sema runs.
1057   // Include-insertion and proximity scoring rely on the include structure.
1058   // This is available after Sema has run.
1059   llvm::Optional<IncludeInserter> Inserter;  // Available during runWithSema.
1060   llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
1061 
1062 public:
1063   // A CodeCompleteFlow object is only useful for calling run() exactly once.
1064   CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
1065                    const CodeCompleteOptions &Opts)
1066       : FileName(FileName), Includes(Includes), Opts(Opts) {}
1067 
1068   CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
1069     trace::Span Tracer("CodeCompleteFlow");
1070 
1071     // We run Sema code completion first. It builds an AST and calculates:
1072     //   - completion results based on the AST.
1073     //   - partial identifier and context. We need these for the index query.
1074     CodeCompleteResult Output;
1075     auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
1076       assert(Recorder && "Recorder is not set");
1077       auto Style =
1078           format::getStyle(format::DefaultFormatStyle, SemaCCInput.FileName,
1079                            format::DefaultFallbackStyle, SemaCCInput.Contents,
1080                            SemaCCInput.VFS.get());
1081       if (!Style) {
1082         log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.",
1083             SemaCCInput.FileName, Style.takeError());
1084         Style = format::getLLVMStyle();
1085       }
1086       // If preprocessor was run, inclusions from preprocessor callback should
1087       // already be added to Includes.
1088       Inserter.emplace(
1089           SemaCCInput.FileName, SemaCCInput.Contents, *Style,
1090           SemaCCInput.Command.Directory,
1091           Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
1092       for (const auto &Inc : Includes.MainFileIncludes)
1093         Inserter->addExisting(Inc);
1094 
1095       // Most of the cost of file proximity is in initializing the FileDistance
1096       // structures based on the observed includes, once per query. Conceptually
1097       // that happens here (though the per-URI-scheme initialization is lazy).
1098       // The per-result proximity scoring is (amortized) very cheap.
1099       FileDistanceOptions ProxOpts{}; // Use defaults.
1100       const auto &SM = Recorder->CCSema->getSourceManager();
1101       llvm::StringMap<SourceParams> ProxSources;
1102       for (auto &Entry : Includes.includeDepth(
1103                SM.getFileEntryForID(SM.getMainFileID())->getName())) {
1104         auto &Source = ProxSources[Entry.getKey()];
1105         Source.Cost = Entry.getValue() * ProxOpts.IncludeCost;
1106         // Symbols near our transitive includes are good, but only consider
1107         // things in the same directory or below it. Otherwise there can be
1108         // many false positives.
1109         if (Entry.getValue() > 0)
1110           Source.MaxUpTraversals = 1;
1111       }
1112       FileProximity.emplace(ProxSources, ProxOpts);
1113 
1114       Output = runWithSema();
1115       Inserter.reset(); // Make sure this doesn't out-live Clang.
1116       SPAN_ATTACH(Tracer, "sema_completion_kind",
1117                   getCompletionKindString(Recorder->CCContext.getKind()));
1118       log("Code complete: sema context {0}, query scopes [{1}]",
1119           getCompletionKindString(Recorder->CCContext.getKind()),
1120           llvm::join(QueryScopes.begin(), QueryScopes.end(), ","));
1121     });
1122 
1123     Recorder = RecorderOwner.get();
1124     semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1125                      SemaCCInput, &Includes);
1126 
1127     SPAN_ATTACH(Tracer, "sema_results", NSema);
1128     SPAN_ATTACH(Tracer, "index_results", NIndex);
1129     SPAN_ATTACH(Tracer, "merged_results", NBoth);
1130     SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
1131     SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
1132     log("Code complete: {0} results from Sema, {1} from Index, "
1133         "{2} matched, {3} returned{4}.",
1134         NSema, NIndex, NBoth, Output.Completions.size(),
1135         Output.HasMore ? " (incomplete)" : "");
1136     assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1137     // We don't assert that isIncomplete means we hit a limit.
1138     // Indexes may choose to impose their own limits even if we don't have one.
1139     return Output;
1140   }
1141 
1142 private:
1143   // This is called by run() once Sema code completion is done, but before the
1144   // Sema data structures are torn down. It does all the real work.
1145   CodeCompleteResult runWithSema() {
1146     const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1147         Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1148     Range TextEditRange;
1149     // When we are getting completions with an empty identifier, for example
1150     //    std::vector<int> asdf;
1151     //    asdf.^;
1152     // Then the range will be invalid and we will be doing insertion, use
1153     // current cursor position in such cases as range.
1154     if (CodeCompletionRange.isValid()) {
1155       TextEditRange = halfOpenToRange(Recorder->CCSema->getSourceManager(),
1156                                       CodeCompletionRange);
1157     } else {
1158       const auto &Pos = sourceLocToPosition(
1159           Recorder->CCSema->getSourceManager(),
1160           Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1161       TextEditRange.start = TextEditRange.end = Pos;
1162     }
1163     Filter = FuzzyMatcher(
1164         Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1165     QueryScopes = getQueryScopes(Recorder->CCContext,
1166                                  Recorder->CCSema->getSourceManager());
1167     // Sema provides the needed context to query the index.
1168     // FIXME: in addition to querying for extra/overlapping symbols, we should
1169     //        explicitly request symbols corresponding to Sema results.
1170     //        We can use their signals even if the index can't suggest them.
1171     // We must copy index results to preserve them, but there are at most Limit.
1172     auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1173                             ? queryIndex()
1174                             : SymbolSlab();
1175     // Merge Sema and Index results, score them, and pick the winners.
1176     auto Top = mergeResults(Recorder->Results, IndexResults);
1177     // Convert the results to final form, assembling the expensive strings.
1178     CodeCompleteResult Output;
1179     for (auto &C : Top) {
1180       Output.Completions.push_back(toCodeCompletion(C.first));
1181       Output.Completions.back().Score = C.second;
1182       Output.Completions.back().CompletionTokenRange = TextEditRange;
1183     }
1184     Output.HasMore = Incomplete;
1185     Output.Context = Recorder->CCContext.getKind();
1186     return Output;
1187   }
1188 
1189   SymbolSlab queryIndex() {
1190     trace::Span Tracer("Query index");
1191     SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
1192 
1193     SymbolSlab::Builder ResultsBuilder;
1194     // Build the query.
1195     FuzzyFindRequest Req;
1196     if (Opts.Limit)
1197       Req.MaxCandidateCount = Opts.Limit;
1198     Req.Query = Filter->pattern();
1199     Req.RestrictForCodeCompletion = true;
1200     Req.Scopes = QueryScopes;
1201     // FIXME: we should send multiple weighted paths here.
1202     Req.ProximityPaths.push_back(FileName);
1203     vlog("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])", Req.Query,
1204          llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ","));
1205     // Run the query against the index.
1206     if (Opts.Index->fuzzyFind(
1207             Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1208       Incomplete = true;
1209     return std::move(ResultsBuilder).build();
1210   }
1211 
1212   // Merges Sema and Index results where possible, to form CompletionCandidates.
1213   // Groups overloads if desired, to form CompletionCandidate::Bundles.
1214   // The bundles are scored and top results are returned, best to worst.
1215   std::vector<ScoredBundle>
1216       mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1217                    const SymbolSlab &IndexResults) {
1218     trace::Span Tracer("Merge and score results");
1219     std::vector<CompletionCandidate::Bundle> Bundles;
1220     llvm::DenseMap<size_t, size_t> BundleLookup;
1221     auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
1222                             const Symbol *IndexResult) {
1223       CompletionCandidate C;
1224       C.SemaResult = SemaResult;
1225       C.IndexResult = IndexResult;
1226       C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1227       if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1228         auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1229         if (Ret.second)
1230           Bundles.emplace_back();
1231         Bundles[Ret.first->second].push_back(std::move(C));
1232       } else {
1233         Bundles.emplace_back();
1234         Bundles.back().push_back(std::move(C));
1235       }
1236     };
1237     llvm::DenseSet<const Symbol *> UsedIndexResults;
1238     auto CorrespondingIndexResult =
1239         [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
1240       if (auto SymID = getSymbolID(SemaResult)) {
1241         auto I = IndexResults.find(*SymID);
1242         if (I != IndexResults.end()) {
1243           UsedIndexResults.insert(&*I);
1244           return &*I;
1245         }
1246       }
1247       return nullptr;
1248     };
1249     // Emit all Sema results, merging them with Index results if possible.
1250     for (auto &SemaResult : Recorder->Results)
1251       AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
1252     // Now emit any Index-only results.
1253     for (const auto &IndexResult : IndexResults) {
1254       if (UsedIndexResults.count(&IndexResult))
1255         continue;
1256       AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
1257     }
1258     // We only keep the best N results at any time, in "native" format.
1259     TopN<ScoredBundle, ScoredBundleGreater> Top(
1260         Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1261     for (auto &Bundle : Bundles)
1262       addCandidate(Top, std::move(Bundle));
1263     return std::move(Top).items();
1264   }
1265 
1266   Optional<float> fuzzyScore(const CompletionCandidate &C) {
1267     // Macros can be very spammy, so we only support prefix completion.
1268     // We won't end up with underfull index results, as macros are sema-only.
1269     if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1270         !C.Name.startswith_lower(Filter->pattern()))
1271       return None;
1272     return Filter->match(C.Name);
1273   }
1274 
1275   // Scores a candidate and adds it to the TopN structure.
1276   void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1277                     CompletionCandidate::Bundle Bundle) {
1278     SymbolQualitySignals Quality;
1279     SymbolRelevanceSignals Relevance;
1280     Relevance.Context = Recorder->CCContext.getKind();
1281     Relevance.Query = SymbolRelevanceSignals::CodeComplete;
1282     Relevance.FileProximityMatch = FileProximity.getPointer();
1283     auto &First = Bundle.front();
1284     if (auto FuzzyScore = fuzzyScore(First))
1285       Relevance.NameMatch = *FuzzyScore;
1286     else
1287       return;
1288     SymbolOrigin Origin = SymbolOrigin::Unknown;
1289     bool FromIndex = false;
1290     for (const auto &Candidate : Bundle) {
1291       if (Candidate.IndexResult) {
1292         Quality.merge(*Candidate.IndexResult);
1293         Relevance.merge(*Candidate.IndexResult);
1294         Origin |= Candidate.IndexResult->Origin;
1295         FromIndex = true;
1296       }
1297       if (Candidate.SemaResult) {
1298         Quality.merge(*Candidate.SemaResult);
1299         Relevance.merge(*Candidate.SemaResult);
1300         Origin |= SymbolOrigin::AST;
1301       }
1302     }
1303 
1304     CodeCompletion::Scores Scores;
1305     Scores.Quality = Quality.evaluate();
1306     Scores.Relevance = Relevance.evaluate();
1307     Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1308     // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1309     Scores.ExcludingName = Relevance.NameMatch
1310                                ? Scores.Total / Relevance.NameMatch
1311                                : Scores.Quality;
1312 
1313     dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
1314          llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
1315          llvm::to_string(Relevance));
1316 
1317     NSema += bool(Origin & SymbolOrigin::AST);
1318     NIndex += FromIndex;
1319     NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
1320     if (Candidates.push({std::move(Bundle), Scores}))
1321       Incomplete = true;
1322   }
1323 
1324   CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
1325     llvm::Optional<CodeCompletionBuilder> Builder;
1326     for (const auto &Item : Bundle) {
1327       CodeCompletionString *SemaCCS =
1328           Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1329                           : nullptr;
1330       if (!Builder)
1331         Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
1332                         *Inserter, FileName, Opts);
1333       else
1334         Builder->add(Item, SemaCCS);
1335     }
1336     return Builder->build();
1337   }
1338 };
1339 
1340 CodeCompleteResult codeComplete(PathRef FileName,
1341                                 const tooling::CompileCommand &Command,
1342                                 PrecompiledPreamble const *Preamble,
1343                                 const IncludeStructure &PreambleInclusions,
1344                                 StringRef Contents, Position Pos,
1345                                 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1346                                 std::shared_ptr<PCHContainerOperations> PCHs,
1347                                 CodeCompleteOptions Opts) {
1348   return CodeCompleteFlow(FileName, PreambleInclusions, Opts)
1349       .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
1350 }
1351 
1352 SignatureHelp signatureHelp(PathRef FileName,
1353                             const tooling::CompileCommand &Command,
1354                             PrecompiledPreamble const *Preamble,
1355                             StringRef Contents, Position Pos,
1356                             IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1357                             std::shared_ptr<PCHContainerOperations> PCHs,
1358                             SymbolIndex *Index) {
1359   SignatureHelp Result;
1360   clang::CodeCompleteOptions Options;
1361   Options.IncludeGlobals = false;
1362   Options.IncludeMacros = false;
1363   Options.IncludeCodePatterns = false;
1364   Options.IncludeBriefComments = false;
1365   IncludeStructure PreambleInclusions; // Unused for signatureHelp
1366   semaCodeComplete(
1367       llvm::make_unique<SignatureHelpCollector>(Options, Index, Result),
1368       Options,
1369       {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1370        std::move(PCHs)});
1371   return Result;
1372 }
1373 
1374 bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1375   using namespace clang::ast_matchers;
1376   auto InTopLevelScope = hasDeclContext(
1377       anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1378   return !match(decl(anyOf(InTopLevelScope,
1379                            hasDeclContext(
1380                                enumDecl(InTopLevelScope, unless(isScoped()))))),
1381                 ND, ASTCtx)
1382               .empty();
1383 }
1384 
1385 CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1386   CompletionItem LSP;
1387   LSP.label = (HeaderInsertion ? Opts.IncludeIndicator.Insert
1388                                : Opts.IncludeIndicator.NoInsert) +
1389               (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
1390               RequiredQualifier + Name + Signature;
1391 
1392   LSP.kind = Kind;
1393   LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
1394                               : ReturnType;
1395   if (!Header.empty())
1396     LSP.detail += "\n" + Header;
1397   LSP.documentation = Documentation;
1398   LSP.sortText = sortText(Score.Total, Name);
1399   LSP.filterText = Name;
1400   LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name};
1401   // Merge continious additionalTextEdits into main edit. The main motivation
1402   // behind this is to help LSP clients, it seems most of them are confused when
1403   // they are provided with additionalTextEdits that are consecutive to main
1404   // edit.
1405   // Note that we store additional text edits from back to front in a line. That
1406   // is mainly to help LSP clients again, so that changes do not effect each
1407   // other.
1408   for (const auto &FixIt : FixIts) {
1409     if (IsRangeConsecutive(FixIt.range, LSP.textEdit->range)) {
1410       LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
1411       LSP.textEdit->range.start = FixIt.range.start;
1412     } else {
1413       LSP.additionalTextEdits.push_back(FixIt);
1414     }
1415   }
1416   if (Opts.EnableSnippets && !SnippetSuffix.empty()) {
1417     if (!Opts.EnableFunctionArgSnippets &&
1418         ((Kind == CompletionItemKind::Function) ||
1419          (Kind == CompletionItemKind::Method)) &&
1420         (SnippetSuffix.front() == '(') && (SnippetSuffix.back() == ')'))
1421       // Check whether function has any parameters or not.
1422       LSP.textEdit->newText += SnippetSuffix.size() > 2 ? "(${0})" : "()";
1423     else
1424       LSP.textEdit->newText += SnippetSuffix;
1425   }
1426 
1427   // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
1428   // compatible with most of the editors.
1429   LSP.insertText = LSP.textEdit->newText;
1430   LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1431                                              : InsertTextFormat::PlainText;
1432   if (HeaderInsertion)
1433     LSP.additionalTextEdits.push_back(*HeaderInsertion);
1434   return LSP;
1435 }
1436 
1437 raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) {
1438   // For now just lean on CompletionItem.
1439   return OS << C.render(CodeCompleteOptions());
1440 }
1441 
1442 raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) {
1443   OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
1444      << " (" << getCompletionKindString(R.Context) << ")"
1445      << " items:\n";
1446   for (const auto &C : R.Completions)
1447     OS << C << "\n";
1448   return OS;
1449 }
1450 
1451 } // namespace clangd
1452 } // namespace clang
1453