blob: 511866893417fe20097c455c399955c63fc8101e [file] [log] [blame]
Sam McCall98775c52017-12-04 13:49:59 +00001//===--- CodeComplete.cpp ---------------------------------------*- C++-*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===---------------------------------------------------------------------===//
9//
10// AST-based completions are provided using the completion hooks in Sema.
11//
12// Signature help works in a similar way as code completion, but it is simpler
13// as there are typically fewer candidates.
14//
15//===---------------------------------------------------------------------===//
16
17#include "CodeComplete.h"
Eric Liu63696e12017-12-20 17:24:31 +000018#include "CodeCompletionStrings.h"
Sam McCall98775c52017-12-04 13:49:59 +000019#include "Compiler.h"
Sam McCall84652cc2018-01-12 16:16:09 +000020#include "FuzzyMatch.h"
Eric Liu63f419a2018-05-15 15:29:32 +000021#include "Headers.h"
Eric Liu6f648df2017-12-19 16:50:37 +000022#include "Logger.h"
Sam McCallc5707b62018-05-15 17:43:27 +000023#include "Quality.h"
Eric Liuc5105f92018-02-16 14:15:55 +000024#include "SourceCode.h"
Sam McCall2b780162018-01-30 17:20:54 +000025#include "Trace.h"
Eric Liu63f419a2018-05-15 15:29:32 +000026#include "URI.h"
Eric Liu6f648df2017-12-19 16:50:37 +000027#include "index/Index.h"
Ilya Biryukovc22d3442018-05-16 12:32:49 +000028#include "clang/Basic/LangOptions.h"
Eric Liuc5105f92018-02-16 14:15:55 +000029#include "clang/Format/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000030#include "clang/Frontend/CompilerInstance.h"
31#include "clang/Frontend/FrontendActions.h"
Sam McCall545a20d2018-01-19 14:34:02 +000032#include "clang/Index/USRGeneration.h"
Sam McCall98775c52017-12-04 13:49:59 +000033#include "clang/Sema/CodeCompleteConsumer.h"
34#include "clang/Sema/Sema.h"
Eric Liuc5105f92018-02-16 14:15:55 +000035#include "clang/Tooling/Core/Replacement.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000036#include "llvm/Support/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000037#include <queue>
38
Sam McCallc5707b62018-05-15 17:43:27 +000039// We log detailed candidate here if you run with -debug-only=codecomplete.
40#define DEBUG_TYPE "codecomplete"
41
Sam McCall98775c52017-12-04 13:49:59 +000042namespace clang {
43namespace clangd {
44namespace {
45
Eric Liu6f648df2017-12-19 16:50:37 +000046CompletionItemKind toCompletionItemKind(CXCursorKind CursorKind) {
Sam McCall98775c52017-12-04 13:49:59 +000047 switch (CursorKind) {
48 case CXCursor_MacroInstantiation:
49 case CXCursor_MacroDefinition:
50 return CompletionItemKind::Text;
51 case CXCursor_CXXMethod:
Eric Liu6f648df2017-12-19 16:50:37 +000052 case CXCursor_Destructor:
Sam McCall98775c52017-12-04 13:49:59 +000053 return CompletionItemKind::Method;
54 case CXCursor_FunctionDecl:
55 case CXCursor_FunctionTemplate:
56 return CompletionItemKind::Function;
57 case CXCursor_Constructor:
Sam McCall98775c52017-12-04 13:49:59 +000058 return CompletionItemKind::Constructor;
59 case CXCursor_FieldDecl:
60 return CompletionItemKind::Field;
61 case CXCursor_VarDecl:
62 case CXCursor_ParmDecl:
63 return CompletionItemKind::Variable;
Eric Liu6f648df2017-12-19 16:50:37 +000064 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
65 // protocol.
Sam McCall98775c52017-12-04 13:49:59 +000066 case CXCursor_StructDecl:
Eric Liu6f648df2017-12-19 16:50:37 +000067 case CXCursor_ClassDecl:
Sam McCall98775c52017-12-04 13:49:59 +000068 case CXCursor_UnionDecl:
69 case CXCursor_ClassTemplate:
70 case CXCursor_ClassTemplatePartialSpecialization:
71 return CompletionItemKind::Class;
72 case CXCursor_Namespace:
73 case CXCursor_NamespaceAlias:
74 case CXCursor_NamespaceRef:
75 return CompletionItemKind::Module;
76 case CXCursor_EnumConstantDecl:
77 return CompletionItemKind::Value;
78 case CXCursor_EnumDecl:
79 return CompletionItemKind::Enum;
Eric Liu6f648df2017-12-19 16:50:37 +000080 // FIXME(ioeric): figure out whether reference is the right type for aliases.
Sam McCall98775c52017-12-04 13:49:59 +000081 case CXCursor_TypeAliasDecl:
82 case CXCursor_TypeAliasTemplateDecl:
83 case CXCursor_TypedefDecl:
84 case CXCursor_MemberRef:
85 case CXCursor_TypeRef:
86 return CompletionItemKind::Reference;
87 default:
88 return CompletionItemKind::Missing;
89 }
90}
91
Eric Liu6f648df2017-12-19 16:50:37 +000092CompletionItemKind
93toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
94 CXCursorKind CursorKind) {
Sam McCall98775c52017-12-04 13:49:59 +000095 switch (ResKind) {
96 case CodeCompletionResult::RK_Declaration:
Eric Liu6f648df2017-12-19 16:50:37 +000097 return toCompletionItemKind(CursorKind);
Sam McCall98775c52017-12-04 13:49:59 +000098 case CodeCompletionResult::RK_Keyword:
99 return CompletionItemKind::Keyword;
100 case CodeCompletionResult::RK_Macro:
101 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
102 // completion items in LSP.
103 case CodeCompletionResult::RK_Pattern:
104 return CompletionItemKind::Snippet;
105 }
106 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
107}
108
Eric Liu6f648df2017-12-19 16:50:37 +0000109CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
110 using SK = index::SymbolKind;
111 switch (Kind) {
112 case SK::Unknown:
113 return CompletionItemKind::Missing;
114 case SK::Module:
115 case SK::Namespace:
116 case SK::NamespaceAlias:
117 return CompletionItemKind::Module;
118 case SK::Macro:
119 return CompletionItemKind::Text;
120 case SK::Enum:
121 return CompletionItemKind::Enum;
122 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
123 // protocol.
124 case SK::Struct:
125 case SK::Class:
126 case SK::Protocol:
127 case SK::Extension:
128 case SK::Union:
129 return CompletionItemKind::Class;
130 // FIXME(ioeric): figure out whether reference is the right type for aliases.
131 case SK::TypeAlias:
132 case SK::Using:
133 return CompletionItemKind::Reference;
134 case SK::Function:
135 // FIXME(ioeric): this should probably be an operator. This should be fixed
136 // when `Operator` is support type in the protocol.
137 case SK::ConversionFunction:
138 return CompletionItemKind::Function;
139 case SK::Variable:
140 case SK::Parameter:
141 return CompletionItemKind::Variable;
142 case SK::Field:
143 return CompletionItemKind::Field;
144 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
145 case SK::EnumConstant:
146 return CompletionItemKind::Value;
147 case SK::InstanceMethod:
148 case SK::ClassMethod:
149 case SK::StaticMethod:
150 case SK::Destructor:
151 return CompletionItemKind::Method;
152 case SK::InstanceProperty:
153 case SK::ClassProperty:
154 case SK::StaticProperty:
155 return CompletionItemKind::Property;
156 case SK::Constructor:
157 return CompletionItemKind::Constructor;
158 }
159 llvm_unreachable("Unhandled clang::index::SymbolKind.");
160}
161
Sam McCall98775c52017-12-04 13:49:59 +0000162/// Get the optional chunk as a string. This function is possibly recursive.
163///
164/// The parameter info for each parameter is appended to the Parameters.
165std::string
166getOptionalParameters(const CodeCompletionString &CCS,
167 std::vector<ParameterInformation> &Parameters) {
168 std::string Result;
169 for (const auto &Chunk : CCS) {
170 switch (Chunk.Kind) {
171 case CodeCompletionString::CK_Optional:
172 assert(Chunk.Optional &&
173 "Expected the optional code completion string to be non-null.");
174 Result += getOptionalParameters(*Chunk.Optional, Parameters);
175 break;
176 case CodeCompletionString::CK_VerticalSpace:
177 break;
178 case CodeCompletionString::CK_Placeholder:
179 // A string that acts as a placeholder for, e.g., a function call
180 // argument.
181 // Intentional fallthrough here.
182 case CodeCompletionString::CK_CurrentParameter: {
183 // A piece of text that describes the parameter that corresponds to
184 // the code-completion location within a function call, message send,
185 // macro invocation, etc.
186 Result += Chunk.Text;
187 ParameterInformation Info;
188 Info.label = Chunk.Text;
189 Parameters.push_back(std::move(Info));
190 break;
191 }
192 default:
193 Result += Chunk.Text;
194 break;
195 }
196 }
197 return Result;
198}
199
Eric Liu63f419a2018-05-15 15:29:32 +0000200/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
201/// include.
202static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
203 llvm::StringRef HintPath) {
204 if (isLiteralInclude(Header))
205 return HeaderFile{Header.str(), /*Verbatim=*/true};
206 auto U = URI::parse(Header);
207 if (!U)
208 return U.takeError();
209
210 auto IncludePath = URI::includeSpelling(*U);
211 if (!IncludePath)
212 return IncludePath.takeError();
213 if (!IncludePath->empty())
214 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
215
216 auto Resolved = URI::resolve(*U, HintPath);
217 if (!Resolved)
218 return Resolved.takeError();
219 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
220}
221
Sam McCall545a20d2018-01-19 14:34:02 +0000222/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000223/// It may be promoted to a CompletionItem if it's among the top-ranked results.
224struct CompletionCandidate {
Sam McCall545a20d2018-01-19 14:34:02 +0000225 llvm::StringRef Name; // Used for filtering and sorting.
226 // We may have a result from Sema, from the index, or both.
227 const CodeCompletionResult *SemaResult = nullptr;
228 const Symbol *IndexResult = nullptr;
Sam McCall98775c52017-12-04 13:49:59 +0000229
Sam McCall545a20d2018-01-19 14:34:02 +0000230 // Builds an LSP completion item.
Eric Liu63f419a2018-05-15 15:29:32 +0000231 CompletionItem build(StringRef FileName, const CompletionItemScores &Scores,
Sam McCall545a20d2018-01-19 14:34:02 +0000232 const CodeCompleteOptions &Opts,
Eric Liu63f419a2018-05-15 15:29:32 +0000233 CodeCompletionString *SemaCCS,
Ilya Biryukov43714502018-05-16 12:32:44 +0000234 const IncludeInserter *Includes,
235 llvm::StringRef SemaDocComment) const {
Sam McCall545a20d2018-01-19 14:34:02 +0000236 assert(bool(SemaResult) == bool(SemaCCS));
237 CompletionItem I;
238 if (SemaResult) {
239 I.kind = toCompletionItemKind(SemaResult->Kind, SemaResult->CursorKind);
240 getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText,
241 Opts.EnableSnippets);
242 I.filterText = getFilterText(*SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +0000243 I.documentation = formatDocumentation(*SemaCCS, SemaDocComment);
Sam McCall545a20d2018-01-19 14:34:02 +0000244 I.detail = getDetail(*SemaCCS);
245 }
246 if (IndexResult) {
247 if (I.kind == CompletionItemKind::Missing)
248 I.kind = toCompletionItemKind(IndexResult->SymInfo.Kind);
249 // FIXME: reintroduce a way to show the index source for debugging.
250 if (I.label.empty())
251 I.label = IndexResult->CompletionLabel;
252 if (I.filterText.empty())
253 I.filterText = IndexResult->Name;
Sam McCall98775c52017-12-04 13:49:59 +0000254
Sam McCall545a20d2018-01-19 14:34:02 +0000255 // FIXME(ioeric): support inserting/replacing scope qualifiers.
256 if (I.insertText.empty())
257 I.insertText = Opts.EnableSnippets
258 ? IndexResult->CompletionSnippetInsertText
259 : IndexResult->CompletionPlainInsertText;
260
261 if (auto *D = IndexResult->Detail) {
262 if (I.documentation.empty())
263 I.documentation = D->Documentation;
264 if (I.detail.empty())
265 I.detail = D->CompletionDetail;
Eric Liu63f419a2018-05-15 15:29:32 +0000266 if (Includes && !D->IncludeHeader.empty()) {
267 auto Edit = [&]() -> Expected<Optional<TextEdit>> {
268 auto ResolvedDeclaring = toHeaderFile(
269 IndexResult->CanonicalDeclaration.FileURI, FileName);
270 if (!ResolvedDeclaring)
271 return ResolvedDeclaring.takeError();
272 auto ResolvedInserted = toHeaderFile(D->IncludeHeader, FileName);
273 if (!ResolvedInserted)
274 return ResolvedInserted.takeError();
275 return Includes->insert(*ResolvedDeclaring, *ResolvedInserted);
276 }();
277 if (!Edit) {
278 std::string ErrMsg =
279 ("Failed to generate include insertion edits for adding header "
280 "(FileURI=\"" +
281 IndexResult->CanonicalDeclaration.FileURI +
282 "\", IncludeHeader=\"" + D->IncludeHeader + "\") into " +
283 FileName)
284 .str();
285 log(ErrMsg + ":" + llvm::toString(Edit.takeError()));
286 } else if (*Edit) {
287 I.additionalTextEdits = {std::move(**Edit)};
288 }
289 }
Sam McCall545a20d2018-01-19 14:34:02 +0000290 }
291 }
292 I.scoreInfo = Scores;
293 I.sortText = sortText(Scores.finalScore, Name);
294 I.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
295 : InsertTextFormat::PlainText;
296 return I;
Sam McCall98775c52017-12-04 13:49:59 +0000297 }
298};
Sam McCallc5707b62018-05-15 17:43:27 +0000299using ScoredCandidate = std::pair<CompletionCandidate, CompletionItemScores>;
Sam McCall98775c52017-12-04 13:49:59 +0000300
Sam McCall545a20d2018-01-19 14:34:02 +0000301// Determine the symbol ID for a Sema code completion result, if possible.
302llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
303 switch (R.Kind) {
304 case CodeCompletionResult::RK_Declaration:
305 case CodeCompletionResult::RK_Pattern: {
306 llvm::SmallString<128> USR;
307 if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
308 return None;
309 return SymbolID(USR);
310 }
311 case CodeCompletionResult::RK_Macro:
312 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
313 case CodeCompletionResult::RK_Keyword:
314 return None;
315 }
316 llvm_unreachable("unknown CodeCompletionResult kind");
317}
318
Haojian Wu061c73e2018-01-23 11:37:26 +0000319// Scopes of the paritial identifier we're trying to complete.
320// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000321struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000322 // The scopes we should look in, determined by Sema.
323 //
324 // If the qualifier was fully resolved, we look for completions in these
325 // scopes; if there is an unresolved part of the qualifier, it should be
326 // resolved within these scopes.
327 //
328 // Examples of qualified completion:
329 //
330 // "::vec" => {""}
331 // "using namespace std; ::vec^" => {"", "std::"}
332 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
333 // "std::vec^" => {""} // "std" unresolved
334 //
335 // Examples of unqualified completion:
336 //
337 // "vec^" => {""}
338 // "using namespace std; vec^" => {"", "std::"}
339 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
340 //
341 // "" for global namespace, "ns::" for normal namespace.
342 std::vector<std::string> AccessibleScopes;
343 // The full scope qualifier as typed by the user (without the leading "::").
344 // Set if the qualifier is not fully resolved by Sema.
345 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000346
Haojian Wu061c73e2018-01-23 11:37:26 +0000347 // Construct scopes being queried in indexes.
348 // This method format the scopes to match the index request representation.
349 std::vector<std::string> scopesForIndexQuery() {
350 std::vector<std::string> Results;
351 for (llvm::StringRef AS : AccessibleScopes) {
352 Results.push_back(AS);
353 if (UnresolvedQualifier)
354 Results.back() += *UnresolvedQualifier;
355 }
356 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000357 }
Eric Liu6f648df2017-12-19 16:50:37 +0000358};
359
Haojian Wu061c73e2018-01-23 11:37:26 +0000360// Get all scopes that will be queried in indexes.
361std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
362 const SourceManager& SM) {
363 auto GetAllAccessibleScopes = [](CodeCompletionContext& CCContext) {
364 SpecifiedScope Info;
365 for (auto* Context : CCContext.getVisitedContexts()) {
366 if (isa<TranslationUnitDecl>(Context))
367 Info.AccessibleScopes.push_back(""); // global namespace
368 else if (const auto*NS = dyn_cast<NamespaceDecl>(Context))
369 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
370 }
371 return Info;
372 };
373
374 auto SS = CCContext.getCXXScopeSpecifier();
375
376 // Unqualified completion (e.g. "vec^").
377 if (!SS) {
378 // FIXME: Once we can insert namespace qualifiers and use the in-scope
379 // namespaces for scoring, search in all namespaces.
380 // FIXME: Capture scopes and use for scoring, for example,
381 // "using namespace std; namespace foo {v^}" =>
382 // foo::value > std::vector > boost::variant
383 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
384 }
385
386 // Qualified completion ("std::vec^"), we have two cases depending on whether
387 // the qualifier can be resolved by Sema.
388 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000389 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
390 }
391
392 // Unresolved qualifier.
393 // FIXME: When Sema can resolve part of a scope chain (e.g.
394 // "known::unknown::id"), we should expand the known part ("known::") rather
395 // than treating the whole thing as unknown.
396 SpecifiedScope Info;
397 Info.AccessibleScopes.push_back(""); // global namespace
398
399 Info.UnresolvedQualifier =
400 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()),
401 SM, clang::LangOptions()).ltrim("::");
402 // Sema excludes the trailing "::".
403 if (!Info.UnresolvedQualifier->empty())
404 *Info.UnresolvedQualifier += "::";
405
406 return Info.scopesForIndexQuery();
407}
408
Sam McCall545a20d2018-01-19 14:34:02 +0000409// The CompletionRecorder captures Sema code-complete output, including context.
410// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
411// It doesn't do scoring or conversion to CompletionItem yet, as we want to
412// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000413// Generally the fields and methods of this object should only be used from
414// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000415struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000416 CompletionRecorder(const CodeCompleteOptions &Opts,
417 UniqueFunction<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000418 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000419 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000420 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
421 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000422 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
423 assert(this->ResultsCallback);
424 }
425
Sam McCall545a20d2018-01-19 14:34:02 +0000426 std::vector<CodeCompletionResult> Results;
427 CodeCompletionContext CCContext;
428 Sema *CCSema = nullptr; // Sema that created the results.
429 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000430
Sam McCall545a20d2018-01-19 14:34:02 +0000431 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
432 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000433 unsigned NumResults) override final {
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000434 if (CCSema) {
435 log(llvm::formatv(
436 "Multiple code complete callbacks (parser backtracked?). "
437 "Dropping results from context {0}, keeping results from {1}.",
438 getCompletionKindString(this->CCContext.getKind()),
439 getCompletionKindString(Context.getKind())));
440 return;
441 }
Sam McCall545a20d2018-01-19 14:34:02 +0000442 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000443 CCSema = &S;
444 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000445
Sam McCall545a20d2018-01-19 14:34:02 +0000446 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000447 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000448 auto &Result = InResults[I];
449 // Drop hidden items which cannot be found by lookup after completion.
450 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000451 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
452 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000453 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000454 (Result.Availability == CXAvailability_NotAvailable ||
455 Result.Availability == CXAvailability_NotAccessible))
456 continue;
Sam McCalld2a95922018-01-22 21:05:00 +0000457 // Destructor completion is rarely useful, and works inconsistently.
458 // (s.^ completes ~string, but s.~st^ is an error).
459 if (dyn_cast_or_null<CXXDestructorDecl>(Result.Declaration))
460 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000461 // We choose to never append '::' to completion results in clangd.
462 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000463 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000464 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000465 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000466 }
467
Sam McCall545a20d2018-01-19 14:34:02 +0000468 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000469 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
470
Sam McCall545a20d2018-01-19 14:34:02 +0000471 // Returns the filtering/sorting name for Result, which must be from Results.
472 // Returned string is owned by this recorder (or the AST).
473 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000474 switch (Result.Kind) {
475 case CodeCompletionResult::RK_Declaration:
476 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000477 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000478 break;
479 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000480 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000481 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000482 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000483 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000484 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000485 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000486 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000487 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000488 }
489
Sam McCall545a20d2018-01-19 14:34:02 +0000490 // Build a CodeCompletion string for R, which must be from Results.
491 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000492 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000493 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
494 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000495 *CCSema, CCContext, *CCAllocator, CCTUInfo,
496 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000497 }
498
Sam McCall545a20d2018-01-19 14:34:02 +0000499private:
500 CodeCompleteOptions Opts;
501 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000502 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000503 UniqueFunction<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000504};
505
Sam McCallc5707b62018-05-15 17:43:27 +0000506struct ScoredCandidateGreater {
507 bool operator()(const ScoredCandidate &L, const ScoredCandidate &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000508 if (L.second.finalScore != R.second.finalScore)
509 return L.second.finalScore > R.second.finalScore;
510 return L.first.Name < R.first.Name; // Earlier name is better.
511 }
Sam McCall545a20d2018-01-19 14:34:02 +0000512};
Sam McCall98775c52017-12-04 13:49:59 +0000513
Sam McCall98775c52017-12-04 13:49:59 +0000514class SignatureHelpCollector final : public CodeCompleteConsumer {
515
516public:
517 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
518 SignatureHelp &SigHelp)
519 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
520 SigHelp(SigHelp),
521 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
522 CCTUInfo(Allocator) {}
523
524 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
525 OverloadCandidate *Candidates,
526 unsigned NumCandidates) override {
527 SigHelp.signatures.reserve(NumCandidates);
528 // FIXME(rwols): How can we determine the "active overload candidate"?
529 // Right now the overloaded candidates seem to be provided in a "best fit"
530 // order, so I'm not too worried about this.
531 SigHelp.activeSignature = 0;
532 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
533 "too many arguments");
534 SigHelp.activeParameter = static_cast<int>(CurrentArg);
535 for (unsigned I = 0; I < NumCandidates; ++I) {
536 const auto &Candidate = Candidates[I];
537 const auto *CCS = Candidate.CreateSignatureString(
538 CurrentArg, S, *Allocator, CCTUInfo, true);
539 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukov43714502018-05-16 12:32:44 +0000540 SigHelp.signatures.push_back(ProcessOverloadCandidate(
541 Candidate, *CCS,
542 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg)));
Sam McCall98775c52017-12-04 13:49:59 +0000543 }
544 }
545
546 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
547
548 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
549
550private:
Eric Liu63696e12017-12-20 17:24:31 +0000551 // FIXME(ioeric): consider moving CodeCompletionString logic here to
552 // CompletionString.h.
Sam McCall98775c52017-12-04 13:49:59 +0000553 SignatureInformation
554 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
Ilya Biryukov43714502018-05-16 12:32:44 +0000555 const CodeCompletionString &CCS,
556 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000557 SignatureInformation Result;
558 const char *ReturnType = nullptr;
559
Ilya Biryukov43714502018-05-16 12:32:44 +0000560 Result.documentation = formatDocumentation(CCS, DocComment);
Sam McCall98775c52017-12-04 13:49:59 +0000561
562 for (const auto &Chunk : CCS) {
563 switch (Chunk.Kind) {
564 case CodeCompletionString::CK_ResultType:
565 // A piece of text that describes the type of an entity or,
566 // for functions and methods, the return type.
567 assert(!ReturnType && "Unexpected CK_ResultType");
568 ReturnType = Chunk.Text;
569 break;
570 case CodeCompletionString::CK_Placeholder:
571 // A string that acts as a placeholder for, e.g., a function call
572 // argument.
573 // Intentional fallthrough here.
574 case CodeCompletionString::CK_CurrentParameter: {
575 // A piece of text that describes the parameter that corresponds to
576 // the code-completion location within a function call, message send,
577 // macro invocation, etc.
578 Result.label += Chunk.Text;
579 ParameterInformation Info;
580 Info.label = Chunk.Text;
581 Result.parameters.push_back(std::move(Info));
582 break;
583 }
584 case CodeCompletionString::CK_Optional: {
585 // The rest of the parameters are defaulted/optional.
586 assert(Chunk.Optional &&
587 "Expected the optional code completion string to be non-null.");
588 Result.label +=
589 getOptionalParameters(*Chunk.Optional, Result.parameters);
590 break;
591 }
592 case CodeCompletionString::CK_VerticalSpace:
593 break;
594 default:
595 Result.label += Chunk.Text;
596 break;
597 }
598 }
599 if (ReturnType) {
600 Result.label += " -> ";
601 Result.label += ReturnType;
602 }
603 return Result;
604 }
605
606 SignatureHelp &SigHelp;
607 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
608 CodeCompletionTUInfo CCTUInfo;
609
610}; // SignatureHelpCollector
611
Sam McCall545a20d2018-01-19 14:34:02 +0000612struct SemaCompleteInput {
613 PathRef FileName;
614 const tooling::CompileCommand &Command;
615 PrecompiledPreamble const *Preamble;
Eric Liu63f419a2018-05-15 15:29:32 +0000616 const std::vector<Inclusion> &PreambleInclusions;
Sam McCall545a20d2018-01-19 14:34:02 +0000617 StringRef Contents;
618 Position Pos;
619 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
620 std::shared_ptr<PCHContainerOperations> PCHs;
621};
622
623// Invokes Sema code completion on a file.
Eric Liu63f419a2018-05-15 15:29:32 +0000624// If \p Includes is set, it will be initialized after a compiler instance has
625// been set up.
Sam McCalld1a7a372018-01-31 13:40:48 +0000626bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000627 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000628 const SemaCompleteInput &Input,
629 std::unique_ptr<IncludeInserter> *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000630 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000631 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000632 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000633 ArgStrs.push_back(S.c_str());
634
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000635 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
636 log("Couldn't set working directory");
637 // We run parsing anyway, our lit-tests rely on results for non-existing
638 // working dirs.
639 }
Sam McCall98775c52017-12-04 13:49:59 +0000640
641 IgnoreDiagnostics DummyDiagsConsumer;
642 auto CI = createInvocationFromCommandLine(
643 ArgStrs,
644 CompilerInstance::createDiagnostics(new DiagnosticOptions,
645 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000646 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000647 if (!CI) {
648 log("Couldn't create CompilerInvocation");;
649 return false;
650 }
Ilya Biryukov71590652018-01-05 13:36:55 +0000651 CI->getFrontendOpts().DisableFree = false;
Ilya Biryukovc22d3442018-05-16 12:32:49 +0000652 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
Sam McCall98775c52017-12-04 13:49:59 +0000653
654 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
Sam McCall545a20d2018-01-19 14:34:02 +0000655 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000656
Ilya Biryukov06a485d2018-05-22 13:10:09 +0000657 // The diagnostic options must be set before creating a CompilerInstance.
658 CI->getDiagnosticOpts().IgnoreWarnings = true;
Ilya Biryukov295c8e12018-01-18 15:17:00 +0000659 // We reuse the preamble whether it's valid or not. This is a
660 // correctness/performance tradeoff: building without a preamble is slow, and
661 // completion is latency-sensitive.
Sam McCall98775c52017-12-04 13:49:59 +0000662 auto Clang = prepareCompilerInstance(
Sam McCall545a20d2018-01-19 14:34:02 +0000663 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
664 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000665
Haojian Wu58d208d2018-01-25 09:44:06 +0000666 // Disable typo correction in Sema.
667 Clang->getLangOpts().SpellChecking = false;
668
Sam McCall98775c52017-12-04 13:49:59 +0000669 auto &FrontendOpts = Clang->getFrontendOpts();
670 FrontendOpts.SkipFunctionBodies = true;
671 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000672 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000673 auto Offset = positionToOffset(Input.Contents, Input.Pos);
674 if (!Offset) {
675 log("Code completion position was invalid " +
676 llvm::toString(Offset.takeError()));
677 return false;
678 }
679 std::tie(FrontendOpts.CodeCompletionAt.Line,
680 FrontendOpts.CodeCompletionAt.Column) =
681 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000682
683 Clang->setCodeCompletionConsumer(Consumer.release());
684
685 SyntaxOnlyAction Action;
686 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000687 log("BeginSourceFile() failed when running codeComplete for " +
688 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000689 return false;
690 }
Eric Liu63f419a2018-05-15 15:29:32 +0000691 if (Includes) {
692 // Initialize Includes if provided.
693
694 // FIXME(ioeric): needs more consistent style support in clangd server.
695 auto Style = format::getStyle("file", Input.FileName, "LLVM",
696 Input.Contents, Input.VFS.get());
697 if (!Style) {
698 log("Failed to get FormatStyle for file" + Input.FileName +
699 ". Fall back to use LLVM style. Error: " +
700 llvm::toString(Style.takeError()));
701 Style = format::getLLVMStyle();
702 }
703 *Includes = llvm::make_unique<IncludeInserter>(
704 Input.FileName, Input.Contents, *Style, Input.Command.Directory,
705 Clang->getPreprocessor().getHeaderSearchInfo());
706 for (const auto &Inc : Input.PreambleInclusions)
707 Includes->get()->addExisting(Inc);
708 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
709 Clang->getSourceManager(), [Includes](Inclusion Inc) {
710 Includes->get()->addExisting(std::move(Inc));
711 }));
712 }
Sam McCall98775c52017-12-04 13:49:59 +0000713 if (!Action.Execute()) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000714 log("Execute() failed when running codeComplete for " + Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000715 return false;
716 }
Sam McCall98775c52017-12-04 13:49:59 +0000717 Action.EndSourceFile();
718
719 return true;
720}
721
Ilya Biryukova907ba42018-05-14 10:50:04 +0000722// Should we perform index-based completion in a context of the specified kind?
Sam McCall545a20d2018-01-19 14:34:02 +0000723// FIXME: consider allowing completion, but restricting the result types.
Ilya Biryukova907ba42018-05-14 10:50:04 +0000724bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
Sam McCall545a20d2018-01-19 14:34:02 +0000725 switch (K) {
726 case CodeCompletionContext::CCC_TopLevel:
727 case CodeCompletionContext::CCC_ObjCInterface:
728 case CodeCompletionContext::CCC_ObjCImplementation:
729 case CodeCompletionContext::CCC_ObjCIvarList:
730 case CodeCompletionContext::CCC_ClassStructUnion:
731 case CodeCompletionContext::CCC_Statement:
732 case CodeCompletionContext::CCC_Expression:
733 case CodeCompletionContext::CCC_ObjCMessageReceiver:
734 case CodeCompletionContext::CCC_EnumTag:
735 case CodeCompletionContext::CCC_UnionTag:
736 case CodeCompletionContext::CCC_ClassOrStructTag:
737 case CodeCompletionContext::CCC_ObjCProtocolName:
738 case CodeCompletionContext::CCC_Namespace:
739 case CodeCompletionContext::CCC_Type:
740 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
741 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
742 case CodeCompletionContext::CCC_ParenthesizedExpression:
743 case CodeCompletionContext::CCC_ObjCInterfaceName:
744 case CodeCompletionContext::CCC_ObjCCategoryName:
745 return true;
746 case CodeCompletionContext::CCC_Other: // Be conservative.
747 case CodeCompletionContext::CCC_OtherWithMacros:
748 case CodeCompletionContext::CCC_DotMemberAccess:
749 case CodeCompletionContext::CCC_ArrowMemberAccess:
750 case CodeCompletionContext::CCC_ObjCPropertyAccess:
751 case CodeCompletionContext::CCC_MacroName:
752 case CodeCompletionContext::CCC_MacroNameUse:
753 case CodeCompletionContext::CCC_PreprocessorExpression:
754 case CodeCompletionContext::CCC_PreprocessorDirective:
755 case CodeCompletionContext::CCC_NaturalLanguage:
756 case CodeCompletionContext::CCC_SelectorName:
757 case CodeCompletionContext::CCC_TypeQualifiers:
758 case CodeCompletionContext::CCC_ObjCInstanceMessage:
759 case CodeCompletionContext::CCC_ObjCClassMessage:
760 case CodeCompletionContext::CCC_Recovery:
761 return false;
762 }
763 llvm_unreachable("unknown code completion context");
764}
765
Ilya Biryukova907ba42018-05-14 10:50:04 +0000766// Should we allow index completions in the specified context?
767bool allowIndex(CodeCompletionContext &CC) {
768 if (!contextAllowsIndex(CC.getKind()))
769 return false;
770 // We also avoid ClassName::bar (but allow namespace::bar).
771 auto Scope = CC.getCXXScopeSpecifier();
772 if (!Scope)
773 return true;
774 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
775 if (!NameSpec)
776 return true;
777 // We only query the index when qualifier is a namespace.
778 // If it's a class, we rely solely on sema completions.
779 switch (NameSpec->getKind()) {
780 case NestedNameSpecifier::Global:
781 case NestedNameSpecifier::Namespace:
782 case NestedNameSpecifier::NamespaceAlias:
783 return true;
784 case NestedNameSpecifier::Super:
785 case NestedNameSpecifier::TypeSpec:
786 case NestedNameSpecifier::TypeSpecWithTemplate:
787 // Unresolved inside a template.
788 case NestedNameSpecifier::Identifier:
789 return false;
790 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000791 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000792}
793
Sam McCall98775c52017-12-04 13:49:59 +0000794} // namespace
795
796clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
797 clang::CodeCompleteOptions Result;
798 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
799 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000800 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000801 // We choose to include full comments and not do doxygen parsing in
802 // completion.
803 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
804 // formatting of the comments.
805 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000806
Sam McCall3d139c52018-01-12 18:30:08 +0000807 // When an is used, Sema is responsible for completing the main file,
808 // the index can provide results from the preamble.
809 // Tell Sema not to deserialize the preamble to look for results.
810 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000811
Sam McCall98775c52017-12-04 13:49:59 +0000812 return Result;
813}
814
Sam McCall545a20d2018-01-19 14:34:02 +0000815// Runs Sema-based (AST) and Index-based completion, returns merged results.
816//
817// There are a few tricky considerations:
818// - the AST provides information needed for the index query (e.g. which
819// namespaces to search in). So Sema must start first.
820// - we only want to return the top results (Opts.Limit).
821// Building CompletionItems for everything else is wasteful, so we want to
822// preserve the "native" format until we're done with scoring.
823// - the data underlying Sema completion items is owned by the AST and various
824// other arenas, which must stay alive for us to build CompletionItems.
825// - we may get duplicate results from Sema and the Index, we need to merge.
826//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000827// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000828// We use the Sema context information to query the index.
829// Then we merge the two result sets, producing items that are Sema/Index/Both.
830// These items are scored, and the top N are synthesized into the LSP response.
831// Finally, we can clean up the data structures created by Sema completion.
832//
833// Main collaborators are:
834// - semaCodeComplete sets up the compiler machinery to run code completion.
835// - CompletionRecorder captures Sema completion results, including context.
836// - SymbolIndex (Opts.Index) provides index completion results as Symbols
837// - CompletionCandidates are the result of merging Sema and Index results.
838// Each candidate points to an underlying CodeCompletionResult (Sema), a
839// Symbol (Index), or both. It computes the result quality score.
840// CompletionCandidate also does conversion to CompletionItem (at the end).
841// - FuzzyMatcher scores how the candidate matches the partial identifier.
842// This score is combined with the result quality score for the final score.
843// - TopN determines the results with the best score.
844class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000845 PathRef FileName;
Sam McCall545a20d2018-01-19 14:34:02 +0000846 const CodeCompleteOptions &Opts;
847 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000848 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000849 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
850 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000851 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
852 std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000853
854public:
855 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Eric Liuc5105f92018-02-16 14:15:55 +0000856 CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000857 : FileName(FileName), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000858
859 CompletionList run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000860 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000861
Sam McCall545a20d2018-01-19 14:34:02 +0000862 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000863 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000864 // - partial identifier and context. We need these for the index query.
865 CompletionList Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000866 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
867 assert(Recorder && "Recorder is not set");
Eric Liu63f419a2018-05-15 15:29:32 +0000868 assert(Includes && "Includes is not set");
869 // If preprocessor was run, inclusions from preprocessor callback should
870 // already be added to Inclusions.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000871 Output = runWithSema();
Eric Liu63f419a2018-05-15 15:29:32 +0000872 Includes.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000873 SPAN_ATTACH(Tracer, "sema_completion_kind",
874 getCompletionKindString(Recorder->CCContext.getKind()));
875 });
876
877 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +0000878 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +0000879 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +0000880
Sam McCall2b780162018-01-30 17:20:54 +0000881 SPAN_ATTACH(Tracer, "sema_results", NSema);
882 SPAN_ATTACH(Tracer, "index_results", NIndex);
883 SPAN_ATTACH(Tracer, "merged_results", NBoth);
884 SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
885 SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
Sam McCalld1a7a372018-01-31 13:40:48 +0000886 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
Sam McCall545a20d2018-01-19 14:34:02 +0000887 "{2} matched, {3} returned{4}.",
888 NSema, NIndex, NBoth, Output.items.size(),
889 Output.isIncomplete ? " (incomplete)" : ""));
890 assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
891 // We don't assert that isIncomplete means we hit a limit.
892 // Indexes may choose to impose their own limits even if we don't have one.
893 return Output;
894 }
895
896private:
897 // This is called by run() once Sema code completion is done, but before the
898 // Sema data structures are torn down. It does all the real work.
899 CompletionList runWithSema() {
900 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000901 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Sam McCall545a20d2018-01-19 14:34:02 +0000902 // Sema provides the needed context to query the index.
903 // FIXME: in addition to querying for extra/overlapping symbols, we should
904 // explicitly request symbols corresponding to Sema results.
905 // We can use their signals even if the index can't suggest them.
906 // We must copy index results to preserve them, but there are at most Limit.
907 auto IndexResults = queryIndex();
908 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000909 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall545a20d2018-01-19 14:34:02 +0000910 // Convert the results to the desired LSP structs.
911 CompletionList Output;
912 for (auto &C : Top)
913 Output.items.push_back(toCompletionItem(C.first, C.second));
914 Output.isIncomplete = Incomplete;
915 return Output;
916 }
917
918 SymbolSlab queryIndex() {
Ilya Biryukova907ba42018-05-14 10:50:04 +0000919 if (!Opts.Index || !allowIndex(Recorder->CCContext))
Sam McCall545a20d2018-01-19 14:34:02 +0000920 return SymbolSlab();
Sam McCalld1a7a372018-01-31 13:40:48 +0000921 trace::Span Tracer("Query index");
Sam McCall2b780162018-01-30 17:20:54 +0000922 SPAN_ATTACH(Tracer, "limit", Opts.Limit);
923
Sam McCall545a20d2018-01-19 14:34:02 +0000924 SymbolSlab::Builder ResultsBuilder;
925 // Build the query.
926 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +0000927 if (Opts.Limit)
928 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +0000929 Req.Query = Filter->pattern();
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000930 Req.Scopes = getQueryScopes(Recorder->CCContext,
931 Recorder->CCSema->getSourceManager());
Sam McCalld1a7a372018-01-31 13:40:48 +0000932 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
Sam McCall2b780162018-01-30 17:20:54 +0000933 Req.Query,
934 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Sam McCall545a20d2018-01-19 14:34:02 +0000935 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +0000936 if (Opts.Index->fuzzyFind(
937 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
938 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000939 return std::move(ResultsBuilder).build();
940 }
941
942 // Merges the Sema and Index results where possible, scores them, and
943 // returns the top results from best to worst.
944 std::vector<std::pair<CompletionCandidate, CompletionItemScores>>
945 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
946 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000947 trace::Span Tracer("Merge and score results");
Sam McCall545a20d2018-01-19 14:34:02 +0000948 // We only keep the best N results at any time, in "native" format.
Sam McCallc5707b62018-05-15 17:43:27 +0000949 TopN<ScoredCandidate, ScoredCandidateGreater> Top(
950 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +0000951 llvm::DenseSet<const Symbol *> UsedIndexResults;
952 auto CorrespondingIndexResult =
953 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
954 if (auto SymID = getSymbolID(SemaResult)) {
955 auto I = IndexResults.find(*SymID);
956 if (I != IndexResults.end()) {
957 UsedIndexResults.insert(&*I);
958 return &*I;
959 }
960 }
961 return nullptr;
962 };
963 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000964 for (auto &SemaResult : Recorder->Results)
Sam McCall545a20d2018-01-19 14:34:02 +0000965 addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult));
966 // Now emit any Index-only results.
967 for (const auto &IndexResult : IndexResults) {
968 if (UsedIndexResults.count(&IndexResult))
969 continue;
970 addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult);
971 }
972 return std::move(Top).items();
973 }
974
975 // Scores a candidate and adds it to the TopN structure.
Sam McCallc5707b62018-05-15 17:43:27 +0000976 void addCandidate(TopN<ScoredCandidate, ScoredCandidateGreater> &Candidates,
977 const CodeCompletionResult *SemaResult,
Sam McCall545a20d2018-01-19 14:34:02 +0000978 const Symbol *IndexResult) {
979 CompletionCandidate C;
980 C.SemaResult = SemaResult;
981 C.IndexResult = IndexResult;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000982 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
Sam McCall545a20d2018-01-19 14:34:02 +0000983
Sam McCallc5707b62018-05-15 17:43:27 +0000984 SymbolQualitySignals Quality;
985 SymbolRelevanceSignals Relevance;
Sam McCall545a20d2018-01-19 14:34:02 +0000986 if (auto FuzzyScore = Filter->match(C.Name))
Sam McCallc5707b62018-05-15 17:43:27 +0000987 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +0000988 else
989 return;
Sam McCallc5707b62018-05-15 17:43:27 +0000990 if (IndexResult)
991 Quality.merge(*IndexResult);
992 if (SemaResult) {
993 Quality.merge(*SemaResult);
994 Relevance.merge(*SemaResult);
995 }
996
997 float QualScore = Quality.evaluate(), RelScore = Relevance.evaluate();
998 CompletionItemScores Scores;
999 Scores.finalScore = evaluateSymbolAndRelevance(QualScore, RelScore);
1000 // The purpose of exporting component scores is to allow NameMatch to be
1001 // replaced on the client-side. So we export (NameMatch, final/NameMatch)
1002 // rather than (RelScore, QualScore).
1003 Scores.filterScore = Relevance.NameMatch;
1004 Scores.symbolScore =
1005 Scores.filterScore ? Scores.finalScore / Scores.filterScore : QualScore;
1006
Nicola Zaghenc9fed132018-05-23 13:57:48 +00001007 LLVM_DEBUG(llvm::dbgs()
1008 << "CodeComplete: " << C.Name << (IndexResult ? " (index)" : "")
1009 << (SemaResult ? " (sema)" : "") << " = " << Scores.finalScore
1010 << "\n"
1011 << Quality << Relevance << "\n");
Sam McCall545a20d2018-01-19 14:34:02 +00001012
1013 NSema += bool(SemaResult);
1014 NIndex += bool(IndexResult);
1015 NBoth += SemaResult && IndexResult;
Sam McCallab8e3932018-02-19 13:04:41 +00001016 if (Candidates.push({C, Scores}))
1017 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001018 }
1019
1020 CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
1021 const CompletionItemScores &Scores) {
1022 CodeCompletionString *SemaCCS = nullptr;
Ilya Biryukov43714502018-05-16 12:32:44 +00001023 std::string DocComment;
1024 if (auto *SR = Candidate.SemaResult) {
1025 SemaCCS = Recorder->codeCompletionString(*SR);
1026 if (Opts.IncludeComments) {
1027 assert(Recorder->CCSema);
1028 DocComment = getDocComment(Recorder->CCSema->getASTContext(), *SR);
1029 }
1030 }
1031 return Candidate.build(FileName, Scores, Opts, SemaCCS, Includes.get(), DocComment);
Sam McCall545a20d2018-01-19 14:34:02 +00001032 }
1033};
1034
Sam McCalld1a7a372018-01-31 13:40:48 +00001035CompletionList codeComplete(PathRef FileName,
Sam McCall98775c52017-12-04 13:49:59 +00001036 const tooling::CompileCommand &Command,
1037 PrecompiledPreamble const *Preamble,
Eric Liu63f419a2018-05-15 15:29:32 +00001038 const std::vector<Inclusion> &PreambleInclusions,
Sam McCall98775c52017-12-04 13:49:59 +00001039 StringRef Contents, Position Pos,
1040 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1041 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001042 CodeCompleteOptions Opts) {
Eric Liuc5105f92018-02-16 14:15:55 +00001043 return CodeCompleteFlow(FileName, Opts)
Eric Liu63f419a2018-05-15 15:29:32 +00001044 .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS,
1045 PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001046}
1047
Sam McCalld1a7a372018-01-31 13:40:48 +00001048SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001049 const tooling::CompileCommand &Command,
1050 PrecompiledPreamble const *Preamble,
1051 StringRef Contents, Position Pos,
1052 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1053 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001054 SignatureHelp Result;
1055 clang::CodeCompleteOptions Options;
1056 Options.IncludeGlobals = false;
1057 Options.IncludeMacros = false;
1058 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001059 Options.IncludeBriefComments = false;
Eric Liu4c0a27b2018-05-16 20:31:38 +00001060 std::vector<Inclusion> PreambleInclusions = {}; // Unused for signatureHelp
Sam McCalld1a7a372018-01-31 13:40:48 +00001061 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1062 Options,
Eric Liu4c0a27b2018-05-16 20:31:38 +00001063 {FileName, Command, Preamble, PreambleInclusions, Contents,
1064 Pos, std::move(VFS), std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001065 return Result;
1066}
1067
1068} // namespace clangd
1069} // namespace clang