blob: 40d9058040fba72712ddb6a366fa41af35c5975c [file] [log] [blame]
Sam McCall98775c52017-12-04 13:49:59 +00001//===--- CodeComplete.cpp ---------------------------------------*- C++-*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===---------------------------------------------------------------------===//
9//
10// AST-based completions are provided using the completion hooks in Sema.
11//
12// Signature help works in a similar way as code completion, but it is simpler
13// as there are typically fewer candidates.
14//
15//===---------------------------------------------------------------------===//
16
17#include "CodeComplete.h"
Eric Liu63696e12017-12-20 17:24:31 +000018#include "CodeCompletionStrings.h"
Sam McCall98775c52017-12-04 13:49:59 +000019#include "Compiler.h"
Sam McCall84652cc2018-01-12 16:16:09 +000020#include "FuzzyMatch.h"
Eric Liu63f419a2018-05-15 15:29:32 +000021#include "Headers.h"
Eric Liu6f648df2017-12-19 16:50:37 +000022#include "Logger.h"
Sam McCallc5707b62018-05-15 17:43:27 +000023#include "Quality.h"
Eric Liuc5105f92018-02-16 14:15:55 +000024#include "SourceCode.h"
Sam McCall2b780162018-01-30 17:20:54 +000025#include "Trace.h"
Eric Liu63f419a2018-05-15 15:29:32 +000026#include "URI.h"
Eric Liu6f648df2017-12-19 16:50:37 +000027#include "index/Index.h"
Ilya Biryukovc22d3442018-05-16 12:32:49 +000028#include "clang/Basic/LangOptions.h"
Eric Liuc5105f92018-02-16 14:15:55 +000029#include "clang/Format/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000030#include "clang/Frontend/CompilerInstance.h"
31#include "clang/Frontend/FrontendActions.h"
Sam McCall545a20d2018-01-19 14:34:02 +000032#include "clang/Index/USRGeneration.h"
Sam McCall98775c52017-12-04 13:49:59 +000033#include "clang/Sema/CodeCompleteConsumer.h"
34#include "clang/Sema/Sema.h"
Eric Liuc5105f92018-02-16 14:15:55 +000035#include "clang/Tooling/Core/Replacement.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000036#include "llvm/Support/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000037#include <queue>
38
Sam McCallc5707b62018-05-15 17:43:27 +000039// We log detailed candidate here if you run with -debug-only=codecomplete.
40#define DEBUG_TYPE "codecomplete"
41
Sam McCall98775c52017-12-04 13:49:59 +000042namespace clang {
43namespace clangd {
44namespace {
45
Eric Liu6f648df2017-12-19 16:50:37 +000046CompletionItemKind toCompletionItemKind(CXCursorKind CursorKind) {
Sam McCall98775c52017-12-04 13:49:59 +000047 switch (CursorKind) {
48 case CXCursor_MacroInstantiation:
49 case CXCursor_MacroDefinition:
50 return CompletionItemKind::Text;
51 case CXCursor_CXXMethod:
Eric Liu6f648df2017-12-19 16:50:37 +000052 case CXCursor_Destructor:
Sam McCall98775c52017-12-04 13:49:59 +000053 return CompletionItemKind::Method;
54 case CXCursor_FunctionDecl:
55 case CXCursor_FunctionTemplate:
56 return CompletionItemKind::Function;
57 case CXCursor_Constructor:
Sam McCall98775c52017-12-04 13:49:59 +000058 return CompletionItemKind::Constructor;
59 case CXCursor_FieldDecl:
60 return CompletionItemKind::Field;
61 case CXCursor_VarDecl:
62 case CXCursor_ParmDecl:
63 return CompletionItemKind::Variable;
Eric Liu6f648df2017-12-19 16:50:37 +000064 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
65 // protocol.
Sam McCall98775c52017-12-04 13:49:59 +000066 case CXCursor_StructDecl:
Eric Liu6f648df2017-12-19 16:50:37 +000067 case CXCursor_ClassDecl:
Sam McCall98775c52017-12-04 13:49:59 +000068 case CXCursor_UnionDecl:
69 case CXCursor_ClassTemplate:
70 case CXCursor_ClassTemplatePartialSpecialization:
71 return CompletionItemKind::Class;
72 case CXCursor_Namespace:
73 case CXCursor_NamespaceAlias:
74 case CXCursor_NamespaceRef:
75 return CompletionItemKind::Module;
76 case CXCursor_EnumConstantDecl:
77 return CompletionItemKind::Value;
78 case CXCursor_EnumDecl:
79 return CompletionItemKind::Enum;
Eric Liu6f648df2017-12-19 16:50:37 +000080 // FIXME(ioeric): figure out whether reference is the right type for aliases.
Sam McCall98775c52017-12-04 13:49:59 +000081 case CXCursor_TypeAliasDecl:
82 case CXCursor_TypeAliasTemplateDecl:
83 case CXCursor_TypedefDecl:
84 case CXCursor_MemberRef:
85 case CXCursor_TypeRef:
86 return CompletionItemKind::Reference;
87 default:
88 return CompletionItemKind::Missing;
89 }
90}
91
Eric Liu6f648df2017-12-19 16:50:37 +000092CompletionItemKind
93toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
94 CXCursorKind CursorKind) {
Sam McCall98775c52017-12-04 13:49:59 +000095 switch (ResKind) {
96 case CodeCompletionResult::RK_Declaration:
Eric Liu6f648df2017-12-19 16:50:37 +000097 return toCompletionItemKind(CursorKind);
Sam McCall98775c52017-12-04 13:49:59 +000098 case CodeCompletionResult::RK_Keyword:
99 return CompletionItemKind::Keyword;
100 case CodeCompletionResult::RK_Macro:
101 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
102 // completion items in LSP.
103 case CodeCompletionResult::RK_Pattern:
104 return CompletionItemKind::Snippet;
105 }
106 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
107}
108
Eric Liu6f648df2017-12-19 16:50:37 +0000109CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
110 using SK = index::SymbolKind;
111 switch (Kind) {
112 case SK::Unknown:
113 return CompletionItemKind::Missing;
114 case SK::Module:
115 case SK::Namespace:
116 case SK::NamespaceAlias:
117 return CompletionItemKind::Module;
118 case SK::Macro:
119 return CompletionItemKind::Text;
120 case SK::Enum:
121 return CompletionItemKind::Enum;
122 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
123 // protocol.
124 case SK::Struct:
125 case SK::Class:
126 case SK::Protocol:
127 case SK::Extension:
128 case SK::Union:
129 return CompletionItemKind::Class;
130 // FIXME(ioeric): figure out whether reference is the right type for aliases.
131 case SK::TypeAlias:
132 case SK::Using:
133 return CompletionItemKind::Reference;
134 case SK::Function:
135 // FIXME(ioeric): this should probably be an operator. This should be fixed
136 // when `Operator` is support type in the protocol.
137 case SK::ConversionFunction:
138 return CompletionItemKind::Function;
139 case SK::Variable:
140 case SK::Parameter:
141 return CompletionItemKind::Variable;
142 case SK::Field:
143 return CompletionItemKind::Field;
144 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
145 case SK::EnumConstant:
146 return CompletionItemKind::Value;
147 case SK::InstanceMethod:
148 case SK::ClassMethod:
149 case SK::StaticMethod:
150 case SK::Destructor:
151 return CompletionItemKind::Method;
152 case SK::InstanceProperty:
153 case SK::ClassProperty:
154 case SK::StaticProperty:
155 return CompletionItemKind::Property;
156 case SK::Constructor:
157 return CompletionItemKind::Constructor;
158 }
159 llvm_unreachable("Unhandled clang::index::SymbolKind.");
160}
161
Sam McCall98775c52017-12-04 13:49:59 +0000162/// Get the optional chunk as a string. This function is possibly recursive.
163///
164/// The parameter info for each parameter is appended to the Parameters.
165std::string
166getOptionalParameters(const CodeCompletionString &CCS,
167 std::vector<ParameterInformation> &Parameters) {
168 std::string Result;
169 for (const auto &Chunk : CCS) {
170 switch (Chunk.Kind) {
171 case CodeCompletionString::CK_Optional:
172 assert(Chunk.Optional &&
173 "Expected the optional code completion string to be non-null.");
174 Result += getOptionalParameters(*Chunk.Optional, Parameters);
175 break;
176 case CodeCompletionString::CK_VerticalSpace:
177 break;
178 case CodeCompletionString::CK_Placeholder:
179 // A string that acts as a placeholder for, e.g., a function call
180 // argument.
181 // Intentional fallthrough here.
182 case CodeCompletionString::CK_CurrentParameter: {
183 // A piece of text that describes the parameter that corresponds to
184 // the code-completion location within a function call, message send,
185 // macro invocation, etc.
186 Result += Chunk.Text;
187 ParameterInformation Info;
188 Info.label = Chunk.Text;
189 Parameters.push_back(std::move(Info));
190 break;
191 }
192 default:
193 Result += Chunk.Text;
194 break;
195 }
196 }
197 return Result;
198}
199
Eric Liu63f419a2018-05-15 15:29:32 +0000200/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
201/// include.
202static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
203 llvm::StringRef HintPath) {
204 if (isLiteralInclude(Header))
205 return HeaderFile{Header.str(), /*Verbatim=*/true};
206 auto U = URI::parse(Header);
207 if (!U)
208 return U.takeError();
209
210 auto IncludePath = URI::includeSpelling(*U);
211 if (!IncludePath)
212 return IncludePath.takeError();
213 if (!IncludePath->empty())
214 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
215
216 auto Resolved = URI::resolve(*U, HintPath);
217 if (!Resolved)
218 return Resolved.takeError();
219 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
220}
221
Sam McCall545a20d2018-01-19 14:34:02 +0000222/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000223/// It may be promoted to a CompletionItem if it's among the top-ranked results.
224struct CompletionCandidate {
Sam McCall545a20d2018-01-19 14:34:02 +0000225 llvm::StringRef Name; // Used for filtering and sorting.
226 // We may have a result from Sema, from the index, or both.
227 const CodeCompletionResult *SemaResult = nullptr;
228 const Symbol *IndexResult = nullptr;
Sam McCall98775c52017-12-04 13:49:59 +0000229
Sam McCall545a20d2018-01-19 14:34:02 +0000230 // Builds an LSP completion item.
Eric Liu63f419a2018-05-15 15:29:32 +0000231 CompletionItem build(StringRef FileName, const CompletionItemScores &Scores,
Sam McCall545a20d2018-01-19 14:34:02 +0000232 const CodeCompleteOptions &Opts,
Eric Liu63f419a2018-05-15 15:29:32 +0000233 CodeCompletionString *SemaCCS,
Ilya Biryukov43714502018-05-16 12:32:44 +0000234 const IncludeInserter *Includes,
235 llvm::StringRef SemaDocComment) const {
Sam McCall545a20d2018-01-19 14:34:02 +0000236 assert(bool(SemaResult) == bool(SemaCCS));
237 CompletionItem I;
Eric Liu9b3cba72018-05-30 09:03:39 +0000238 bool ShouldInsertInclude = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000239 if (SemaResult) {
240 I.kind = toCompletionItemKind(SemaResult->Kind, SemaResult->CursorKind);
241 getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText,
242 Opts.EnableSnippets);
243 I.filterText = getFilterText(*SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +0000244 I.documentation = formatDocumentation(*SemaCCS, SemaDocComment);
Sam McCall545a20d2018-01-19 14:34:02 +0000245 I.detail = getDetail(*SemaCCS);
Eric Liu9b3cba72018-05-30 09:03:39 +0000246 // Avoid inserting new #include if the declaration is found in the current
247 // file e.g. the symbol is forward declared.
248 if (SemaResult->Kind == CodeCompletionResult::RK_Declaration) {
249 if (const auto *D = SemaResult->getDeclaration()) {
250 const auto &SM = D->getASTContext().getSourceManager();
251 ShouldInsertInclude =
252 ShouldInsertInclude &&
253 std::none_of(D->redecls_begin(), D->redecls_end(),
254 [&SM](const Decl *RD) {
255 return SM.isInMainFile(
256 SM.getExpansionLoc(RD->getLocStart()));
257 });
258 }
259 }
Sam McCall545a20d2018-01-19 14:34:02 +0000260 }
261 if (IndexResult) {
262 if (I.kind == CompletionItemKind::Missing)
263 I.kind = toCompletionItemKind(IndexResult->SymInfo.Kind);
264 // FIXME: reintroduce a way to show the index source for debugging.
265 if (I.label.empty())
266 I.label = IndexResult->CompletionLabel;
267 if (I.filterText.empty())
268 I.filterText = IndexResult->Name;
Sam McCall98775c52017-12-04 13:49:59 +0000269
Sam McCall545a20d2018-01-19 14:34:02 +0000270 // FIXME(ioeric): support inserting/replacing scope qualifiers.
271 if (I.insertText.empty())
272 I.insertText = Opts.EnableSnippets
273 ? IndexResult->CompletionSnippetInsertText
274 : IndexResult->CompletionPlainInsertText;
275
276 if (auto *D = IndexResult->Detail) {
277 if (I.documentation.empty())
278 I.documentation = D->Documentation;
279 if (I.detail.empty())
280 I.detail = D->CompletionDetail;
Eric Liu9b3cba72018-05-30 09:03:39 +0000281 if (ShouldInsertInclude && Includes && !D->IncludeHeader.empty()) {
Eric Liu63f419a2018-05-15 15:29:32 +0000282 auto Edit = [&]() -> Expected<Optional<TextEdit>> {
283 auto ResolvedDeclaring = toHeaderFile(
284 IndexResult->CanonicalDeclaration.FileURI, FileName);
285 if (!ResolvedDeclaring)
286 return ResolvedDeclaring.takeError();
287 auto ResolvedInserted = toHeaderFile(D->IncludeHeader, FileName);
288 if (!ResolvedInserted)
289 return ResolvedInserted.takeError();
290 return Includes->insert(*ResolvedDeclaring, *ResolvedInserted);
291 }();
292 if (!Edit) {
293 std::string ErrMsg =
294 ("Failed to generate include insertion edits for adding header "
295 "(FileURI=\"" +
296 IndexResult->CanonicalDeclaration.FileURI +
297 "\", IncludeHeader=\"" + D->IncludeHeader + "\") into " +
298 FileName)
299 .str();
300 log(ErrMsg + ":" + llvm::toString(Edit.takeError()));
301 } else if (*Edit) {
302 I.additionalTextEdits = {std::move(**Edit)};
303 }
304 }
Sam McCall545a20d2018-01-19 14:34:02 +0000305 }
306 }
307 I.scoreInfo = Scores;
308 I.sortText = sortText(Scores.finalScore, Name);
309 I.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
310 : InsertTextFormat::PlainText;
311 return I;
Sam McCall98775c52017-12-04 13:49:59 +0000312 }
313};
Sam McCallc5707b62018-05-15 17:43:27 +0000314using ScoredCandidate = std::pair<CompletionCandidate, CompletionItemScores>;
Sam McCall98775c52017-12-04 13:49:59 +0000315
Sam McCall545a20d2018-01-19 14:34:02 +0000316// Determine the symbol ID for a Sema code completion result, if possible.
317llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
318 switch (R.Kind) {
319 case CodeCompletionResult::RK_Declaration:
320 case CodeCompletionResult::RK_Pattern: {
321 llvm::SmallString<128> USR;
322 if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
323 return None;
324 return SymbolID(USR);
325 }
326 case CodeCompletionResult::RK_Macro:
327 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
328 case CodeCompletionResult::RK_Keyword:
329 return None;
330 }
331 llvm_unreachable("unknown CodeCompletionResult kind");
332}
333
Haojian Wu061c73e2018-01-23 11:37:26 +0000334// Scopes of the paritial identifier we're trying to complete.
335// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000336struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000337 // The scopes we should look in, determined by Sema.
338 //
339 // If the qualifier was fully resolved, we look for completions in these
340 // scopes; if there is an unresolved part of the qualifier, it should be
341 // resolved within these scopes.
342 //
343 // Examples of qualified completion:
344 //
345 // "::vec" => {""}
346 // "using namespace std; ::vec^" => {"", "std::"}
347 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
348 // "std::vec^" => {""} // "std" unresolved
349 //
350 // Examples of unqualified completion:
351 //
352 // "vec^" => {""}
353 // "using namespace std; vec^" => {"", "std::"}
354 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
355 //
356 // "" for global namespace, "ns::" for normal namespace.
357 std::vector<std::string> AccessibleScopes;
358 // The full scope qualifier as typed by the user (without the leading "::").
359 // Set if the qualifier is not fully resolved by Sema.
360 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000361
Haojian Wu061c73e2018-01-23 11:37:26 +0000362 // Construct scopes being queried in indexes.
363 // This method format the scopes to match the index request representation.
364 std::vector<std::string> scopesForIndexQuery() {
365 std::vector<std::string> Results;
366 for (llvm::StringRef AS : AccessibleScopes) {
367 Results.push_back(AS);
368 if (UnresolvedQualifier)
369 Results.back() += *UnresolvedQualifier;
370 }
371 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000372 }
Eric Liu6f648df2017-12-19 16:50:37 +0000373};
374
Haojian Wu061c73e2018-01-23 11:37:26 +0000375// Get all scopes that will be queried in indexes.
376std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000377 const SourceManager &SM) {
378 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000379 SpecifiedScope Info;
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000380 for (auto *Context : CCContext.getVisitedContexts()) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000381 if (isa<TranslationUnitDecl>(Context))
382 Info.AccessibleScopes.push_back(""); // global namespace
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000383 else if (const auto *NS = dyn_cast<NamespaceDecl>(Context))
Haojian Wu061c73e2018-01-23 11:37:26 +0000384 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
385 }
386 return Info;
387 };
388
389 auto SS = CCContext.getCXXScopeSpecifier();
390
391 // Unqualified completion (e.g. "vec^").
392 if (!SS) {
393 // FIXME: Once we can insert namespace qualifiers and use the in-scope
394 // namespaces for scoring, search in all namespaces.
395 // FIXME: Capture scopes and use for scoring, for example,
396 // "using namespace std; namespace foo {v^}" =>
397 // foo::value > std::vector > boost::variant
398 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
399 }
400
401 // Qualified completion ("std::vec^"), we have two cases depending on whether
402 // the qualifier can be resolved by Sema.
403 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000404 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
405 }
406
407 // Unresolved qualifier.
408 // FIXME: When Sema can resolve part of a scope chain (e.g.
409 // "known::unknown::id"), we should expand the known part ("known::") rather
410 // than treating the whole thing as unknown.
411 SpecifiedScope Info;
412 Info.AccessibleScopes.push_back(""); // global namespace
413
414 Info.UnresolvedQualifier =
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000415 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM,
416 clang::LangOptions())
417 .ltrim("::");
Haojian Wu061c73e2018-01-23 11:37:26 +0000418 // Sema excludes the trailing "::".
419 if (!Info.UnresolvedQualifier->empty())
420 *Info.UnresolvedQualifier += "::";
421
422 return Info.scopesForIndexQuery();
423}
424
Eric Liu42abe412018-05-24 11:20:19 +0000425// Should we perform index-based completion in a context of the specified kind?
426// FIXME: consider allowing completion, but restricting the result types.
427bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
428 switch (K) {
429 case CodeCompletionContext::CCC_TopLevel:
430 case CodeCompletionContext::CCC_ObjCInterface:
431 case CodeCompletionContext::CCC_ObjCImplementation:
432 case CodeCompletionContext::CCC_ObjCIvarList:
433 case CodeCompletionContext::CCC_ClassStructUnion:
434 case CodeCompletionContext::CCC_Statement:
435 case CodeCompletionContext::CCC_Expression:
436 case CodeCompletionContext::CCC_ObjCMessageReceiver:
437 case CodeCompletionContext::CCC_EnumTag:
438 case CodeCompletionContext::CCC_UnionTag:
439 case CodeCompletionContext::CCC_ClassOrStructTag:
440 case CodeCompletionContext::CCC_ObjCProtocolName:
441 case CodeCompletionContext::CCC_Namespace:
442 case CodeCompletionContext::CCC_Type:
443 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
444 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
445 case CodeCompletionContext::CCC_ParenthesizedExpression:
446 case CodeCompletionContext::CCC_ObjCInterfaceName:
447 case CodeCompletionContext::CCC_ObjCCategoryName:
448 return true;
449 case CodeCompletionContext::CCC_Other: // Be conservative.
450 case CodeCompletionContext::CCC_OtherWithMacros:
451 case CodeCompletionContext::CCC_DotMemberAccess:
452 case CodeCompletionContext::CCC_ArrowMemberAccess:
453 case CodeCompletionContext::CCC_ObjCPropertyAccess:
454 case CodeCompletionContext::CCC_MacroName:
455 case CodeCompletionContext::CCC_MacroNameUse:
456 case CodeCompletionContext::CCC_PreprocessorExpression:
457 case CodeCompletionContext::CCC_PreprocessorDirective:
458 case CodeCompletionContext::CCC_NaturalLanguage:
459 case CodeCompletionContext::CCC_SelectorName:
460 case CodeCompletionContext::CCC_TypeQualifiers:
461 case CodeCompletionContext::CCC_ObjCInstanceMessage:
462 case CodeCompletionContext::CCC_ObjCClassMessage:
463 case CodeCompletionContext::CCC_Recovery:
464 return false;
465 }
466 llvm_unreachable("unknown code completion context");
467}
468
Sam McCall545a20d2018-01-19 14:34:02 +0000469// The CompletionRecorder captures Sema code-complete output, including context.
470// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
471// It doesn't do scoring or conversion to CompletionItem yet, as we want to
472// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000473// Generally the fields and methods of this object should only be used from
474// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000475struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000476 CompletionRecorder(const CodeCompleteOptions &Opts,
477 UniqueFunction<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000478 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000479 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000480 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
481 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000482 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
483 assert(this->ResultsCallback);
484 }
485
Sam McCall545a20d2018-01-19 14:34:02 +0000486 std::vector<CodeCompletionResult> Results;
487 CodeCompletionContext CCContext;
488 Sema *CCSema = nullptr; // Sema that created the results.
489 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000490
Sam McCall545a20d2018-01-19 14:34:02 +0000491 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
492 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000493 unsigned NumResults) override final {
Eric Liu42abe412018-05-24 11:20:19 +0000494 // If a callback is called without any sema result and the context does not
495 // support index-based completion, we simply skip it to give way to
496 // potential future callbacks with results.
497 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
498 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000499 if (CCSema) {
500 log(llvm::formatv(
501 "Multiple code complete callbacks (parser backtracked?). "
502 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000503 getCompletionKindString(Context.getKind()),
504 getCompletionKindString(this->CCContext.getKind())));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000505 return;
506 }
Sam McCall545a20d2018-01-19 14:34:02 +0000507 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000508 CCSema = &S;
509 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000510
Sam McCall545a20d2018-01-19 14:34:02 +0000511 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000512 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000513 auto &Result = InResults[I];
514 // Drop hidden items which cannot be found by lookup after completion.
515 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000516 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
517 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000518 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000519 (Result.Availability == CXAvailability_NotAvailable ||
520 Result.Availability == CXAvailability_NotAccessible))
521 continue;
Sam McCalld2a95922018-01-22 21:05:00 +0000522 // Destructor completion is rarely useful, and works inconsistently.
523 // (s.^ completes ~string, but s.~st^ is an error).
524 if (dyn_cast_or_null<CXXDestructorDecl>(Result.Declaration))
525 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000526 // We choose to never append '::' to completion results in clangd.
527 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000528 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000529 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000530 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000531 }
532
Sam McCall545a20d2018-01-19 14:34:02 +0000533 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000534 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
535
Sam McCall545a20d2018-01-19 14:34:02 +0000536 // Returns the filtering/sorting name for Result, which must be from Results.
537 // Returned string is owned by this recorder (or the AST).
538 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000539 switch (Result.Kind) {
540 case CodeCompletionResult::RK_Declaration:
541 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000542 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000543 break;
544 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000545 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000546 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000547 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000548 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000549 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000550 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000551 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000552 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000553 }
554
Sam McCall545a20d2018-01-19 14:34:02 +0000555 // Build a CodeCompletion string for R, which must be from Results.
556 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000557 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000558 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
559 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000560 *CCSema, CCContext, *CCAllocator, CCTUInfo,
561 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000562 }
563
Sam McCall545a20d2018-01-19 14:34:02 +0000564private:
565 CodeCompleteOptions Opts;
566 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000567 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000568 UniqueFunction<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000569};
570
Sam McCallc5707b62018-05-15 17:43:27 +0000571struct ScoredCandidateGreater {
572 bool operator()(const ScoredCandidate &L, const ScoredCandidate &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000573 if (L.second.finalScore != R.second.finalScore)
574 return L.second.finalScore > R.second.finalScore;
575 return L.first.Name < R.first.Name; // Earlier name is better.
576 }
Sam McCall545a20d2018-01-19 14:34:02 +0000577};
Sam McCall98775c52017-12-04 13:49:59 +0000578
Sam McCall98775c52017-12-04 13:49:59 +0000579class SignatureHelpCollector final : public CodeCompleteConsumer {
580
581public:
582 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
583 SignatureHelp &SigHelp)
584 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
585 SigHelp(SigHelp),
586 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
587 CCTUInfo(Allocator) {}
588
589 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
590 OverloadCandidate *Candidates,
591 unsigned NumCandidates) override {
592 SigHelp.signatures.reserve(NumCandidates);
593 // FIXME(rwols): How can we determine the "active overload candidate"?
594 // Right now the overloaded candidates seem to be provided in a "best fit"
595 // order, so I'm not too worried about this.
596 SigHelp.activeSignature = 0;
597 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
598 "too many arguments");
599 SigHelp.activeParameter = static_cast<int>(CurrentArg);
600 for (unsigned I = 0; I < NumCandidates; ++I) {
601 const auto &Candidate = Candidates[I];
602 const auto *CCS = Candidate.CreateSignatureString(
603 CurrentArg, S, *Allocator, CCTUInfo, true);
604 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000605 // FIXME: for headers, we need to get a comment from the index.
Ilya Biryukov43714502018-05-16 12:32:44 +0000606 SigHelp.signatures.push_back(ProcessOverloadCandidate(
607 Candidate, *CCS,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000608 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000609 /*CommentsFromHeaders=*/false)));
Sam McCall98775c52017-12-04 13:49:59 +0000610 }
611 }
612
613 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
614
615 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
616
617private:
Eric Liu63696e12017-12-20 17:24:31 +0000618 // FIXME(ioeric): consider moving CodeCompletionString logic here to
619 // CompletionString.h.
Sam McCall98775c52017-12-04 13:49:59 +0000620 SignatureInformation
621 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
Ilya Biryukov43714502018-05-16 12:32:44 +0000622 const CodeCompletionString &CCS,
623 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000624 SignatureInformation Result;
625 const char *ReturnType = nullptr;
626
Ilya Biryukov43714502018-05-16 12:32:44 +0000627 Result.documentation = formatDocumentation(CCS, DocComment);
Sam McCall98775c52017-12-04 13:49:59 +0000628
629 for (const auto &Chunk : CCS) {
630 switch (Chunk.Kind) {
631 case CodeCompletionString::CK_ResultType:
632 // A piece of text that describes the type of an entity or,
633 // for functions and methods, the return type.
634 assert(!ReturnType && "Unexpected CK_ResultType");
635 ReturnType = Chunk.Text;
636 break;
637 case CodeCompletionString::CK_Placeholder:
638 // A string that acts as a placeholder for, e.g., a function call
639 // argument.
640 // Intentional fallthrough here.
641 case CodeCompletionString::CK_CurrentParameter: {
642 // A piece of text that describes the parameter that corresponds to
643 // the code-completion location within a function call, message send,
644 // macro invocation, etc.
645 Result.label += Chunk.Text;
646 ParameterInformation Info;
647 Info.label = Chunk.Text;
648 Result.parameters.push_back(std::move(Info));
649 break;
650 }
651 case CodeCompletionString::CK_Optional: {
652 // The rest of the parameters are defaulted/optional.
653 assert(Chunk.Optional &&
654 "Expected the optional code completion string to be non-null.");
655 Result.label +=
656 getOptionalParameters(*Chunk.Optional, Result.parameters);
657 break;
658 }
659 case CodeCompletionString::CK_VerticalSpace:
660 break;
661 default:
662 Result.label += Chunk.Text;
663 break;
664 }
665 }
666 if (ReturnType) {
667 Result.label += " -> ";
668 Result.label += ReturnType;
669 }
670 return Result;
671 }
672
673 SignatureHelp &SigHelp;
674 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
675 CodeCompletionTUInfo CCTUInfo;
676
677}; // SignatureHelpCollector
678
Sam McCall545a20d2018-01-19 14:34:02 +0000679struct SemaCompleteInput {
680 PathRef FileName;
681 const tooling::CompileCommand &Command;
682 PrecompiledPreamble const *Preamble;
Eric Liu63f419a2018-05-15 15:29:32 +0000683 const std::vector<Inclusion> &PreambleInclusions;
Sam McCall545a20d2018-01-19 14:34:02 +0000684 StringRef Contents;
685 Position Pos;
686 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
687 std::shared_ptr<PCHContainerOperations> PCHs;
688};
689
690// Invokes Sema code completion on a file.
Eric Liu63f419a2018-05-15 15:29:32 +0000691// If \p Includes is set, it will be initialized after a compiler instance has
692// been set up.
Sam McCalld1a7a372018-01-31 13:40:48 +0000693bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000694 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000695 const SemaCompleteInput &Input,
696 std::unique_ptr<IncludeInserter> *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000697 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000698 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000699 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000700 ArgStrs.push_back(S.c_str());
701
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000702 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
703 log("Couldn't set working directory");
704 // We run parsing anyway, our lit-tests rely on results for non-existing
705 // working dirs.
706 }
Sam McCall98775c52017-12-04 13:49:59 +0000707
708 IgnoreDiagnostics DummyDiagsConsumer;
709 auto CI = createInvocationFromCommandLine(
710 ArgStrs,
711 CompilerInstance::createDiagnostics(new DiagnosticOptions,
712 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000713 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000714 if (!CI) {
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000715 log("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000716 return false;
717 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000718 auto &FrontendOpts = CI->getFrontendOpts();
719 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000720 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000721 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
722 // Disable typo correction in Sema.
723 CI->getLangOpts()->SpellChecking = false;
724 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +0000725 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000726 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000727 auto Offset = positionToOffset(Input.Contents, Input.Pos);
728 if (!Offset) {
729 log("Code completion position was invalid " +
730 llvm::toString(Offset.takeError()));
731 return false;
732 }
733 std::tie(FrontendOpts.CodeCompletionAt.Line,
734 FrontendOpts.CodeCompletionAt.Column) =
735 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000736
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000737 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
738 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
739 // The diagnostic options must be set before creating a CompilerInstance.
740 CI->getDiagnosticOpts().IgnoreWarnings = true;
741 // We reuse the preamble whether it's valid or not. This is a
742 // correctness/performance tradeoff: building without a preamble is slow, and
743 // completion is latency-sensitive.
744 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
745 // the remapped buffers do not get freed.
746 auto Clang = prepareCompilerInstance(
747 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
748 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000749 Clang->setCodeCompletionConsumer(Consumer.release());
750
751 SyntaxOnlyAction Action;
752 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000753 log("BeginSourceFile() failed when running codeComplete for " +
754 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000755 return false;
756 }
Eric Liu63f419a2018-05-15 15:29:32 +0000757 if (Includes) {
758 // Initialize Includes if provided.
759
760 // FIXME(ioeric): needs more consistent style support in clangd server.
761 auto Style = format::getStyle("file", Input.FileName, "LLVM",
762 Input.Contents, Input.VFS.get());
763 if (!Style) {
764 log("Failed to get FormatStyle for file" + Input.FileName +
765 ". Fall back to use LLVM style. Error: " +
766 llvm::toString(Style.takeError()));
767 Style = format::getLLVMStyle();
768 }
769 *Includes = llvm::make_unique<IncludeInserter>(
770 Input.FileName, Input.Contents, *Style, Input.Command.Directory,
771 Clang->getPreprocessor().getHeaderSearchInfo());
772 for (const auto &Inc : Input.PreambleInclusions)
773 Includes->get()->addExisting(Inc);
774 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
775 Clang->getSourceManager(), [Includes](Inclusion Inc) {
776 Includes->get()->addExisting(std::move(Inc));
777 }));
778 }
Sam McCall98775c52017-12-04 13:49:59 +0000779 if (!Action.Execute()) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000780 log("Execute() failed when running codeComplete for " + Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000781 return false;
782 }
Sam McCall98775c52017-12-04 13:49:59 +0000783 Action.EndSourceFile();
784
785 return true;
786}
787
Ilya Biryukova907ba42018-05-14 10:50:04 +0000788// Should we allow index completions in the specified context?
789bool allowIndex(CodeCompletionContext &CC) {
790 if (!contextAllowsIndex(CC.getKind()))
791 return false;
792 // We also avoid ClassName::bar (but allow namespace::bar).
793 auto Scope = CC.getCXXScopeSpecifier();
794 if (!Scope)
795 return true;
796 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
797 if (!NameSpec)
798 return true;
799 // We only query the index when qualifier is a namespace.
800 // If it's a class, we rely solely on sema completions.
801 switch (NameSpec->getKind()) {
802 case NestedNameSpecifier::Global:
803 case NestedNameSpecifier::Namespace:
804 case NestedNameSpecifier::NamespaceAlias:
805 return true;
806 case NestedNameSpecifier::Super:
807 case NestedNameSpecifier::TypeSpec:
808 case NestedNameSpecifier::TypeSpecWithTemplate:
809 // Unresolved inside a template.
810 case NestedNameSpecifier::Identifier:
811 return false;
812 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000813 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000814}
815
Sam McCall98775c52017-12-04 13:49:59 +0000816} // namespace
817
818clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
819 clang::CodeCompleteOptions Result;
820 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
821 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000822 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000823 // We choose to include full comments and not do doxygen parsing in
824 // completion.
825 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
826 // formatting of the comments.
827 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000828
Sam McCall3d139c52018-01-12 18:30:08 +0000829 // When an is used, Sema is responsible for completing the main file,
830 // the index can provide results from the preamble.
831 // Tell Sema not to deserialize the preamble to look for results.
832 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000833
Sam McCall98775c52017-12-04 13:49:59 +0000834 return Result;
835}
836
Sam McCall545a20d2018-01-19 14:34:02 +0000837// Runs Sema-based (AST) and Index-based completion, returns merged results.
838//
839// There are a few tricky considerations:
840// - the AST provides information needed for the index query (e.g. which
841// namespaces to search in). So Sema must start first.
842// - we only want to return the top results (Opts.Limit).
843// Building CompletionItems for everything else is wasteful, so we want to
844// preserve the "native" format until we're done with scoring.
845// - the data underlying Sema completion items is owned by the AST and various
846// other arenas, which must stay alive for us to build CompletionItems.
847// - we may get duplicate results from Sema and the Index, we need to merge.
848//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000849// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000850// We use the Sema context information to query the index.
851// Then we merge the two result sets, producing items that are Sema/Index/Both.
852// These items are scored, and the top N are synthesized into the LSP response.
853// Finally, we can clean up the data structures created by Sema completion.
854//
855// Main collaborators are:
856// - semaCodeComplete sets up the compiler machinery to run code completion.
857// - CompletionRecorder captures Sema completion results, including context.
858// - SymbolIndex (Opts.Index) provides index completion results as Symbols
859// - CompletionCandidates are the result of merging Sema and Index results.
860// Each candidate points to an underlying CodeCompletionResult (Sema), a
861// Symbol (Index), or both. It computes the result quality score.
862// CompletionCandidate also does conversion to CompletionItem (at the end).
863// - FuzzyMatcher scores how the candidate matches the partial identifier.
864// This score is combined with the result quality score for the final score.
865// - TopN determines the results with the best score.
866class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000867 PathRef FileName;
Sam McCall545a20d2018-01-19 14:34:02 +0000868 const CodeCompleteOptions &Opts;
869 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000870 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000871 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
872 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000873 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
874 std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000875
876public:
877 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Eric Liuc5105f92018-02-16 14:15:55 +0000878 CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000879 : FileName(FileName), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000880
881 CompletionList run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000882 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000883
Sam McCall545a20d2018-01-19 14:34:02 +0000884 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000885 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000886 // - partial identifier and context. We need these for the index query.
887 CompletionList Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000888 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
889 assert(Recorder && "Recorder is not set");
Eric Liu63f419a2018-05-15 15:29:32 +0000890 assert(Includes && "Includes is not set");
891 // If preprocessor was run, inclusions from preprocessor callback should
892 // already be added to Inclusions.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000893 Output = runWithSema();
Eric Liu63f419a2018-05-15 15:29:32 +0000894 Includes.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000895 SPAN_ATTACH(Tracer, "sema_completion_kind",
896 getCompletionKindString(Recorder->CCContext.getKind()));
897 });
898
899 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +0000900 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +0000901 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +0000902
Sam McCall2b780162018-01-30 17:20:54 +0000903 SPAN_ATTACH(Tracer, "sema_results", NSema);
904 SPAN_ATTACH(Tracer, "index_results", NIndex);
905 SPAN_ATTACH(Tracer, "merged_results", NBoth);
906 SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
907 SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
Sam McCalld1a7a372018-01-31 13:40:48 +0000908 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
Sam McCall545a20d2018-01-19 14:34:02 +0000909 "{2} matched, {3} returned{4}.",
910 NSema, NIndex, NBoth, Output.items.size(),
911 Output.isIncomplete ? " (incomplete)" : ""));
912 assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
913 // We don't assert that isIncomplete means we hit a limit.
914 // Indexes may choose to impose their own limits even if we don't have one.
915 return Output;
916 }
917
918private:
919 // This is called by run() once Sema code completion is done, but before the
920 // Sema data structures are torn down. It does all the real work.
921 CompletionList runWithSema() {
922 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000923 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Sam McCall545a20d2018-01-19 14:34:02 +0000924 // Sema provides the needed context to query the index.
925 // FIXME: in addition to querying for extra/overlapping symbols, we should
926 // explicitly request symbols corresponding to Sema results.
927 // We can use their signals even if the index can't suggest them.
928 // We must copy index results to preserve them, but there are at most Limit.
929 auto IndexResults = queryIndex();
930 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000931 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall545a20d2018-01-19 14:34:02 +0000932 // Convert the results to the desired LSP structs.
933 CompletionList Output;
934 for (auto &C : Top)
935 Output.items.push_back(toCompletionItem(C.first, C.second));
936 Output.isIncomplete = Incomplete;
937 return Output;
938 }
939
940 SymbolSlab queryIndex() {
Ilya Biryukova907ba42018-05-14 10:50:04 +0000941 if (!Opts.Index || !allowIndex(Recorder->CCContext))
Sam McCall545a20d2018-01-19 14:34:02 +0000942 return SymbolSlab();
Sam McCalld1a7a372018-01-31 13:40:48 +0000943 trace::Span Tracer("Query index");
Sam McCall2b780162018-01-30 17:20:54 +0000944 SPAN_ATTACH(Tracer, "limit", Opts.Limit);
945
Sam McCall545a20d2018-01-19 14:34:02 +0000946 SymbolSlab::Builder ResultsBuilder;
947 // Build the query.
948 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +0000949 if (Opts.Limit)
950 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +0000951 Req.Query = Filter->pattern();
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000952 Req.Scopes = getQueryScopes(Recorder->CCContext,
953 Recorder->CCSema->getSourceManager());
Sam McCalld1a7a372018-01-31 13:40:48 +0000954 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
Sam McCall2b780162018-01-30 17:20:54 +0000955 Req.Query,
956 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Sam McCall545a20d2018-01-19 14:34:02 +0000957 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +0000958 if (Opts.Index->fuzzyFind(
959 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
960 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000961 return std::move(ResultsBuilder).build();
962 }
963
964 // Merges the Sema and Index results where possible, scores them, and
965 // returns the top results from best to worst.
966 std::vector<std::pair<CompletionCandidate, CompletionItemScores>>
967 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
968 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000969 trace::Span Tracer("Merge and score results");
Sam McCall545a20d2018-01-19 14:34:02 +0000970 // We only keep the best N results at any time, in "native" format.
Sam McCallc5707b62018-05-15 17:43:27 +0000971 TopN<ScoredCandidate, ScoredCandidateGreater> Top(
972 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +0000973 llvm::DenseSet<const Symbol *> UsedIndexResults;
974 auto CorrespondingIndexResult =
975 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
976 if (auto SymID = getSymbolID(SemaResult)) {
977 auto I = IndexResults.find(*SymID);
978 if (I != IndexResults.end()) {
979 UsedIndexResults.insert(&*I);
980 return &*I;
981 }
982 }
983 return nullptr;
984 };
985 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000986 for (auto &SemaResult : Recorder->Results)
Sam McCall545a20d2018-01-19 14:34:02 +0000987 addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult));
988 // Now emit any Index-only results.
989 for (const auto &IndexResult : IndexResults) {
990 if (UsedIndexResults.count(&IndexResult))
991 continue;
992 addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult);
993 }
994 return std::move(Top).items();
995 }
996
997 // Scores a candidate and adds it to the TopN structure.
Sam McCallc5707b62018-05-15 17:43:27 +0000998 void addCandidate(TopN<ScoredCandidate, ScoredCandidateGreater> &Candidates,
999 const CodeCompletionResult *SemaResult,
Sam McCall545a20d2018-01-19 14:34:02 +00001000 const Symbol *IndexResult) {
1001 CompletionCandidate C;
1002 C.SemaResult = SemaResult;
1003 C.IndexResult = IndexResult;
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001004 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001005
Sam McCallc5707b62018-05-15 17:43:27 +00001006 SymbolQualitySignals Quality;
1007 SymbolRelevanceSignals Relevance;
Sam McCall545a20d2018-01-19 14:34:02 +00001008 if (auto FuzzyScore = Filter->match(C.Name))
Sam McCallc5707b62018-05-15 17:43:27 +00001009 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001010 else
1011 return;
Sam McCallc5707b62018-05-15 17:43:27 +00001012 if (IndexResult)
1013 Quality.merge(*IndexResult);
1014 if (SemaResult) {
1015 Quality.merge(*SemaResult);
1016 Relevance.merge(*SemaResult);
1017 }
1018
1019 float QualScore = Quality.evaluate(), RelScore = Relevance.evaluate();
1020 CompletionItemScores Scores;
1021 Scores.finalScore = evaluateSymbolAndRelevance(QualScore, RelScore);
1022 // The purpose of exporting component scores is to allow NameMatch to be
1023 // replaced on the client-side. So we export (NameMatch, final/NameMatch)
1024 // rather than (RelScore, QualScore).
1025 Scores.filterScore = Relevance.NameMatch;
1026 Scores.symbolScore =
1027 Scores.filterScore ? Scores.finalScore / Scores.filterScore : QualScore;
1028
Nicola Zaghenc9fed132018-05-23 13:57:48 +00001029 LLVM_DEBUG(llvm::dbgs()
1030 << "CodeComplete: " << C.Name << (IndexResult ? " (index)" : "")
1031 << (SemaResult ? " (sema)" : "") << " = " << Scores.finalScore
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +00001032 << "\n"
Nicola Zaghenc9fed132018-05-23 13:57:48 +00001033 << Quality << Relevance << "\n");
Sam McCall545a20d2018-01-19 14:34:02 +00001034
1035 NSema += bool(SemaResult);
1036 NIndex += bool(IndexResult);
1037 NBoth += SemaResult && IndexResult;
Sam McCallab8e3932018-02-19 13:04:41 +00001038 if (Candidates.push({C, Scores}))
1039 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001040 }
1041
1042 CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
1043 const CompletionItemScores &Scores) {
1044 CodeCompletionString *SemaCCS = nullptr;
Ilya Biryukov43714502018-05-16 12:32:44 +00001045 std::string DocComment;
1046 if (auto *SR = Candidate.SemaResult) {
1047 SemaCCS = Recorder->codeCompletionString(*SR);
1048 if (Opts.IncludeComments) {
1049 assert(Recorder->CCSema);
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001050 DocComment = getDocComment(Recorder->CCSema->getASTContext(), *SR,
1051 /*CommentsFromHeader=*/false);
Ilya Biryukov43714502018-05-16 12:32:44 +00001052 }
1053 }
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +00001054 return Candidate.build(FileName, Scores, Opts, SemaCCS, Includes.get(),
1055 DocComment);
Sam McCall545a20d2018-01-19 14:34:02 +00001056 }
1057};
1058
Sam McCalld1a7a372018-01-31 13:40:48 +00001059CompletionList codeComplete(PathRef FileName,
Sam McCall98775c52017-12-04 13:49:59 +00001060 const tooling::CompileCommand &Command,
1061 PrecompiledPreamble const *Preamble,
Eric Liu63f419a2018-05-15 15:29:32 +00001062 const std::vector<Inclusion> &PreambleInclusions,
Sam McCall98775c52017-12-04 13:49:59 +00001063 StringRef Contents, Position Pos,
1064 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1065 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001066 CodeCompleteOptions Opts) {
Eric Liuc5105f92018-02-16 14:15:55 +00001067 return CodeCompleteFlow(FileName, Opts)
Eric Liu63f419a2018-05-15 15:29:32 +00001068 .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS,
1069 PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001070}
1071
Sam McCalld1a7a372018-01-31 13:40:48 +00001072SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001073 const tooling::CompileCommand &Command,
1074 PrecompiledPreamble const *Preamble,
1075 StringRef Contents, Position Pos,
1076 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1077 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001078 SignatureHelp Result;
1079 clang::CodeCompleteOptions Options;
1080 Options.IncludeGlobals = false;
1081 Options.IncludeMacros = false;
1082 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001083 Options.IncludeBriefComments = false;
Eric Liu4c0a27b2018-05-16 20:31:38 +00001084 std::vector<Inclusion> PreambleInclusions = {}; // Unused for signatureHelp
Sam McCalld1a7a372018-01-31 13:40:48 +00001085 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1086 Options,
Eric Liu4c0a27b2018-05-16 20:31:38 +00001087 {FileName, Command, Preamble, PreambleInclusions, Contents,
1088 Pos, std::move(VFS), std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001089 return Result;
1090}
1091
1092} // namespace clangd
1093} // namespace clang