blob: 083ed5754816c8443e6bd6a4bdb2aeaa9ae2992c [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 McCall4caa8512018-06-07 12:49:17 +0000470// Some member calls are blacklisted because they're so rarely useful.
471static bool isBlacklistedMember(const NamedDecl &D) {
472 // Destructor completion is rarely useful, and works inconsistently.
473 // (s.^ completes ~string, but s.~st^ is an error).
474 if (D.getKind() == Decl::CXXDestructor)
475 return true;
476 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
477 if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
478 if (R->isInjectedClassName())
479 return true;
480 // Explicit calls to operators are also rare.
481 auto NameKind = D.getDeclName().getNameKind();
482 if (NameKind == DeclarationName::CXXOperatorName ||
483 NameKind == DeclarationName::CXXLiteralOperatorName ||
484 NameKind == DeclarationName::CXXConversionFunctionName)
485 return true;
486 return false;
487}
488
Sam McCall545a20d2018-01-19 14:34:02 +0000489// The CompletionRecorder captures Sema code-complete output, including context.
490// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
491// It doesn't do scoring or conversion to CompletionItem yet, as we want to
492// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000493// Generally the fields and methods of this object should only be used from
494// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000495struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000496 CompletionRecorder(const CodeCompleteOptions &Opts,
497 UniqueFunction<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000498 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000499 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000500 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
501 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000502 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
503 assert(this->ResultsCallback);
504 }
505
Sam McCall545a20d2018-01-19 14:34:02 +0000506 std::vector<CodeCompletionResult> Results;
507 CodeCompletionContext CCContext;
508 Sema *CCSema = nullptr; // Sema that created the results.
509 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000510
Sam McCall545a20d2018-01-19 14:34:02 +0000511 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
512 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000513 unsigned NumResults) override final {
Eric Liu42abe412018-05-24 11:20:19 +0000514 // If a callback is called without any sema result and the context does not
515 // support index-based completion, we simply skip it to give way to
516 // potential future callbacks with results.
517 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
518 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000519 if (CCSema) {
520 log(llvm::formatv(
521 "Multiple code complete callbacks (parser backtracked?). "
522 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000523 getCompletionKindString(Context.getKind()),
524 getCompletionKindString(this->CCContext.getKind())));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000525 return;
526 }
Sam McCall545a20d2018-01-19 14:34:02 +0000527 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000528 CCSema = &S;
529 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000530
Sam McCall545a20d2018-01-19 14:34:02 +0000531 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000532 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000533 auto &Result = InResults[I];
534 // Drop hidden items which cannot be found by lookup after completion.
535 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000536 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
537 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000538 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000539 (Result.Availability == CXAvailability_NotAvailable ||
540 Result.Availability == CXAvailability_NotAccessible))
541 continue;
Sam McCall4caa8512018-06-07 12:49:17 +0000542 if (Result.Declaration &&
543 !Context.getBaseType().isNull() // is this a member-access context?
544 && isBlacklistedMember(*Result.Declaration))
Sam McCalld2a95922018-01-22 21:05:00 +0000545 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000546 // We choose to never append '::' to completion results in clangd.
547 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000548 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000549 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000550 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000551 }
552
Sam McCall545a20d2018-01-19 14:34:02 +0000553 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000554 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
555
Sam McCall545a20d2018-01-19 14:34:02 +0000556 // Returns the filtering/sorting name for Result, which must be from Results.
557 // Returned string is owned by this recorder (or the AST).
558 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000559 switch (Result.Kind) {
560 case CodeCompletionResult::RK_Declaration:
561 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000562 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000563 break;
564 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000565 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000566 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000567 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000568 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000569 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000570 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000571 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000572 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000573 }
574
Sam McCall545a20d2018-01-19 14:34:02 +0000575 // Build a CodeCompletion string for R, which must be from Results.
576 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000577 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000578 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
579 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000580 *CCSema, CCContext, *CCAllocator, CCTUInfo,
581 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000582 }
583
Sam McCall545a20d2018-01-19 14:34:02 +0000584private:
585 CodeCompleteOptions Opts;
586 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000587 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000588 UniqueFunction<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000589};
590
Sam McCallc5707b62018-05-15 17:43:27 +0000591struct ScoredCandidateGreater {
592 bool operator()(const ScoredCandidate &L, const ScoredCandidate &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000593 if (L.second.finalScore != R.second.finalScore)
594 return L.second.finalScore > R.second.finalScore;
595 return L.first.Name < R.first.Name; // Earlier name is better.
596 }
Sam McCall545a20d2018-01-19 14:34:02 +0000597};
Sam McCall98775c52017-12-04 13:49:59 +0000598
Sam McCall98775c52017-12-04 13:49:59 +0000599class SignatureHelpCollector final : public CodeCompleteConsumer {
600
601public:
602 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
603 SignatureHelp &SigHelp)
604 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
605 SigHelp(SigHelp),
606 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
607 CCTUInfo(Allocator) {}
608
609 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
610 OverloadCandidate *Candidates,
611 unsigned NumCandidates) override {
612 SigHelp.signatures.reserve(NumCandidates);
613 // FIXME(rwols): How can we determine the "active overload candidate"?
614 // Right now the overloaded candidates seem to be provided in a "best fit"
615 // order, so I'm not too worried about this.
616 SigHelp.activeSignature = 0;
617 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
618 "too many arguments");
619 SigHelp.activeParameter = static_cast<int>(CurrentArg);
620 for (unsigned I = 0; I < NumCandidates; ++I) {
621 const auto &Candidate = Candidates[I];
622 const auto *CCS = Candidate.CreateSignatureString(
623 CurrentArg, S, *Allocator, CCTUInfo, true);
624 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000625 // FIXME: for headers, we need to get a comment from the index.
Ilya Biryukov43714502018-05-16 12:32:44 +0000626 SigHelp.signatures.push_back(ProcessOverloadCandidate(
627 Candidate, *CCS,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000628 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000629 /*CommentsFromHeaders=*/false)));
Sam McCall98775c52017-12-04 13:49:59 +0000630 }
631 }
632
633 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
634
635 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
636
637private:
Eric Liu63696e12017-12-20 17:24:31 +0000638 // FIXME(ioeric): consider moving CodeCompletionString logic here to
639 // CompletionString.h.
Sam McCall98775c52017-12-04 13:49:59 +0000640 SignatureInformation
641 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
Ilya Biryukov43714502018-05-16 12:32:44 +0000642 const CodeCompletionString &CCS,
643 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000644 SignatureInformation Result;
645 const char *ReturnType = nullptr;
646
Ilya Biryukov43714502018-05-16 12:32:44 +0000647 Result.documentation = formatDocumentation(CCS, DocComment);
Sam McCall98775c52017-12-04 13:49:59 +0000648
649 for (const auto &Chunk : CCS) {
650 switch (Chunk.Kind) {
651 case CodeCompletionString::CK_ResultType:
652 // A piece of text that describes the type of an entity or,
653 // for functions and methods, the return type.
654 assert(!ReturnType && "Unexpected CK_ResultType");
655 ReturnType = Chunk.Text;
656 break;
657 case CodeCompletionString::CK_Placeholder:
658 // A string that acts as a placeholder for, e.g., a function call
659 // argument.
660 // Intentional fallthrough here.
661 case CodeCompletionString::CK_CurrentParameter: {
662 // A piece of text that describes the parameter that corresponds to
663 // the code-completion location within a function call, message send,
664 // macro invocation, etc.
665 Result.label += Chunk.Text;
666 ParameterInformation Info;
667 Info.label = Chunk.Text;
668 Result.parameters.push_back(std::move(Info));
669 break;
670 }
671 case CodeCompletionString::CK_Optional: {
672 // The rest of the parameters are defaulted/optional.
673 assert(Chunk.Optional &&
674 "Expected the optional code completion string to be non-null.");
675 Result.label +=
676 getOptionalParameters(*Chunk.Optional, Result.parameters);
677 break;
678 }
679 case CodeCompletionString::CK_VerticalSpace:
680 break;
681 default:
682 Result.label += Chunk.Text;
683 break;
684 }
685 }
686 if (ReturnType) {
687 Result.label += " -> ";
688 Result.label += ReturnType;
689 }
690 return Result;
691 }
692
693 SignatureHelp &SigHelp;
694 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
695 CodeCompletionTUInfo CCTUInfo;
696
697}; // SignatureHelpCollector
698
Sam McCall545a20d2018-01-19 14:34:02 +0000699struct SemaCompleteInput {
700 PathRef FileName;
701 const tooling::CompileCommand &Command;
702 PrecompiledPreamble const *Preamble;
Eric Liu63f419a2018-05-15 15:29:32 +0000703 const std::vector<Inclusion> &PreambleInclusions;
Sam McCall545a20d2018-01-19 14:34:02 +0000704 StringRef Contents;
705 Position Pos;
706 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
707 std::shared_ptr<PCHContainerOperations> PCHs;
708};
709
710// Invokes Sema code completion on a file.
Eric Liu63f419a2018-05-15 15:29:32 +0000711// If \p Includes is set, it will be initialized after a compiler instance has
712// been set up.
Sam McCalld1a7a372018-01-31 13:40:48 +0000713bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000714 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000715 const SemaCompleteInput &Input,
716 std::unique_ptr<IncludeInserter> *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000717 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000718 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000719 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000720 ArgStrs.push_back(S.c_str());
721
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000722 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
723 log("Couldn't set working directory");
724 // We run parsing anyway, our lit-tests rely on results for non-existing
725 // working dirs.
726 }
Sam McCall98775c52017-12-04 13:49:59 +0000727
728 IgnoreDiagnostics DummyDiagsConsumer;
729 auto CI = createInvocationFromCommandLine(
730 ArgStrs,
731 CompilerInstance::createDiagnostics(new DiagnosticOptions,
732 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000733 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000734 if (!CI) {
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000735 log("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000736 return false;
737 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000738 auto &FrontendOpts = CI->getFrontendOpts();
739 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000740 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000741 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
742 // Disable typo correction in Sema.
743 CI->getLangOpts()->SpellChecking = false;
744 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +0000745 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000746 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000747 auto Offset = positionToOffset(Input.Contents, Input.Pos);
748 if (!Offset) {
749 log("Code completion position was invalid " +
750 llvm::toString(Offset.takeError()));
751 return false;
752 }
753 std::tie(FrontendOpts.CodeCompletionAt.Line,
754 FrontendOpts.CodeCompletionAt.Column) =
755 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000756
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000757 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
758 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
759 // The diagnostic options must be set before creating a CompilerInstance.
760 CI->getDiagnosticOpts().IgnoreWarnings = true;
761 // We reuse the preamble whether it's valid or not. This is a
762 // correctness/performance tradeoff: building without a preamble is slow, and
763 // completion is latency-sensitive.
764 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
765 // the remapped buffers do not get freed.
766 auto Clang = prepareCompilerInstance(
767 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
768 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000769 Clang->setCodeCompletionConsumer(Consumer.release());
770
771 SyntaxOnlyAction Action;
772 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000773 log("BeginSourceFile() failed when running codeComplete for " +
774 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000775 return false;
776 }
Eric Liu63f419a2018-05-15 15:29:32 +0000777 if (Includes) {
778 // Initialize Includes if provided.
779
780 // FIXME(ioeric): needs more consistent style support in clangd server.
781 auto Style = format::getStyle("file", Input.FileName, "LLVM",
782 Input.Contents, Input.VFS.get());
783 if (!Style) {
784 log("Failed to get FormatStyle for file" + Input.FileName +
785 ". Fall back to use LLVM style. Error: " +
786 llvm::toString(Style.takeError()));
787 Style = format::getLLVMStyle();
788 }
789 *Includes = llvm::make_unique<IncludeInserter>(
790 Input.FileName, Input.Contents, *Style, Input.Command.Directory,
791 Clang->getPreprocessor().getHeaderSearchInfo());
792 for (const auto &Inc : Input.PreambleInclusions)
793 Includes->get()->addExisting(Inc);
794 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
795 Clang->getSourceManager(), [Includes](Inclusion Inc) {
796 Includes->get()->addExisting(std::move(Inc));
797 }));
798 }
Sam McCall98775c52017-12-04 13:49:59 +0000799 if (!Action.Execute()) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000800 log("Execute() failed when running codeComplete for " + Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000801 return false;
802 }
Sam McCall98775c52017-12-04 13:49:59 +0000803 Action.EndSourceFile();
804
805 return true;
806}
807
Ilya Biryukova907ba42018-05-14 10:50:04 +0000808// Should we allow index completions in the specified context?
809bool allowIndex(CodeCompletionContext &CC) {
810 if (!contextAllowsIndex(CC.getKind()))
811 return false;
812 // We also avoid ClassName::bar (but allow namespace::bar).
813 auto Scope = CC.getCXXScopeSpecifier();
814 if (!Scope)
815 return true;
816 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
817 if (!NameSpec)
818 return true;
819 // We only query the index when qualifier is a namespace.
820 // If it's a class, we rely solely on sema completions.
821 switch (NameSpec->getKind()) {
822 case NestedNameSpecifier::Global:
823 case NestedNameSpecifier::Namespace:
824 case NestedNameSpecifier::NamespaceAlias:
825 return true;
826 case NestedNameSpecifier::Super:
827 case NestedNameSpecifier::TypeSpec:
828 case NestedNameSpecifier::TypeSpecWithTemplate:
829 // Unresolved inside a template.
830 case NestedNameSpecifier::Identifier:
831 return false;
832 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000833 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000834}
835
Sam McCall98775c52017-12-04 13:49:59 +0000836} // namespace
837
838clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
839 clang::CodeCompleteOptions Result;
840 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
841 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000842 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000843 // We choose to include full comments and not do doxygen parsing in
844 // completion.
845 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
846 // formatting of the comments.
847 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000848
Sam McCall3d139c52018-01-12 18:30:08 +0000849 // When an is used, Sema is responsible for completing the main file,
850 // the index can provide results from the preamble.
851 // Tell Sema not to deserialize the preamble to look for results.
852 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000853
Sam McCall98775c52017-12-04 13:49:59 +0000854 return Result;
855}
856
Sam McCall545a20d2018-01-19 14:34:02 +0000857// Runs Sema-based (AST) and Index-based completion, returns merged results.
858//
859// There are a few tricky considerations:
860// - the AST provides information needed for the index query (e.g. which
861// namespaces to search in). So Sema must start first.
862// - we only want to return the top results (Opts.Limit).
863// Building CompletionItems for everything else is wasteful, so we want to
864// preserve the "native" format until we're done with scoring.
865// - the data underlying Sema completion items is owned by the AST and various
866// other arenas, which must stay alive for us to build CompletionItems.
867// - we may get duplicate results from Sema and the Index, we need to merge.
868//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000869// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000870// We use the Sema context information to query the index.
871// Then we merge the two result sets, producing items that are Sema/Index/Both.
872// These items are scored, and the top N are synthesized into the LSP response.
873// Finally, we can clean up the data structures created by Sema completion.
874//
875// Main collaborators are:
876// - semaCodeComplete sets up the compiler machinery to run code completion.
877// - CompletionRecorder captures Sema completion results, including context.
878// - SymbolIndex (Opts.Index) provides index completion results as Symbols
879// - CompletionCandidates are the result of merging Sema and Index results.
880// Each candidate points to an underlying CodeCompletionResult (Sema), a
881// Symbol (Index), or both. It computes the result quality score.
882// CompletionCandidate also does conversion to CompletionItem (at the end).
883// - FuzzyMatcher scores how the candidate matches the partial identifier.
884// This score is combined with the result quality score for the final score.
885// - TopN determines the results with the best score.
886class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000887 PathRef FileName;
Sam McCall545a20d2018-01-19 14:34:02 +0000888 const CodeCompleteOptions &Opts;
889 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000890 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000891 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
892 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000893 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
894 std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000895
896public:
897 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Eric Liuc5105f92018-02-16 14:15:55 +0000898 CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000899 : FileName(FileName), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000900
901 CompletionList run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000902 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000903
Sam McCall545a20d2018-01-19 14:34:02 +0000904 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000905 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000906 // - partial identifier and context. We need these for the index query.
907 CompletionList Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000908 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
909 assert(Recorder && "Recorder is not set");
Eric Liu63f419a2018-05-15 15:29:32 +0000910 assert(Includes && "Includes is not set");
911 // If preprocessor was run, inclusions from preprocessor callback should
912 // already be added to Inclusions.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000913 Output = runWithSema();
Eric Liu63f419a2018-05-15 15:29:32 +0000914 Includes.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000915 SPAN_ATTACH(Tracer, "sema_completion_kind",
916 getCompletionKindString(Recorder->CCContext.getKind()));
917 });
918
919 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +0000920 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +0000921 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +0000922
Sam McCall2b780162018-01-30 17:20:54 +0000923 SPAN_ATTACH(Tracer, "sema_results", NSema);
924 SPAN_ATTACH(Tracer, "index_results", NIndex);
925 SPAN_ATTACH(Tracer, "merged_results", NBoth);
926 SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
927 SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
Sam McCalld1a7a372018-01-31 13:40:48 +0000928 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
Sam McCall545a20d2018-01-19 14:34:02 +0000929 "{2} matched, {3} returned{4}.",
930 NSema, NIndex, NBoth, Output.items.size(),
931 Output.isIncomplete ? " (incomplete)" : ""));
932 assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
933 // We don't assert that isIncomplete means we hit a limit.
934 // Indexes may choose to impose their own limits even if we don't have one.
935 return Output;
936 }
937
938private:
939 // This is called by run() once Sema code completion is done, but before the
940 // Sema data structures are torn down. It does all the real work.
941 CompletionList runWithSema() {
942 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000943 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Sam McCall545a20d2018-01-19 14:34:02 +0000944 // Sema provides the needed context to query the index.
945 // FIXME: in addition to querying for extra/overlapping symbols, we should
946 // explicitly request symbols corresponding to Sema results.
947 // We can use their signals even if the index can't suggest them.
948 // We must copy index results to preserve them, but there are at most Limit.
949 auto IndexResults = queryIndex();
950 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000951 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall545a20d2018-01-19 14:34:02 +0000952 // Convert the results to the desired LSP structs.
953 CompletionList Output;
954 for (auto &C : Top)
955 Output.items.push_back(toCompletionItem(C.first, C.second));
956 Output.isIncomplete = Incomplete;
957 return Output;
958 }
959
960 SymbolSlab queryIndex() {
Ilya Biryukova907ba42018-05-14 10:50:04 +0000961 if (!Opts.Index || !allowIndex(Recorder->CCContext))
Sam McCall545a20d2018-01-19 14:34:02 +0000962 return SymbolSlab();
Sam McCalld1a7a372018-01-31 13:40:48 +0000963 trace::Span Tracer("Query index");
Sam McCall2b780162018-01-30 17:20:54 +0000964 SPAN_ATTACH(Tracer, "limit", Opts.Limit);
965
Sam McCall545a20d2018-01-19 14:34:02 +0000966 SymbolSlab::Builder ResultsBuilder;
967 // Build the query.
968 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +0000969 if (Opts.Limit)
970 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +0000971 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +0000972 Req.RestrictForCodeCompletion = true;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000973 Req.Scopes = getQueryScopes(Recorder->CCContext,
974 Recorder->CCSema->getSourceManager());
Sam McCalld1a7a372018-01-31 13:40:48 +0000975 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
Sam McCall2b780162018-01-30 17:20:54 +0000976 Req.Query,
977 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Sam McCall545a20d2018-01-19 14:34:02 +0000978 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +0000979 if (Opts.Index->fuzzyFind(
980 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
981 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000982 return std::move(ResultsBuilder).build();
983 }
984
985 // Merges the Sema and Index results where possible, scores them, and
986 // returns the top results from best to worst.
987 std::vector<std::pair<CompletionCandidate, CompletionItemScores>>
988 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
989 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000990 trace::Span Tracer("Merge and score results");
Sam McCall545a20d2018-01-19 14:34:02 +0000991 // We only keep the best N results at any time, in "native" format.
Sam McCallc5707b62018-05-15 17:43:27 +0000992 TopN<ScoredCandidate, ScoredCandidateGreater> Top(
993 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +0000994 llvm::DenseSet<const Symbol *> UsedIndexResults;
995 auto CorrespondingIndexResult =
996 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
997 if (auto SymID = getSymbolID(SemaResult)) {
998 auto I = IndexResults.find(*SymID);
999 if (I != IndexResults.end()) {
1000 UsedIndexResults.insert(&*I);
1001 return &*I;
1002 }
1003 }
1004 return nullptr;
1005 };
1006 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001007 for (auto &SemaResult : Recorder->Results)
Sam McCall545a20d2018-01-19 14:34:02 +00001008 addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult));
1009 // Now emit any Index-only results.
1010 for (const auto &IndexResult : IndexResults) {
1011 if (UsedIndexResults.count(&IndexResult))
1012 continue;
1013 addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult);
1014 }
1015 return std::move(Top).items();
1016 }
1017
Sam McCall80ad7072018-06-08 13:32:25 +00001018 Optional<float> fuzzyScore(const CompletionCandidate &C) {
1019 // Macros can be very spammy, so we only support prefix completion.
1020 // We won't end up with underfull index results, as macros are sema-only.
1021 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1022 !C.Name.startswith_lower(Filter->pattern()))
1023 return None;
1024 return Filter->match(C.Name);
1025 }
1026
Sam McCall545a20d2018-01-19 14:34:02 +00001027 // Scores a candidate and adds it to the TopN structure.
Sam McCallc5707b62018-05-15 17:43:27 +00001028 void addCandidate(TopN<ScoredCandidate, ScoredCandidateGreater> &Candidates,
1029 const CodeCompletionResult *SemaResult,
Sam McCall545a20d2018-01-19 14:34:02 +00001030 const Symbol *IndexResult) {
1031 CompletionCandidate C;
1032 C.SemaResult = SemaResult;
1033 C.IndexResult = IndexResult;
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001034 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001035
Sam McCallc5707b62018-05-15 17:43:27 +00001036 SymbolQualitySignals Quality;
1037 SymbolRelevanceSignals Relevance;
Sam McCalld9b54f02018-06-05 16:30:25 +00001038 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Sam McCall80ad7072018-06-08 13:32:25 +00001039 if (auto FuzzyScore = fuzzyScore(C))
Sam McCallc5707b62018-05-15 17:43:27 +00001040 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001041 else
1042 return;
Sam McCalld9b54f02018-06-05 16:30:25 +00001043 if (IndexResult) {
Sam McCallc5707b62018-05-15 17:43:27 +00001044 Quality.merge(*IndexResult);
Sam McCalld9b54f02018-06-05 16:30:25 +00001045 Relevance.merge(*IndexResult);
1046 }
Sam McCallc5707b62018-05-15 17:43:27 +00001047 if (SemaResult) {
1048 Quality.merge(*SemaResult);
1049 Relevance.merge(*SemaResult);
1050 }
1051
1052 float QualScore = Quality.evaluate(), RelScore = Relevance.evaluate();
1053 CompletionItemScores Scores;
1054 Scores.finalScore = evaluateSymbolAndRelevance(QualScore, RelScore);
1055 // The purpose of exporting component scores is to allow NameMatch to be
1056 // replaced on the client-side. So we export (NameMatch, final/NameMatch)
1057 // rather than (RelScore, QualScore).
1058 Scores.filterScore = Relevance.NameMatch;
1059 Scores.symbolScore =
1060 Scores.filterScore ? Scores.finalScore / Scores.filterScore : QualScore;
1061
Nicola Zaghenc9fed132018-05-23 13:57:48 +00001062 LLVM_DEBUG(llvm::dbgs()
1063 << "CodeComplete: " << C.Name << (IndexResult ? " (index)" : "")
1064 << (SemaResult ? " (sema)" : "") << " = " << Scores.finalScore
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +00001065 << "\n"
Nicola Zaghenc9fed132018-05-23 13:57:48 +00001066 << Quality << Relevance << "\n");
Sam McCall545a20d2018-01-19 14:34:02 +00001067
1068 NSema += bool(SemaResult);
1069 NIndex += bool(IndexResult);
1070 NBoth += SemaResult && IndexResult;
Sam McCallab8e3932018-02-19 13:04:41 +00001071 if (Candidates.push({C, Scores}))
1072 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001073 }
1074
1075 CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
1076 const CompletionItemScores &Scores) {
1077 CodeCompletionString *SemaCCS = nullptr;
Ilya Biryukov43714502018-05-16 12:32:44 +00001078 std::string DocComment;
1079 if (auto *SR = Candidate.SemaResult) {
1080 SemaCCS = Recorder->codeCompletionString(*SR);
1081 if (Opts.IncludeComments) {
1082 assert(Recorder->CCSema);
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +00001083 DocComment = getDocComment(Recorder->CCSema->getASTContext(), *SR,
1084 /*CommentsFromHeader=*/false);
Ilya Biryukov43714502018-05-16 12:32:44 +00001085 }
1086 }
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +00001087 return Candidate.build(FileName, Scores, Opts, SemaCCS, Includes.get(),
1088 DocComment);
Sam McCall545a20d2018-01-19 14:34:02 +00001089 }
1090};
1091
Sam McCalld1a7a372018-01-31 13:40:48 +00001092CompletionList codeComplete(PathRef FileName,
Sam McCall98775c52017-12-04 13:49:59 +00001093 const tooling::CompileCommand &Command,
1094 PrecompiledPreamble const *Preamble,
Eric Liu63f419a2018-05-15 15:29:32 +00001095 const std::vector<Inclusion> &PreambleInclusions,
Sam McCall98775c52017-12-04 13:49:59 +00001096 StringRef Contents, Position Pos,
1097 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1098 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001099 CodeCompleteOptions Opts) {
Eric Liuc5105f92018-02-16 14:15:55 +00001100 return CodeCompleteFlow(FileName, Opts)
Eric Liu63f419a2018-05-15 15:29:32 +00001101 .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS,
1102 PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001103}
1104
Sam McCalld1a7a372018-01-31 13:40:48 +00001105SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001106 const tooling::CompileCommand &Command,
1107 PrecompiledPreamble const *Preamble,
1108 StringRef Contents, Position Pos,
1109 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1110 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001111 SignatureHelp Result;
1112 clang::CodeCompleteOptions Options;
1113 Options.IncludeGlobals = false;
1114 Options.IncludeMacros = false;
1115 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001116 Options.IncludeBriefComments = false;
Eric Liu4c0a27b2018-05-16 20:31:38 +00001117 std::vector<Inclusion> PreambleInclusions = {}; // Unused for signatureHelp
Sam McCalld1a7a372018-01-31 13:40:48 +00001118 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1119 Options,
Eric Liu4c0a27b2018-05-16 20:31:38 +00001120 {FileName, Command, Preamble, PreambleInclusions, Contents,
1121 Pos, std::move(VFS), std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001122 return Result;
1123}
1124
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001125bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1126 using namespace clang::ast_matchers;
1127 auto InTopLevelScope = hasDeclContext(
1128 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1129 return !match(decl(anyOf(InTopLevelScope,
1130 hasDeclContext(
1131 enumDecl(InTopLevelScope, unless(isScoped()))))),
1132 ND, ASTCtx)
1133 .empty();
1134}
1135
Sam McCall98775c52017-12-04 13:49:59 +00001136} // namespace clangd
1137} // namespace clang