blob: 7ec4671498a22e91c5e8b7ed45340d00c693b1ab [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"
Eric Liuc5105f92018-02-16 14:15:55 +000028#include "clang/Format/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000029#include "clang/Frontend/CompilerInstance.h"
30#include "clang/Frontend/FrontendActions.h"
Sam McCall545a20d2018-01-19 14:34:02 +000031#include "clang/Index/USRGeneration.h"
Sam McCall98775c52017-12-04 13:49:59 +000032#include "clang/Sema/CodeCompleteConsumer.h"
33#include "clang/Sema/Sema.h"
Eric Liuc5105f92018-02-16 14:15:55 +000034#include "clang/Tooling/Core/Replacement.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000035#include "llvm/Support/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000036#include <queue>
37
Sam McCallc5707b62018-05-15 17:43:27 +000038// We log detailed candidate here if you run with -debug-only=codecomplete.
39#define DEBUG_TYPE "codecomplete"
40
Sam McCall98775c52017-12-04 13:49:59 +000041namespace clang {
42namespace clangd {
43namespace {
44
Eric Liu6f648df2017-12-19 16:50:37 +000045CompletionItemKind toCompletionItemKind(CXCursorKind CursorKind) {
Sam McCall98775c52017-12-04 13:49:59 +000046 switch (CursorKind) {
47 case CXCursor_MacroInstantiation:
48 case CXCursor_MacroDefinition:
49 return CompletionItemKind::Text;
50 case CXCursor_CXXMethod:
Eric Liu6f648df2017-12-19 16:50:37 +000051 case CXCursor_Destructor:
Sam McCall98775c52017-12-04 13:49:59 +000052 return CompletionItemKind::Method;
53 case CXCursor_FunctionDecl:
54 case CXCursor_FunctionTemplate:
55 return CompletionItemKind::Function;
56 case CXCursor_Constructor:
Sam McCall98775c52017-12-04 13:49:59 +000057 return CompletionItemKind::Constructor;
58 case CXCursor_FieldDecl:
59 return CompletionItemKind::Field;
60 case CXCursor_VarDecl:
61 case CXCursor_ParmDecl:
62 return CompletionItemKind::Variable;
Eric Liu6f648df2017-12-19 16:50:37 +000063 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
64 // protocol.
Sam McCall98775c52017-12-04 13:49:59 +000065 case CXCursor_StructDecl:
Eric Liu6f648df2017-12-19 16:50:37 +000066 case CXCursor_ClassDecl:
Sam McCall98775c52017-12-04 13:49:59 +000067 case CXCursor_UnionDecl:
68 case CXCursor_ClassTemplate:
69 case CXCursor_ClassTemplatePartialSpecialization:
70 return CompletionItemKind::Class;
71 case CXCursor_Namespace:
72 case CXCursor_NamespaceAlias:
73 case CXCursor_NamespaceRef:
74 return CompletionItemKind::Module;
75 case CXCursor_EnumConstantDecl:
76 return CompletionItemKind::Value;
77 case CXCursor_EnumDecl:
78 return CompletionItemKind::Enum;
Eric Liu6f648df2017-12-19 16:50:37 +000079 // FIXME(ioeric): figure out whether reference is the right type for aliases.
Sam McCall98775c52017-12-04 13:49:59 +000080 case CXCursor_TypeAliasDecl:
81 case CXCursor_TypeAliasTemplateDecl:
82 case CXCursor_TypedefDecl:
83 case CXCursor_MemberRef:
84 case CXCursor_TypeRef:
85 return CompletionItemKind::Reference;
86 default:
87 return CompletionItemKind::Missing;
88 }
89}
90
Eric Liu6f648df2017-12-19 16:50:37 +000091CompletionItemKind
92toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
93 CXCursorKind CursorKind) {
Sam McCall98775c52017-12-04 13:49:59 +000094 switch (ResKind) {
95 case CodeCompletionResult::RK_Declaration:
Eric Liu6f648df2017-12-19 16:50:37 +000096 return toCompletionItemKind(CursorKind);
Sam McCall98775c52017-12-04 13:49:59 +000097 case CodeCompletionResult::RK_Keyword:
98 return CompletionItemKind::Keyword;
99 case CodeCompletionResult::RK_Macro:
100 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
101 // completion items in LSP.
102 case CodeCompletionResult::RK_Pattern:
103 return CompletionItemKind::Snippet;
104 }
105 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
106}
107
Eric Liu6f648df2017-12-19 16:50:37 +0000108CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
109 using SK = index::SymbolKind;
110 switch (Kind) {
111 case SK::Unknown:
112 return CompletionItemKind::Missing;
113 case SK::Module:
114 case SK::Namespace:
115 case SK::NamespaceAlias:
116 return CompletionItemKind::Module;
117 case SK::Macro:
118 return CompletionItemKind::Text;
119 case SK::Enum:
120 return CompletionItemKind::Enum;
121 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
122 // protocol.
123 case SK::Struct:
124 case SK::Class:
125 case SK::Protocol:
126 case SK::Extension:
127 case SK::Union:
128 return CompletionItemKind::Class;
129 // FIXME(ioeric): figure out whether reference is the right type for aliases.
130 case SK::TypeAlias:
131 case SK::Using:
132 return CompletionItemKind::Reference;
133 case SK::Function:
134 // FIXME(ioeric): this should probably be an operator. This should be fixed
135 // when `Operator` is support type in the protocol.
136 case SK::ConversionFunction:
137 return CompletionItemKind::Function;
138 case SK::Variable:
139 case SK::Parameter:
140 return CompletionItemKind::Variable;
141 case SK::Field:
142 return CompletionItemKind::Field;
143 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
144 case SK::EnumConstant:
145 return CompletionItemKind::Value;
146 case SK::InstanceMethod:
147 case SK::ClassMethod:
148 case SK::StaticMethod:
149 case SK::Destructor:
150 return CompletionItemKind::Method;
151 case SK::InstanceProperty:
152 case SK::ClassProperty:
153 case SK::StaticProperty:
154 return CompletionItemKind::Property;
155 case SK::Constructor:
156 return CompletionItemKind::Constructor;
157 }
158 llvm_unreachable("Unhandled clang::index::SymbolKind.");
159}
160
Sam McCall98775c52017-12-04 13:49:59 +0000161/// Get the optional chunk as a string. This function is possibly recursive.
162///
163/// The parameter info for each parameter is appended to the Parameters.
164std::string
165getOptionalParameters(const CodeCompletionString &CCS,
166 std::vector<ParameterInformation> &Parameters) {
167 std::string Result;
168 for (const auto &Chunk : CCS) {
169 switch (Chunk.Kind) {
170 case CodeCompletionString::CK_Optional:
171 assert(Chunk.Optional &&
172 "Expected the optional code completion string to be non-null.");
173 Result += getOptionalParameters(*Chunk.Optional, Parameters);
174 break;
175 case CodeCompletionString::CK_VerticalSpace:
176 break;
177 case CodeCompletionString::CK_Placeholder:
178 // A string that acts as a placeholder for, e.g., a function call
179 // argument.
180 // Intentional fallthrough here.
181 case CodeCompletionString::CK_CurrentParameter: {
182 // A piece of text that describes the parameter that corresponds to
183 // the code-completion location within a function call, message send,
184 // macro invocation, etc.
185 Result += Chunk.Text;
186 ParameterInformation Info;
187 Info.label = Chunk.Text;
188 Parameters.push_back(std::move(Info));
189 break;
190 }
191 default:
192 Result += Chunk.Text;
193 break;
194 }
195 }
196 return Result;
197}
198
Eric Liu63f419a2018-05-15 15:29:32 +0000199/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
200/// include.
201static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
202 llvm::StringRef HintPath) {
203 if (isLiteralInclude(Header))
204 return HeaderFile{Header.str(), /*Verbatim=*/true};
205 auto U = URI::parse(Header);
206 if (!U)
207 return U.takeError();
208
209 auto IncludePath = URI::includeSpelling(*U);
210 if (!IncludePath)
211 return IncludePath.takeError();
212 if (!IncludePath->empty())
213 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
214
215 auto Resolved = URI::resolve(*U, HintPath);
216 if (!Resolved)
217 return Resolved.takeError();
218 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
219}
220
Sam McCall545a20d2018-01-19 14:34:02 +0000221/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000222/// It may be promoted to a CompletionItem if it's among the top-ranked results.
223struct CompletionCandidate {
Sam McCall545a20d2018-01-19 14:34:02 +0000224 llvm::StringRef Name; // Used for filtering and sorting.
225 // We may have a result from Sema, from the index, or both.
226 const CodeCompletionResult *SemaResult = nullptr;
227 const Symbol *IndexResult = nullptr;
Sam McCall98775c52017-12-04 13:49:59 +0000228
Sam McCall545a20d2018-01-19 14:34:02 +0000229 // Builds an LSP completion item.
Eric Liu63f419a2018-05-15 15:29:32 +0000230 CompletionItem build(StringRef FileName, const CompletionItemScores &Scores,
Sam McCall545a20d2018-01-19 14:34:02 +0000231 const CodeCompleteOptions &Opts,
Eric Liu63f419a2018-05-15 15:29:32 +0000232 CodeCompletionString *SemaCCS,
233 const IncludeInserter *Includes) const {
Sam McCall545a20d2018-01-19 14:34:02 +0000234 assert(bool(SemaResult) == bool(SemaCCS));
235 CompletionItem I;
236 if (SemaResult) {
237 I.kind = toCompletionItemKind(SemaResult->Kind, SemaResult->CursorKind);
238 getLabelAndInsertText(*SemaCCS, &I.label, &I.insertText,
239 Opts.EnableSnippets);
240 I.filterText = getFilterText(*SemaCCS);
241 I.documentation = getDocumentation(*SemaCCS);
242 I.detail = getDetail(*SemaCCS);
243 }
244 if (IndexResult) {
245 if (I.kind == CompletionItemKind::Missing)
246 I.kind = toCompletionItemKind(IndexResult->SymInfo.Kind);
247 // FIXME: reintroduce a way to show the index source for debugging.
248 if (I.label.empty())
249 I.label = IndexResult->CompletionLabel;
250 if (I.filterText.empty())
251 I.filterText = IndexResult->Name;
Sam McCall98775c52017-12-04 13:49:59 +0000252
Sam McCall545a20d2018-01-19 14:34:02 +0000253 // FIXME(ioeric): support inserting/replacing scope qualifiers.
254 if (I.insertText.empty())
255 I.insertText = Opts.EnableSnippets
256 ? IndexResult->CompletionSnippetInsertText
257 : IndexResult->CompletionPlainInsertText;
258
259 if (auto *D = IndexResult->Detail) {
260 if (I.documentation.empty())
261 I.documentation = D->Documentation;
262 if (I.detail.empty())
263 I.detail = D->CompletionDetail;
Eric Liu63f419a2018-05-15 15:29:32 +0000264 if (Includes && !D->IncludeHeader.empty()) {
265 auto Edit = [&]() -> Expected<Optional<TextEdit>> {
266 auto ResolvedDeclaring = toHeaderFile(
267 IndexResult->CanonicalDeclaration.FileURI, FileName);
268 if (!ResolvedDeclaring)
269 return ResolvedDeclaring.takeError();
270 auto ResolvedInserted = toHeaderFile(D->IncludeHeader, FileName);
271 if (!ResolvedInserted)
272 return ResolvedInserted.takeError();
273 return Includes->insert(*ResolvedDeclaring, *ResolvedInserted);
274 }();
275 if (!Edit) {
276 std::string ErrMsg =
277 ("Failed to generate include insertion edits for adding header "
278 "(FileURI=\"" +
279 IndexResult->CanonicalDeclaration.FileURI +
280 "\", IncludeHeader=\"" + D->IncludeHeader + "\") into " +
281 FileName)
282 .str();
283 log(ErrMsg + ":" + llvm::toString(Edit.takeError()));
284 } else if (*Edit) {
285 I.additionalTextEdits = {std::move(**Edit)};
286 }
287 }
Sam McCall545a20d2018-01-19 14:34:02 +0000288 }
289 }
290 I.scoreInfo = Scores;
291 I.sortText = sortText(Scores.finalScore, Name);
292 I.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
293 : InsertTextFormat::PlainText;
294 return I;
Sam McCall98775c52017-12-04 13:49:59 +0000295 }
296};
Sam McCallc5707b62018-05-15 17:43:27 +0000297using ScoredCandidate = std::pair<CompletionCandidate, CompletionItemScores>;
Sam McCall98775c52017-12-04 13:49:59 +0000298
Sam McCall545a20d2018-01-19 14:34:02 +0000299// Determine the symbol ID for a Sema code completion result, if possible.
300llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
301 switch (R.Kind) {
302 case CodeCompletionResult::RK_Declaration:
303 case CodeCompletionResult::RK_Pattern: {
304 llvm::SmallString<128> USR;
305 if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
306 return None;
307 return SymbolID(USR);
308 }
309 case CodeCompletionResult::RK_Macro:
310 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
311 case CodeCompletionResult::RK_Keyword:
312 return None;
313 }
314 llvm_unreachable("unknown CodeCompletionResult kind");
315}
316
Haojian Wu061c73e2018-01-23 11:37:26 +0000317// Scopes of the paritial identifier we're trying to complete.
318// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000319struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000320 // The scopes we should look in, determined by Sema.
321 //
322 // If the qualifier was fully resolved, we look for completions in these
323 // scopes; if there is an unresolved part of the qualifier, it should be
324 // resolved within these scopes.
325 //
326 // Examples of qualified completion:
327 //
328 // "::vec" => {""}
329 // "using namespace std; ::vec^" => {"", "std::"}
330 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
331 // "std::vec^" => {""} // "std" unresolved
332 //
333 // Examples of unqualified completion:
334 //
335 // "vec^" => {""}
336 // "using namespace std; vec^" => {"", "std::"}
337 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
338 //
339 // "" for global namespace, "ns::" for normal namespace.
340 std::vector<std::string> AccessibleScopes;
341 // The full scope qualifier as typed by the user (without the leading "::").
342 // Set if the qualifier is not fully resolved by Sema.
343 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000344
Haojian Wu061c73e2018-01-23 11:37:26 +0000345 // Construct scopes being queried in indexes.
346 // This method format the scopes to match the index request representation.
347 std::vector<std::string> scopesForIndexQuery() {
348 std::vector<std::string> Results;
349 for (llvm::StringRef AS : AccessibleScopes) {
350 Results.push_back(AS);
351 if (UnresolvedQualifier)
352 Results.back() += *UnresolvedQualifier;
353 }
354 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000355 }
Eric Liu6f648df2017-12-19 16:50:37 +0000356};
357
Haojian Wu061c73e2018-01-23 11:37:26 +0000358// Get all scopes that will be queried in indexes.
359std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
360 const SourceManager& SM) {
361 auto GetAllAccessibleScopes = [](CodeCompletionContext& CCContext) {
362 SpecifiedScope Info;
363 for (auto* Context : CCContext.getVisitedContexts()) {
364 if (isa<TranslationUnitDecl>(Context))
365 Info.AccessibleScopes.push_back(""); // global namespace
366 else if (const auto*NS = dyn_cast<NamespaceDecl>(Context))
367 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
368 }
369 return Info;
370 };
371
372 auto SS = CCContext.getCXXScopeSpecifier();
373
374 // Unqualified completion (e.g. "vec^").
375 if (!SS) {
376 // FIXME: Once we can insert namespace qualifiers and use the in-scope
377 // namespaces for scoring, search in all namespaces.
378 // FIXME: Capture scopes and use for scoring, for example,
379 // "using namespace std; namespace foo {v^}" =>
380 // foo::value > std::vector > boost::variant
381 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
382 }
383
384 // Qualified completion ("std::vec^"), we have two cases depending on whether
385 // the qualifier can be resolved by Sema.
386 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000387 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
388 }
389
390 // Unresolved qualifier.
391 // FIXME: When Sema can resolve part of a scope chain (e.g.
392 // "known::unknown::id"), we should expand the known part ("known::") rather
393 // than treating the whole thing as unknown.
394 SpecifiedScope Info;
395 Info.AccessibleScopes.push_back(""); // global namespace
396
397 Info.UnresolvedQualifier =
398 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()),
399 SM, clang::LangOptions()).ltrim("::");
400 // Sema excludes the trailing "::".
401 if (!Info.UnresolvedQualifier->empty())
402 *Info.UnresolvedQualifier += "::";
403
404 return Info.scopesForIndexQuery();
405}
406
Sam McCall545a20d2018-01-19 14:34:02 +0000407// The CompletionRecorder captures Sema code-complete output, including context.
408// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
409// It doesn't do scoring or conversion to CompletionItem yet, as we want to
410// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000411// Generally the fields and methods of this object should only be used from
412// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000413struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000414 CompletionRecorder(const CodeCompleteOptions &Opts,
415 UniqueFunction<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000416 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000417 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000418 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
419 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000420 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
421 assert(this->ResultsCallback);
422 }
423
Sam McCall545a20d2018-01-19 14:34:02 +0000424 std::vector<CodeCompletionResult> Results;
425 CodeCompletionContext CCContext;
426 Sema *CCSema = nullptr; // Sema that created the results.
427 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000428
Sam McCall545a20d2018-01-19 14:34:02 +0000429 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
430 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000431 unsigned NumResults) override final {
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000432 if (CCSema) {
433 log(llvm::formatv(
434 "Multiple code complete callbacks (parser backtracked?). "
435 "Dropping results from context {0}, keeping results from {1}.",
436 getCompletionKindString(this->CCContext.getKind()),
437 getCompletionKindString(Context.getKind())));
438 return;
439 }
Sam McCall545a20d2018-01-19 14:34:02 +0000440 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000441 CCSema = &S;
442 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000443
Sam McCall545a20d2018-01-19 14:34:02 +0000444 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000445 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000446 auto &Result = InResults[I];
447 // Drop hidden items which cannot be found by lookup after completion.
448 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000449 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
450 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000451 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000452 (Result.Availability == CXAvailability_NotAvailable ||
453 Result.Availability == CXAvailability_NotAccessible))
454 continue;
Sam McCalld2a95922018-01-22 21:05:00 +0000455 // Destructor completion is rarely useful, and works inconsistently.
456 // (s.^ completes ~string, but s.~st^ is an error).
457 if (dyn_cast_or_null<CXXDestructorDecl>(Result.Declaration))
458 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000459 // We choose to never append '::' to completion results in clangd.
460 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000461 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000462 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000463 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000464 }
465
Sam McCall545a20d2018-01-19 14:34:02 +0000466 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000467 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
468
Sam McCall545a20d2018-01-19 14:34:02 +0000469 // Returns the filtering/sorting name for Result, which must be from Results.
470 // Returned string is owned by this recorder (or the AST).
471 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000472 switch (Result.Kind) {
473 case CodeCompletionResult::RK_Declaration:
474 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000475 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000476 break;
477 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000478 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000479 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000480 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000481 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000482 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000483 }
Sam McCall545a20d2018-01-19 14:34:02 +0000484 auto *CCS = codeCompletionString(Result, /*IncludeBriefComments=*/false);
485 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000486 }
487
Sam McCall545a20d2018-01-19 14:34:02 +0000488 // Build a CodeCompletion string for R, which must be from Results.
489 // The CCS will be owned by this recorder.
490 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R,
491 bool IncludeBriefComments) {
492 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
493 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
494 *CCSema, CCContext, *CCAllocator, CCTUInfo, IncludeBriefComments);
Sam McCall98775c52017-12-04 13:49:59 +0000495 }
496
Sam McCall545a20d2018-01-19 14:34:02 +0000497private:
498 CodeCompleteOptions Opts;
499 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000500 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000501 UniqueFunction<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000502};
503
Sam McCallc5707b62018-05-15 17:43:27 +0000504struct ScoredCandidateGreater {
505 bool operator()(const ScoredCandidate &L, const ScoredCandidate &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000506 if (L.second.finalScore != R.second.finalScore)
507 return L.second.finalScore > R.second.finalScore;
508 return L.first.Name < R.first.Name; // Earlier name is better.
509 }
Sam McCall545a20d2018-01-19 14:34:02 +0000510};
Sam McCall98775c52017-12-04 13:49:59 +0000511
Sam McCall98775c52017-12-04 13:49:59 +0000512class SignatureHelpCollector final : public CodeCompleteConsumer {
513
514public:
515 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
516 SignatureHelp &SigHelp)
517 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
518 SigHelp(SigHelp),
519 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
520 CCTUInfo(Allocator) {}
521
522 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
523 OverloadCandidate *Candidates,
524 unsigned NumCandidates) override {
525 SigHelp.signatures.reserve(NumCandidates);
526 // FIXME(rwols): How can we determine the "active overload candidate"?
527 // Right now the overloaded candidates seem to be provided in a "best fit"
528 // order, so I'm not too worried about this.
529 SigHelp.activeSignature = 0;
530 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
531 "too many arguments");
532 SigHelp.activeParameter = static_cast<int>(CurrentArg);
533 for (unsigned I = 0; I < NumCandidates; ++I) {
534 const auto &Candidate = Candidates[I];
535 const auto *CCS = Candidate.CreateSignatureString(
536 CurrentArg, S, *Allocator, CCTUInfo, true);
537 assert(CCS && "Expected the CodeCompletionString to be non-null");
538 SigHelp.signatures.push_back(ProcessOverloadCandidate(Candidate, *CCS));
539 }
540 }
541
542 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
543
544 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
545
546private:
Eric Liu63696e12017-12-20 17:24:31 +0000547 // FIXME(ioeric): consider moving CodeCompletionString logic here to
548 // CompletionString.h.
Sam McCall98775c52017-12-04 13:49:59 +0000549 SignatureInformation
550 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
551 const CodeCompletionString &CCS) const {
552 SignatureInformation Result;
553 const char *ReturnType = nullptr;
554
555 Result.documentation = getDocumentation(CCS);
556
557 for (const auto &Chunk : CCS) {
558 switch (Chunk.Kind) {
559 case CodeCompletionString::CK_ResultType:
560 // A piece of text that describes the type of an entity or,
561 // for functions and methods, the return type.
562 assert(!ReturnType && "Unexpected CK_ResultType");
563 ReturnType = Chunk.Text;
564 break;
565 case CodeCompletionString::CK_Placeholder:
566 // A string that acts as a placeholder for, e.g., a function call
567 // argument.
568 // Intentional fallthrough here.
569 case CodeCompletionString::CK_CurrentParameter: {
570 // A piece of text that describes the parameter that corresponds to
571 // the code-completion location within a function call, message send,
572 // macro invocation, etc.
573 Result.label += Chunk.Text;
574 ParameterInformation Info;
575 Info.label = Chunk.Text;
576 Result.parameters.push_back(std::move(Info));
577 break;
578 }
579 case CodeCompletionString::CK_Optional: {
580 // The rest of the parameters are defaulted/optional.
581 assert(Chunk.Optional &&
582 "Expected the optional code completion string to be non-null.");
583 Result.label +=
584 getOptionalParameters(*Chunk.Optional, Result.parameters);
585 break;
586 }
587 case CodeCompletionString::CK_VerticalSpace:
588 break;
589 default:
590 Result.label += Chunk.Text;
591 break;
592 }
593 }
594 if (ReturnType) {
595 Result.label += " -> ";
596 Result.label += ReturnType;
597 }
598 return Result;
599 }
600
601 SignatureHelp &SigHelp;
602 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
603 CodeCompletionTUInfo CCTUInfo;
604
605}; // SignatureHelpCollector
606
Sam McCall545a20d2018-01-19 14:34:02 +0000607struct SemaCompleteInput {
608 PathRef FileName;
609 const tooling::CompileCommand &Command;
610 PrecompiledPreamble const *Preamble;
Eric Liu63f419a2018-05-15 15:29:32 +0000611 const std::vector<Inclusion> &PreambleInclusions;
Sam McCall545a20d2018-01-19 14:34:02 +0000612 StringRef Contents;
613 Position Pos;
614 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
615 std::shared_ptr<PCHContainerOperations> PCHs;
616};
617
618// Invokes Sema code completion on a file.
Eric Liu63f419a2018-05-15 15:29:32 +0000619// If \p Includes is set, it will be initialized after a compiler instance has
620// been set up.
Sam McCalld1a7a372018-01-31 13:40:48 +0000621bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000622 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000623 const SemaCompleteInput &Input,
624 std::unique_ptr<IncludeInserter> *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000625 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000626 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000627 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000628 ArgStrs.push_back(S.c_str());
629
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000630 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
631 log("Couldn't set working directory");
632 // We run parsing anyway, our lit-tests rely on results for non-existing
633 // working dirs.
634 }
Sam McCall98775c52017-12-04 13:49:59 +0000635
636 IgnoreDiagnostics DummyDiagsConsumer;
637 auto CI = createInvocationFromCommandLine(
638 ArgStrs,
639 CompilerInstance::createDiagnostics(new DiagnosticOptions,
640 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000641 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000642 if (!CI) {
643 log("Couldn't create CompilerInvocation");;
644 return false;
645 }
Ilya Biryukov71590652018-01-05 13:36:55 +0000646 CI->getFrontendOpts().DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000647
648 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
Sam McCall545a20d2018-01-19 14:34:02 +0000649 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000650
Ilya Biryukov295c8e12018-01-18 15:17:00 +0000651 // We reuse the preamble whether it's valid or not. This is a
652 // correctness/performance tradeoff: building without a preamble is slow, and
653 // completion is latency-sensitive.
Sam McCall545a20d2018-01-19 14:34:02 +0000654 if (Input.Preamble) {
Sam McCall98775c52017-12-04 13:49:59 +0000655 auto Bounds =
656 ComputePreambleBounds(*CI->getLangOpts(), ContentsBuffer.get(), 0);
Ilya Biryukov295c8e12018-01-18 15:17:00 +0000657 // FIXME(ibiryukov): Remove this call to CanReuse() after we'll fix
658 // clients relying on getting stats for preamble files during code
659 // completion.
660 // Note that results of CanReuse() are ignored, see the comment above.
Sam McCall545a20d2018-01-19 14:34:02 +0000661 Input.Preamble->CanReuse(*CI, ContentsBuffer.get(), Bounds,
662 Input.VFS.get());
Sam McCall98775c52017-12-04 13:49:59 +0000663 }
Haojian Wub603a5e2018-02-22 13:35:01 +0000664 // The diagnostic options must be set before creating a CompilerInstance.
665 CI->getDiagnosticOpts().IgnoreWarnings = true;
Sam McCall98775c52017-12-04 13:49:59 +0000666 auto Clang = prepareCompilerInstance(
Sam McCall545a20d2018-01-19 14:34:02 +0000667 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
668 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000669
Haojian Wu58d208d2018-01-25 09:44:06 +0000670 // Disable typo correction in Sema.
671 Clang->getLangOpts().SpellChecking = false;
672
Sam McCall98775c52017-12-04 13:49:59 +0000673 auto &FrontendOpts = Clang->getFrontendOpts();
674 FrontendOpts.SkipFunctionBodies = true;
675 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000676 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000677 auto Offset = positionToOffset(Input.Contents, Input.Pos);
678 if (!Offset) {
679 log("Code completion position was invalid " +
680 llvm::toString(Offset.takeError()));
681 return false;
682 }
683 std::tie(FrontendOpts.CodeCompletionAt.Line,
684 FrontendOpts.CodeCompletionAt.Column) =
685 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000686
687 Clang->setCodeCompletionConsumer(Consumer.release());
688
689 SyntaxOnlyAction Action;
690 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000691 log("BeginSourceFile() failed when running codeComplete for " +
692 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000693 return false;
694 }
Eric Liu63f419a2018-05-15 15:29:32 +0000695 if (Includes) {
696 // Initialize Includes if provided.
697
698 // FIXME(ioeric): needs more consistent style support in clangd server.
699 auto Style = format::getStyle("file", Input.FileName, "LLVM",
700 Input.Contents, Input.VFS.get());
701 if (!Style) {
702 log("Failed to get FormatStyle for file" + Input.FileName +
703 ". Fall back to use LLVM style. Error: " +
704 llvm::toString(Style.takeError()));
705 Style = format::getLLVMStyle();
706 }
707 *Includes = llvm::make_unique<IncludeInserter>(
708 Input.FileName, Input.Contents, *Style, Input.Command.Directory,
709 Clang->getPreprocessor().getHeaderSearchInfo());
710 for (const auto &Inc : Input.PreambleInclusions)
711 Includes->get()->addExisting(Inc);
712 Clang->getPreprocessor().addPPCallbacks(collectInclusionsInMainFileCallback(
713 Clang->getSourceManager(), [Includes](Inclusion Inc) {
714 Includes->get()->addExisting(std::move(Inc));
715 }));
716 }
Sam McCall98775c52017-12-04 13:49:59 +0000717 if (!Action.Execute()) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000718 log("Execute() failed when running codeComplete for " + Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000719 return false;
720 }
Sam McCall98775c52017-12-04 13:49:59 +0000721 Action.EndSourceFile();
722
723 return true;
724}
725
Ilya Biryukova907ba42018-05-14 10:50:04 +0000726// Should we perform index-based completion in a context of the specified kind?
Sam McCall545a20d2018-01-19 14:34:02 +0000727// FIXME: consider allowing completion, but restricting the result types.
Ilya Biryukova907ba42018-05-14 10:50:04 +0000728bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
Sam McCall545a20d2018-01-19 14:34:02 +0000729 switch (K) {
730 case CodeCompletionContext::CCC_TopLevel:
731 case CodeCompletionContext::CCC_ObjCInterface:
732 case CodeCompletionContext::CCC_ObjCImplementation:
733 case CodeCompletionContext::CCC_ObjCIvarList:
734 case CodeCompletionContext::CCC_ClassStructUnion:
735 case CodeCompletionContext::CCC_Statement:
736 case CodeCompletionContext::CCC_Expression:
737 case CodeCompletionContext::CCC_ObjCMessageReceiver:
738 case CodeCompletionContext::CCC_EnumTag:
739 case CodeCompletionContext::CCC_UnionTag:
740 case CodeCompletionContext::CCC_ClassOrStructTag:
741 case CodeCompletionContext::CCC_ObjCProtocolName:
742 case CodeCompletionContext::CCC_Namespace:
743 case CodeCompletionContext::CCC_Type:
744 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
745 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
746 case CodeCompletionContext::CCC_ParenthesizedExpression:
747 case CodeCompletionContext::CCC_ObjCInterfaceName:
748 case CodeCompletionContext::CCC_ObjCCategoryName:
749 return true;
750 case CodeCompletionContext::CCC_Other: // Be conservative.
751 case CodeCompletionContext::CCC_OtherWithMacros:
752 case CodeCompletionContext::CCC_DotMemberAccess:
753 case CodeCompletionContext::CCC_ArrowMemberAccess:
754 case CodeCompletionContext::CCC_ObjCPropertyAccess:
755 case CodeCompletionContext::CCC_MacroName:
756 case CodeCompletionContext::CCC_MacroNameUse:
757 case CodeCompletionContext::CCC_PreprocessorExpression:
758 case CodeCompletionContext::CCC_PreprocessorDirective:
759 case CodeCompletionContext::CCC_NaturalLanguage:
760 case CodeCompletionContext::CCC_SelectorName:
761 case CodeCompletionContext::CCC_TypeQualifiers:
762 case CodeCompletionContext::CCC_ObjCInstanceMessage:
763 case CodeCompletionContext::CCC_ObjCClassMessage:
764 case CodeCompletionContext::CCC_Recovery:
765 return false;
766 }
767 llvm_unreachable("unknown code completion context");
768}
769
Ilya Biryukova907ba42018-05-14 10:50:04 +0000770// Should we allow index completions in the specified context?
771bool allowIndex(CodeCompletionContext &CC) {
772 if (!contextAllowsIndex(CC.getKind()))
773 return false;
774 // We also avoid ClassName::bar (but allow namespace::bar).
775 auto Scope = CC.getCXXScopeSpecifier();
776 if (!Scope)
777 return true;
778 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
779 if (!NameSpec)
780 return true;
781 // We only query the index when qualifier is a namespace.
782 // If it's a class, we rely solely on sema completions.
783 switch (NameSpec->getKind()) {
784 case NestedNameSpecifier::Global:
785 case NestedNameSpecifier::Namespace:
786 case NestedNameSpecifier::NamespaceAlias:
787 return true;
788 case NestedNameSpecifier::Super:
789 case NestedNameSpecifier::TypeSpec:
790 case NestedNameSpecifier::TypeSpecWithTemplate:
791 // Unresolved inside a template.
792 case NestedNameSpecifier::Identifier:
793 return false;
794 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000795 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000796}
797
Sam McCall98775c52017-12-04 13:49:59 +0000798} // namespace
799
800clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
801 clang::CodeCompleteOptions Result;
802 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
803 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000804 Result.IncludeGlobals = true;
Sam McCall98775c52017-12-04 13:49:59 +0000805 Result.IncludeBriefComments = IncludeBriefComments;
806
Sam McCall3d139c52018-01-12 18:30:08 +0000807 // When an is used, Sema is responsible for completing the main file,
808 // the index can provide results from the preamble.
809 // Tell Sema not to deserialize the preamble to look for results.
810 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000811
Sam McCall98775c52017-12-04 13:49:59 +0000812 return Result;
813}
814
Sam McCall545a20d2018-01-19 14:34:02 +0000815// Runs Sema-based (AST) and Index-based completion, returns merged results.
816//
817// There are a few tricky considerations:
818// - the AST provides information needed for the index query (e.g. which
819// namespaces to search in). So Sema must start first.
820// - we only want to return the top results (Opts.Limit).
821// Building CompletionItems for everything else is wasteful, so we want to
822// preserve the "native" format until we're done with scoring.
823// - the data underlying Sema completion items is owned by the AST and various
824// other arenas, which must stay alive for us to build CompletionItems.
825// - we may get duplicate results from Sema and the Index, we need to merge.
826//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000827// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000828// We use the Sema context information to query the index.
829// Then we merge the two result sets, producing items that are Sema/Index/Both.
830// These items are scored, and the top N are synthesized into the LSP response.
831// Finally, we can clean up the data structures created by Sema completion.
832//
833// Main collaborators are:
834// - semaCodeComplete sets up the compiler machinery to run code completion.
835// - CompletionRecorder captures Sema completion results, including context.
836// - SymbolIndex (Opts.Index) provides index completion results as Symbols
837// - CompletionCandidates are the result of merging Sema and Index results.
838// Each candidate points to an underlying CodeCompletionResult (Sema), a
839// Symbol (Index), or both. It computes the result quality score.
840// CompletionCandidate also does conversion to CompletionItem (at the end).
841// - FuzzyMatcher scores how the candidate matches the partial identifier.
842// This score is combined with the result quality score for the final score.
843// - TopN determines the results with the best score.
844class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000845 PathRef FileName;
Sam McCall545a20d2018-01-19 14:34:02 +0000846 const CodeCompleteOptions &Opts;
847 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000848 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000849 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
850 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000851 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
852 std::unique_ptr<IncludeInserter> Includes; // Initialized once compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000853
854public:
855 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Eric Liuc5105f92018-02-16 14:15:55 +0000856 CodeCompleteFlow(PathRef FileName, const CodeCompleteOptions &Opts)
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000857 : FileName(FileName), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000858
859 CompletionList run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000860 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000861
Sam McCall545a20d2018-01-19 14:34:02 +0000862 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000863 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000864 // - partial identifier and context. We need these for the index query.
865 CompletionList Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000866 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
867 assert(Recorder && "Recorder is not set");
Eric Liu63f419a2018-05-15 15:29:32 +0000868 assert(Includes && "Includes is not set");
869 // If preprocessor was run, inclusions from preprocessor callback should
870 // already be added to Inclusions.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000871 Output = runWithSema();
Eric Liu63f419a2018-05-15 15:29:32 +0000872 Includes.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000873 SPAN_ATTACH(Tracer, "sema_completion_kind",
874 getCompletionKindString(Recorder->CCContext.getKind()));
875 });
876
877 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +0000878 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +0000879 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +0000880
Sam McCall2b780162018-01-30 17:20:54 +0000881 SPAN_ATTACH(Tracer, "sema_results", NSema);
882 SPAN_ATTACH(Tracer, "index_results", NIndex);
883 SPAN_ATTACH(Tracer, "merged_results", NBoth);
884 SPAN_ATTACH(Tracer, "returned_results", Output.items.size());
885 SPAN_ATTACH(Tracer, "incomplete", Output.isIncomplete);
Sam McCalld1a7a372018-01-31 13:40:48 +0000886 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
Sam McCall545a20d2018-01-19 14:34:02 +0000887 "{2} matched, {3} returned{4}.",
888 NSema, NIndex, NBoth, Output.items.size(),
889 Output.isIncomplete ? " (incomplete)" : ""));
890 assert(!Opts.Limit || Output.items.size() <= Opts.Limit);
891 // We don't assert that isIncomplete means we hit a limit.
892 // Indexes may choose to impose their own limits even if we don't have one.
893 return Output;
894 }
895
896private:
897 // This is called by run() once Sema code completion is done, but before the
898 // Sema data structures are torn down. It does all the real work.
899 CompletionList runWithSema() {
900 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000901 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Sam McCall545a20d2018-01-19 14:34:02 +0000902 // Sema provides the needed context to query the index.
903 // FIXME: in addition to querying for extra/overlapping symbols, we should
904 // explicitly request symbols corresponding to Sema results.
905 // We can use their signals even if the index can't suggest them.
906 // We must copy index results to preserve them, but there are at most Limit.
907 auto IndexResults = queryIndex();
908 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000909 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall545a20d2018-01-19 14:34:02 +0000910 // Convert the results to the desired LSP structs.
911 CompletionList Output;
912 for (auto &C : Top)
913 Output.items.push_back(toCompletionItem(C.first, C.second));
914 Output.isIncomplete = Incomplete;
915 return Output;
916 }
917
918 SymbolSlab queryIndex() {
Ilya Biryukova907ba42018-05-14 10:50:04 +0000919 if (!Opts.Index || !allowIndex(Recorder->CCContext))
Sam McCall545a20d2018-01-19 14:34:02 +0000920 return SymbolSlab();
Sam McCalld1a7a372018-01-31 13:40:48 +0000921 trace::Span Tracer("Query index");
Sam McCall2b780162018-01-30 17:20:54 +0000922 SPAN_ATTACH(Tracer, "limit", Opts.Limit);
923
Sam McCall545a20d2018-01-19 14:34:02 +0000924 SymbolSlab::Builder ResultsBuilder;
925 // Build the query.
926 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +0000927 if (Opts.Limit)
928 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +0000929 Req.Query = Filter->pattern();
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000930 Req.Scopes = getQueryScopes(Recorder->CCContext,
931 Recorder->CCSema->getSourceManager());
Sam McCalld1a7a372018-01-31 13:40:48 +0000932 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
Sam McCall2b780162018-01-30 17:20:54 +0000933 Req.Query,
934 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Sam McCall545a20d2018-01-19 14:34:02 +0000935 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +0000936 if (Opts.Index->fuzzyFind(
937 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
938 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +0000939 return std::move(ResultsBuilder).build();
940 }
941
942 // Merges the Sema and Index results where possible, scores them, and
943 // returns the top results from best to worst.
944 std::vector<std::pair<CompletionCandidate, CompletionItemScores>>
945 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
946 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000947 trace::Span Tracer("Merge and score results");
Sam McCall545a20d2018-01-19 14:34:02 +0000948 // We only keep the best N results at any time, in "native" format.
Sam McCallc5707b62018-05-15 17:43:27 +0000949 TopN<ScoredCandidate, ScoredCandidateGreater> Top(
950 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +0000951 llvm::DenseSet<const Symbol *> UsedIndexResults;
952 auto CorrespondingIndexResult =
953 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
954 if (auto SymID = getSymbolID(SemaResult)) {
955 auto I = IndexResults.find(*SymID);
956 if (I != IndexResults.end()) {
957 UsedIndexResults.insert(&*I);
958 return &*I;
959 }
960 }
961 return nullptr;
962 };
963 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000964 for (auto &SemaResult : Recorder->Results)
Sam McCall545a20d2018-01-19 14:34:02 +0000965 addCandidate(Top, &SemaResult, CorrespondingIndexResult(SemaResult));
966 // Now emit any Index-only results.
967 for (const auto &IndexResult : IndexResults) {
968 if (UsedIndexResults.count(&IndexResult))
969 continue;
970 addCandidate(Top, /*SemaResult=*/nullptr, &IndexResult);
971 }
972 return std::move(Top).items();
973 }
974
975 // Scores a candidate and adds it to the TopN structure.
Sam McCallc5707b62018-05-15 17:43:27 +0000976 void addCandidate(TopN<ScoredCandidate, ScoredCandidateGreater> &Candidates,
977 const CodeCompletionResult *SemaResult,
Sam McCall545a20d2018-01-19 14:34:02 +0000978 const Symbol *IndexResult) {
979 CompletionCandidate C;
980 C.SemaResult = SemaResult;
981 C.IndexResult = IndexResult;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000982 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
Sam McCall545a20d2018-01-19 14:34:02 +0000983
Sam McCallc5707b62018-05-15 17:43:27 +0000984 SymbolQualitySignals Quality;
985 SymbolRelevanceSignals Relevance;
Sam McCall545a20d2018-01-19 14:34:02 +0000986 if (auto FuzzyScore = Filter->match(C.Name))
Sam McCallc5707b62018-05-15 17:43:27 +0000987 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +0000988 else
989 return;
Sam McCallc5707b62018-05-15 17:43:27 +0000990 if (IndexResult)
991 Quality.merge(*IndexResult);
992 if (SemaResult) {
993 Quality.merge(*SemaResult);
994 Relevance.merge(*SemaResult);
995 }
996
997 float QualScore = Quality.evaluate(), RelScore = Relevance.evaluate();
998 CompletionItemScores Scores;
999 Scores.finalScore = evaluateSymbolAndRelevance(QualScore, RelScore);
1000 // The purpose of exporting component scores is to allow NameMatch to be
1001 // replaced on the client-side. So we export (NameMatch, final/NameMatch)
1002 // rather than (RelScore, QualScore).
1003 Scores.filterScore = Relevance.NameMatch;
1004 Scores.symbolScore =
1005 Scores.filterScore ? Scores.finalScore / Scores.filterScore : QualScore;
1006
1007 DEBUG(llvm::dbgs() << "CodeComplete: " << C.Name
1008 << (IndexResult ? " (index)" : "")
1009 << (SemaResult ? " (sema)" : "") << " = "
1010 << Scores.finalScore << "\n"
1011 << Quality << Relevance << "\n");
Sam McCall545a20d2018-01-19 14:34:02 +00001012
1013 NSema += bool(SemaResult);
1014 NIndex += bool(IndexResult);
1015 NBoth += SemaResult && IndexResult;
Sam McCallab8e3932018-02-19 13:04:41 +00001016 if (Candidates.push({C, Scores}))
1017 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001018 }
1019
1020 CompletionItem toCompletionItem(const CompletionCandidate &Candidate,
1021 const CompletionItemScores &Scores) {
1022 CodeCompletionString *SemaCCS = nullptr;
1023 if (auto *SR = Candidate.SemaResult)
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001024 SemaCCS = Recorder->codeCompletionString(*SR, Opts.IncludeBriefComments);
Eric Liu63f419a2018-05-15 15:29:32 +00001025 return Candidate.build(FileName, Scores, Opts, SemaCCS, Includes.get());
Sam McCall545a20d2018-01-19 14:34:02 +00001026 }
1027};
1028
Sam McCalld1a7a372018-01-31 13:40:48 +00001029CompletionList codeComplete(PathRef FileName,
Sam McCall98775c52017-12-04 13:49:59 +00001030 const tooling::CompileCommand &Command,
1031 PrecompiledPreamble const *Preamble,
Eric Liu63f419a2018-05-15 15:29:32 +00001032 const std::vector<Inclusion> &PreambleInclusions,
Sam McCall98775c52017-12-04 13:49:59 +00001033 StringRef Contents, Position Pos,
1034 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1035 std::shared_ptr<PCHContainerOperations> PCHs,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001036 CodeCompleteOptions Opts) {
Eric Liuc5105f92018-02-16 14:15:55 +00001037 return CodeCompleteFlow(FileName, Opts)
Eric Liu63f419a2018-05-15 15:29:32 +00001038 .run({FileName, Command, Preamble, PreambleInclusions, Contents, Pos, VFS,
1039 PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001040}
1041
Sam McCalld1a7a372018-01-31 13:40:48 +00001042SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001043 const tooling::CompileCommand &Command,
1044 PrecompiledPreamble const *Preamble,
1045 StringRef Contents, Position Pos,
1046 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1047 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001048 SignatureHelp Result;
1049 clang::CodeCompleteOptions Options;
1050 Options.IncludeGlobals = false;
1051 Options.IncludeMacros = false;
1052 Options.IncludeCodePatterns = false;
1053 Options.IncludeBriefComments = true;
Sam McCalld1a7a372018-01-31 13:40:48 +00001054 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1055 Options,
Eric Liu63f419a2018-05-15 15:29:32 +00001056 {FileName, Command, Preamble,
1057 /*PreambleInclusions=*/{}, Contents, Pos, std::move(VFS),
Sam McCalld1a7a372018-01-31 13:40:48 +00001058 std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001059 return Result;
1060}
1061
1062} // namespace clangd
1063} // namespace clang