blob: d00be58a19cd30996437eb834599df4908252ef3 [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 Biryukov295c8e12018-01-18 15:17:00 +0000657 // We reuse the preamble whether it's valid or not. This is a
658 // correctness/performance tradeoff: building without a preamble is slow, and
659 // completion is latency-sensitive.
Sam McCall545a20d2018-01-19 14:34:02 +0000660 if (Input.Preamble) {
Sam McCall98775c52017-12-04 13:49:59 +0000661 auto Bounds =
662 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov295c8e12018-01-18 15:17:00 +0000663 // FIXME(ibiryukov): Remove this call to CanReuse() after we'll fix
664 // clients relying on getting stats for preamble files during code
665 // completion.
666 // Note that results of CanReuse() are ignored, see the comment above.
Sam McCall545a20d2018-01-19 14:34:02 +0000667 Input.Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds,
668 Input.VFS.get());
Sam McCall98775c52017-12-04 13:49:59 +0000669 }
Haojian Wub603a5e2018-02-22 13:35:01 +0000670 // The diagnostic options must be set before creating a CompilerInstance.
671 CI->getDiagnosticOpts().IgnoreWarnings = true;
Sam McCall98775c52017-12-04 13:49:59 +0000672 auto Clang = prepareCompilerInstance(
Sam McCall545a20d2018-01-19 14:34:02 +0000673 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
674 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000675
Haojian Wu58d208d2018-01-25 09:44:06 +0000676 // Disable typo correction in Sema.
677 Clang->getLangOpts().SpellChecking = false;
678
Sam McCall98775c52017-12-04 13:49:59 +0000679 auto &FrontendOpts = Clang->getFrontendOpts();
680 FrontendOpts.SkipFunctionBodies = true;
681 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000682 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000683 auto Offset = positionToOffset(Input.Contents, Input.Pos);
684 if (!Offset) {
685 log("Code completion position was invalid " +
686 llvm::toString(Offset.takeError()));
687 return false;
688 }
689 std::tie(FrontendOpts.CodeCompletionAt.Line,
690 FrontendOpts.CodeCompletionAt.Column) =
691 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000692
693 Clang->setCodeCompletionConsumer(Consumer.release());
694
695 SyntaxOnlyAction Action;
696 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000697 log("BeginSourceFile() failed when running codeComplete for " +
698 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000699 return false;
700 }
Eric Liu63f419a2018-05-15 15:29:32 +0000701 if (Includes) {
702 // Initialize Includes if provided.
703
704 // FIXME(ioeric): needs more consistent style support in clangd server.
705 auto Style = format::getStyle("file", Input.FileName, "LLVM",
706 Input.Contents, Input.VFS.get());
707 if (!Style) {
708 log("Failed to get FormatStyle for file" + Input.FileName +
709 ". Fall back to use LLVM style. Error: " +
710 llvm::toString(Style.takeError()));
711 Style = format::getLLVMStyle();
712 }
713 *Includes = llvm::make_unique<IncludeInserter>(
714 Input.FileName, Input.Contents, *Style, Input.Command.Directory,
715 Clang->getPreprocessor().getHeaderSearchInfo());
716 for (const auto &Inc : Input.PreambleInclusions)
717 Includes->get()->addExisting(Inc);
718 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
719 Clang->getSourceManager(), [Includes](Inclusion Inc) {
720 Includes->get()->addExisting(std::move(Inc));
721 }));
722 }
Sam McCall98775c52017-12-04 13:49:59 +0000723 if (!Action.Execute()) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000724 log("Execute() failed when running codeComplete for " + Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000725 return false;
726 }
Sam McCall98775c52017-12-04 13:49:59 +0000727 Action.EndSourceFile();
728
729 return true;
730}
731
Ilya Biryukova907ba42018-05-14 10:50:04 +0000732// Should we perform index-based completion in a context of the specified kind?
Sam McCall545a20d2018-01-19 14:34:02 +0000733// FIXME: consider allowing completion, but restricting the result types.
Ilya Biryukova907ba42018-05-14 10:50:04 +0000734bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
Sam McCall545a20d2018-01-19 14:34:02 +0000735 switch (K) {
736 case CodeCompletionContext::CCC_TopLevel:
737 case CodeCompletionContext::CCC_ObjCInterface:
738 case CodeCompletionContext::CCC_ObjCImplementation:
739 case CodeCompletionContext::CCC_ObjCIvarList:
740 case CodeCompletionContext::CCC_ClassStructUnion:
741 case CodeCompletionContext::CCC_Statement:
742 case CodeCompletionContext::CCC_Expression:
743 case CodeCompletionContext::CCC_ObjCMessageReceiver:
744 case CodeCompletionContext::CCC_EnumTag:
745 case CodeCompletionContext::CCC_UnionTag:
746 case CodeCompletionContext::CCC_ClassOrStructTag:
747 case CodeCompletionContext::CCC_ObjCProtocolName:
748 case CodeCompletionContext::CCC_Namespace:
749 case CodeCompletionContext::CCC_Type:
750 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
751 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
752 case CodeCompletionContext::CCC_ParenthesizedExpression:
753 case CodeCompletionContext::CCC_ObjCInterfaceName:
754 case CodeCompletionContext::CCC_ObjCCategoryName:
755 return true;
756 case CodeCompletionContext::CCC_Other: // Be conservative.
757 case CodeCompletionContext::CCC_OtherWithMacros:
758 case CodeCompletionContext::CCC_DotMemberAccess:
759 case CodeCompletionContext::CCC_ArrowMemberAccess:
760 case CodeCompletionContext::CCC_ObjCPropertyAccess:
761 case CodeCompletionContext::CCC_MacroName:
762 case CodeCompletionContext::CCC_MacroNameUse:
763 case CodeCompletionContext::CCC_PreprocessorExpression:
764 case CodeCompletionContext::CCC_PreprocessorDirective:
765 case CodeCompletionContext::CCC_NaturalLanguage:
766 case CodeCompletionContext::CCC_SelectorName:
767 case CodeCompletionContext::CCC_TypeQualifiers:
768 case CodeCompletionContext::CCC_ObjCInstanceMessage:
769 case CodeCompletionContext::CCC_ObjCClassMessage:
770 case CodeCompletionContext::CCC_Recovery:
771 return false;
772 }
773 llvm_unreachable("unknown code completion context");
774}
775
Ilya Biryukova907ba42018-05-14 10:50:04 +0000776// Should we allow index completions in the specified context?
777bool allowIndex(CodeCompletionContext &CC) {
778 if (!contextAllowsIndex(CC.getKind()))
779 return false;
780 // We also avoid ClassName::bar (but allow namespace::bar).
781 auto Scope = CC.getCXXScopeSpecifier();
782 if (!Scope)
783 return true;
784 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
785 if (!NameSpec)
786 return true;
787 // We only query the index when qualifier is a namespace.
788 // If it's a class, we rely solely on sema completions.
789 switch (NameSpec->getKind()) {
790 case NestedNameSpecifier::Global:
791 case NestedNameSpecifier::Namespace:
792 case NestedNameSpecifier::NamespaceAlias:
793 return true;
794 case NestedNameSpecifier::Super:
795 case NestedNameSpecifier::TypeSpec:
796 case NestedNameSpecifier::TypeSpecWithTemplate:
797 // Unresolved inside a template.
798 case NestedNameSpecifier::Identifier:
799 return false;
800 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000801 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000802}
803
Sam McCall98775c52017-12-04 13:49:59 +0000804} // namespace
805
806clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
807 clang::CodeCompleteOptions Result;
808 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
809 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000810 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000811 // We choose to include full comments and not do doxygen parsing in
812 // completion.
813 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
814 // formatting of the comments.
815 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000816
Sam McCall3d139c52018-01-12 18:30:08 +0000817 // When an is used, Sema is responsible for completing the main file,
818 // the index can provide results from the preamble.
819 // Tell Sema not to deserialize the preamble to look for results.
820 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000821
Sam McCall98775c52017-12-04 13:49:59 +0000822 return Result;
823}
824
Sam McCall545a20d2018-01-19 14:34:02 +0000825// Runs Sema-based (AST) and Index-based completion, returns merged results.
826//
827// There are a few tricky considerations:
828// - the AST provides information needed for the index query (e.g. which
829// namespaces to search in). So Sema must start first.
830// - we only want to return the top results (Opts.Limit).
831// Building CompletionItems for everything else is wasteful, so we want to
832// preserve the "native" format until we're done with scoring.
833// - the data underlying Sema completion items is owned by the AST and various
834// other arenas, which must stay alive for us to build CompletionItems.
835// - we may get duplicate results from Sema and the Index, we need to merge.
836//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000837// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000838// We use the Sema context information to query the index.
839// Then we merge the two result sets, producing items that are Sema/Index/Both.
840// These items are scored, and the top N are synthesized into the LSP response.
841// Finally, we can clean up the data structures created by Sema completion.
842//
843// Main collaborators are:
844// - semaCodeComplete sets up the compiler machinery to run code completion.
845// - CompletionRecorder captures Sema completion results, including context.
846// - SymbolIndex (Opts.Index) provides index completion results as Symbols
847// - CompletionCandidates are the result of merging Sema and Index results.
848// Each candidate points to an underlying CodeCompletionResult (Sema), a
849// Symbol (Index), or both. It computes the result quality score.
850// CompletionCandidate also does conversion to CompletionItem (at the end).
851// - FuzzyMatcher scores how the candidate matches the partial identifier.
852// This score is combined with the result quality score for the final score.
853// - TopN determines the results with the best score.
854class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000855 PathRef FileName;
Sam McCall545a20d2018-01-19 14:34:02 +0000856 const CodeCompleteOptions &Opts;
857 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000858 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000859 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
860 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000861 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
862 std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000863
864public:
865 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Eric Liuc5105f92018-02-16 14:15:55 +0000866 CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000867 : FileName(FileName), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000868
869 CompletionList run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000870 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000871
Sam McCall545a20d2018-01-19 14:34:02 +0000872 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000873 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000874 // - partial identifier and context. We need these for the index query.
875 CompletionList Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000876 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
877 assert(Recorder && "Recorder is not set");
Eric Liu63f419a2018-05-15 15:29:32 +0000878 assert(Includes && "Includes is not set");
879 // If preprocessor was run, inclusions from preprocessor callback should
880 // already be added to Inclusions.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000881 Output = runWithSema();
Eric Liu63f419a2018-05-15 15:29:32 +0000882 Includes.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000883 SPAN_ATTACH(Tracer, "sema_completion_kind",
884 getCompletionKindString(Recorder->CCContext.getKind()));
885 });
886
887 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +0000888 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +0000889 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +0000890
Sam McCall2b780162018-01-30 17:20:54 +0000891 SPAN_ATTACH(Tracer, "sema_results", NSema);
892 SPAN_ATTACH(Tracer, "index_results", NIndex);
893 SPAN_ATTACH(Tracer, "merged_results", NBoth);
894 SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
895 SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
Sam McCalld1a7a372018-01-31 13:40:48 +0000896 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
Sam McCall545a20d2018-01-19 14:34:02 +0000897 "{2} matched, {3} returned{4}.",
898 NSema, NIndex, NBoth, Output.items.size(),
899 Output.isIncomplete ? " (incomplete)" : ""));
900 assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
901 // We don't assert that isIncomplete means we hit a limit.
902 // Indexes may choose to impose their own limits even if we don't have one.
903 return Output;
904 }
905
906private:
907 // This is called by run() once Sema code completion is done, but before the
908 // Sema data structures are torn down. It does all the real work.
909 CompletionList runWithSema() {
910 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000911 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Sam McCall545a20d2018-01-19 14:34:02 +0000912 // Sema provides the needed context to query the index.
913 // FIXME: in addition to querying for extra/overlapping symbols, we should
914 // explicitly request symbols corresponding to Sema results.
915 // We can use their signals even if the index can't suggest them.
916 // We must copy index results to preserve them, but there are at most Limit.
917 auto IndexResults = queryIndex();
918 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000919 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall545a20d2018-01-19 14:34:02 +0000920 // Convert the results to the desired LSP structs.
921 CompletionList Output;
922 for (auto &C : Top)
923 Output.items.push_back(toCompletionItem(C.first, C.second));
924 Output.isIncomplete = Incomplete;
925 return Output;
926 }
927
928 SymbolSlab queryIndex() {
Ilya Biryukova907ba42018-05-14 10:50:04 +0000929 if (!Opts.Index || !allowIndex(Recorder->CCContext))
Sam McCall545a20d2018-01-19 14:34:02 +0000930 return SymbolSlab();
Sam McCalld1a7a372018-01-31 13:40:48 +0000931 trace::Span Tracer("Query index");
Sam McCall2b780162018-01-30 17:20:54 +0000932 SPAN_ATTACH(Tracer, "limit", Opts.Limit);
933
Sam McCall545a20d2018-01-19 14:34:02 +0000934 SymbolSlab::Builder ResultsBuilder;
935 // Build the query.
936 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +0000937 if (Opts.Limit)
938 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +0000939 Req.Query = Filter->pattern();
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000940 Req.Scopes = getQueryScopes(Recorder->CCContext,
941 Recorder->CCSema->getSourceManager());
Sam McCalld1a7a372018-01-31 13:40:48 +0000942 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
Sam McCall2b780162018-01-30 17:20:54 +0000943 Req.Query,
944 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Sam McCall545a20d2018-01-19 14:34:02 +0000945 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +0000946 if (Opts.Index->fuzzyFind(
947 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
948 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000949 return std::move(ResultsBuilder).build();
950 }
951
952 // Merges the Sema and Index results where possible, scores them, and
953 // returns the top results from best to worst.
954 std::vector<std::pair<CompletionCandidate, CompletionItemScores>>
955 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
956 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000957 trace::Span Tracer("Merge and score results");
Sam McCall545a20d2018-01-19 14:34:02 +0000958 // We only keep the best N results at any time, in "native" format.
Sam McCallc5707b62018-05-15 17:43:27 +0000959 TopN<ScoredCandidate, ScoredCandidateGreater> Top(
960 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +0000961 llvm::DenseSet<const Symbol *> UsedIndexResults;
962 auto CorrespondingIndexResult =
963 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
964 if (auto SymID = getSymbolID(SemaResult)) {
965 auto I = IndexResults.find(*SymID);
966 if (I != IndexResults.end()) {
967 UsedIndexResults.insert(&*I);
968 return &*I;
969 }
970 }
971 return nullptr;
972 };
973 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000974 for (auto &SemaResult : Recorder->Results)
Sam McCall545a20d2018-01-19 14:34:02 +0000975 addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult));
976 // Now emit any Index-only results.
977 for (const auto &IndexResult : IndexResults) {
978 if (UsedIndexResults.count(&IndexResult))
979 continue;
980 addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult);
981 }
982 return std::move(Top).items();
983 }
984
985 // Scores a candidate and adds it to the TopN structure.
Sam McCallc5707b62018-05-15 17:43:27 +0000986 void addCandidate(TopN<ScoredCandidate, ScoredCandidateGreater> &Candidates,
987 const CodeCompletionResult *SemaResult,
Sam McCall545a20d2018-01-19 14:34:02 +0000988 const Symbol *IndexResult) {
989 CompletionCandidate C;
990 C.SemaResult = SemaResult;
991 C.IndexResult = IndexResult;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000992 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
Sam McCall545a20d2018-01-19 14:34:02 +0000993
Sam McCallc5707b62018-05-15 17:43:27 +0000994 SymbolQualitySignals Quality;
995 SymbolRelevanceSignals Relevance;
Sam McCall545a20d2018-01-19 14:34:02 +0000996 if (auto FuzzyScore = Filter->match(C.Name))
Sam McCallc5707b62018-05-15 17:43:27 +0000997 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +0000998 else
999 return;
Sam McCallc5707b62018-05-15 17:43:27 +00001000 if (IndexResult)
1001 Quality.merge(*IndexResult);
1002 if (SemaResult) {
1003 Quality.merge(*SemaResult);
1004 Relevance.merge(*SemaResult);
1005 }
1006
1007 float QualScore = Quality.evaluate(), RelScore = Relevance.evaluate();
1008 CompletionItemScores Scores;
1009 Scores.finalScore = evaluateSymbolAndRelevance(QualScore, RelScore);
1010 // The purpose of exporting component scores is to allow NameMatch to be
1011 // replaced on the client-side. So we export (NameMatch, final/NameMatch)
1012 // rather than (RelScore, QualScore).
1013 Scores.filterScore = Relevance.NameMatch;
1014 Scores.symbolScore =
1015 Scores.filterScore ? Scores.finalScore / Scores.filterScore : QualScore;
1016
1017 DEBUG(llvm::dbgs() << "CodeComplete: " << C.Name
1018 << (IndexResult ? " (index)" : "")
1019 << (SemaResult ? " (sema)" : "") << " = "
1020 << Scores.finalScore << "\n"
1021 << Quality << Relevance << "\n");
Sam McCall545a20d2018-01-19 14:34:02 +00001022
1023 NSema += bool(SemaResult);
1024 NIndex += bool(IndexResult);
1025 NBoth += SemaResult && IndexResult;
Sam McCallab8e3932018-02-19 13:04:41 +00001026 if (Candidates.push({C, Scores}))
1027 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001028 }
1029
1030 CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
1031 const CompletionItemScores &Scores) {
1032 CodeCompletionString *SemaCCS = nullptr;
Ilya Biryukov43714502018-05-16 12:32:44 +00001033 std::string DocComment;
1034 if (auto *SR = Candidate.SemaResult) {
1035 SemaCCS = Recorder->codeCompletionString(*SR);
1036 if (Opts.IncludeComments) {
1037 assert(Recorder->CCSema);
1038 DocComment = getDocComment(Recorder->CCSema->getASTContext(), *SR);
1039 }
1040 }
1041 return Candidate.build(FileName, Scores, Opts, SemaCCS, Includes.get(), DocComment);
Sam McCall545a20d2018-01-19 14:34:02 +00001042 }
1043};
1044
Sam McCalld1a7a372018-01-31 13:40:48 +00001045CompletionList codeComplete(PathRef FileName,
Sam McCall98775c52017-12-04 13:49:59 +00001046 const tooling::CompileCommand &Command,
1047 PrecompiledPreamble const *Preamble,
Eric Liu63f419a2018-05-15 15:29:32 +00001048 const std::vector<Inclusion> &PreambleInclusions,
Sam McCall98775c52017-12-04 13:49:59 +00001049 StringRef Contents, Position Pos,
1050 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1051 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001052 CodeCompleteOptions Opts) {
Eric Liuc5105f92018-02-16 14:15:55 +00001053 return CodeCompleteFlow(FileName, Opts)
Eric Liu63f419a2018-05-15 15:29:32 +00001054 .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS,
1055 PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001056}
1057
Sam McCalld1a7a372018-01-31 13:40:48 +00001058SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001059 const tooling::CompileCommand &Command,
1060 PrecompiledPreamble const *Preamble,
1061 StringRef Contents, Position Pos,
1062 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1063 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001064 SignatureHelp Result;
1065 clang::CodeCompleteOptions Options;
1066 Options.IncludeGlobals = false;
1067 Options.IncludeMacros = false;
1068 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001069 Options.IncludeBriefComments = false;
Sam McCalld1a7a372018-01-31 13:40:48 +00001070 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1071 Options,
Eric Liuf8947da2018-05-16 19:59:49 +00001072 {FileName, Command, Preamble, std::vector<Inclusion>(),
1073 Contents, Pos, std::move(VFS), std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001074 return Result;
1075}
1076
1077} // namespace clangd
1078} // namespace clang