blob: 1581914257a88363ce4706ef63a97d53320b6fa9 [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"
Eric Liuc5105f92018-02-16 14:15:55 +000028#include "clang/Format/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000029#include "clang/Frontend/CompilerInstance.h"
30#include "clang/Frontend/FrontendActions.h"
Sam McCall545a20d2018-01-19 14:34:02 +000031#include "clang/Index/USRGeneration.h"
Sam McCall98775c52017-12-04 13:49:59 +000032#include "clang/Sema/CodeCompleteConsumer.h"
33#include "clang/Sema/Sema.h"
Eric Liuc5105f92018-02-16 14:15:55 +000034#include "clang/Tooling/Core/Replacement.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000035#include "llvm/Support/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000036#include <queue>
37
Sam McCallc5707b62018-05-15 17:43:27 +000038// We log detailed candidate here if you run with -debug-only=codecomplete.
39#define DEBUG_TYPE "codecomplete"
40
Sam McCall98775c52017-12-04 13:49:59 +000041namespace clang {
42namespace clangd {
43namespace {
44
Eric Liu6f648df2017-12-19 16:50:37 +000045CompletionItemKind toCompletionItemKind(CXCursorKind CursorKind) {
Sam McCall98775c52017-12-04 13:49:59 +000046 switch (CursorKind) {
47 case CXCursor_MacroInstantiation:
48 case CXCursor_MacroDefinition:
49 return CompletionItemKind::Text;
50 case CXCursor_CXXMethod:
Eric Liu6f648df2017-12-19 16:50:37 +000051 case CXCursor_Destructor:
Sam McCall98775c52017-12-04 13:49:59 +000052 return CompletionItemKind::Method;
53 case CXCursor_FunctionDecl:
54 case CXCursor_FunctionTemplate:
55 return CompletionItemKind::Function;
56 case CXCursor_Constructor:
Sam McCall98775c52017-12-04 13:49:59 +000057 return CompletionItemKind::Constructor;
58 case CXCursor_FieldDecl:
59 return CompletionItemKind::Field;
60 case CXCursor_VarDecl:
61 case CXCursor_ParmDecl:
62 return CompletionItemKind::Variable;
Eric Liu6f648df2017-12-19 16:50:37 +000063 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
64 // protocol.
Sam McCall98775c52017-12-04 13:49:59 +000065 case CXCursor_StructDecl:
Eric Liu6f648df2017-12-19 16:50:37 +000066 case CXCursor_ClassDecl:
Sam McCall98775c52017-12-04 13:49:59 +000067 case CXCursor_UnionDecl:
68 case CXCursor_ClassTemplate:
69 case CXCursor_ClassTemplatePartialSpecialization:
70 return CompletionItemKind::Class;
71 case CXCursor_Namespace:
72 case CXCursor_NamespaceAlias:
73 case CXCursor_NamespaceRef:
74 return CompletionItemKind::Module;
75 case CXCursor_EnumConstantDecl:
76 return CompletionItemKind::Value;
77 case CXCursor_EnumDecl:
78 return CompletionItemKind::Enum;
Eric Liu6f648df2017-12-19 16:50:37 +000079 // FIXME(ioeric): figure out whether reference is the right type for aliases.
Sam McCall98775c52017-12-04 13:49:59 +000080 case CXCursor_TypeAliasDecl:
81 case CXCursor_TypeAliasTemplateDecl:
82 case CXCursor_TypedefDecl:
83 case CXCursor_MemberRef:
84 case CXCursor_TypeRef:
85 return CompletionItemKind::Reference;
86 default:
87 return CompletionItemKind::Missing;
88 }
89}
90
Eric Liu6f648df2017-12-19 16:50:37 +000091CompletionItemKind
92toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
93 CXCursorKind CursorKind) {
Sam McCall98775c52017-12-04 13:49:59 +000094 switch (ResKind) {
95 case CodeCompletionResult::RK_Declaration:
Eric Liu6f648df2017-12-19 16:50:37 +000096 return toCompletionItemKind(CursorKind);
Sam McCall98775c52017-12-04 13:49:59 +000097 case CodeCompletionResult::RK_Keyword:
98 return CompletionItemKind::Keyword;
99 case CodeCompletionResult::RK_Macro:
100 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
101 // completion items in LSP.
102 case CodeCompletionResult::RK_Pattern:
103 return CompletionItemKind::Snippet;
104 }
105 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
106}
107
Eric Liu6f648df2017-12-19 16:50:37 +0000108CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
109 using SK = index::SymbolKind;
110 switch (Kind) {
111 case SK::Unknown:
112 return CompletionItemKind::Missing;
113 case SK::Module:
114 case SK::Namespace:
115 case SK::NamespaceAlias:
116 return CompletionItemKind::Module;
117 case SK::Macro:
118 return CompletionItemKind::Text;
119 case SK::Enum:
120 return CompletionItemKind::Enum;
121 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
122 // protocol.
123 case SK::Struct:
124 case SK::Class:
125 case SK::Protocol:
126 case SK::Extension:
127 case SK::Union:
128 return CompletionItemKind::Class;
129 // FIXME(ioeric): figure out whether reference is the right type for aliases.
130 case SK::TypeAlias:
131 case SK::Using:
132 return CompletionItemKind::Reference;
133 case SK::Function:
134 // FIXME(ioeric): this should probably be an operator. This should be fixed
135 // when `Operator` is support type in the protocol.
136 case SK::ConversionFunction:
137 return CompletionItemKind::Function;
138 case SK::Variable:
139 case SK::Parameter:
140 return CompletionItemKind::Variable;
141 case SK::Field:
142 return CompletionItemKind::Field;
143 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
144 case SK::EnumConstant:
145 return CompletionItemKind::Value;
146 case SK::InstanceMethod:
147 case SK::ClassMethod:
148 case SK::StaticMethod:
149 case SK::Destructor:
150 return CompletionItemKind::Method;
151 case SK::InstanceProperty:
152 case SK::ClassProperty:
153 case SK::StaticProperty:
154 return CompletionItemKind::Property;
155 case SK::Constructor:
156 return CompletionItemKind::Constructor;
157 }
158 llvm_unreachable("Unhandled clang::index::SymbolKind.");
159}
160
Sam McCall98775c52017-12-04 13:49:59 +0000161/// Get the optional chunk as a string. This function is possibly recursive.
162///
163/// The parameter info for each parameter is appended to the Parameters.
164std::string
165getOptionalParameters(const CodeCompletionString &CCS,
166 std::vector<ParameterInformation> &Parameters) {
167 std::string Result;
168 for (const auto &Chunk : CCS) {
169 switch (Chunk.Kind) {
170 case CodeCompletionString::CK_Optional:
171 assert(Chunk.Optional &&
172 "Expected the optional code completion string to be non-null.");
173 Result += getOptionalParameters(*Chunk.Optional, Parameters);
174 break;
175 case CodeCompletionString::CK_VerticalSpace:
176 break;
177 case CodeCompletionString::CK_Placeholder:
178 // A string that acts as a placeholder for, e.g., a function call
179 // argument.
180 // Intentional fallthrough here.
181 case CodeCompletionString::CK_CurrentParameter: {
182 // A piece of text that describes the parameter that corresponds to
183 // the code-completion location within a function call, message send,
184 // macro invocation, etc.
185 Result += Chunk.Text;
186 ParameterInformation Info;
187 Info.label = Chunk.Text;
188 Parameters.push_back(std::move(Info));
189 break;
190 }
191 default:
192 Result += Chunk.Text;
193 break;
194 }
195 }
196 return Result;
197}
198
Eric Liu63f419a2018-05-15 15:29:32 +0000199/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
200/// include.
201static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
202 llvm::StringRef HintPath) {
203 if (isLiteralInclude(Header))
204 return HeaderFile{Header.str(), /*Verbatim=*/true};
205 auto U = URI::parse(Header);
206 if (!U)
207 return U.takeError();
208
209 auto IncludePath = URI::includeSpelling(*U);
210 if (!IncludePath)
211 return IncludePath.takeError();
212 if (!IncludePath->empty())
213 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
214
215 auto Resolved = URI::resolve(*U, HintPath);
216 if (!Resolved)
217 return Resolved.takeError();
218 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
219}
220
Sam McCall545a20d2018-01-19 14:34:02 +0000221/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000222/// It may be promoted to a CompletionItem if it's among the top-ranked results.
223struct CompletionCandidate {
Sam McCall545a20d2018-01-19 14:34:02 +0000224 llvm::StringRef Name; // Used for filtering and sorting.
225 // We may have a result from Sema, from the index, or both.
226 const CodeCompletionResult *SemaResult = nullptr;
227 const Symbol *IndexResult = nullptr;
Sam McCall98775c52017-12-04 13:49:59 +0000228
Sam McCall545a20d2018-01-19 14:34:02 +0000229 // Builds an LSP completion item.
Eric Liu63f419a2018-05-15 15:29:32 +0000230 CompletionItem build(StringRef FileName, const CompletionItemScores &Scores,
Sam McCall545a20d2018-01-19 14:34:02 +0000231 const CodeCompleteOptions &Opts,
Eric Liu63f419a2018-05-15 15:29:32 +0000232 CodeCompletionString *SemaCCS,
Ilya Biryukov43714502018-05-16 12:32:44 +0000233 const IncludeInserter *Includes,
234 llvm::StringRef SemaDocComment) const {
Sam McCall545a20d2018-01-19 14:34:02 +0000235 assert(bool(SemaResult) == bool(SemaCCS));
236 CompletionItem I;
237 if (SemaResult) {
238 I.kind = toCompletionItemKind(SemaResult->Kind, SemaResult->CursorKind);
239 getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText,
240 Opts.EnableSnippets);
241 I.filterText = getFilterText(*SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +0000242 I.documentation = formatDocumentation(*SemaCCS, SemaDocComment);
Sam McCall545a20d2018-01-19 14:34:02 +0000243 I.detail = getDetail(*SemaCCS);
244 }
245 if (IndexResult) {
246 if (I.kind == CompletionItemKind::Missing)
247 I.kind = toCompletionItemKind(IndexResult->SymInfo.Kind);
248 // FIXME: reintroduce a way to show the index source for debugging.
249 if (I.label.empty())
250 I.label = IndexResult->CompletionLabel;
251 if (I.filterText.empty())
252 I.filterText = IndexResult->Name;
Sam McCall98775c52017-12-04 13:49:59 +0000253
Sam McCall545a20d2018-01-19 14:34:02 +0000254 // FIXME(ioeric): support inserting/replacing scope qualifiers.
255 if (I.insertText.empty())
256 I.insertText = Opts.EnableSnippets
257 ? IndexResult->CompletionSnippetInsertText
258 : IndexResult->CompletionPlainInsertText;
259
260 if (auto *D = IndexResult->Detail) {
261 if (I.documentation.empty())
262 I.documentation = D->Documentation;
263 if (I.detail.empty())
264 I.detail = D->CompletionDetail;
Eric Liu63f419a2018-05-15 15:29:32 +0000265 if (Includes && !D->IncludeHeader.empty()) {
266 auto Edit = [&]() -> Expected<Optional<TextEdit>> {
267 auto ResolvedDeclaring = toHeaderFile(
268 IndexResult->CanonicalDeclaration.FileURI, FileName);
269 if (!ResolvedDeclaring)
270 return ResolvedDeclaring.takeError();
271 auto ResolvedInserted = toHeaderFile(D->IncludeHeader, FileName);
272 if (!ResolvedInserted)
273 return ResolvedInserted.takeError();
274 return Includes->insert(*ResolvedDeclaring, *ResolvedInserted);
275 }();
276 if (!Edit) {
277 std::string ErrMsg =
278 ("Failed to generate include insertion edits for adding header "
279 "(FileURI=\"" +
280 IndexResult->CanonicalDeclaration.FileURI +
281 "\", IncludeHeader=\"" + D->IncludeHeader + "\") into " +
282 FileName)
283 .str();
284 log(ErrMsg + ":" + llvm::toString(Edit.takeError()));
285 } else if (*Edit) {
286 I.additionalTextEdits = {std::move(**Edit)};
287 }
288 }
Sam McCall545a20d2018-01-19 14:34:02 +0000289 }
290 }
291 I.scoreInfo = Scores;
292 I.sortText = sortText(Scores.finalScore, Name);
293 I.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
294 : InsertTextFormat::PlainText;
295 return I;
Sam McCall98775c52017-12-04 13:49:59 +0000296 }
297};
Sam McCallc5707b62018-05-15 17:43:27 +0000298using ScoredCandidate = std::pair<CompletionCandidate, CompletionItemScores>;
Sam McCall98775c52017-12-04 13:49:59 +0000299
Sam McCall545a20d2018-01-19 14:34:02 +0000300// Determine the symbol ID for a Sema code completion result, if possible.
301llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
302 switch (R.Kind) {
303 case CodeCompletionResult::RK_Declaration:
304 case CodeCompletionResult::RK_Pattern: {
305 llvm::SmallString<128> USR;
306 if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
307 return None;
308 return SymbolID(USR);
309 }
310 case CodeCompletionResult::RK_Macro:
311 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
312 case CodeCompletionResult::RK_Keyword:
313 return None;
314 }
315 llvm_unreachable("unknown CodeCompletionResult kind");
316}
317
Haojian Wu061c73e2018-01-23 11:37:26 +0000318// Scopes of the paritial identifier we're trying to complete.
319// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000320struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000321 // The scopes we should look in, determined by Sema.
322 //
323 // If the qualifier was fully resolved, we look for completions in these
324 // scopes; if there is an unresolved part of the qualifier, it should be
325 // resolved within these scopes.
326 //
327 // Examples of qualified completion:
328 //
329 // "::vec" => {""}
330 // "using namespace std; ::vec^" => {"", "std::"}
331 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
332 // "std::vec^" => {""} // "std" unresolved
333 //
334 // Examples of unqualified completion:
335 //
336 // "vec^" => {""}
337 // "using namespace std; vec^" => {"", "std::"}
338 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
339 //
340 // "" for global namespace, "ns::" for normal namespace.
341 std::vector<std::string> AccessibleScopes;
342 // The full scope qualifier as typed by the user (without the leading "::").
343 // Set if the qualifier is not fully resolved by Sema.
344 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000345
Haojian Wu061c73e2018-01-23 11:37:26 +0000346 // Construct scopes being queried in indexes.
347 // This method format the scopes to match the index request representation.
348 std::vector<std::string> scopesForIndexQuery() {
349 std::vector<std::string> Results;
350 for (llvm::StringRef AS : AccessibleScopes) {
351 Results.push_back(AS);
352 if (UnresolvedQualifier)
353 Results.back() += *UnresolvedQualifier;
354 }
355 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000356 }
Eric Liu6f648df2017-12-19 16:50:37 +0000357};
358
Haojian Wu061c73e2018-01-23 11:37:26 +0000359// Get all scopes that will be queried in indexes.
360std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
361 const SourceManager& SM) {
362 auto GetAllAccessibleScopes = [](CodeCompletionContext& CCContext) {
363 SpecifiedScope Info;
364 for (auto* Context : CCContext.getVisitedContexts()) {
365 if (isa<TranslationUnitDecl>(Context))
366 Info.AccessibleScopes.push_back(""); // global namespace
367 else if (const auto*NS = dyn_cast<NamespaceDecl>(Context))
368 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
369 }
370 return Info;
371 };
372
373 auto SS = CCContext.getCXXScopeSpecifier();
374
375 // Unqualified completion (e.g. "vec^").
376 if (!SS) {
377 // FIXME: Once we can insert namespace qualifiers and use the in-scope
378 // namespaces for scoring, search in all namespaces.
379 // FIXME: Capture scopes and use for scoring, for example,
380 // "using namespace std; namespace foo {v^}" =>
381 // foo::value > std::vector > boost::variant
382 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
383 }
384
385 // Qualified completion ("std::vec^"), we have two cases depending on whether
386 // the qualifier can be resolved by Sema.
387 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000388 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
389 }
390
391 // Unresolved qualifier.
392 // FIXME: When Sema can resolve part of a scope chain (e.g.
393 // "known::unknown::id"), we should expand the known part ("known::") rather
394 // than treating the whole thing as unknown.
395 SpecifiedScope Info;
396 Info.AccessibleScopes.push_back(""); // global namespace
397
398 Info.UnresolvedQualifier =
399 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()),
400 SM, clang::LangOptions()).ltrim("::");
401 // Sema excludes the trailing "::".
402 if (!Info.UnresolvedQualifier->empty())
403 *Info.UnresolvedQualifier += "::";
404
405 return Info.scopesForIndexQuery();
406}
407
Sam McCall545a20d2018-01-19 14:34:02 +0000408// The CompletionRecorder captures Sema code-complete output, including context.
409// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
410// It doesn't do scoring or conversion to CompletionItem yet, as we want to
411// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000412// Generally the fields and methods of this object should only be used from
413// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000414struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000415 CompletionRecorder(const CodeCompleteOptions &Opts,
416 UniqueFunction<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000417 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000418 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000419 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
420 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000421 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
422 assert(this->ResultsCallback);
423 }
424
Sam McCall545a20d2018-01-19 14:34:02 +0000425 std::vector<CodeCompletionResult> Results;
426 CodeCompletionContext CCContext;
427 Sema *CCSema = nullptr; // Sema that created the results.
428 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000429
Sam McCall545a20d2018-01-19 14:34:02 +0000430 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
431 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000432 unsigned NumResults) override final {
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000433 if (CCSema) {
434 log(llvm::formatv(
435 "Multiple code complete callbacks (parser backtracked?). "
436 "Dropping results from context {0}, keeping results from {1}.",
437 getCompletionKindString(this->CCContext.getKind()),
438 getCompletionKindString(Context.getKind())));
439 return;
440 }
Sam McCall545a20d2018-01-19 14:34:02 +0000441 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000442 CCSema = &S;
443 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000444
Sam McCall545a20d2018-01-19 14:34:02 +0000445 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000446 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000447 auto &Result = InResults[I];
448 // Drop hidden items which cannot be found by lookup after completion.
449 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000450 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
451 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000452 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000453 (Result.Availability == CXAvailability_NotAvailable ||
454 Result.Availability == CXAvailability_NotAccessible))
455 continue;
Sam McCalld2a95922018-01-22 21:05:00 +0000456 // Destructor completion is rarely useful, and works inconsistently.
457 // (s.^ completes ~string, but s.~st^ is an error).
458 if (dyn_cast_or_null<CXXDestructorDecl>(Result.Declaration))
459 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000460 // We choose to never append '::' to completion results in clangd.
461 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000462 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000463 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000464 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000465 }
466
Sam McCall545a20d2018-01-19 14:34:02 +0000467 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000468 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
469
Sam McCall545a20d2018-01-19 14:34:02 +0000470 // Returns the filtering/sorting name for Result, which must be from Results.
471 // Returned string is owned by this recorder (or the AST).
472 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000473 switch (Result.Kind) {
474 case CodeCompletionResult::RK_Declaration:
475 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000476 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000477 break;
478 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000479 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000480 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000481 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000482 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000483 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000484 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000485 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000486 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000487 }
488
Sam McCall545a20d2018-01-19 14:34:02 +0000489 // Build a CodeCompletion string for R, which must be from Results.
490 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000491 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000492 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
493 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000494 *CCSema, CCContext, *CCAllocator, CCTUInfo,
495 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000496 }
497
Sam McCall545a20d2018-01-19 14:34:02 +0000498private:
499 CodeCompleteOptions Opts;
500 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000501 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000502 UniqueFunction<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000503};
504
Sam McCallc5707b62018-05-15 17:43:27 +0000505struct ScoredCandidateGreater {
506 bool operator()(const ScoredCandidate &L, const ScoredCandidate &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000507 if (L.second.finalScore != R.second.finalScore)
508 return L.second.finalScore > R.second.finalScore;
509 return L.first.Name < R.first.Name; // Earlier name is better.
510 }
Sam McCall545a20d2018-01-19 14:34:02 +0000511};
Sam McCall98775c52017-12-04 13:49:59 +0000512
Sam McCall98775c52017-12-04 13:49:59 +0000513class SignatureHelpCollector final : public CodeCompleteConsumer {
514
515public:
516 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
517 SignatureHelp &SigHelp)
518 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
519 SigHelp(SigHelp),
520 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
521 CCTUInfo(Allocator) {}
522
523 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
524 OverloadCandidate *Candidates,
525 unsigned NumCandidates) override {
526 SigHelp.signatures.reserve(NumCandidates);
527 // FIXME(rwols): How can we determine the "active overload candidate"?
528 // Right now the overloaded candidates seem to be provided in a "best fit"
529 // order, so I'm not too worried about this.
530 SigHelp.activeSignature = 0;
531 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
532 "too many arguments");
533 SigHelp.activeParameter = static_cast<int>(CurrentArg);
534 for (unsigned I = 0; I < NumCandidates; ++I) {
535 const auto &Candidate = Candidates[I];
536 const auto *CCS = Candidate.CreateSignatureString(
537 CurrentArg, S, *Allocator, CCTUInfo, true);
538 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukov43714502018-05-16 12:32:44 +0000539 SigHelp.signatures.push_back(ProcessOverloadCandidate(
540 Candidate, *CCS,
541 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg)));
Sam McCall98775c52017-12-04 13:49:59 +0000542 }
543 }
544
545 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
546
547 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
548
549private:
Eric Liu63696e12017-12-20 17:24:31 +0000550 // FIXME(ioeric): consider moving CodeCompletionString logic here to
551 // CompletionString.h.
Sam McCall98775c52017-12-04 13:49:59 +0000552 SignatureInformation
553 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
Ilya Biryukov43714502018-05-16 12:32:44 +0000554 const CodeCompletionString &CCS,
555 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000556 SignatureInformation Result;
557 const char *ReturnType = nullptr;
558
Ilya Biryukov43714502018-05-16 12:32:44 +0000559 Result.documentation = formatDocumentation(CCS, DocComment);
Sam McCall98775c52017-12-04 13:49:59 +0000560
561 for (const auto &Chunk : CCS) {
562 switch (Chunk.Kind) {
563 case CodeCompletionString::CK_ResultType:
564 // A piece of text that describes the type of an entity or,
565 // for functions and methods, the return type.
566 assert(!ReturnType && "Unexpected CK_ResultType");
567 ReturnType = Chunk.Text;
568 break;
569 case CodeCompletionString::CK_Placeholder:
570 // A string that acts as a placeholder for, e.g., a function call
571 // argument.
572 // Intentional fallthrough here.
573 case CodeCompletionString::CK_CurrentParameter: {
574 // A piece of text that describes the parameter that corresponds to
575 // the code-completion location within a function call, message send,
576 // macro invocation, etc.
577 Result.label += Chunk.Text;
578 ParameterInformation Info;
579 Info.label = Chunk.Text;
580 Result.parameters.push_back(std::move(Info));
581 break;
582 }
583 case CodeCompletionString::CK_Optional: {
584 // The rest of the parameters are defaulted/optional.
585 assert(Chunk.Optional &&
586 "Expected the optional code completion string to be non-null.");
587 Result.label +=
588 getOptionalParameters(*Chunk.Optional, Result.parameters);
589 break;
590 }
591 case CodeCompletionString::CK_VerticalSpace:
592 break;
593 default:
594 Result.label += Chunk.Text;
595 break;
596 }
597 }
598 if (ReturnType) {
599 Result.label += " -> ";
600 Result.label += ReturnType;
601 }
602 return Result;
603 }
604
605 SignatureHelp &SigHelp;
606 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
607 CodeCompletionTUInfo CCTUInfo;
608
609}; // SignatureHelpCollector
610
Sam McCall545a20d2018-01-19 14:34:02 +0000611struct SemaCompleteInput {
612 PathRef FileName;
613 const tooling::CompileCommand &Command;
614 PrecompiledPreamble const *Preamble;
Eric Liu63f419a2018-05-15 15:29:32 +0000615 const std::vector<Inclusion> &PreambleInclusions;
Sam McCall545a20d2018-01-19 14:34:02 +0000616 StringRef Contents;
617 Position Pos;
618 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
619 std::shared_ptr<PCHContainerOperations> PCHs;
620};
621
622// Invokes Sema code completion on a file.
Eric Liu63f419a2018-05-15 15:29:32 +0000623// If \p Includes is set, it will be initialized after a compiler instance has
624// been set up.
Sam McCalld1a7a372018-01-31 13:40:48 +0000625bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000626 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000627 const SemaCompleteInput &Input,
628 std::unique_ptr<IncludeInserter> *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000629 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000630 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000631 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000632 ArgStrs.push_back(S.c_str());
633
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000634 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
635 log("Couldn't set working directory");
636 // We run parsing anyway, our lit-tests rely on results for non-existing
637 // working dirs.
638 }
Sam McCall98775c52017-12-04 13:49:59 +0000639
640 IgnoreDiagnostics DummyDiagsConsumer;
641 auto CI = createInvocationFromCommandLine(
642 ArgStrs,
643 CompilerInstance::createDiagnostics(new DiagnosticOptions,
644 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000645 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000646 if (!CI) {
647 log("Couldn't create CompilerInvocation");;
648 return false;
649 }
Ilya Biryukov71590652018-01-05 13:36:55 +0000650 CI->getFrontendOpts().DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000651
652 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
Sam McCall545a20d2018-01-19 14:34:02 +0000653 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000654
Ilya Biryukov295c8e12018-01-18 15:17:00 +0000655 // We reuse the preamble whether it's valid or not. This is a
656 // correctness/performance tradeoff: building without a preamble is slow, and
657 // completion is latency-sensitive.
Sam McCall545a20d2018-01-19 14:34:02 +0000658 if (Input.Preamble) {
Sam McCall98775c52017-12-04 13:49:59 +0000659 auto Bounds =
660 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov295c8e12018-01-18 15:17:00 +0000661 // FIXME(ibiryukov): Remove this call to CanReuse() after we'll fix
662 // clients relying on getting stats for preamble files during code
663 // completion.
664 // Note that results of CanReuse() are ignored, see the comment above.
Sam McCall545a20d2018-01-19 14:34:02 +0000665 Input.Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds,
666 Input.VFS.get());
Sam McCall98775c52017-12-04 13:49:59 +0000667 }
Haojian Wub603a5e2018-02-22 13:35:01 +0000668 // The diagnostic options must be set before creating a CompilerInstance.
669 CI->getDiagnosticOpts().IgnoreWarnings = true;
Sam McCall98775c52017-12-04 13:49:59 +0000670 auto Clang = prepareCompilerInstance(
Sam McCall545a20d2018-01-19 14:34:02 +0000671 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
672 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000673
Haojian Wu58d208d2018-01-25 09:44:06 +0000674 // Disable typo correction in Sema.
675 Clang->getLangOpts().SpellChecking = false;
676
Sam McCall98775c52017-12-04 13:49:59 +0000677 auto &FrontendOpts = Clang->getFrontendOpts();
678 FrontendOpts.SkipFunctionBodies = true;
679 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000680 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000681 auto Offset = positionToOffset(Input.Contents, Input.Pos);
682 if (!Offset) {
683 log("Code completion position was invalid " +
684 llvm::toString(Offset.takeError()));
685 return false;
686 }
687 std::tie(FrontendOpts.CodeCompletionAt.Line,
688 FrontendOpts.CodeCompletionAt.Column) =
689 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000690
691 Clang->setCodeCompletionConsumer(Consumer.release());
692
693 SyntaxOnlyAction Action;
694 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000695 log("BeginSourceFile() failed when running codeComplete for " +
696 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000697 return false;
698 }
Eric Liu63f419a2018-05-15 15:29:32 +0000699 if (Includes) {
700 // Initialize Includes if provided.
701
702 // FIXME(ioeric): needs more consistent style support in clangd server.
703 auto Style = format::getStyle("file", Input.FileName, "LLVM",
704 Input.Contents, Input.VFS.get());
705 if (!Style) {
706 log("Failed to get FormatStyle for file" + Input.FileName +
707 ". Fall back to use LLVM style. Error: " +
708 llvm::toString(Style.takeError()));
709 Style = format::getLLVMStyle();
710 }
711 *Includes = llvm::make_unique<IncludeInserter>(
712 Input.FileName, Input.Contents, *Style, Input.Command.Directory,
713 Clang->getPreprocessor().getHeaderSearchInfo());
714 for (const auto &Inc : Input.PreambleInclusions)
715 Includes->get()->addExisting(Inc);
716 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
717 Clang->getSourceManager(), [Includes](Inclusion Inc) {
718 Includes->get()->addExisting(std::move(Inc));
719 }));
720 }
Sam McCall98775c52017-12-04 13:49:59 +0000721 if (!Action.Execute()) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000722 log("Execute() failed when running codeComplete for " + Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000723 return false;
724 }
Sam McCall98775c52017-12-04 13:49:59 +0000725 Action.EndSourceFile();
726
727 return true;
728}
729
Ilya Biryukova907ba42018-05-14 10:50:04 +0000730// Should we perform index-based completion in a context of the specified kind?
Sam McCall545a20d2018-01-19 14:34:02 +0000731// FIXME: consider allowing completion, but restricting the result types.
Ilya Biryukova907ba42018-05-14 10:50:04 +0000732bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
Sam McCall545a20d2018-01-19 14:34:02 +0000733 switch (K) {
734 case CodeCompletionContext::CCC_TopLevel:
735 case CodeCompletionContext::CCC_ObjCInterface:
736 case CodeCompletionContext::CCC_ObjCImplementation:
737 case CodeCompletionContext::CCC_ObjCIvarList:
738 case CodeCompletionContext::CCC_ClassStructUnion:
739 case CodeCompletionContext::CCC_Statement:
740 case CodeCompletionContext::CCC_Expression:
741 case CodeCompletionContext::CCC_ObjCMessageReceiver:
742 case CodeCompletionContext::CCC_EnumTag:
743 case CodeCompletionContext::CCC_UnionTag:
744 case CodeCompletionContext::CCC_ClassOrStructTag:
745 case CodeCompletionContext::CCC_ObjCProtocolName:
746 case CodeCompletionContext::CCC_Namespace:
747 case CodeCompletionContext::CCC_Type:
748 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
749 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
750 case CodeCompletionContext::CCC_ParenthesizedExpression:
751 case CodeCompletionContext::CCC_ObjCInterfaceName:
752 case CodeCompletionContext::CCC_ObjCCategoryName:
753 return true;
754 case CodeCompletionContext::CCC_Other: // Be conservative.
755 case CodeCompletionContext::CCC_OtherWithMacros:
756 case CodeCompletionContext::CCC_DotMemberAccess:
757 case CodeCompletionContext::CCC_ArrowMemberAccess:
758 case CodeCompletionContext::CCC_ObjCPropertyAccess:
759 case CodeCompletionContext::CCC_MacroName:
760 case CodeCompletionContext::CCC_MacroNameUse:
761 case CodeCompletionContext::CCC_PreprocessorExpression:
762 case CodeCompletionContext::CCC_PreprocessorDirective:
763 case CodeCompletionContext::CCC_NaturalLanguage:
764 case CodeCompletionContext::CCC_SelectorName:
765 case CodeCompletionContext::CCC_TypeQualifiers:
766 case CodeCompletionContext::CCC_ObjCInstanceMessage:
767 case CodeCompletionContext::CCC_ObjCClassMessage:
768 case CodeCompletionContext::CCC_Recovery:
769 return false;
770 }
771 llvm_unreachable("unknown code completion context");
772}
773
Ilya Biryukova907ba42018-05-14 10:50:04 +0000774// Should we allow index completions in the specified context?
775bool allowIndex(CodeCompletionContext &CC) {
776 if (!contextAllowsIndex(CC.getKind()))
777 return false;
778 // We also avoid ClassName::bar (but allow namespace::bar).
779 auto Scope = CC.getCXXScopeSpecifier();
780 if (!Scope)
781 return true;
782 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
783 if (!NameSpec)
784 return true;
785 // We only query the index when qualifier is a namespace.
786 // If it's a class, we rely solely on sema completions.
787 switch (NameSpec->getKind()) {
788 case NestedNameSpecifier::Global:
789 case NestedNameSpecifier::Namespace:
790 case NestedNameSpecifier::NamespaceAlias:
791 return true;
792 case NestedNameSpecifier::Super:
793 case NestedNameSpecifier::TypeSpec:
794 case NestedNameSpecifier::TypeSpecWithTemplate:
795 // Unresolved inside a template.
796 case NestedNameSpecifier::Identifier:
797 return false;
798 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000799 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000800}
801
Sam McCall98775c52017-12-04 13:49:59 +0000802} // namespace
803
804clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
805 clang::CodeCompleteOptions Result;
806 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
807 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000808 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000809 // We choose to include full comments and not do doxygen parsing in
810 // completion.
811 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
812 // formatting of the comments.
813 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000814
Sam McCall3d139c52018-01-12 18:30:08 +0000815 // When an is used, Sema is responsible for completing the main file,
816 // the index can provide results from the preamble.
817 // Tell Sema not to deserialize the preamble to look for results.
818 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000819
Sam McCall98775c52017-12-04 13:49:59 +0000820 return Result;
821}
822
Sam McCall545a20d2018-01-19 14:34:02 +0000823// Runs Sema-based (AST) and Index-based completion, returns merged results.
824//
825// There are a few tricky considerations:
826// - the AST provides information needed for the index query (e.g. which
827// namespaces to search in). So Sema must start first.
828// - we only want to return the top results (Opts.Limit).
829// Building CompletionItems for everything else is wasteful, so we want to
830// preserve the "native" format until we're done with scoring.
831// - the data underlying Sema completion items is owned by the AST and various
832// other arenas, which must stay alive for us to build CompletionItems.
833// - we may get duplicate results from Sema and the Index, we need to merge.
834//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000835// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000836// We use the Sema context information to query the index.
837// Then we merge the two result sets, producing items that are Sema/Index/Both.
838// These items are scored, and the top N are synthesized into the LSP response.
839// Finally, we can clean up the data structures created by Sema completion.
840//
841// Main collaborators are:
842// - semaCodeComplete sets up the compiler machinery to run code completion.
843// - CompletionRecorder captures Sema completion results, including context.
844// - SymbolIndex (Opts.Index) provides index completion results as Symbols
845// - CompletionCandidates are the result of merging Sema and Index results.
846// Each candidate points to an underlying CodeCompletionResult (Sema), a
847// Symbol (Index), or both. It computes the result quality score.
848// CompletionCandidate also does conversion to CompletionItem (at the end).
849// - FuzzyMatcher scores how the candidate matches the partial identifier.
850// This score is combined with the result quality score for the final score.
851// - TopN determines the results with the best score.
852class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000853 PathRef FileName;
Sam McCall545a20d2018-01-19 14:34:02 +0000854 const CodeCompleteOptions &Opts;
855 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000856 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000857 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
858 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000859 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
860 std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000861
862public:
863 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Eric Liuc5105f92018-02-16 14:15:55 +0000864 CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000865 : FileName(FileName), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000866
867 CompletionList run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000868 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000869
Sam McCall545a20d2018-01-19 14:34:02 +0000870 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000871 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000872 // - partial identifier and context. We need these for the index query.
873 CompletionList Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000874 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
875 assert(Recorder && "Recorder is not set");
Eric Liu63f419a2018-05-15 15:29:32 +0000876 assert(Includes && "Includes is not set");
877 // If preprocessor was run, inclusions from preprocessor callback should
878 // already be added to Inclusions.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000879 Output = runWithSema();
Eric Liu63f419a2018-05-15 15:29:32 +0000880 Includes.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000881 SPAN_ATTACH(Tracer, "sema_completion_kind",
882 getCompletionKindString(Recorder->CCContext.getKind()));
883 });
884
885 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +0000886 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +0000887 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +0000888
Sam McCall2b780162018-01-30 17:20:54 +0000889 SPAN_ATTACH(Tracer, "sema_results", NSema);
890 SPAN_ATTACH(Tracer, "index_results", NIndex);
891 SPAN_ATTACH(Tracer, "merged_results", NBoth);
892 SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
893 SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
Sam McCalld1a7a372018-01-31 13:40:48 +0000894 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
Sam McCall545a20d2018-01-19 14:34:02 +0000895 "{2} matched, {3} returned{4}.",
896 NSema, NIndex, NBoth, Output.items.size(),
897 Output.isIncomplete ? " (incomplete)" : ""));
898 assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
899 // We don't assert that isIncomplete means we hit a limit.
900 // Indexes may choose to impose their own limits even if we don't have one.
901 return Output;
902 }
903
904private:
905 // This is called by run() once Sema code completion is done, but before the
906 // Sema data structures are torn down. It does all the real work.
907 CompletionList runWithSema() {
908 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000909 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Sam McCall545a20d2018-01-19 14:34:02 +0000910 // Sema provides the needed context to query the index.
911 // FIXME: in addition to querying for extra/overlapping symbols, we should
912 // explicitly request symbols corresponding to Sema results.
913 // We can use their signals even if the index can't suggest them.
914 // We must copy index results to preserve them, but there are at most Limit.
915 auto IndexResults = queryIndex();
916 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000917 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall545a20d2018-01-19 14:34:02 +0000918 // Convert the results to the desired LSP structs.
919 CompletionList Output;
920 for (auto &C : Top)
921 Output.items.push_back(toCompletionItem(C.first, C.second));
922 Output.isIncomplete = Incomplete;
923 return Output;
924 }
925
926 SymbolSlab queryIndex() {
Ilya Biryukova907ba42018-05-14 10:50:04 +0000927 if (!Opts.Index || !allowIndex(Recorder->CCContext))
Sam McCall545a20d2018-01-19 14:34:02 +0000928 return SymbolSlab();
Sam McCalld1a7a372018-01-31 13:40:48 +0000929 trace::Span Tracer("Query index");
Sam McCall2b780162018-01-30 17:20:54 +0000930 SPAN_ATTACH(Tracer, "limit", Opts.Limit);
931
Sam McCall545a20d2018-01-19 14:34:02 +0000932 SymbolSlab::Builder ResultsBuilder;
933 // Build the query.
934 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +0000935 if (Opts.Limit)
936 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +0000937 Req.Query = Filter->pattern();
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000938 Req.Scopes = getQueryScopes(Recorder->CCContext,
939 Recorder->CCSema->getSourceManager());
Sam McCalld1a7a372018-01-31 13:40:48 +0000940 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
Sam McCall2b780162018-01-30 17:20:54 +0000941 Req.Query,
942 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Sam McCall545a20d2018-01-19 14:34:02 +0000943 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +0000944 if (Opts.Index->fuzzyFind(
945 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
946 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000947 return std::move(ResultsBuilder).build();
948 }
949
950 // Merges the Sema and Index results where possible, scores them, and
951 // returns the top results from best to worst.
952 std::vector<std::pair<CompletionCandidate, CompletionItemScores>>
953 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
954 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000955 trace::Span Tracer("Merge and score results");
Sam McCall545a20d2018-01-19 14:34:02 +0000956 // We only keep the best N results at any time, in "native" format.
Sam McCallc5707b62018-05-15 17:43:27 +0000957 TopN<ScoredCandidate, ScoredCandidateGreater> Top(
958 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +0000959 llvm::DenseSet<const Symbol *> UsedIndexResults;
960 auto CorrespondingIndexResult =
961 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
962 if (auto SymID = getSymbolID(SemaResult)) {
963 auto I = IndexResults.find(*SymID);
964 if (I != IndexResults.end()) {
965 UsedIndexResults.insert(&*I);
966 return &*I;
967 }
968 }
969 return nullptr;
970 };
971 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000972 for (auto &SemaResult : Recorder->Results)
Sam McCall545a20d2018-01-19 14:34:02 +0000973 addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult));
974 // Now emit any Index-only results.
975 for (const auto &IndexResult : IndexResults) {
976 if (UsedIndexResults.count(&IndexResult))
977 continue;
978 addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult);
979 }
980 return std::move(Top).items();
981 }
982
983 // Scores a candidate and adds it to the TopN structure.
Sam McCallc5707b62018-05-15 17:43:27 +0000984 void addCandidate(TopN<ScoredCandidate, ScoredCandidateGreater> &Candidates,
985 const CodeCompletionResult *SemaResult,
Sam McCall545a20d2018-01-19 14:34:02 +0000986 const Symbol *IndexResult) {
987 CompletionCandidate C;
988 C.SemaResult = SemaResult;
989 C.IndexResult = IndexResult;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000990 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
Sam McCall545a20d2018-01-19 14:34:02 +0000991
Sam McCallc5707b62018-05-15 17:43:27 +0000992 SymbolQualitySignals Quality;
993 SymbolRelevanceSignals Relevance;
Sam McCall545a20d2018-01-19 14:34:02 +0000994 if (auto FuzzyScore = Filter->match(C.Name))
Sam McCallc5707b62018-05-15 17:43:27 +0000995 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +0000996 else
997 return;
Sam McCallc5707b62018-05-15 17:43:27 +0000998 if (IndexResult)
999 Quality.merge(*IndexResult);
1000 if (SemaResult) {
1001 Quality.merge(*SemaResult);
1002 Relevance.merge(*SemaResult);
1003 }
1004
1005 float QualScore = Quality.evaluate(), RelScore = Relevance.evaluate();
1006 CompletionItemScores Scores;
1007 Scores.finalScore = evaluateSymbolAndRelevance(QualScore, RelScore);
1008 // The purpose of exporting component scores is to allow NameMatch to be
1009 // replaced on the client-side. So we export (NameMatch, final/NameMatch)
1010 // rather than (RelScore, QualScore).
1011 Scores.filterScore = Relevance.NameMatch;
1012 Scores.symbolScore =
1013 Scores.filterScore ? Scores.finalScore / Scores.filterScore : QualScore;
1014
1015 DEBUG(llvm::dbgs() << "CodeComplete: " << C.Name
1016 << (IndexResult ? " (index)" : "")
1017 << (SemaResult ? " (sema)" : "") << " = "
1018 << Scores.finalScore << "\n"
1019 << Quality << Relevance << "\n");
Sam McCall545a20d2018-01-19 14:34:02 +00001020
1021 NSema += bool(SemaResult);
1022 NIndex += bool(IndexResult);
1023 NBoth += SemaResult && IndexResult;
Sam McCallab8e3932018-02-19 13:04:41 +00001024 if (Candidates.push({C, Scores}))
1025 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001026 }
1027
1028 CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
1029 const CompletionItemScores &Scores) {
1030 CodeCompletionString *SemaCCS = nullptr;
Ilya Biryukov43714502018-05-16 12:32:44 +00001031 std::string DocComment;
1032 if (auto *SR = Candidate.SemaResult) {
1033 SemaCCS = Recorder->codeCompletionString(*SR);
1034 if (Opts.IncludeComments) {
1035 assert(Recorder->CCSema);
1036 DocComment = getDocComment(Recorder->CCSema->getASTContext(), *SR);
1037 }
1038 }
1039 return Candidate.build(FileName, Scores, Opts, SemaCCS, Includes.get(), DocComment);
Sam McCall545a20d2018-01-19 14:34:02 +00001040 }
1041};
1042
Sam McCalld1a7a372018-01-31 13:40:48 +00001043CompletionList codeComplete(PathRef FileName,
Sam McCall98775c52017-12-04 13:49:59 +00001044 const tooling::CompileCommand &Command,
1045 PrecompiledPreamble const *Preamble,
Eric Liu63f419a2018-05-15 15:29:32 +00001046 const std::vector<Inclusion> &PreambleInclusions,
Sam McCall98775c52017-12-04 13:49:59 +00001047 StringRef Contents, Position Pos,
1048 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1049 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001050 CodeCompleteOptions Opts) {
Eric Liuc5105f92018-02-16 14:15:55 +00001051 return CodeCompleteFlow(FileName, Opts)
Eric Liu63f419a2018-05-15 15:29:32 +00001052 .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS,
1053 PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001054}
1055
Sam McCalld1a7a372018-01-31 13:40:48 +00001056SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001057 const tooling::CompileCommand &Command,
1058 PrecompiledPreamble const *Preamble,
1059 StringRef Contents, Position Pos,
1060 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1061 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001062 SignatureHelp Result;
1063 clang::CodeCompleteOptions Options;
1064 Options.IncludeGlobals = false;
1065 Options.IncludeMacros = false;
1066 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001067 Options.IncludeBriefComments = false;
Sam McCalld1a7a372018-01-31 13:40:48 +00001068 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1069 Options,
Eric Liu63f419a2018-05-15 15:29:32 +00001070 {FileName, Command, Preamble,
1071 /*PreambleInclusions=*/{}, Contents, Pos, std::move(VFS),
Sam McCalld1a7a372018-01-31 13:40:48 +00001072 std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001073 return Result;
1074}
1075
1076} // namespace clangd
1077} // namespace clang