blob: 6fb1d9a186c4053f01d24c1bdbb279c058640e3c [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(CXCursorKind CursorKind) {
Sam McCall98775c52017-12-04 13:49:59 +000048 switch (CursorKind) {
49 case CXCursor_MacroInstantiation:
50 case CXCursor_MacroDefinition:
51 return CompletionItemKind::Text;
52 case CXCursor_CXXMethod:
Eric Liu6f648df2017-12-19 16:50:37 +000053 case CXCursor_Destructor:
Sam McCall98775c52017-12-04 13:49:59 +000054 return CompletionItemKind::Method;
55 case CXCursor_FunctionDecl:
56 case CXCursor_FunctionTemplate:
57 return CompletionItemKind::Function;
58 case CXCursor_Constructor:
Sam McCall98775c52017-12-04 13:49:59 +000059 return CompletionItemKind::Constructor;
60 case CXCursor_FieldDecl:
61 return CompletionItemKind::Field;
62 case CXCursor_VarDecl:
63 case CXCursor_ParmDecl:
64 return CompletionItemKind::Variable;
Eric Liu6f648df2017-12-19 16:50:37 +000065 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
66 // protocol.
Sam McCall98775c52017-12-04 13:49:59 +000067 case CXCursor_StructDecl:
Eric Liu6f648df2017-12-19 16:50:37 +000068 case CXCursor_ClassDecl:
Sam McCall98775c52017-12-04 13:49:59 +000069 case CXCursor_UnionDecl:
70 case CXCursor_ClassTemplate:
71 case CXCursor_ClassTemplatePartialSpecialization:
72 return CompletionItemKind::Class;
73 case CXCursor_Namespace:
74 case CXCursor_NamespaceAlias:
75 case CXCursor_NamespaceRef:
76 return CompletionItemKind::Module;
77 case CXCursor_EnumConstantDecl:
78 return CompletionItemKind::Value;
79 case CXCursor_EnumDecl:
80 return CompletionItemKind::Enum;
Eric Liu6f648df2017-12-19 16:50:37 +000081 // FIXME(ioeric): figure out whether reference is the right type for aliases.
Sam McCall98775c52017-12-04 13:49:59 +000082 case CXCursor_TypeAliasDecl:
83 case CXCursor_TypeAliasTemplateDecl:
84 case CXCursor_TypedefDecl:
85 case CXCursor_MemberRef:
86 case CXCursor_TypeRef:
87 return CompletionItemKind::Reference;
88 default:
89 return CompletionItemKind::Missing;
90 }
91}
92
Eric Liu6f648df2017-12-19 16:50:37 +000093CompletionItemKind
94toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
95 CXCursorKind CursorKind) {
Sam McCall98775c52017-12-04 13:49:59 +000096 switch (ResKind) {
97 case CodeCompletionResult::RK_Declaration:
Eric Liu6f648df2017-12-19 16:50:37 +000098 return toCompletionItemKind(CursorKind);
Sam McCall98775c52017-12-04 13:49:59 +000099 case CodeCompletionResult::RK_Keyword:
100 return CompletionItemKind::Keyword;
101 case CodeCompletionResult::RK_Macro:
102 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
103 // completion items in LSP.
104 case CodeCompletionResult::RK_Pattern:
105 return CompletionItemKind::Snippet;
106 }
107 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
108}
109
Eric Liu6f648df2017-12-19 16:50:37 +0000110CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
111 using SK = index::SymbolKind;
112 switch (Kind) {
113 case SK::Unknown:
114 return CompletionItemKind::Missing;
115 case SK::Module:
116 case SK::Namespace:
117 case SK::NamespaceAlias:
118 return CompletionItemKind::Module;
119 case SK::Macro:
120 return CompletionItemKind::Text;
121 case SK::Enum:
122 return CompletionItemKind::Enum;
123 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
124 // protocol.
125 case SK::Struct:
126 case SK::Class:
127 case SK::Protocol:
128 case SK::Extension:
129 case SK::Union:
130 return CompletionItemKind::Class;
131 // FIXME(ioeric): figure out whether reference is the right type for aliases.
132 case SK::TypeAlias:
133 case SK::Using:
134 return CompletionItemKind::Reference;
135 case SK::Function:
136 // FIXME(ioeric): this should probably be an operator. This should be fixed
137 // when `Operator` is support type in the protocol.
138 case SK::ConversionFunction:
139 return CompletionItemKind::Function;
140 case SK::Variable:
141 case SK::Parameter:
142 return CompletionItemKind::Variable;
143 case SK::Field:
144 return CompletionItemKind::Field;
145 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
146 case SK::EnumConstant:
147 return CompletionItemKind::Value;
148 case SK::InstanceMethod:
149 case SK::ClassMethod:
150 case SK::StaticMethod:
151 case SK::Destructor:
152 return CompletionItemKind::Method;
153 case SK::InstanceProperty:
154 case SK::ClassProperty:
155 case SK::StaticProperty:
156 return CompletionItemKind::Property;
157 case SK::Constructor:
158 return CompletionItemKind::Constructor;
159 }
160 llvm_unreachable("Unhandled clang::index::SymbolKind.");
161}
162
Sam McCall98775c52017-12-04 13:49:59 +0000163/// Get the optional chunk as a string. This function is possibly recursive.
164///
165/// The parameter info for each parameter is appended to the Parameters.
166std::string
167getOptionalParameters(const CodeCompletionString &CCS,
168 std::vector<ParameterInformation> &Parameters) {
169 std::string Result;
170 for (const auto &Chunk : CCS) {
171 switch (Chunk.Kind) {
172 case CodeCompletionString::CK_Optional:
173 assert(Chunk.Optional &&
174 "Expected the optional code completion string to be non-null.");
175 Result += getOptionalParameters(*Chunk.Optional, Parameters);
176 break;
177 case CodeCompletionString::CK_VerticalSpace:
178 break;
179 case CodeCompletionString::CK_Placeholder:
180 // A string that acts as a placeholder for, e.g., a function call
181 // argument.
182 // Intentional fallthrough here.
183 case CodeCompletionString::CK_CurrentParameter: {
184 // A piece of text that describes the parameter that corresponds to
185 // the code-completion location within a function call, message send,
186 // macro invocation, etc.
187 Result += Chunk.Text;
188 ParameterInformation Info;
189 Info.label = Chunk.Text;
190 Parameters.push_back(std::move(Info));
191 break;
192 }
193 default:
194 Result += Chunk.Text;
195 break;
196 }
197 }
198 return Result;
199}
200
Eric Liu63f419a2018-05-15 15:29:32 +0000201/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
202/// include.
203static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
204 llvm::StringRef HintPath) {
205 if (isLiteralInclude(Header))
206 return HeaderFile{Header.str(), /*Verbatim=*/true};
207 auto U = URI::parse(Header);
208 if (!U)
209 return U.takeError();
210
211 auto IncludePath = URI::includeSpelling(*U);
212 if (!IncludePath)
213 return IncludePath.takeError();
214 if (!IncludePath->empty())
215 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
216
217 auto Resolved = URI::resolve(*U, HintPath);
218 if (!Resolved)
219 return Resolved.takeError();
220 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
221}
222
Sam McCall545a20d2018-01-19 14:34:02 +0000223/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000224/// It may be promoted to a CompletionItem if it's among the top-ranked results.
225struct CompletionCandidate {
Sam McCall545a20d2018-01-19 14:34:02 +0000226 llvm::StringRef Name; // Used for filtering and sorting.
227 // We may have a result from Sema, from the index, or both.
228 const CodeCompletionResult *SemaResult = nullptr;
229 const Symbol *IndexResult = nullptr;
Sam McCall98775c52017-12-04 13:49:59 +0000230
Sam McCall545a20d2018-01-19 14:34:02 +0000231 // Builds an LSP completion item.
Eric Liu63f419a2018-05-15 15:29:32 +0000232 CompletionItem build(StringRef FileName, const CompletionItemScores &Scores,
Sam McCall545a20d2018-01-19 14:34:02 +0000233 const CodeCompleteOptions &Opts,
Eric Liu63f419a2018-05-15 15:29:32 +0000234 CodeCompletionString *SemaCCS,
Ilya Biryukov43714502018-05-16 12:32:44 +0000235 const IncludeInserter *Includes,
236 llvm::StringRef SemaDocComment) const {
Sam McCall545a20d2018-01-19 14:34:02 +0000237 assert(bool(SemaResult) == bool(SemaCCS));
238 CompletionItem I;
Eric Liu9b3cba72018-05-30 09:03:39 +0000239 bool ShouldInsertInclude = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000240 if (SemaResult) {
241 I.kind = toCompletionItemKind(SemaResult->Kind, SemaResult->CursorKind);
242 getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText,
243 Opts.EnableSnippets);
244 I.filterText = getFilterText(*SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +0000245 I.documentation = formatDocumentation(*SemaCCS, SemaDocComment);
Sam McCall545a20d2018-01-19 14:34:02 +0000246 I.detail = getDetail(*SemaCCS);
Eric Liu9b3cba72018-05-30 09:03:39 +0000247 // Avoid inserting new #include if the declaration is found in the current
248 // file e.g. the symbol is forward declared.
249 if (SemaResult->Kind == CodeCompletionResult::RK_Declaration) {
250 if (const auto *D = SemaResult->getDeclaration()) {
251 const auto &SM = D->getASTContext().getSourceManager();
252 ShouldInsertInclude =
253 ShouldInsertInclude &&
254 std::none_of(D->redecls_begin(), D->redecls_end(),
255 [&SM](const Decl *RD) {
256 return SM.isInMainFile(
257 SM.getExpansionLoc(RD->getLocStart()));
258 });
259 }
260 }
Sam McCall545a20d2018-01-19 14:34:02 +0000261 }
262 if (IndexResult) {
263 if (I.kind == CompletionItemKind::Missing)
264 I.kind = toCompletionItemKind(IndexResult->SymInfo.Kind);
265 // FIXME: reintroduce a way to show the index source for debugging.
266 if (I.label.empty())
267 I.label = IndexResult->CompletionLabel;
268 if (I.filterText.empty())
269 I.filterText = IndexResult->Name;
Sam McCall98775c52017-12-04 13:49:59 +0000270
Sam McCall545a20d2018-01-19 14:34:02 +0000271 // FIXME(ioeric): support inserting/replacing scope qualifiers.
272 if (I.insertText.empty())
273 I.insertText = Opts.EnableSnippets
274 ? IndexResult->CompletionSnippetInsertText
275 : IndexResult->CompletionPlainInsertText;
276
277 if (auto *D = IndexResult->Detail) {
278 if (I.documentation.empty())
279 I.documentation = D->Documentation;
280 if (I.detail.empty())
281 I.detail = D->CompletionDetail;
Eric Liu9b3cba72018-05-30 09:03:39 +0000282 if (ShouldInsertInclude && Includes && !D->IncludeHeader.empty()) {
Eric Liu63f419a2018-05-15 15:29:32 +0000283 auto Edit = [&]() -> Expected<Optional<TextEdit>> {
284 auto ResolvedDeclaring = toHeaderFile(
285 IndexResult->CanonicalDeclaration.FileURI, FileName);
286 if (!ResolvedDeclaring)
287 return ResolvedDeclaring.takeError();
288 auto ResolvedInserted = toHeaderFile(D->IncludeHeader, FileName);
289 if (!ResolvedInserted)
290 return ResolvedInserted.takeError();
291 return Includes->insert(*ResolvedDeclaring, *ResolvedInserted);
292 }();
293 if (!Edit) {
294 std::string ErrMsg =
295 ("Failed to generate include insertion edits for adding header "
296 "(FileURI=\"" +
297 IndexResult->CanonicalDeclaration.FileURI +
298 "\", IncludeHeader=\"" + D->IncludeHeader + "\") into " +
299 FileName)
300 .str();
301 log(ErrMsg + ":" + llvm::toString(Edit.takeError()));
302 } else if (*Edit) {
303 I.additionalTextEdits = {std::move(**Edit)};
304 }
305 }
Sam McCall545a20d2018-01-19 14:34:02 +0000306 }
307 }
308 I.scoreInfo = Scores;
309 I.sortText = sortText(Scores.finalScore, Name);
310 I.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
311 : InsertTextFormat::PlainText;
312 return I;
Sam McCall98775c52017-12-04 13:49:59 +0000313 }
314};
Sam McCallc5707b62018-05-15 17:43:27 +0000315using ScoredCandidate = std::pair<CompletionCandidate, CompletionItemScores>;
Sam McCall98775c52017-12-04 13:49:59 +0000316
Sam McCall545a20d2018-01-19 14:34:02 +0000317// Determine the symbol ID for a Sema code completion result, if possible.
318llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
319 switch (R.Kind) {
320 case CodeCompletionResult::RK_Declaration:
321 case CodeCompletionResult::RK_Pattern: {
322 llvm::SmallString<128> USR;
323 if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
324 return None;
325 return SymbolID(USR);
326 }
327 case CodeCompletionResult::RK_Macro:
328 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
329 case CodeCompletionResult::RK_Keyword:
330 return None;
331 }
332 llvm_unreachable("unknown CodeCompletionResult kind");
333}
334
Haojian Wu061c73e2018-01-23 11:37:26 +0000335// Scopes of the paritial identifier we're trying to complete.
336// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000337struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000338 // The scopes we should look in, determined by Sema.
339 //
340 // If the qualifier was fully resolved, we look for completions in these
341 // scopes; if there is an unresolved part of the qualifier, it should be
342 // resolved within these scopes.
343 //
344 // Examples of qualified completion:
345 //
346 // "::vec" => {""}
347 // "using namespace std; ::vec^" => {"", "std::"}
348 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
349 // "std::vec^" => {""} // "std" unresolved
350 //
351 // Examples of unqualified completion:
352 //
353 // "vec^" => {""}
354 // "using namespace std; vec^" => {"", "std::"}
355 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
356 //
357 // "" for global namespace, "ns::" for normal namespace.
358 std::vector<std::string> AccessibleScopes;
359 // The full scope qualifier as typed by the user (without the leading "::").
360 // Set if the qualifier is not fully resolved by Sema.
361 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000362
Haojian Wu061c73e2018-01-23 11:37:26 +0000363 // Construct scopes being queried in indexes.
364 // This method format the scopes to match the index request representation.
365 std::vector<std::string> scopesForIndexQuery() {
366 std::vector<std::string> Results;
367 for (llvm::StringRef AS : AccessibleScopes) {
368 Results.push_back(AS);
369 if (UnresolvedQualifier)
370 Results.back() += *UnresolvedQualifier;
371 }
372 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000373 }
Eric Liu6f648df2017-12-19 16:50:37 +0000374};
375
Haojian Wu061c73e2018-01-23 11:37:26 +0000376// Get all scopes that will be queried in indexes.
377std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000378 const SourceManager &SM) {
379 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000380 SpecifiedScope Info;
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000381 for (auto *Context : CCContext.getVisitedContexts()) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000382 if (isa<TranslationUnitDecl>(Context))
383 Info.AccessibleScopes.push_back(""); // global namespace
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000384 else if (const auto *NS = dyn_cast<NamespaceDecl>(Context))
Haojian Wu061c73e2018-01-23 11:37:26 +0000385 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
386 }
387 return Info;
388 };
389
390 auto SS = CCContext.getCXXScopeSpecifier();
391
392 // Unqualified completion (e.g. "vec^").
393 if (!SS) {
394 // FIXME: Once we can insert namespace qualifiers and use the in-scope
395 // namespaces for scoring, search in all namespaces.
396 // FIXME: Capture scopes and use for scoring, for example,
397 // "using namespace std; namespace foo {v^}" =>
398 // foo::value > std::vector > boost::variant
399 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
400 }
401
402 // Qualified completion ("std::vec^"), we have two cases depending on whether
403 // the qualifier can be resolved by Sema.
404 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000405 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
406 }
407
408 // Unresolved qualifier.
409 // FIXME: When Sema can resolve part of a scope chain (e.g.
410 // "known::unknown::id"), we should expand the known part ("known::") rather
411 // than treating the whole thing as unknown.
412 SpecifiedScope Info;
413 Info.AccessibleScopes.push_back(""); // global namespace
414
415 Info.UnresolvedQualifier =
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000416 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM,
417 clang::LangOptions())
418 .ltrim("::");
Haojian Wu061c73e2018-01-23 11:37:26 +0000419 // Sema excludes the trailing "::".
420 if (!Info.UnresolvedQualifier->empty())
421 *Info.UnresolvedQualifier += "::";
422
423 return Info.scopesForIndexQuery();
424}
425
Eric Liu42abe412018-05-24 11:20:19 +0000426// Should we perform index-based completion in a context of the specified kind?
427// FIXME: consider allowing completion, but restricting the result types.
428bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
429 switch (K) {
430 case CodeCompletionContext::CCC_TopLevel:
431 case CodeCompletionContext::CCC_ObjCInterface:
432 case CodeCompletionContext::CCC_ObjCImplementation:
433 case CodeCompletionContext::CCC_ObjCIvarList:
434 case CodeCompletionContext::CCC_ClassStructUnion:
435 case CodeCompletionContext::CCC_Statement:
436 case CodeCompletionContext::CCC_Expression:
437 case CodeCompletionContext::CCC_ObjCMessageReceiver:
438 case CodeCompletionContext::CCC_EnumTag:
439 case CodeCompletionContext::CCC_UnionTag:
440 case CodeCompletionContext::CCC_ClassOrStructTag:
441 case CodeCompletionContext::CCC_ObjCProtocolName:
442 case CodeCompletionContext::CCC_Namespace:
443 case CodeCompletionContext::CCC_Type:
444 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
445 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
446 case CodeCompletionContext::CCC_ParenthesizedExpression:
447 case CodeCompletionContext::CCC_ObjCInterfaceName:
448 case CodeCompletionContext::CCC_ObjCCategoryName:
449 return true;
450 case CodeCompletionContext::CCC_Other: // Be conservative.
451 case CodeCompletionContext::CCC_OtherWithMacros:
452 case CodeCompletionContext::CCC_DotMemberAccess:
453 case CodeCompletionContext::CCC_ArrowMemberAccess:
454 case CodeCompletionContext::CCC_ObjCPropertyAccess:
455 case CodeCompletionContext::CCC_MacroName:
456 case CodeCompletionContext::CCC_MacroNameUse:
457 case CodeCompletionContext::CCC_PreprocessorExpression:
458 case CodeCompletionContext::CCC_PreprocessorDirective:
459 case CodeCompletionContext::CCC_NaturalLanguage:
460 case CodeCompletionContext::CCC_SelectorName:
461 case CodeCompletionContext::CCC_TypeQualifiers:
462 case CodeCompletionContext::CCC_ObjCInstanceMessage:
463 case CodeCompletionContext::CCC_ObjCClassMessage:
464 case CodeCompletionContext::CCC_Recovery:
465 return false;
466 }
467 llvm_unreachable("unknown code completion context");
468}
469
Sam McCall545a20d2018-01-19 14:34:02 +0000470// The CompletionRecorder captures Sema code-complete output, including context.
471// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
472// It doesn't do scoring or conversion to CompletionItem yet, as we want to
473// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000474// Generally the fields and methods of this object should only be used from
475// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000476struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000477 CompletionRecorder(const CodeCompleteOptions &Opts,
478 UniqueFunction<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000479 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000480 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000481 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
482 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000483 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
484 assert(this->ResultsCallback);
485 }
486
Sam McCall545a20d2018-01-19 14:34:02 +0000487 std::vector<CodeCompletionResult> Results;
488 CodeCompletionContext CCContext;
489 Sema *CCSema = nullptr; // Sema that created the results.
490 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000491
Sam McCall545a20d2018-01-19 14:34:02 +0000492 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
493 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000494 unsigned NumResults) override final {
Eric Liu42abe412018-05-24 11:20:19 +0000495 // If a callback is called without any sema result and the context does not
496 // support index-based completion, we simply skip it to give way to
497 // potential future callbacks with results.
498 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
499 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000500 if (CCSema) {
501 log(llvm::formatv(
502 "Multiple code complete callbacks (parser backtracked?). "
503 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000504 getCompletionKindString(Context.getKind()),
505 getCompletionKindString(this->CCContext.getKind())));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000506 return;
507 }
Sam McCall545a20d2018-01-19 14:34:02 +0000508 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000509 CCSema = &S;
510 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000511
Sam McCall545a20d2018-01-19 14:34:02 +0000512 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000513 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000514 auto &Result = InResults[I];
515 // Drop hidden items which cannot be found by lookup after completion.
516 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000517 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
518 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000519 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000520 (Result.Availability == CXAvailability_NotAvailable ||
521 Result.Availability == CXAvailability_NotAccessible))
522 continue;
Sam McCalld2a95922018-01-22 21:05:00 +0000523 // Destructor completion is rarely useful, and works inconsistently.
524 // (s.^ completes ~string, but s.~st^ is an error).
525 if (dyn_cast_or_null<CXXDestructorDecl>(Result.Declaration))
526 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000527 // We choose to never append '::' to completion results in clangd.
528 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000529 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000530 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000531 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000532 }
533
Sam McCall545a20d2018-01-19 14:34:02 +0000534 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000535 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
536
Sam McCall545a20d2018-01-19 14:34:02 +0000537 // Returns the filtering/sorting name for Result, which must be from Results.
538 // Returned string is owned by this recorder (or the AST).
539 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000540 switch (Result.Kind) {
541 case CodeCompletionResult::RK_Declaration:
542 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000543 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000544 break;
545 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000546 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000547 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000548 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000549 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000550 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000551 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000552 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000553 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000554 }
555
Sam McCall545a20d2018-01-19 14:34:02 +0000556 // Build a CodeCompletion string for R, which must be from Results.
557 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000558 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000559 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
560 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000561 *CCSema, CCContext, *CCAllocator, CCTUInfo,
562 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000563 }
564
Sam McCall545a20d2018-01-19 14:34:02 +0000565private:
566 CodeCompleteOptions Opts;
567 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000568 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000569 UniqueFunction<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000570};
571
Sam McCallc5707b62018-05-15 17:43:27 +0000572struct ScoredCandidateGreater {
573 bool operator()(const ScoredCandidate &L, const ScoredCandidate &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000574 if (L.second.finalScore != R.second.finalScore)
575 return L.second.finalScore > R.second.finalScore;
576 return L.first.Name < R.first.Name; // Earlier name is better.
577 }
Sam McCall545a20d2018-01-19 14:34:02 +0000578};
Sam McCall98775c52017-12-04 13:49:59 +0000579
Sam McCall98775c52017-12-04 13:49:59 +0000580class SignatureHelpCollector final : public CodeCompleteConsumer {
581
582public:
583 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
584 SignatureHelp &SigHelp)
585 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
586 SigHelp(SigHelp),
587 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
588 CCTUInfo(Allocator) {}
589
590 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
591 OverloadCandidate *Candidates,
592 unsigned NumCandidates) override {
593 SigHelp.signatures.reserve(NumCandidates);
594 // FIXME(rwols): How can we determine the "active overload candidate"?
595 // Right now the overloaded candidates seem to be provided in a "best fit"
596 // order, so I'm not too worried about this.
597 SigHelp.activeSignature = 0;
598 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
599 "too many arguments");
600 SigHelp.activeParameter = static_cast<int>(CurrentArg);
601 for (unsigned I = 0; I < NumCandidates; ++I) {
602 const auto &Candidate = Candidates[I];
603 const auto *CCS = Candidate.CreateSignatureString(
604 CurrentArg, S, *Allocator, CCTUInfo, true);
605 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000606 // FIXME: for headers, we need to get a comment from the index.
Ilya Biryukov43714502018-05-16 12:32:44 +0000607 SigHelp.signatures.push_back(ProcessOverloadCandidate(
608 Candidate, *CCS,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000609 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000610 /*CommentsFromHeaders=*/false)));
Sam McCall98775c52017-12-04 13:49:59 +0000611 }
612 }
613
614 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
615
616 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
617
618private:
Eric Liu63696e12017-12-20 17:24:31 +0000619 // FIXME(ioeric): consider moving CodeCompletionString logic here to
620 // CompletionString.h.
Sam McCall98775c52017-12-04 13:49:59 +0000621 SignatureInformation
622 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
Ilya Biryukov43714502018-05-16 12:32:44 +0000623 const CodeCompletionString &CCS,
624 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000625 SignatureInformation Result;
626 const char *ReturnType = nullptr;
627
Ilya Biryukov43714502018-05-16 12:32:44 +0000628 Result.documentation = formatDocumentation(CCS, DocComment);
Sam McCall98775c52017-12-04 13:49:59 +0000629
630 for (const auto &Chunk : CCS) {
631 switch (Chunk.Kind) {
632 case CodeCompletionString::CK_ResultType:
633 // A piece of text that describes the type of an entity or,
634 // for functions and methods, the return type.
635 assert(!ReturnType && "Unexpected CK_ResultType");
636 ReturnType = Chunk.Text;
637 break;
638 case CodeCompletionString::CK_Placeholder:
639 // A string that acts as a placeholder for, e.g., a function call
640 // argument.
641 // Intentional fallthrough here.
642 case CodeCompletionString::CK_CurrentParameter: {
643 // A piece of text that describes the parameter that corresponds to
644 // the code-completion location within a function call, message send,
645 // macro invocation, etc.
646 Result.label += Chunk.Text;
647 ParameterInformation Info;
648 Info.label = Chunk.Text;
649 Result.parameters.push_back(std::move(Info));
650 break;
651 }
652 case CodeCompletionString::CK_Optional: {
653 // The rest of the parameters are defaulted/optional.
654 assert(Chunk.Optional &&
655 "Expected the optional code completion string to be non-null.");
656 Result.label +=
657 getOptionalParameters(*Chunk.Optional, Result.parameters);
658 break;
659 }
660 case CodeCompletionString::CK_VerticalSpace:
661 break;
662 default:
663 Result.label += Chunk.Text;
664 break;
665 }
666 }
667 if (ReturnType) {
668 Result.label += " -> ";
669 Result.label += ReturnType;
670 }
671 return Result;
672 }
673
674 SignatureHelp &SigHelp;
675 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
676 CodeCompletionTUInfo CCTUInfo;
677
678}; // SignatureHelpCollector
679
Sam McCall545a20d2018-01-19 14:34:02 +0000680struct SemaCompleteInput {
681 PathRef FileName;
682 const tooling::CompileCommand &Command;
683 PrecompiledPreamble const *Preamble;
Eric Liu63f419a2018-05-15 15:29:32 +0000684 const std::vector<Inclusion> &PreambleInclusions;
Sam McCall545a20d2018-01-19 14:34:02 +0000685 StringRef Contents;
686 Position Pos;
687 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
688 std::shared_ptr<PCHContainerOperations> PCHs;
689};
690
691// Invokes Sema code completion on a file.
Eric Liu63f419a2018-05-15 15:29:32 +0000692// If \p Includes is set, it will be initialized after a compiler instance has
693// been set up.
Sam McCalld1a7a372018-01-31 13:40:48 +0000694bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000695 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000696 const SemaCompleteInput &Input,
697 std::unique_ptr<IncludeInserter> *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000698 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000699 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000700 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000701 ArgStrs.push_back(S.c_str());
702
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000703 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
704 log("Couldn't set working directory");
705 // We run parsing anyway, our lit-tests rely on results for non-existing
706 // working dirs.
707 }
Sam McCall98775c52017-12-04 13:49:59 +0000708
709 IgnoreDiagnostics DummyDiagsConsumer;
710 auto CI = createInvocationFromCommandLine(
711 ArgStrs,
712 CompilerInstance::createDiagnostics(new DiagnosticOptions,
713 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000714 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000715 if (!CI) {
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000716 log("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000717 return false;
718 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000719 auto &FrontendOpts = CI->getFrontendOpts();
720 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000721 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000722 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
723 // Disable typo correction in Sema.
724 CI->getLangOpts()->SpellChecking = false;
725 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +0000726 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000727 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000728 auto Offset = positionToOffset(Input.Contents, Input.Pos);
729 if (!Offset) {
730 log("Code completion position was invalid " +
731 llvm::toString(Offset.takeError()));
732 return false;
733 }
734 std::tie(FrontendOpts.CodeCompletionAt.Line,
735 FrontendOpts.CodeCompletionAt.Column) =
736 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000737
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000738 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
739 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
740 // The diagnostic options must be set before creating a CompilerInstance.
741 CI->getDiagnosticOpts().IgnoreWarnings = true;
742 // We reuse the preamble whether it's valid or not. This is a
743 // correctness/performance tradeoff: building without a preamble is slow, and
744 // completion is latency-sensitive.
745 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
746 // the remapped buffers do not get freed.
747 auto Clang = prepareCompilerInstance(
748 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
749 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000750 Clang->setCodeCompletionConsumer(Consumer.release());
751
752 SyntaxOnlyAction Action;
753 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000754 log("BeginSourceFile() failed when running codeComplete for " +
755 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000756 return false;
757 }
Eric Liu63f419a2018-05-15 15:29:32 +0000758 if (Includes) {
759 // Initialize Includes if provided.
760
761 // FIXME(ioeric): needs more consistent style support in clangd server.
762 auto Style = format::getStyle("file", Input.FileName, "LLVM",
763 Input.Contents, Input.VFS.get());
764 if (!Style) {
765 log("Failed to get FormatStyle for file" + Input.FileName +
766 ". Fall back to use LLVM style. Error: " +
767 llvm::toString(Style.takeError()));
768 Style = format::getLLVMStyle();
769 }
770 *Includes = llvm::make_unique<IncludeInserter>(
771 Input.FileName, Input.Contents, *Style, Input.Command.Directory,
772 Clang->getPreprocessor().getHeaderSearchInfo());
773 for (const auto &Inc : Input.PreambleInclusions)
774 Includes->get()->addExisting(Inc);
775 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
776 Clang->getSourceManager(), [Includes](Inclusion Inc) {
777 Includes->get()->addExisting(std::move(Inc));
778 }));
779 }
Sam McCall98775c52017-12-04 13:49:59 +0000780 if (!Action.Execute()) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000781 log("Execute() failed when running codeComplete for " + Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000782 return false;
783 }
Sam McCall98775c52017-12-04 13:49:59 +0000784 Action.EndSourceFile();
785
786 return true;
787}
788
Ilya Biryukova907ba42018-05-14 10:50:04 +0000789// Should we allow index completions in the specified context?
790bool allowIndex(CodeCompletionContext &CC) {
791 if (!contextAllowsIndex(CC.getKind()))
792 return false;
793 // We also avoid ClassName::bar (but allow namespace::bar).
794 auto Scope = CC.getCXXScopeSpecifier();
795 if (!Scope)
796 return true;
797 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
798 if (!NameSpec)
799 return true;
800 // We only query the index when qualifier is a namespace.
801 // If it's a class, we rely solely on sema completions.
802 switch (NameSpec->getKind()) {
803 case NestedNameSpecifier::Global:
804 case NestedNameSpecifier::Namespace:
805 case NestedNameSpecifier::NamespaceAlias:
806 return true;
807 case NestedNameSpecifier::Super:
808 case NestedNameSpecifier::TypeSpec:
809 case NestedNameSpecifier::TypeSpecWithTemplate:
810 // Unresolved inside a template.
811 case NestedNameSpecifier::Identifier:
812 return false;
813 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000814 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000815}
816
Sam McCall98775c52017-12-04 13:49:59 +0000817} // namespace
818
819clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
820 clang::CodeCompleteOptions Result;
821 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
822 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000823 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000824 // We choose to include full comments and not do doxygen parsing in
825 // completion.
826 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
827 // formatting of the comments.
828 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000829
Sam McCall3d139c52018-01-12 18:30:08 +0000830 // When an is used, Sema is responsible for completing the main file,
831 // the index can provide results from the preamble.
832 // Tell Sema not to deserialize the preamble to look for results.
833 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000834
Sam McCall98775c52017-12-04 13:49:59 +0000835 return Result;
836}
837
Sam McCall545a20d2018-01-19 14:34:02 +0000838// Runs Sema-based (AST) and Index-based completion, returns merged results.
839//
840// There are a few tricky considerations:
841// - the AST provides information needed for the index query (e.g. which
842// namespaces to search in). So Sema must start first.
843// - we only want to return the top results (Opts.Limit).
844// Building CompletionItems for everything else is wasteful, so we want to
845// preserve the "native" format until we're done with scoring.
846// - the data underlying Sema completion items is owned by the AST and various
847// other arenas, which must stay alive for us to build CompletionItems.
848// - we may get duplicate results from Sema and the Index, we need to merge.
849//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000850// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000851// We use the Sema context information to query the index.
852// Then we merge the two result sets, producing items that are Sema/Index/Both.
853// These items are scored, and the top N are synthesized into the LSP response.
854// Finally, we can clean up the data structures created by Sema completion.
855//
856// Main collaborators are:
857// - semaCodeComplete sets up the compiler machinery to run code completion.
858// - CompletionRecorder captures Sema completion results, including context.
859// - SymbolIndex (Opts.Index) provides index completion results as Symbols
860// - CompletionCandidates are the result of merging Sema and Index results.
861// Each candidate points to an underlying CodeCompletionResult (Sema), a
862// Symbol (Index), or both. It computes the result quality score.
863// CompletionCandidate also does conversion to CompletionItem (at the end).
864// - FuzzyMatcher scores how the candidate matches the partial identifier.
865// This score is combined with the result quality score for the final score.
866// - TopN determines the results with the best score.
867class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000868 PathRef FileName;
Sam McCall545a20d2018-01-19 14:34:02 +0000869 const CodeCompleteOptions &Opts;
870 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000871 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000872 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
873 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000874 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
875 std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000876
877public:
878 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Eric Liuc5105f92018-02-16 14:15:55 +0000879 CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000880 : FileName(FileName), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000881
882 CompletionList run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000883 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000884
Sam McCall545a20d2018-01-19 14:34:02 +0000885 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000886 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000887 // - partial identifier and context. We need these for the index query.
888 CompletionList Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000889 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
890 assert(Recorder && "Recorder is not set");
Eric Liu63f419a2018-05-15 15:29:32 +0000891 assert(Includes && "Includes is not set");
892 // If preprocessor was run, inclusions from preprocessor callback should
893 // already be added to Inclusions.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000894 Output = runWithSema();
Eric Liu63f419a2018-05-15 15:29:32 +0000895 Includes.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000896 SPAN_ATTACH(Tracer, "sema_completion_kind",
897 getCompletionKindString(Recorder->CCContext.getKind()));
898 });
899
900 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +0000901 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +0000902 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +0000903
Sam McCall2b780162018-01-30 17:20:54 +0000904 SPAN_ATTACH(Tracer, "sema_results", NSema);
905 SPAN_ATTACH(Tracer, "index_results", NIndex);
906 SPAN_ATTACH(Tracer, "merged_results", NBoth);
907 SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
908 SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
Sam McCalld1a7a372018-01-31 13:40:48 +0000909 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
Sam McCall545a20d2018-01-19 14:34:02 +0000910 "{2} matched, {3} returned{4}.",
911 NSema, NIndex, NBoth, Output.items.size(),
912 Output.isIncomplete ? " (incomplete)" : ""));
913 assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
914 // We don't assert that isIncomplete means we hit a limit.
915 // Indexes may choose to impose their own limits even if we don't have one.
916 return Output;
917 }
918
919private:
920 // This is called by run() once Sema code completion is done, but before the
921 // Sema data structures are torn down. It does all the real work.
922 CompletionList runWithSema() {
923 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000924 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Sam McCall545a20d2018-01-19 14:34:02 +0000925 // Sema provides the needed context to query the index.
926 // FIXME: in addition to querying for extra/overlapping symbols, we should
927 // explicitly request symbols corresponding to Sema results.
928 // We can use their signals even if the index can't suggest them.
929 // We must copy index results to preserve them, but there are at most Limit.
930 auto IndexResults = queryIndex();
931 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000932 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall545a20d2018-01-19 14:34:02 +0000933 // Convert the results to the desired LSP structs.
934 CompletionList Output;
935 for (auto &C : Top)
936 Output.items.push_back(toCompletionItem(C.first, C.second));
937 Output.isIncomplete = Incomplete;
938 return Output;
939 }
940
941 SymbolSlab queryIndex() {
Ilya Biryukova907ba42018-05-14 10:50:04 +0000942 if (!Opts.Index || !allowIndex(Recorder->CCContext))
Sam McCall545a20d2018-01-19 14:34:02 +0000943 return SymbolSlab();
Sam McCalld1a7a372018-01-31 13:40:48 +0000944 trace::Span Tracer("Query index");
Sam McCall2b780162018-01-30 17:20:54 +0000945 SPAN_ATTACH(Tracer, "limit", Opts.Limit);
946
Sam McCall545a20d2018-01-19 14:34:02 +0000947 SymbolSlab::Builder ResultsBuilder;
948 // Build the query.
949 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +0000950 if (Opts.Limit)
951 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +0000952 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000953 Req.RestrictForCodeCompletion = true;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000954 Req.Scopes = getQueryScopes(Recorder->CCContext,
955 Recorder->CCSema->getSourceManager());
Sam McCalld1a7a372018-01-31 13:40:48 +0000956 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
Sam McCall2b780162018-01-30 17:20:54 +0000957 Req.Query,
958 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Sam McCall545a20d2018-01-19 14:34:02 +0000959 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +0000960 if (Opts.Index->fuzzyFind(
961 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
962 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000963 return std::move(ResultsBuilder).build();
964 }
965
966 // Merges the Sema and Index results where possible, scores them, and
967 // returns the top results from best to worst.
968 std::vector<std::pair<CompletionCandidate, CompletionItemScores>>
969 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
970 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000971 trace::Span Tracer("Merge and score results");
Sam McCall545a20d2018-01-19 14:34:02 +0000972 // We only keep the best N results at any time, in "native" format.
Sam McCallc5707b62018-05-15 17:43:27 +0000973 TopN<ScoredCandidate, ScoredCandidateGreater> Top(
974 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +0000975 llvm::DenseSet<const Symbol *> UsedIndexResults;
976 auto CorrespondingIndexResult =
977 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
978 if (auto SymID = getSymbolID(SemaResult)) {
979 auto I = IndexResults.find(*SymID);
980 if (I != IndexResults.end()) {
981 UsedIndexResults.insert(&*I);
982 return &*I;
983 }
984 }
985 return nullptr;
986 };
987 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000988 for (auto &SemaResult : Recorder->Results)
Sam McCall545a20d2018-01-19 14:34:02 +0000989 addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult));
990 // Now emit any Index-only results.
991 for (const auto &IndexResult : IndexResults) {
992 if (UsedIndexResults.count(&IndexResult))
993 continue;
994 addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult);
995 }
996 return std::move(Top).items();
997 }
998
999 // Scores a candidate and adds it to the TopN structure.
Sam McCallc5707b62018-05-15 17:43:27 +00001000 void addCandidate(TopN<ScoredCandidate, ScoredCandidateGreater> &Candidates,
1001 const CodeCompletionResult *SemaResult,
Sam McCall545a20d2018-01-19 14:34:02 +00001002 const Symbol *IndexResult) {
1003 CompletionCandidate C;
1004 C.SemaResult = SemaResult;
1005 C.IndexResult = IndexResult;
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001006 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001007
Sam McCallc5707b62018-05-15 17:43:27 +00001008 SymbolQualitySignals Quality;
1009 SymbolRelevanceSignals Relevance;
Sam McCalld9b54f02018-06-05 16:30:25 +00001010 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Sam McCall545a20d2018-01-19 14:34:02 +00001011 if (auto FuzzyScore = Filter->match(C.Name))
Sam McCallc5707b62018-05-15 17:43:27 +00001012 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001013 else
1014 return;
Sam McCalld9b54f02018-06-05 16:30:25 +00001015 if (IndexResult) {
Sam McCallc5707b62018-05-15 17:43:27 +00001016 Quality.merge(*IndexResult);
Sam McCalld9b54f02018-06-05 16:30:25 +00001017 Relevance.merge(*IndexResult);
1018 }
Sam McCallc5707b62018-05-15 17:43:27 +00001019 if (SemaResult) {
1020 Quality.merge(*SemaResult);
1021 Relevance.merge(*SemaResult);
1022 }
1023
1024 float QualScore = Quality.evaluate(), RelScore = Relevance.evaluate();
1025 CompletionItemScores Scores;
1026 Scores.finalScore = evaluateSymbolAndRelevance(QualScore, RelScore);
1027 // The purpose of exporting component scores is to allow NameMatch to be
1028 // replaced on the client-side. So we export (NameMatch, final/NameMatch)
1029 // rather than (RelScore, QualScore).
1030 Scores.filterScore = Relevance.NameMatch;
1031 Scores.symbolScore =
1032 Scores.filterScore ? Scores.finalScore / Scores.filterScore : QualScore;
1033
Nicola Zaghenc9fed132018-05-23 13:57:48 +00001034 LLVM_DEBUG(llvm::dbgs()
1035 << "CodeComplete: " << C.Name << (IndexResult ? " (index)" : "")
1036 << (SemaResult ? " (sema)" : "") << " = " << Scores.finalScore
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +00001037 << "\n"
Nicola Zaghenc9fed132018-05-23 13:57:48 +00001038 << Quality << Relevance << "\n");
Sam McCall545a20d2018-01-19 14:34:02 +00001039
1040 NSema += bool(SemaResult);
1041 NIndex += bool(IndexResult);
1042 NBoth += SemaResult && IndexResult;
Sam McCallab8e3932018-02-19 13:04:41 +00001043 if (Candidates.push({C, Scores}))
1044 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001045 }
1046
1047 CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
1048 const CompletionItemScores &Scores) {
1049 CodeCompletionString *SemaCCS = nullptr;
Ilya Biryukov43714502018-05-16 12:32:44 +00001050 std::string DocComment;
1051 if (auto *SR = Candidate.SemaResult) {
1052 SemaCCS = Recorder->codeCompletionString(*SR);
1053 if (Opts.IncludeComments) {
1054 assert(Recorder->CCSema);
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001055 DocComment = getDocComment(Recorder->CCSema->getASTContext(), *SR,
1056 /*CommentsFromHeader=*/false);
Ilya Biryukov43714502018-05-16 12:32:44 +00001057 }
1058 }
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +00001059 return Candidate.build(FileName, Scores, Opts, SemaCCS, Includes.get(),
1060 DocComment);
Sam McCall545a20d2018-01-19 14:34:02 +00001061 }
1062};
1063
Sam McCalld1a7a372018-01-31 13:40:48 +00001064CompletionList codeComplete(PathRef FileName,
Sam McCall98775c52017-12-04 13:49:59 +00001065 const tooling::CompileCommand &Command,
1066 PrecompiledPreamble const *Preamble,
Eric Liu63f419a2018-05-15 15:29:32 +00001067 const std::vector<Inclusion> &PreambleInclusions,
Sam McCall98775c52017-12-04 13:49:59 +00001068 StringRef Contents, Position Pos,
1069 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1070 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001071 CodeCompleteOptions Opts) {
Eric Liuc5105f92018-02-16 14:15:55 +00001072 return CodeCompleteFlow(FileName, Opts)
Eric Liu63f419a2018-05-15 15:29:32 +00001073 .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS,
1074 PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001075}
1076
Sam McCalld1a7a372018-01-31 13:40:48 +00001077SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001078 const tooling::CompileCommand &Command,
1079 PrecompiledPreamble const *Preamble,
1080 StringRef Contents, Position Pos,
1081 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1082 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001083 SignatureHelp Result;
1084 clang::CodeCompleteOptions Options;
1085 Options.IncludeGlobals = false;
1086 Options.IncludeMacros = false;
1087 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001088 Options.IncludeBriefComments = false;
Eric Liu4c0a27b2018-05-16 20:31:38 +00001089 std::vector<Inclusion> PreambleInclusions = {}; // Unused for signatureHelp
Sam McCalld1a7a372018-01-31 13:40:48 +00001090 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1091 Options,
Eric Liu4c0a27b2018-05-16 20:31:38 +00001092 {FileName, Command, Preamble, PreambleInclusions, Contents,
1093 Pos, std::move(VFS), std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001094 return Result;
1095}
1096
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001097bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1098 using namespace clang::ast_matchers;
1099 auto InTopLevelScope = hasDeclContext(
1100 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1101 return !match(decl(anyOf(InTopLevelScope,
1102 hasDeclContext(
1103 enumDecl(InTopLevelScope, unless(isScoped()))))),
1104 ND, ASTCtx)
1105 .empty();
1106}
1107
Sam McCall98775c52017-12-04 13:49:59 +00001108} // namespace clangd
1109} // namespace clang