blob: dc2a603441322c3341a83db23ff3aa8b05fe8713 [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"
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +000028#include "clang/ASTMatchers/ASTMatchFinder.h"
Ilya Biryukovc22d3442018-05-16 12:32:49 +000029#include "clang/Basic/LangOptions.h"
Eric Liuc5105f92018-02-16 14:15:55 +000030#include "clang/Format/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000031#include "clang/Frontend/CompilerInstance.h"
32#include "clang/Frontend/FrontendActions.h"
Sam McCall545a20d2018-01-19 14:34:02 +000033#include "clang/Index/USRGeneration.h"
Sam McCall98775c52017-12-04 13:49:59 +000034#include "clang/Sema/CodeCompleteConsumer.h"
35#include "clang/Sema/Sema.h"
Eric Liuc5105f92018-02-16 14:15:55 +000036#include "clang/Tooling/Core/Replacement.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000037#include "llvm/Support/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000038#include <queue>
39
Sam McCallc5707b62018-05-15 17:43:27 +000040// We log detailed candidate here if you run with -debug-only=codecomplete.
41#define DEBUG_TYPE "codecomplete"
42
Sam McCall98775c52017-12-04 13:49:59 +000043namespace clang {
44namespace clangd {
45namespace {
46
Eric Liu6f648df2017-12-19 16:50:37 +000047CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
48 using SK = index::SymbolKind;
49 switch (Kind) {
50 case SK::Unknown:
51 return CompletionItemKind::Missing;
52 case SK::Module:
53 case SK::Namespace:
54 case SK::NamespaceAlias:
55 return CompletionItemKind::Module;
56 case SK::Macro:
57 return CompletionItemKind::Text;
58 case SK::Enum:
59 return CompletionItemKind::Enum;
60 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
61 // protocol.
62 case SK::Struct:
63 case SK::Class:
64 case SK::Protocol:
65 case SK::Extension:
66 case SK::Union:
67 return CompletionItemKind::Class;
68 // FIXME(ioeric): figure out whether reference is the right type for aliases.
69 case SK::TypeAlias:
70 case SK::Using:
71 return CompletionItemKind::Reference;
72 case SK::Function:
73 // FIXME(ioeric): this should probably be an operator. This should be fixed
74 // when `Operator` is support type in the protocol.
75 case SK::ConversionFunction:
76 return CompletionItemKind::Function;
77 case SK::Variable:
78 case SK::Parameter:
79 return CompletionItemKind::Variable;
80 case SK::Field:
81 return CompletionItemKind::Field;
82 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
83 case SK::EnumConstant:
84 return CompletionItemKind::Value;
85 case SK::InstanceMethod:
86 case SK::ClassMethod:
87 case SK::StaticMethod:
88 case SK::Destructor:
89 return CompletionItemKind::Method;
90 case SK::InstanceProperty:
91 case SK::ClassProperty:
92 case SK::StaticProperty:
93 return CompletionItemKind::Property;
94 case SK::Constructor:
95 return CompletionItemKind::Constructor;
96 }
97 llvm_unreachable("Unhandled clang::index::SymbolKind.");
98}
99
Sam McCall83305892018-06-08 21:17:19 +0000100CompletionItemKind
101toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
102 const NamedDecl *Decl) {
103 if (Decl)
104 return toCompletionItemKind(index::getSymbolInfo(Decl).Kind);
105 switch (ResKind) {
106 case CodeCompletionResult::RK_Declaration:
107 llvm_unreachable("RK_Declaration without Decl");
108 case CodeCompletionResult::RK_Keyword:
109 return CompletionItemKind::Keyword;
110 case CodeCompletionResult::RK_Macro:
111 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
112 // completion items in LSP.
113 case CodeCompletionResult::RK_Pattern:
114 return CompletionItemKind::Snippet;
115 }
116 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
117}
118
Sam McCall98775c52017-12-04 13:49:59 +0000119/// Get the optional chunk as a string. This function is possibly recursive.
120///
121/// The parameter info for each parameter is appended to the Parameters.
122std::string
123getOptionalParameters(const CodeCompletionString &CCS,
124 std::vector<ParameterInformation> &Parameters) {
125 std::string Result;
126 for (const auto &Chunk : CCS) {
127 switch (Chunk.Kind) {
128 case CodeCompletionString::CK_Optional:
129 assert(Chunk.Optional &&
130 "Expected the optional code completion string to be non-null.");
131 Result += getOptionalParameters(*Chunk.Optional, Parameters);
132 break;
133 case CodeCompletionString::CK_VerticalSpace:
134 break;
135 case CodeCompletionString::CK_Placeholder:
136 // A string that acts as a placeholder for, e.g., a function call
137 // argument.
138 // Intentional fallthrough here.
139 case CodeCompletionString::CK_CurrentParameter: {
140 // A piece of text that describes the parameter that corresponds to
141 // the code-completion location within a function call, message send,
142 // macro invocation, etc.
143 Result += Chunk.Text;
144 ParameterInformation Info;
145 Info.label = Chunk.Text;
146 Parameters.push_back(std::move(Info));
147 break;
148 }
149 default:
150 Result += Chunk.Text;
151 break;
152 }
153 }
154 return Result;
155}
156
Eric Liu63f419a2018-05-15 15:29:32 +0000157/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
158/// include.
159static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
160 llvm::StringRef HintPath) {
161 if (isLiteralInclude(Header))
162 return HeaderFile{Header.str(), /*Verbatim=*/true};
163 auto U = URI::parse(Header);
164 if (!U)
165 return U.takeError();
166
167 auto IncludePath = URI::includeSpelling(*U);
168 if (!IncludePath)
169 return IncludePath.takeError();
170 if (!IncludePath->empty())
171 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
172
173 auto Resolved = URI::resolve(*U, HintPath);
174 if (!Resolved)
175 return Resolved.takeError();
176 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
177}
178
Sam McCall545a20d2018-01-19 14:34:02 +0000179/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000180/// It may be promoted to a CompletionItem if it's among the top-ranked results.
181struct CompletionCandidate {
Sam McCall545a20d2018-01-19 14:34:02 +0000182 llvm::StringRef Name; // Used for filtering and sorting.
183 // We may have a result from Sema, from the index, or both.
184 const CodeCompletionResult *SemaResult = nullptr;
185 const Symbol *IndexResult = nullptr;
Sam McCall98775c52017-12-04 13:49:59 +0000186
Sam McCall545a20d2018-01-19 14:34:02 +0000187 // Builds an LSP completion item.
Eric Liu63f419a2018-05-15 15:29:32 +0000188 CompletionItem build(StringRef FileName, const CompletionItemScores &Scores,
Sam McCall545a20d2018-01-19 14:34:02 +0000189 const CodeCompleteOptions &Opts,
Eric Liu63f419a2018-05-15 15:29:32 +0000190 CodeCompletionString *SemaCCS,
Ilya Biryukov43714502018-05-16 12:32:44 +0000191 const IncludeInserter *Includes,
192 llvm::StringRef SemaDocComment) const {
Sam McCall545a20d2018-01-19 14:34:02 +0000193 assert(bool(SemaResult) == bool(SemaCCS));
194 CompletionItem I;
Eric Liu9b3cba72018-05-30 09:03:39 +0000195 bool ShouldInsertInclude = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000196 if (SemaResult) {
Sam McCall83305892018-06-08 21:17:19 +0000197 I.kind = toCompletionItemKind(SemaResult->Kind, SemaResult->Declaration);
Sam McCall545a20d2018-01-19 14:34:02 +0000198 getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText,
199 Opts.EnableSnippets);
200 I.filterText = getFilterText(*SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +0000201 I.documentation = formatDocumentation(*SemaCCS, SemaDocComment);
Sam McCall545a20d2018-01-19 14:34:02 +0000202 I.detail = getDetail(*SemaCCS);
Eric Liu9b3cba72018-05-30 09:03:39 +0000203 // Avoid inserting new #include if the declaration is found in the current
204 // file e.g. the symbol is forward declared.
205 if (SemaResult->Kind == CodeCompletionResult::RK_Declaration) {
206 if (const auto *D = SemaResult->getDeclaration()) {
207 const auto &SM = D->getASTContext().getSourceManager();
208 ShouldInsertInclude =
209 ShouldInsertInclude &&
210 std::none_of(D->redecls_begin(), D->redecls_end(),
211 [&SM](const Decl *RD) {
212 return SM.isInMainFile(
213 SM.getExpansionLoc(RD->getLocStart()));
214 });
215 }
216 }
Sam McCall545a20d2018-01-19 14:34:02 +0000217 }
218 if (IndexResult) {
219 if (I.kind == CompletionItemKind::Missing)
220 I.kind = toCompletionItemKind(IndexResult->SymInfo.Kind);
221 // FIXME: reintroduce a way to show the index source for debugging.
222 if (I.label.empty())
223 I.label = IndexResult->CompletionLabel;
224 if (I.filterText.empty())
225 I.filterText = IndexResult->Name;
Sam McCall98775c52017-12-04 13:49:59 +0000226
Sam McCall545a20d2018-01-19 14:34:02 +0000227 // FIXME(ioeric): support inserting/replacing scope qualifiers.
228 if (I.insertText.empty())
229 I.insertText = Opts.EnableSnippets
230 ? IndexResult->CompletionSnippetInsertText
231 : IndexResult->CompletionPlainInsertText;
232
233 if (auto *D = IndexResult->Detail) {
234 if (I.documentation.empty())
235 I.documentation = D->Documentation;
236 if (I.detail.empty())
237 I.detail = D->CompletionDetail;
Eric Liu9b3cba72018-05-30 09:03:39 +0000238 if (ShouldInsertInclude && Includes && !D->IncludeHeader.empty()) {
Eric Liu63f419a2018-05-15 15:29:32 +0000239 auto Edit = [&]() -> Expected<Optional<TextEdit>> {
240 auto ResolvedDeclaring = toHeaderFile(
241 IndexResult->CanonicalDeclaration.FileURI, FileName);
242 if (!ResolvedDeclaring)
243 return ResolvedDeclaring.takeError();
244 auto ResolvedInserted = toHeaderFile(D->IncludeHeader, FileName);
245 if (!ResolvedInserted)
246 return ResolvedInserted.takeError();
247 return Includes->insert(*ResolvedDeclaring, *ResolvedInserted);
248 }();
249 if (!Edit) {
250 std::string ErrMsg =
251 ("Failed to generate include insertion edits for adding header "
252 "(FileURI=\"" +
253 IndexResult->CanonicalDeclaration.FileURI +
254 "\", IncludeHeader=\"" + D->IncludeHeader + "\") into " +
255 FileName)
256 .str();
257 log(ErrMsg + ":" + llvm::toString(Edit.takeError()));
258 } else if (*Edit) {
259 I.additionalTextEdits = {std::move(**Edit)};
260 }
261 }
Sam McCall545a20d2018-01-19 14:34:02 +0000262 }
263 }
264 I.scoreInfo = Scores;
265 I.sortText = sortText(Scores.finalScore, Name);
266 I.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
267 : InsertTextFormat::PlainText;
268 return I;
Sam McCall98775c52017-12-04 13:49:59 +0000269 }
270};
Sam McCallc5707b62018-05-15 17:43:27 +0000271using ScoredCandidate = std::pair<CompletionCandidate, CompletionItemScores>;
Sam McCall98775c52017-12-04 13:49:59 +0000272
Sam McCall545a20d2018-01-19 14:34:02 +0000273// Determine the symbol ID for a Sema code completion result, if possible.
274llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
275 switch (R.Kind) {
276 case CodeCompletionResult::RK_Declaration:
277 case CodeCompletionResult::RK_Pattern: {
278 llvm::SmallString<128> USR;
279 if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
280 return None;
281 return SymbolID(USR);
282 }
283 case CodeCompletionResult::RK_Macro:
284 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
285 case CodeCompletionResult::RK_Keyword:
286 return None;
287 }
288 llvm_unreachable("unknown CodeCompletionResult kind");
289}
290
Haojian Wu061c73e2018-01-23 11:37:26 +0000291// Scopes of the paritial identifier we're trying to complete.
292// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000293struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000294 // The scopes we should look in, determined by Sema.
295 //
296 // If the qualifier was fully resolved, we look for completions in these
297 // scopes; if there is an unresolved part of the qualifier, it should be
298 // resolved within these scopes.
299 //
300 // Examples of qualified completion:
301 //
302 // "::vec" => {""}
303 // "using namespace std; ::vec^" => {"", "std::"}
304 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
305 // "std::vec^" => {""} // "std" unresolved
306 //
307 // Examples of unqualified completion:
308 //
309 // "vec^" => {""}
310 // "using namespace std; vec^" => {"", "std::"}
311 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
312 //
313 // "" for global namespace, "ns::" for normal namespace.
314 std::vector<std::string> AccessibleScopes;
315 // The full scope qualifier as typed by the user (without the leading "::").
316 // Set if the qualifier is not fully resolved by Sema.
317 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000318
Haojian Wu061c73e2018-01-23 11:37:26 +0000319 // Construct scopes being queried in indexes.
320 // This method format the scopes to match the index request representation.
321 std::vector<std::string> scopesForIndexQuery() {
322 std::vector<std::string> Results;
323 for (llvm::StringRef AS : AccessibleScopes) {
324 Results.push_back(AS);
325 if (UnresolvedQualifier)
326 Results.back() += *UnresolvedQualifier;
327 }
328 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000329 }
Eric Liu6f648df2017-12-19 16:50:37 +0000330};
331
Haojian Wu061c73e2018-01-23 11:37:26 +0000332// Get all scopes that will be queried in indexes.
333std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000334 const SourceManager &SM) {
335 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000336 SpecifiedScope Info;
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000337 for (auto *Context : CCContext.getVisitedContexts()) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000338 if (isa<TranslationUnitDecl>(Context))
339 Info.AccessibleScopes.push_back(""); // global namespace
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000340 else if (const auto *NS = dyn_cast<NamespaceDecl>(Context))
Haojian Wu061c73e2018-01-23 11:37:26 +0000341 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
342 }
343 return Info;
344 };
345
346 auto SS = CCContext.getCXXScopeSpecifier();
347
348 // Unqualified completion (e.g. "vec^").
349 if (!SS) {
350 // FIXME: Once we can insert namespace qualifiers and use the in-scope
351 // namespaces for scoring, search in all namespaces.
352 // FIXME: Capture scopes and use for scoring, for example,
353 // "using namespace std; namespace foo {v^}" =>
354 // foo::value > std::vector > boost::variant
355 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
356 }
357
358 // Qualified completion ("std::vec^"), we have two cases depending on whether
359 // the qualifier can be resolved by Sema.
360 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000361 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
362 }
363
364 // Unresolved qualifier.
365 // FIXME: When Sema can resolve part of a scope chain (e.g.
366 // "known::unknown::id"), we should expand the known part ("known::") rather
367 // than treating the whole thing as unknown.
368 SpecifiedScope Info;
369 Info.AccessibleScopes.push_back(""); // global namespace
370
371 Info.UnresolvedQualifier =
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000372 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM,
373 clang::LangOptions())
374 .ltrim("::");
Haojian Wu061c73e2018-01-23 11:37:26 +0000375 // Sema excludes the trailing "::".
376 if (!Info.UnresolvedQualifier->empty())
377 *Info.UnresolvedQualifier += "::";
378
379 return Info.scopesForIndexQuery();
380}
381
Eric Liu42abe412018-05-24 11:20:19 +0000382// Should we perform index-based completion in a context of the specified kind?
383// FIXME: consider allowing completion, but restricting the result types.
384bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
385 switch (K) {
386 case CodeCompletionContext::CCC_TopLevel:
387 case CodeCompletionContext::CCC_ObjCInterface:
388 case CodeCompletionContext::CCC_ObjCImplementation:
389 case CodeCompletionContext::CCC_ObjCIvarList:
390 case CodeCompletionContext::CCC_ClassStructUnion:
391 case CodeCompletionContext::CCC_Statement:
392 case CodeCompletionContext::CCC_Expression:
393 case CodeCompletionContext::CCC_ObjCMessageReceiver:
394 case CodeCompletionContext::CCC_EnumTag:
395 case CodeCompletionContext::CCC_UnionTag:
396 case CodeCompletionContext::CCC_ClassOrStructTag:
397 case CodeCompletionContext::CCC_ObjCProtocolName:
398 case CodeCompletionContext::CCC_Namespace:
399 case CodeCompletionContext::CCC_Type:
400 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
401 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
402 case CodeCompletionContext::CCC_ParenthesizedExpression:
403 case CodeCompletionContext::CCC_ObjCInterfaceName:
404 case CodeCompletionContext::CCC_ObjCCategoryName:
405 return true;
406 case CodeCompletionContext::CCC_Other: // Be conservative.
407 case CodeCompletionContext::CCC_OtherWithMacros:
408 case CodeCompletionContext::CCC_DotMemberAccess:
409 case CodeCompletionContext::CCC_ArrowMemberAccess:
410 case CodeCompletionContext::CCC_ObjCPropertyAccess:
411 case CodeCompletionContext::CCC_MacroName:
412 case CodeCompletionContext::CCC_MacroNameUse:
413 case CodeCompletionContext::CCC_PreprocessorExpression:
414 case CodeCompletionContext::CCC_PreprocessorDirective:
415 case CodeCompletionContext::CCC_NaturalLanguage:
416 case CodeCompletionContext::CCC_SelectorName:
417 case CodeCompletionContext::CCC_TypeQualifiers:
418 case CodeCompletionContext::CCC_ObjCInstanceMessage:
419 case CodeCompletionContext::CCC_ObjCClassMessage:
420 case CodeCompletionContext::CCC_Recovery:
421 return false;
422 }
423 llvm_unreachable("unknown code completion context");
424}
425
Sam McCall4caa8512018-06-07 12:49:17 +0000426// Some member calls are blacklisted because they're so rarely useful.
427static bool isBlacklistedMember(const NamedDecl &D) {
428 // Destructor completion is rarely useful, and works inconsistently.
429 // (s.^ completes ~string, but s.~st^ is an error).
430 if (D.getKind() == Decl::CXXDestructor)
431 return true;
432 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
433 if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
434 if (R->isInjectedClassName())
435 return true;
436 // Explicit calls to operators are also rare.
437 auto NameKind = D.getDeclName().getNameKind();
438 if (NameKind == DeclarationName::CXXOperatorName ||
439 NameKind == DeclarationName::CXXLiteralOperatorName ||
440 NameKind == DeclarationName::CXXConversionFunctionName)
441 return true;
442 return false;
443}
444
Sam McCall545a20d2018-01-19 14:34:02 +0000445// The CompletionRecorder captures Sema code-complete output, including context.
446// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
447// It doesn't do scoring or conversion to CompletionItem yet, as we want to
448// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000449// Generally the fields and methods of this object should only be used from
450// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000451struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000452 CompletionRecorder(const CodeCompleteOptions &Opts,
453 UniqueFunction<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000454 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000455 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000456 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
457 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000458 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
459 assert(this->ResultsCallback);
460 }
461
Sam McCall545a20d2018-01-19 14:34:02 +0000462 std::vector<CodeCompletionResult> Results;
463 CodeCompletionContext CCContext;
464 Sema *CCSema = nullptr; // Sema that created the results.
465 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000466
Sam McCall545a20d2018-01-19 14:34:02 +0000467 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
468 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000469 unsigned NumResults) override final {
Eric Liu42abe412018-05-24 11:20:19 +0000470 // If a callback is called without any sema result and the context does not
471 // support index-based completion, we simply skip it to give way to
472 // potential future callbacks with results.
473 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
474 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000475 if (CCSema) {
476 log(llvm::formatv(
477 "Multiple code complete callbacks (parser backtracked?). "
478 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000479 getCompletionKindString(Context.getKind()),
480 getCompletionKindString(this->CCContext.getKind())));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000481 return;
482 }
Sam McCall545a20d2018-01-19 14:34:02 +0000483 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000484 CCSema = &S;
485 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000486
Sam McCall545a20d2018-01-19 14:34:02 +0000487 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000488 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000489 auto &Result = InResults[I];
490 // Drop hidden items which cannot be found by lookup after completion.
491 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000492 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
493 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000494 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000495 (Result.Availability == CXAvailability_NotAvailable ||
496 Result.Availability == CXAvailability_NotAccessible))
497 continue;
Sam McCall4caa8512018-06-07 12:49:17 +0000498 if (Result.Declaration &&
499 !Context.getBaseType().isNull() // is this a member-access context?
500 && isBlacklistedMember(*Result.Declaration))
Sam McCalld2a95922018-01-22 21:05:00 +0000501 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000502 // We choose to never append '::' to completion results in clangd.
503 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000504 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000505 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000506 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000507 }
508
Sam McCall545a20d2018-01-19 14:34:02 +0000509 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000510 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
511
Sam McCall545a20d2018-01-19 14:34:02 +0000512 // Returns the filtering/sorting name for Result, which must be from Results.
513 // Returned string is owned by this recorder (or the AST).
514 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000515 switch (Result.Kind) {
516 case CodeCompletionResult::RK_Declaration:
517 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000518 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000519 break;
520 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000521 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000522 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000523 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000524 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000525 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000526 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000527 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000528 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000529 }
530
Sam McCall545a20d2018-01-19 14:34:02 +0000531 // Build a CodeCompletion string for R, which must be from Results.
532 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000533 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000534 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
535 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000536 *CCSema, CCContext, *CCAllocator, CCTUInfo,
537 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000538 }
539
Sam McCall545a20d2018-01-19 14:34:02 +0000540private:
541 CodeCompleteOptions Opts;
542 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000543 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000544 UniqueFunction<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000545};
546
Sam McCallc5707b62018-05-15 17:43:27 +0000547struct ScoredCandidateGreater {
548 bool operator()(const ScoredCandidate &L, const ScoredCandidate &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000549 if (L.second.finalScore != R.second.finalScore)
550 return L.second.finalScore > R.second.finalScore;
551 return L.first.Name < R.first.Name; // Earlier name is better.
552 }
Sam McCall545a20d2018-01-19 14:34:02 +0000553};
Sam McCall98775c52017-12-04 13:49:59 +0000554
Sam McCall98775c52017-12-04 13:49:59 +0000555class SignatureHelpCollector final : public CodeCompleteConsumer {
556
557public:
558 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
559 SignatureHelp &SigHelp)
560 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
561 SigHelp(SigHelp),
562 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
563 CCTUInfo(Allocator) {}
564
565 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
566 OverloadCandidate *Candidates,
567 unsigned NumCandidates) override {
568 SigHelp.signatures.reserve(NumCandidates);
569 // FIXME(rwols): How can we determine the "active overload candidate"?
570 // Right now the overloaded candidates seem to be provided in a "best fit"
571 // order, so I'm not too worried about this.
572 SigHelp.activeSignature = 0;
573 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
574 "too many arguments");
575 SigHelp.activeParameter = static_cast<int>(CurrentArg);
576 for (unsigned I = 0; I < NumCandidates; ++I) {
577 const auto &Candidate = Candidates[I];
578 const auto *CCS = Candidate.CreateSignatureString(
579 CurrentArg, S, *Allocator, CCTUInfo, true);
580 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000581 // FIXME: for headers, we need to get a comment from the index.
Ilya Biryukov43714502018-05-16 12:32:44 +0000582 SigHelp.signatures.push_back(ProcessOverloadCandidate(
583 Candidate, *CCS,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000584 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000585 /*CommentsFromHeaders=*/false)));
Sam McCall98775c52017-12-04 13:49:59 +0000586 }
587 }
588
589 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
590
591 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
592
593private:
Eric Liu63696e12017-12-20 17:24:31 +0000594 // FIXME(ioeric): consider moving CodeCompletionString logic here to
595 // CompletionString.h.
Sam McCall98775c52017-12-04 13:49:59 +0000596 SignatureInformation
597 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
Ilya Biryukov43714502018-05-16 12:32:44 +0000598 const CodeCompletionString &CCS,
599 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000600 SignatureInformation Result;
601 const char *ReturnType = nullptr;
602
Ilya Biryukov43714502018-05-16 12:32:44 +0000603 Result.documentation = formatDocumentation(CCS, DocComment);
Sam McCall98775c52017-12-04 13:49:59 +0000604
605 for (const auto &Chunk : CCS) {
606 switch (Chunk.Kind) {
607 case CodeCompletionString::CK_ResultType:
608 // A piece of text that describes the type of an entity or,
609 // for functions and methods, the return type.
610 assert(!ReturnType && "Unexpected CK_ResultType");
611 ReturnType = Chunk.Text;
612 break;
613 case CodeCompletionString::CK_Placeholder:
614 // A string that acts as a placeholder for, e.g., a function call
615 // argument.
616 // Intentional fallthrough here.
617 case CodeCompletionString::CK_CurrentParameter: {
618 // A piece of text that describes the parameter that corresponds to
619 // the code-completion location within a function call, message send,
620 // macro invocation, etc.
621 Result.label += Chunk.Text;
622 ParameterInformation Info;
623 Info.label = Chunk.Text;
624 Result.parameters.push_back(std::move(Info));
625 break;
626 }
627 case CodeCompletionString::CK_Optional: {
628 // The rest of the parameters are defaulted/optional.
629 assert(Chunk.Optional &&
630 "Expected the optional code completion string to be non-null.");
631 Result.label +=
632 getOptionalParameters(*Chunk.Optional, Result.parameters);
633 break;
634 }
635 case CodeCompletionString::CK_VerticalSpace:
636 break;
637 default:
638 Result.label += Chunk.Text;
639 break;
640 }
641 }
642 if (ReturnType) {
643 Result.label += " -> ";
644 Result.label += ReturnType;
645 }
646 return Result;
647 }
648
649 SignatureHelp &SigHelp;
650 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
651 CodeCompletionTUInfo CCTUInfo;
652
653}; // SignatureHelpCollector
654
Sam McCall545a20d2018-01-19 14:34:02 +0000655struct SemaCompleteInput {
656 PathRef FileName;
657 const tooling::CompileCommand &Command;
658 PrecompiledPreamble const *Preamble;
Eric Liu63f419a2018-05-15 15:29:32 +0000659 const std::vector<Inclusion> &PreambleInclusions;
Sam McCall545a20d2018-01-19 14:34:02 +0000660 StringRef Contents;
661 Position Pos;
662 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
663 std::shared_ptr<PCHContainerOperations> PCHs;
664};
665
666// Invokes Sema code completion on a file.
Eric Liu63f419a2018-05-15 15:29:32 +0000667// If \p Includes is set, it will be initialized after a compiler instance has
668// been set up.
Sam McCalld1a7a372018-01-31 13:40:48 +0000669bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000670 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000671 const SemaCompleteInput &Input,
672 std::unique_ptr<IncludeInserter> *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000673 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000674 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000675 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000676 ArgStrs.push_back(S.c_str());
677
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000678 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
679 log("Couldn't set working directory");
680 // We run parsing anyway, our lit-tests rely on results for non-existing
681 // working dirs.
682 }
Sam McCall98775c52017-12-04 13:49:59 +0000683
684 IgnoreDiagnostics DummyDiagsConsumer;
685 auto CI = createInvocationFromCommandLine(
686 ArgStrs,
687 CompilerInstance::createDiagnostics(new DiagnosticOptions,
688 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000689 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000690 if (!CI) {
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000691 log("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000692 return false;
693 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000694 auto &FrontendOpts = CI->getFrontendOpts();
695 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000696 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000697 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
698 // Disable typo correction in Sema.
699 CI->getLangOpts()->SpellChecking = false;
700 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +0000701 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000702 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000703 auto Offset = positionToOffset(Input.Contents, Input.Pos);
704 if (!Offset) {
705 log("Code completion position was invalid " +
706 llvm::toString(Offset.takeError()));
707 return false;
708 }
709 std::tie(FrontendOpts.CodeCompletionAt.Line,
710 FrontendOpts.CodeCompletionAt.Column) =
711 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000712
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000713 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
714 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
715 // The diagnostic options must be set before creating a CompilerInstance.
716 CI->getDiagnosticOpts().IgnoreWarnings = true;
717 // We reuse the preamble whether it's valid or not. This is a
718 // correctness/performance tradeoff: building without a preamble is slow, and
719 // completion is latency-sensitive.
720 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
721 // the remapped buffers do not get freed.
722 auto Clang = prepareCompilerInstance(
723 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
724 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000725 Clang->setCodeCompletionConsumer(Consumer.release());
726
727 SyntaxOnlyAction Action;
728 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000729 log("BeginSourceFile() failed when running codeComplete for " +
730 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000731 return false;
732 }
Eric Liu63f419a2018-05-15 15:29:32 +0000733 if (Includes) {
734 // Initialize Includes if provided.
735
736 // FIXME(ioeric): needs more consistent style support in clangd server.
737 auto Style = format::getStyle("file", Input.FileName, "LLVM",
738 Input.Contents, Input.VFS.get());
739 if (!Style) {
740 log("Failed to get FormatStyle for file" + Input.FileName +
741 ". Fall back to use LLVM style. Error: " +
742 llvm::toString(Style.takeError()));
743 Style = format::getLLVMStyle();
744 }
745 *Includes = llvm::make_unique<IncludeInserter>(
746 Input.FileName, Input.Contents, *Style, Input.Command.Directory,
747 Clang->getPreprocessor().getHeaderSearchInfo());
748 for (const auto &Inc : Input.PreambleInclusions)
749 Includes->get()->addExisting(Inc);
750 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
751 Clang->getSourceManager(), [Includes](Inclusion Inc) {
752 Includes->get()->addExisting(std::move(Inc));
753 }));
754 }
Sam McCall98775c52017-12-04 13:49:59 +0000755 if (!Action.Execute()) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000756 log("Execute() failed when running codeComplete for " + Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000757 return false;
758 }
Sam McCall98775c52017-12-04 13:49:59 +0000759 Action.EndSourceFile();
760
761 return true;
762}
763
Ilya Biryukova907ba42018-05-14 10:50:04 +0000764// Should we allow index completions in the specified context?
765bool allowIndex(CodeCompletionContext &CC) {
766 if (!contextAllowsIndex(CC.getKind()))
767 return false;
768 // We also avoid ClassName::bar (but allow namespace::bar).
769 auto Scope = CC.getCXXScopeSpecifier();
770 if (!Scope)
771 return true;
772 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
773 if (!NameSpec)
774 return true;
775 // We only query the index when qualifier is a namespace.
776 // If it's a class, we rely solely on sema completions.
777 switch (NameSpec->getKind()) {
778 case NestedNameSpecifier::Global:
779 case NestedNameSpecifier::Namespace:
780 case NestedNameSpecifier::NamespaceAlias:
781 return true;
782 case NestedNameSpecifier::Super:
783 case NestedNameSpecifier::TypeSpec:
784 case NestedNameSpecifier::TypeSpecWithTemplate:
785 // Unresolved inside a template.
786 case NestedNameSpecifier::Identifier:
787 return false;
788 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000789 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000790}
791
Sam McCall98775c52017-12-04 13:49:59 +0000792} // namespace
793
794clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
795 clang::CodeCompleteOptions Result;
796 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
797 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000798 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000799 // We choose to include full comments and not do doxygen parsing in
800 // completion.
801 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
802 // formatting of the comments.
803 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000804
Sam McCall3d139c52018-01-12 18:30:08 +0000805 // When an is used, Sema is responsible for completing the main file,
806 // the index can provide results from the preamble.
807 // Tell Sema not to deserialize the preamble to look for results.
808 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000809
Sam McCall98775c52017-12-04 13:49:59 +0000810 return Result;
811}
812
Sam McCall545a20d2018-01-19 14:34:02 +0000813// Runs Sema-based (AST) and Index-based completion, returns merged results.
814//
815// There are a few tricky considerations:
816// - the AST provides information needed for the index query (e.g. which
817// namespaces to search in). So Sema must start first.
818// - we only want to return the top results (Opts.Limit).
819// Building CompletionItems for everything else is wasteful, so we want to
820// preserve the "native" format until we're done with scoring.
821// - the data underlying Sema completion items is owned by the AST and various
822// other arenas, which must stay alive for us to build CompletionItems.
823// - we may get duplicate results from Sema and the Index, we need to merge.
824//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000825// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000826// We use the Sema context information to query the index.
827// Then we merge the two result sets, producing items that are Sema/Index/Both.
828// These items are scored, and the top N are synthesized into the LSP response.
829// Finally, we can clean up the data structures created by Sema completion.
830//
831// Main collaborators are:
832// - semaCodeComplete sets up the compiler machinery to run code completion.
833// - CompletionRecorder captures Sema completion results, including context.
834// - SymbolIndex (Opts.Index) provides index completion results as Symbols
835// - CompletionCandidates are the result of merging Sema and Index results.
836// Each candidate points to an underlying CodeCompletionResult (Sema), a
837// Symbol (Index), or both. It computes the result quality score.
838// CompletionCandidate also does conversion to CompletionItem (at the end).
839// - FuzzyMatcher scores how the candidate matches the partial identifier.
840// This score is combined with the result quality score for the final score.
841// - TopN determines the results with the best score.
842class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000843 PathRef FileName;
Sam McCall545a20d2018-01-19 14:34:02 +0000844 const CodeCompleteOptions &Opts;
845 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000846 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000847 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
848 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000849 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
850 std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs.
Eric Liu09c3c372018-06-15 08:58:12 +0000851 FileProximityMatcher FileProximityMatch;
Sam McCall545a20d2018-01-19 14:34:02 +0000852
853public:
854 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Eric Liuc5105f92018-02-16 14:15:55 +0000855 CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
Eric Liu09c3c372018-06-15 08:58:12 +0000856 : FileName(FileName), Opts(Opts),
857 // FIXME: also use path of the main header corresponding to FileName to
858 // calculate the file proximity, which would capture include/ and src/
859 // project setup where headers and implementations are not in the same
860 // directory.
Haojian Wu7943d4f2018-06-15 09:32:36 +0000861 FileProximityMatch(ArrayRef<StringRef>({FileName})) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000862
863 CompletionList run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000864 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000865
Sam McCall545a20d2018-01-19 14:34:02 +0000866 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000867 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000868 // - partial identifier and context. We need these for the index query.
869 CompletionList Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000870 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
871 assert(Recorder && "Recorder is not set");
Eric Liu63f419a2018-05-15 15:29:32 +0000872 assert(Includes && "Includes is not set");
873 // If preprocessor was run, inclusions from preprocessor callback should
874 // already be added to Inclusions.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000875 Output = runWithSema();
Eric Liu63f419a2018-05-15 15:29:32 +0000876 Includes.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000877 SPAN_ATTACH(Tracer, "sema_completion_kind",
878 getCompletionKindString(Recorder->CCContext.getKind()));
879 });
880
881 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +0000882 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +0000883 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +0000884
Sam McCall2b780162018-01-30 17:20:54 +0000885 SPAN_ATTACH(Tracer, "sema_results", NSema);
886 SPAN_ATTACH(Tracer, "index_results", NIndex);
887 SPAN_ATTACH(Tracer, "merged_results", NBoth);
888 SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
889 SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
Sam McCall0f8df3e2018-06-13 11:31:20 +0000890 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
891 "{2} matched, {3} returned{4}.",
892 NSema, NIndex, NBoth, Output.items.size(),
893 Output.isIncomplete ? " (incomplete)" : ""));
Sam McCall545a20d2018-01-19 14:34:02 +0000894 assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
895 // We don't assert that isIncomplete means we hit a limit.
896 // Indexes may choose to impose their own limits even if we don't have one.
897 return Output;
898 }
899
900private:
901 // This is called by run() once Sema code completion is done, but before the
902 // Sema data structures are torn down. It does all the real work.
903 CompletionList runWithSema() {
904 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000905 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Sam McCall545a20d2018-01-19 14:34:02 +0000906 // Sema provides the needed context to query the index.
907 // FIXME: in addition to querying for extra/overlapping symbols, we should
908 // explicitly request symbols corresponding to Sema results.
909 // We can use their signals even if the index can't suggest them.
910 // We must copy index results to preserve them, but there are at most Limit.
911 auto IndexResults = queryIndex();
912 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000913 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall545a20d2018-01-19 14:34:02 +0000914 // Convert the results to the desired LSP structs.
915 CompletionList Output;
916 for (auto &C : Top)
917 Output.items.push_back(toCompletionItem(C.first, C.second));
918 Output.isIncomplete = Incomplete;
919 return Output;
920 }
921
922 SymbolSlab queryIndex() {
Ilya Biryukova907ba42018-05-14 10:50:04 +0000923 if (!Opts.Index || !allowIndex(Recorder->CCContext))
Sam McCall545a20d2018-01-19 14:34:02 +0000924 return SymbolSlab();
Sam McCalld1a7a372018-01-31 13:40:48 +0000925 trace::Span Tracer("Query index");
Sam McCall2b780162018-01-30 17:20:54 +0000926 SPAN_ATTACH(Tracer, "limit", Opts.Limit);
927
Sam McCall545a20d2018-01-19 14:34:02 +0000928 SymbolSlab::Builder ResultsBuilder;
929 // Build the query.
930 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +0000931 if (Opts.Limit)
932 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +0000933 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000934 Req.RestrictForCodeCompletion = true;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000935 Req.Scopes = getQueryScopes(Recorder->CCContext,
936 Recorder->CCSema->getSourceManager());
Eric Liu6de95ec2018-06-12 08:48:20 +0000937 Req.ProximityPaths.push_back(FileName);
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
Sam McCall80ad7072018-06-08 13:32:25 +0000981 Optional<float> fuzzyScore(const CompletionCandidate &C) {
982 // Macros can be very spammy, so we only support prefix completion.
983 // We won't end up with underfull index results, as macros are sema-only.
984 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
985 !C.Name.startswith_lower(Filter->pattern()))
986 return None;
987 return Filter->match(C.Name);
988 }
989
Sam McCall545a20d2018-01-19 14:34:02 +0000990 // Scores a candidate and adds it to the TopN structure.
Sam McCallc5707b62018-05-15 17:43:27 +0000991 void addCandidate(TopN<ScoredCandidate, ScoredCandidateGreater> &Candidates,
992 const CodeCompletionResult *SemaResult,
Sam McCall545a20d2018-01-19 14:34:02 +0000993 const Symbol *IndexResult) {
994 CompletionCandidate C;
995 C.SemaResult = SemaResult;
996 C.IndexResult = IndexResult;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000997 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
Sam McCall545a20d2018-01-19 14:34:02 +0000998
Sam McCallc5707b62018-05-15 17:43:27 +0000999 SymbolQualitySignals Quality;
1000 SymbolRelevanceSignals Relevance;
Sam McCalld9b54f02018-06-05 16:30:25 +00001001 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Eric Liu09c3c372018-06-15 08:58:12 +00001002 Relevance.FileProximityMatch = &FileProximityMatch;
Sam McCall80ad7072018-06-08 13:32:25 +00001003 if (auto FuzzyScore = fuzzyScore(C))
Sam McCallc5707b62018-05-15 17:43:27 +00001004 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001005 else
1006 return;
Sam McCalld9b54f02018-06-05 16:30:25 +00001007 if (IndexResult) {
Sam McCallc5707b62018-05-15 17:43:27 +00001008 Quality.merge(*IndexResult);
Sam McCalld9b54f02018-06-05 16:30:25 +00001009 Relevance.merge(*IndexResult);
1010 }
Sam McCallc5707b62018-05-15 17:43:27 +00001011 if (SemaResult) {
1012 Quality.merge(*SemaResult);
1013 Relevance.merge(*SemaResult);
1014 }
1015
1016 float QualScore = Quality.evaluate(), RelScore = Relevance.evaluate();
1017 CompletionItemScores Scores;
1018 Scores.finalScore = evaluateSymbolAndRelevance(QualScore, RelScore);
1019 // The purpose of exporting component scores is to allow NameMatch to be
1020 // replaced on the client-side. So we export (NameMatch, final/NameMatch)
1021 // rather than (RelScore, QualScore).
1022 Scores.filterScore = Relevance.NameMatch;
1023 Scores.symbolScore =
1024 Scores.filterScore ? Scores.finalScore / Scores.filterScore : QualScore;
1025
Nicola Zaghenc9fed132018-05-23 13:57:48 +00001026 LLVM_DEBUG(llvm::dbgs()
1027 << "CodeComplete: " << C.Name << (IndexResult ? " (index)" : "")
1028 << (SemaResult ? " (sema)" : "") << " = " << Scores.finalScore
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +00001029 << "\n"
Nicola Zaghenc9fed132018-05-23 13:57:48 +00001030 << Quality << Relevance << "\n");
Sam McCall545a20d2018-01-19 14:34:02 +00001031
1032 NSema += bool(SemaResult);
1033 NIndex += bool(IndexResult);
1034 NBoth += SemaResult && IndexResult;
Sam McCallab8e3932018-02-19 13:04:41 +00001035 if (Candidates.push({C, Scores}))
1036 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001037 }
1038
1039 CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
1040 const CompletionItemScores &Scores) {
1041 CodeCompletionString *SemaCCS = nullptr;
Ilya Biryukov43714502018-05-16 12:32:44 +00001042 std::string DocComment;
1043 if (auto *SR = Candidate.SemaResult) {
1044 SemaCCS = Recorder->codeCompletionString(*SR);
1045 if (Opts.IncludeComments) {
1046 assert(Recorder->CCSema);
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001047 DocComment = getDocComment(Recorder->CCSema->getASTContext(), *SR,
1048 /*CommentsFromHeader=*/false);
Ilya Biryukov43714502018-05-16 12:32:44 +00001049 }
1050 }
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +00001051 return Candidate.build(FileName, Scores, Opts, SemaCCS, Includes.get(),
1052 DocComment);
Sam McCall545a20d2018-01-19 14:34:02 +00001053 }
1054};
1055
Sam McCalld1a7a372018-01-31 13:40:48 +00001056CompletionList codeComplete(PathRef FileName,
Sam McCall98775c52017-12-04 13:49:59 +00001057 const tooling::CompileCommand &Command,
1058 PrecompiledPreamble const *Preamble,
Eric Liu63f419a2018-05-15 15:29:32 +00001059 const std::vector<Inclusion> &PreambleInclusions,
Sam McCall98775c52017-12-04 13:49:59 +00001060 StringRef Contents, Position Pos,
1061 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1062 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001063 CodeCompleteOptions Opts) {
Eric Liuc5105f92018-02-16 14:15:55 +00001064 return CodeCompleteFlow(FileName, Opts)
Eric Liu63f419a2018-05-15 15:29:32 +00001065 .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS,
1066 PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001067}
1068
Sam McCalld1a7a372018-01-31 13:40:48 +00001069SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001070 const tooling::CompileCommand &Command,
1071 PrecompiledPreamble const *Preamble,
1072 StringRef Contents, Position Pos,
1073 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1074 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001075 SignatureHelp Result;
1076 clang::CodeCompleteOptions Options;
1077 Options.IncludeGlobals = false;
1078 Options.IncludeMacros = false;
1079 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001080 Options.IncludeBriefComments = false;
Eric Liu4c0a27b2018-05-16 20:31:38 +00001081 std::vector<Inclusion> PreambleInclusions = {}; // Unused for signatureHelp
Sam McCalld1a7a372018-01-31 13:40:48 +00001082 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1083 Options,
Eric Liu4c0a27b2018-05-16 20:31:38 +00001084 {FileName, Command, Preamble, PreambleInclusions, Contents,
1085 Pos, std::move(VFS), std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001086 return Result;
1087}
1088
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001089bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1090 using namespace clang::ast_matchers;
1091 auto InTopLevelScope = hasDeclContext(
1092 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1093 return !match(decl(anyOf(InTopLevelScope,
1094 hasDeclContext(
1095 enumDecl(InTopLevelScope, unless(isScoped()))))),
1096 ND, ASTCtx)
1097 .empty();
1098}
1099
Sam McCall98775c52017-12-04 13:49:59 +00001100} // namespace clangd
1101} // namespace clang