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