blob: cfebb3e3c9410a0e6b5e74b7697207bb35e6346a [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
Eric Liu42abe412018-05-24 11:20:19 +0000409// Should we perform index-based completion in a context of the specified kind?
410// FIXME: consider allowing completion, but restricting the result types.
411bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
412 switch (K) {
413 case CodeCompletionContext::CCC_TopLevel:
414 case CodeCompletionContext::CCC_ObjCInterface:
415 case CodeCompletionContext::CCC_ObjCImplementation:
416 case CodeCompletionContext::CCC_ObjCIvarList:
417 case CodeCompletionContext::CCC_ClassStructUnion:
418 case CodeCompletionContext::CCC_Statement:
419 case CodeCompletionContext::CCC_Expression:
420 case CodeCompletionContext::CCC_ObjCMessageReceiver:
421 case CodeCompletionContext::CCC_EnumTag:
422 case CodeCompletionContext::CCC_UnionTag:
423 case CodeCompletionContext::CCC_ClassOrStructTag:
424 case CodeCompletionContext::CCC_ObjCProtocolName:
425 case CodeCompletionContext::CCC_Namespace:
426 case CodeCompletionContext::CCC_Type:
427 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
428 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
429 case CodeCompletionContext::CCC_ParenthesizedExpression:
430 case CodeCompletionContext::CCC_ObjCInterfaceName:
431 case CodeCompletionContext::CCC_ObjCCategoryName:
432 return true;
433 case CodeCompletionContext::CCC_Other: // Be conservative.
434 case CodeCompletionContext::CCC_OtherWithMacros:
435 case CodeCompletionContext::CCC_DotMemberAccess:
436 case CodeCompletionContext::CCC_ArrowMemberAccess:
437 case CodeCompletionContext::CCC_ObjCPropertyAccess:
438 case CodeCompletionContext::CCC_MacroName:
439 case CodeCompletionContext::CCC_MacroNameUse:
440 case CodeCompletionContext::CCC_PreprocessorExpression:
441 case CodeCompletionContext::CCC_PreprocessorDirective:
442 case CodeCompletionContext::CCC_NaturalLanguage:
443 case CodeCompletionContext::CCC_SelectorName:
444 case CodeCompletionContext::CCC_TypeQualifiers:
445 case CodeCompletionContext::CCC_ObjCInstanceMessage:
446 case CodeCompletionContext::CCC_ObjCClassMessage:
447 case CodeCompletionContext::CCC_Recovery:
448 return false;
449 }
450 llvm_unreachable("unknown code completion context");
451}
452
Sam McCall545a20d2018-01-19 14:34:02 +0000453// The CompletionRecorder captures Sema code-complete output, including context.
454// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
455// It doesn't do scoring or conversion to CompletionItem yet, as we want to
456// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000457// Generally the fields and methods of this object should only be used from
458// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000459struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000460 CompletionRecorder(const CodeCompleteOptions &Opts,
461 UniqueFunction<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000462 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000463 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000464 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
465 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000466 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
467 assert(this->ResultsCallback);
468 }
469
Sam McCall545a20d2018-01-19 14:34:02 +0000470 std::vector<CodeCompletionResult> Results;
471 CodeCompletionContext CCContext;
472 Sema *CCSema = nullptr; // Sema that created the results.
473 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000474
Sam McCall545a20d2018-01-19 14:34:02 +0000475 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
476 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000477 unsigned NumResults) override final {
Eric Liu42abe412018-05-24 11:20:19 +0000478 // If a callback is called without any sema result and the context does not
479 // support index-based completion, we simply skip it to give way to
480 // potential future callbacks with results.
481 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
482 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000483 if (CCSema) {
484 log(llvm::formatv(
485 "Multiple code complete callbacks (parser backtracked?). "
486 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000487 getCompletionKindString(Context.getKind()),
488 getCompletionKindString(this->CCContext.getKind())));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000489 return;
490 }
Sam McCall545a20d2018-01-19 14:34:02 +0000491 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000492 CCSema = &S;
493 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000494
Sam McCall545a20d2018-01-19 14:34:02 +0000495 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000496 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000497 auto &Result = InResults[I];
498 // Drop hidden items which cannot be found by lookup after completion.
499 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000500 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
501 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000502 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000503 (Result.Availability == CXAvailability_NotAvailable ||
504 Result.Availability == CXAvailability_NotAccessible))
505 continue;
Sam McCalld2a95922018-01-22 21:05:00 +0000506 // Destructor completion is rarely useful, and works inconsistently.
507 // (s.^ completes ~string, but s.~st^ is an error).
508 if (dyn_cast_or_null<CXXDestructorDecl>(Result.Declaration))
509 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000510 // We choose to never append '::' to completion results in clangd.
511 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000512 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000513 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000514 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000515 }
516
Sam McCall545a20d2018-01-19 14:34:02 +0000517 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000518 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
519
Sam McCall545a20d2018-01-19 14:34:02 +0000520 // Returns the filtering/sorting name for Result, which must be from Results.
521 // Returned string is owned by this recorder (or the AST).
522 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000523 switch (Result.Kind) {
524 case CodeCompletionResult::RK_Declaration:
525 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000526 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000527 break;
528 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000529 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000530 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000531 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000532 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000533 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000534 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000535 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000536 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000537 }
538
Sam McCall545a20d2018-01-19 14:34:02 +0000539 // Build a CodeCompletion string for R, which must be from Results.
540 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000541 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000542 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
543 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000544 *CCSema, CCContext, *CCAllocator, CCTUInfo,
545 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000546 }
547
Sam McCall545a20d2018-01-19 14:34:02 +0000548private:
549 CodeCompleteOptions Opts;
550 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000551 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000552 UniqueFunction<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000553};
554
Sam McCallc5707b62018-05-15 17:43:27 +0000555struct ScoredCandidateGreater {
556 bool operator()(const ScoredCandidate &L, const ScoredCandidate &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000557 if (L.second.finalScore != R.second.finalScore)
558 return L.second.finalScore > R.second.finalScore;
559 return L.first.Name < R.first.Name; // Earlier name is better.
560 }
Sam McCall545a20d2018-01-19 14:34:02 +0000561};
Sam McCall98775c52017-12-04 13:49:59 +0000562
Sam McCall98775c52017-12-04 13:49:59 +0000563class SignatureHelpCollector final : public CodeCompleteConsumer {
564
565public:
566 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
567 SignatureHelp &SigHelp)
568 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
569 SigHelp(SigHelp),
570 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
571 CCTUInfo(Allocator) {}
572
573 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
574 OverloadCandidate *Candidates,
575 unsigned NumCandidates) override {
576 SigHelp.signatures.reserve(NumCandidates);
577 // FIXME(rwols): How can we determine the "active overload candidate"?
578 // Right now the overloaded candidates seem to be provided in a "best fit"
579 // order, so I'm not too worried about this.
580 SigHelp.activeSignature = 0;
581 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
582 "too many arguments");
583 SigHelp.activeParameter = static_cast<int>(CurrentArg);
584 for (unsigned I = 0; I < NumCandidates; ++I) {
585 const auto &Candidate = Candidates[I];
586 const auto *CCS = Candidate.CreateSignatureString(
587 CurrentArg, S, *Allocator, CCTUInfo, true);
588 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000589 // FIXME: for headers, we need to get a comment from the index.
Ilya Biryukov43714502018-05-16 12:32:44 +0000590 SigHelp.signatures.push_back(ProcessOverloadCandidate(
591 Candidate, *CCS,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000592 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
593 /*CommentsFromHeader=*/false)));
Sam McCall98775c52017-12-04 13:49:59 +0000594 }
595 }
596
597 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
598
599 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
600
601private:
Eric Liu63696e12017-12-20 17:24:31 +0000602 // FIXME(ioeric): consider moving CodeCompletionString logic here to
603 // CompletionString.h.
Sam McCall98775c52017-12-04 13:49:59 +0000604 SignatureInformation
605 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
Ilya Biryukov43714502018-05-16 12:32:44 +0000606 const CodeCompletionString &CCS,
607 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000608 SignatureInformation Result;
609 const char *ReturnType = nullptr;
610
Ilya Biryukov43714502018-05-16 12:32:44 +0000611 Result.documentation = formatDocumentation(CCS, DocComment);
Sam McCall98775c52017-12-04 13:49:59 +0000612
613 for (const auto &Chunk : CCS) {
614 switch (Chunk.Kind) {
615 case CodeCompletionString::CK_ResultType:
616 // A piece of text that describes the type of an entity or,
617 // for functions and methods, the return type.
618 assert(!ReturnType && "Unexpected CK_ResultType");
619 ReturnType = Chunk.Text;
620 break;
621 case CodeCompletionString::CK_Placeholder:
622 // A string that acts as a placeholder for, e.g., a function call
623 // argument.
624 // Intentional fallthrough here.
625 case CodeCompletionString::CK_CurrentParameter: {
626 // A piece of text that describes the parameter that corresponds to
627 // the code-completion location within a function call, message send,
628 // macro invocation, etc.
629 Result.label += Chunk.Text;
630 ParameterInformation Info;
631 Info.label = Chunk.Text;
632 Result.parameters.push_back(std::move(Info));
633 break;
634 }
635 case CodeCompletionString::CK_Optional: {
636 // The rest of the parameters are defaulted/optional.
637 assert(Chunk.Optional &&
638 "Expected the optional code completion string to be non-null.");
639 Result.label +=
640 getOptionalParameters(*Chunk.Optional, Result.parameters);
641 break;
642 }
643 case CodeCompletionString::CK_VerticalSpace:
644 break;
645 default:
646 Result.label += Chunk.Text;
647 break;
648 }
649 }
650 if (ReturnType) {
651 Result.label += " -> ";
652 Result.label += ReturnType;
653 }
654 return Result;
655 }
656
657 SignatureHelp &SigHelp;
658 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
659 CodeCompletionTUInfo CCTUInfo;
660
661}; // SignatureHelpCollector
662
Sam McCall545a20d2018-01-19 14:34:02 +0000663struct SemaCompleteInput {
664 PathRef FileName;
665 const tooling::CompileCommand &Command;
666 PrecompiledPreamble const *Preamble;
Eric Liu63f419a2018-05-15 15:29:32 +0000667 const std::vector<Inclusion> &PreambleInclusions;
Sam McCall545a20d2018-01-19 14:34:02 +0000668 StringRef Contents;
669 Position Pos;
670 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
671 std::shared_ptr<PCHContainerOperations> PCHs;
672};
673
674// Invokes Sema code completion on a file.
Eric Liu63f419a2018-05-15 15:29:32 +0000675// If \p Includes is set, it will be initialized after a compiler instance has
676// been set up.
Sam McCalld1a7a372018-01-31 13:40:48 +0000677bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000678 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000679 const SemaCompleteInput &Input,
680 std::unique_ptr<IncludeInserter> *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000681 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000682 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000683 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000684 ArgStrs.push_back(S.c_str());
685
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000686 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
687 log("Couldn't set working directory");
688 // We run parsing anyway, our lit-tests rely on results for non-existing
689 // working dirs.
690 }
Sam McCall98775c52017-12-04 13:49:59 +0000691
692 IgnoreDiagnostics DummyDiagsConsumer;
693 auto CI = createInvocationFromCommandLine(
694 ArgStrs,
695 CompilerInstance::createDiagnostics(new DiagnosticOptions,
696 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000697 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000698 if (!CI) {
699 log("Couldn't create CompilerInvocation");;
700 return false;
701 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000702 auto &FrontendOpts = CI->getFrontendOpts();
703 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000704 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000705 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
706 // Disable typo correction in Sema.
707 CI->getLangOpts()->SpellChecking = false;
708 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +0000709 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000710 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000711 auto Offset = positionToOffset(Input.Contents, Input.Pos);
712 if (!Offset) {
713 log("Code completion position was invalid " +
714 llvm::toString(Offset.takeError()));
715 return false;
716 }
717 std::tie(FrontendOpts.CodeCompletionAt.Line,
718 FrontendOpts.CodeCompletionAt.Column) =
719 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000720
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000721 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
722 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
723 // The diagnostic options must be set before creating a CompilerInstance.
724 CI->getDiagnosticOpts().IgnoreWarnings = true;
725 // We reuse the preamble whether it's valid or not. This is a
726 // correctness/performance tradeoff: building without a preamble is slow, and
727 // completion is latency-sensitive.
728 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
729 // the remapped buffers do not get freed.
730 auto Clang = prepareCompilerInstance(
731 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
732 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000733 Clang->setCodeCompletionConsumer(Consumer.release());
734
735 SyntaxOnlyAction Action;
736 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000737 log("BeginSourceFile() failed when running codeComplete for " +
738 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000739 return false;
740 }
Eric Liu63f419a2018-05-15 15:29:32 +0000741 if (Includes) {
742 // Initialize Includes if provided.
743
744 // FIXME(ioeric): needs more consistent style support in clangd server.
745 auto Style = format::getStyle("file", Input.FileName, "LLVM",
746 Input.Contents, Input.VFS.get());
747 if (!Style) {
748 log("Failed to get FormatStyle for file" + Input.FileName +
749 ". Fall back to use LLVM style. Error: " +
750 llvm::toString(Style.takeError()));
751 Style = format::getLLVMStyle();
752 }
753 *Includes = llvm::make_unique<IncludeInserter>(
754 Input.FileName, Input.Contents, *Style, Input.Command.Directory,
755 Clang->getPreprocessor().getHeaderSearchInfo());
756 for (const auto &Inc : Input.PreambleInclusions)
757 Includes->get()->addExisting(Inc);
758 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
759 Clang->getSourceManager(), [Includes](Inclusion Inc) {
760 Includes->get()->addExisting(std::move(Inc));
761 }));
762 }
Sam McCall98775c52017-12-04 13:49:59 +0000763 if (!Action.Execute()) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000764 log("Execute() failed when running codeComplete for " + Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000765 return false;
766 }
Sam McCall98775c52017-12-04 13:49:59 +0000767 Action.EndSourceFile();
768
769 return true;
770}
771
Ilya Biryukova907ba42018-05-14 10:50:04 +0000772// Should we allow index completions in the specified context?
773bool allowIndex(CodeCompletionContext &CC) {
774 if (!contextAllowsIndex(CC.getKind()))
775 return false;
776 // We also avoid ClassName::bar (but allow namespace::bar).
777 auto Scope = CC.getCXXScopeSpecifier();
778 if (!Scope)
779 return true;
780 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
781 if (!NameSpec)
782 return true;
783 // We only query the index when qualifier is a namespace.
784 // If it's a class, we rely solely on sema completions.
785 switch (NameSpec->getKind()) {
786 case NestedNameSpecifier::Global:
787 case NestedNameSpecifier::Namespace:
788 case NestedNameSpecifier::NamespaceAlias:
789 return true;
790 case NestedNameSpecifier::Super:
791 case NestedNameSpecifier::TypeSpec:
792 case NestedNameSpecifier::TypeSpecWithTemplate:
793 // Unresolved inside a template.
794 case NestedNameSpecifier::Identifier:
795 return false;
796 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000797 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000798}
799
Sam McCall98775c52017-12-04 13:49:59 +0000800} // namespace
801
802clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
803 clang::CodeCompleteOptions Result;
804 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
805 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000806 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000807 // We choose to include full comments and not do doxygen parsing in
808 // completion.
809 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
810 // formatting of the comments.
811 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000812
Sam McCall3d139c52018-01-12 18:30:08 +0000813 // When an is used, Sema is responsible for completing the main file,
814 // the index can provide results from the preamble.
815 // Tell Sema not to deserialize the preamble to look for results.
816 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000817
Sam McCall98775c52017-12-04 13:49:59 +0000818 return Result;
819}
820
Sam McCall545a20d2018-01-19 14:34:02 +0000821// Runs Sema-based (AST) and Index-based completion, returns merged results.
822//
823// There are a few tricky considerations:
824// - the AST provides information needed for the index query (e.g. which
825// namespaces to search in). So Sema must start first.
826// - we only want to return the top results (Opts.Limit).
827// Building CompletionItems for everything else is wasteful, so we want to
828// preserve the "native" format until we're done with scoring.
829// - the data underlying Sema completion items is owned by the AST and various
830// other arenas, which must stay alive for us to build CompletionItems.
831// - we may get duplicate results from Sema and the Index, we need to merge.
832//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000833// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000834// We use the Sema context information to query the index.
835// Then we merge the two result sets, producing items that are Sema/Index/Both.
836// These items are scored, and the top N are synthesized into the LSP response.
837// Finally, we can clean up the data structures created by Sema completion.
838//
839// Main collaborators are:
840// - semaCodeComplete sets up the compiler machinery to run code completion.
841// - CompletionRecorder captures Sema completion results, including context.
842// - SymbolIndex (Opts.Index) provides index completion results as Symbols
843// - CompletionCandidates are the result of merging Sema and Index results.
844// Each candidate points to an underlying CodeCompletionResult (Sema), a
845// Symbol (Index), or both. It computes the result quality score.
846// CompletionCandidate also does conversion to CompletionItem (at the end).
847// - FuzzyMatcher scores how the candidate matches the partial identifier.
848// This score is combined with the result quality score for the final score.
849// - TopN determines the results with the best score.
850class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000851 PathRef FileName;
Sam McCall545a20d2018-01-19 14:34:02 +0000852 const CodeCompleteOptions &Opts;
853 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000854 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000855 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
856 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000857 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
858 std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000859
860public:
861 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Eric Liuc5105f92018-02-16 14:15:55 +0000862 CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000863 : FileName(FileName), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000864
865 CompletionList run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000866 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000867
Sam McCall545a20d2018-01-19 14:34:02 +0000868 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000869 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000870 // - partial identifier and context. We need these for the index query.
871 CompletionList Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000872 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
873 assert(Recorder && "Recorder is not set");
Eric Liu63f419a2018-05-15 15:29:32 +0000874 assert(Includes && "Includes is not set");
875 // If preprocessor was run, inclusions from preprocessor callback should
876 // already be added to Inclusions.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000877 Output = runWithSema();
Eric Liu63f419a2018-05-15 15:29:32 +0000878 Includes.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000879 SPAN_ATTACH(Tracer, "sema_completion_kind",
880 getCompletionKindString(Recorder->CCContext.getKind()));
881 });
882
883 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +0000884 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +0000885 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +0000886
Sam McCall2b780162018-01-30 17:20:54 +0000887 SPAN_ATTACH(Tracer, "sema_results", NSema);
888 SPAN_ATTACH(Tracer, "index_results", NIndex);
889 SPAN_ATTACH(Tracer, "merged_results", NBoth);
890 SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
891 SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
Sam McCalld1a7a372018-01-31 13:40:48 +0000892 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
Sam McCall545a20d2018-01-19 14:34:02 +0000893 "{2} matched, {3} returned{4}.",
894 NSema, NIndex, NBoth, Output.items.size(),
895 Output.isIncomplete ? " (incomplete)" : ""));
896 assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
897 // We don't assert that isIncomplete means we hit a limit.
898 // Indexes may choose to impose their own limits even if we don't have one.
899 return Output;
900 }
901
902private:
903 // This is called by run() once Sema code completion is done, but before the
904 // Sema data structures are torn down. It does all the real work.
905 CompletionList runWithSema() {
906 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000907 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Sam McCall545a20d2018-01-19 14:34:02 +0000908 // Sema provides the needed context to query the index.
909 // FIXME: in addition to querying for extra/overlapping symbols, we should
910 // explicitly request symbols corresponding to Sema results.
911 // We can use their signals even if the index can't suggest them.
912 // We must copy index results to preserve them, but there are at most Limit.
913 auto IndexResults = queryIndex();
914 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000915 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall545a20d2018-01-19 14:34:02 +0000916 // Convert the results to the desired LSP structs.
917 CompletionList Output;
918 for (auto &C : Top)
919 Output.items.push_back(toCompletionItem(C.first, C.second));
920 Output.isIncomplete = Incomplete;
921 return Output;
922 }
923
924 SymbolSlab queryIndex() {
Ilya Biryukova907ba42018-05-14 10:50:04 +0000925 if (!Opts.Index || !allowIndex(Recorder->CCContext))
Sam McCall545a20d2018-01-19 14:34:02 +0000926 return SymbolSlab();
Sam McCalld1a7a372018-01-31 13:40:48 +0000927 trace::Span Tracer("Query index");
Sam McCall2b780162018-01-30 17:20:54 +0000928 SPAN_ATTACH(Tracer, "limit", Opts.Limit);
929
Sam McCall545a20d2018-01-19 14:34:02 +0000930 SymbolSlab::Builder ResultsBuilder;
931 // Build the query.
932 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +0000933 if (Opts.Limit)
934 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +0000935 Req.Query = Filter->pattern();
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000936 Req.Scopes = getQueryScopes(Recorder->CCContext,
937 Recorder->CCSema->getSourceManager());
Sam McCalld1a7a372018-01-31 13:40:48 +0000938 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
Sam McCall2b780162018-01-30 17:20:54 +0000939 Req.Query,
940 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Sam McCall545a20d2018-01-19 14:34:02 +0000941 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +0000942 if (Opts.Index->fuzzyFind(
943 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
944 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000945 return std::move(ResultsBuilder).build();
946 }
947
948 // Merges the Sema and Index results where possible, scores them, and
949 // returns the top results from best to worst.
950 std::vector<std::pair<CompletionCandidate, CompletionItemScores>>
951 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
952 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000953 trace::Span Tracer("Merge and score results");
Sam McCall545a20d2018-01-19 14:34:02 +0000954 // We only keep the best N results at any time, in "native" format.
Sam McCallc5707b62018-05-15 17:43:27 +0000955 TopN<ScoredCandidate, ScoredCandidateGreater> Top(
956 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +0000957 llvm::DenseSet<const Symbol *> UsedIndexResults;
958 auto CorrespondingIndexResult =
959 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
960 if (auto SymID = getSymbolID(SemaResult)) {
961 auto I = IndexResults.find(*SymID);
962 if (I != IndexResults.end()) {
963 UsedIndexResults.insert(&*I);
964 return &*I;
965 }
966 }
967 return nullptr;
968 };
969 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000970 for (auto &SemaResult : Recorder->Results)
Sam McCall545a20d2018-01-19 14:34:02 +0000971 addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult));
972 // Now emit any Index-only results.
973 for (const auto &IndexResult : IndexResults) {
974 if (UsedIndexResults.count(&IndexResult))
975 continue;
976 addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult);
977 }
978 return std::move(Top).items();
979 }
980
981 // Scores a candidate and adds it to the TopN structure.
Sam McCallc5707b62018-05-15 17:43:27 +0000982 void addCandidate(TopN<ScoredCandidate, ScoredCandidateGreater> &Candidates,
983 const CodeCompletionResult *SemaResult,
Sam McCall545a20d2018-01-19 14:34:02 +0000984 const Symbol *IndexResult) {
985 CompletionCandidate C;
986 C.SemaResult = SemaResult;
987 C.IndexResult = IndexResult;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000988 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
Sam McCall545a20d2018-01-19 14:34:02 +0000989
Sam McCallc5707b62018-05-15 17:43:27 +0000990 SymbolQualitySignals Quality;
991 SymbolRelevanceSignals Relevance;
Sam McCall545a20d2018-01-19 14:34:02 +0000992 if (auto FuzzyScore = Filter->match(C.Name))
Sam McCallc5707b62018-05-15 17:43:27 +0000993 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +0000994 else
995 return;
Sam McCallc5707b62018-05-15 17:43:27 +0000996 if (IndexResult)
997 Quality.merge(*IndexResult);
998 if (SemaResult) {
999 Quality.merge(*SemaResult);
1000 Relevance.merge(*SemaResult);
1001 }
1002
1003 float QualScore = Quality.evaluate(), RelScore = Relevance.evaluate();
1004 CompletionItemScores Scores;
1005 Scores.finalScore = evaluateSymbolAndRelevance(QualScore, RelScore);
1006 // The purpose of exporting component scores is to allow NameMatch to be
1007 // replaced on the client-side. So we export (NameMatch, final/NameMatch)
1008 // rather than (RelScore, QualScore).
1009 Scores.filterScore = Relevance.NameMatch;
1010 Scores.symbolScore =
1011 Scores.filterScore ? Scores.finalScore / Scores.filterScore : QualScore;
1012
Nicola Zaghenc9fed132018-05-23 13:57:48 +00001013 LLVM_DEBUG(llvm::dbgs()
1014 << "CodeComplete: " << C.Name << (IndexResult ? " (index)" : "")
1015 << (SemaResult ? " (sema)" : "") << " = " << Scores.finalScore
1016 << "\n"
1017 << Quality << Relevance << "\n");
Sam McCall545a20d2018-01-19 14:34:02 +00001018
1019 NSema += bool(SemaResult);
1020 NIndex += bool(IndexResult);
1021 NBoth += SemaResult && IndexResult;
Sam McCallab8e3932018-02-19 13:04:41 +00001022 if (Candidates.push({C, Scores}))
1023 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001024 }
1025
1026 CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
1027 const CompletionItemScores &Scores) {
1028 CodeCompletionString *SemaCCS = nullptr;
Ilya Biryukov43714502018-05-16 12:32:44 +00001029 std::string DocComment;
1030 if (auto *SR = Candidate.SemaResult) {
1031 SemaCCS = Recorder->codeCompletionString(*SR);
1032 if (Opts.IncludeComments) {
1033 assert(Recorder->CCSema);
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001034 DocComment = getDocComment(Recorder->CCSema->getASTContext(), *SR,
1035 /*CommentsFromHeader=*/false);
Ilya Biryukov43714502018-05-16 12:32:44 +00001036 }
1037 }
1038 return Candidate.build(FileName, Scores, Opts, SemaCCS, Includes.get(), DocComment);
Sam McCall545a20d2018-01-19 14:34:02 +00001039 }
1040};
1041
Sam McCalld1a7a372018-01-31 13:40:48 +00001042CompletionList codeComplete(PathRef FileName,
Sam McCall98775c52017-12-04 13:49:59 +00001043 const tooling::CompileCommand &Command,
1044 PrecompiledPreamble const *Preamble,
Eric Liu63f419a2018-05-15 15:29:32 +00001045 const std::vector<Inclusion> &PreambleInclusions,
Sam McCall98775c52017-12-04 13:49:59 +00001046 StringRef Contents, Position Pos,
1047 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1048 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001049 CodeCompleteOptions Opts) {
Eric Liuc5105f92018-02-16 14:15:55 +00001050 return CodeCompleteFlow(FileName, Opts)
Eric Liu63f419a2018-05-15 15:29:32 +00001051 .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS,
1052 PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001053}
1054
Sam McCalld1a7a372018-01-31 13:40:48 +00001055SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001056 const tooling::CompileCommand &Command,
1057 PrecompiledPreamble const *Preamble,
1058 StringRef Contents, Position Pos,
1059 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1060 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001061 SignatureHelp Result;
1062 clang::CodeCompleteOptions Options;
1063 Options.IncludeGlobals = false;
1064 Options.IncludeMacros = false;
1065 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001066 Options.IncludeBriefComments = false;
Eric Liu4c0a27b2018-05-16 20:31:38 +00001067 std::vector<Inclusion> PreambleInclusions = {}; // Unused for signatureHelp
Sam McCalld1a7a372018-01-31 13:40:48 +00001068 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1069 Options,
Eric Liu4c0a27b2018-05-16 20:31:38 +00001070 {FileName, Command, Preamble, PreambleInclusions, Contents,
1071 Pos, std::move(VFS), std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001072 return Result;
1073}
1074
1075} // namespace clangd
1076} // namespace clang