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