blob: 72e395f1e095841601f69b6aed59785857459df5 [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//
Sam McCallc18c2802018-06-15 11:06:29 +000010// Code completion has several moving parts:
11// - AST-based completions are provided using the completion hooks in Sema.
12// - external completions are retrieved from the index (using hints from Sema)
13// - the two sources overlap, and must be merged and overloads bundled
14// - results must be scored and ranked (see Quality.h) before rendering
Sam McCall98775c52017-12-04 13:49:59 +000015//
Sam McCallc18c2802018-06-15 11:06:29 +000016// Signature help works in a similar way as code completion, but it is simpler:
17// it's purely AST-based, and there are few candidates.
Sam McCall98775c52017-12-04 13:49:59 +000018//
19//===---------------------------------------------------------------------===//
20
21#include "CodeComplete.h"
Eric Liu7ad16962018-06-22 10:46:59 +000022#include "AST.h"
Eric Liu63696e12017-12-20 17:24:31 +000023#include "CodeCompletionStrings.h"
Sam McCall98775c52017-12-04 13:49:59 +000024#include "Compiler.h"
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +000025#include "Diagnostics.h"
Sam McCall3f0243f2018-07-03 08:09:29 +000026#include "FileDistance.h"
Sam McCall84652cc2018-01-12 16:16:09 +000027#include "FuzzyMatch.h"
Eric Liu63f419a2018-05-15 15:29:32 +000028#include "Headers.h"
Eric Liu6f648df2017-12-19 16:50:37 +000029#include "Logger.h"
Sam McCallc5707b62018-05-15 17:43:27 +000030#include "Quality.h"
Eric Liuc5105f92018-02-16 14:15:55 +000031#include "SourceCode.h"
Sam McCall2b780162018-01-30 17:20:54 +000032#include "Trace.h"
Eric Liu63f419a2018-05-15 15:29:32 +000033#include "URI.h"
Eric Liu6f648df2017-12-19 16:50:37 +000034#include "index/Index.h"
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +000035#include "clang/ASTMatchers/ASTMatchFinder.h"
Ilya Biryukovc22d3442018-05-16 12:32:49 +000036#include "clang/Basic/LangOptions.h"
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +000037#include "clang/Basic/SourceLocation.h"
Eric Liuc5105f92018-02-16 14:15:55 +000038#include "clang/Format/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000039#include "clang/Frontend/CompilerInstance.h"
40#include "clang/Frontend/FrontendActions.h"
Sam McCall545a20d2018-01-19 14:34:02 +000041#include "clang/Index/USRGeneration.h"
Sam McCall98775c52017-12-04 13:49:59 +000042#include "clang/Sema/CodeCompleteConsumer.h"
43#include "clang/Sema/Sema.h"
Eric Liuc5105f92018-02-16 14:15:55 +000044#include "clang/Tooling/Core/Replacement.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000045#include "llvm/Support/Format.h"
Eric Liubc25ef72018-07-05 08:29:33 +000046#include "llvm/Support/FormatVariadic.h"
Sam McCall2161ec72018-07-05 06:20:41 +000047#include "llvm/Support/ScopedPrinter.h"
Sam McCall98775c52017-12-04 13:49:59 +000048#include <queue>
49
Sam McCallc5707b62018-05-15 17:43:27 +000050// We log detailed candidate here if you run with -debug-only=codecomplete.
Sam McCall27c979a2018-06-29 14:47:57 +000051#define DEBUG_TYPE "CodeComplete"
Sam McCallc5707b62018-05-15 17:43:27 +000052
Sam McCall98775c52017-12-04 13:49:59 +000053namespace clang {
54namespace clangd {
55namespace {
56
Eric Liu6f648df2017-12-19 16:50:37 +000057CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
58 using SK = index::SymbolKind;
59 switch (Kind) {
60 case SK::Unknown:
61 return CompletionItemKind::Missing;
62 case SK::Module:
63 case SK::Namespace:
64 case SK::NamespaceAlias:
65 return CompletionItemKind::Module;
66 case SK::Macro:
67 return CompletionItemKind::Text;
68 case SK::Enum:
69 return CompletionItemKind::Enum;
70 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
71 // protocol.
72 case SK::Struct:
73 case SK::Class:
74 case SK::Protocol:
75 case SK::Extension:
76 case SK::Union:
77 return CompletionItemKind::Class;
78 // FIXME(ioeric): figure out whether reference is the right type for aliases.
79 case SK::TypeAlias:
80 case SK::Using:
81 return CompletionItemKind::Reference;
82 case SK::Function:
83 // FIXME(ioeric): this should probably be an operator. This should be fixed
84 // when `Operator` is support type in the protocol.
85 case SK::ConversionFunction:
86 return CompletionItemKind::Function;
87 case SK::Variable:
88 case SK::Parameter:
89 return CompletionItemKind::Variable;
90 case SK::Field:
91 return CompletionItemKind::Field;
92 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
93 case SK::EnumConstant:
94 return CompletionItemKind::Value;
95 case SK::InstanceMethod:
96 case SK::ClassMethod:
97 case SK::StaticMethod:
98 case SK::Destructor:
99 return CompletionItemKind::Method;
100 case SK::InstanceProperty:
101 case SK::ClassProperty:
102 case SK::StaticProperty:
103 return CompletionItemKind::Property;
104 case SK::Constructor:
105 return CompletionItemKind::Constructor;
106 }
107 llvm_unreachable("Unhandled clang::index::SymbolKind.");
108}
109
Sam McCall83305892018-06-08 21:17:19 +0000110CompletionItemKind
111toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
112 const NamedDecl *Decl) {
113 if (Decl)
114 return toCompletionItemKind(index::getSymbolInfo(Decl).Kind);
115 switch (ResKind) {
116 case CodeCompletionResult::RK_Declaration:
117 llvm_unreachable("RK_Declaration without Decl");
118 case CodeCompletionResult::RK_Keyword:
119 return CompletionItemKind::Keyword;
120 case CodeCompletionResult::RK_Macro:
121 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
122 // completion items in LSP.
123 case CodeCompletionResult::RK_Pattern:
124 return CompletionItemKind::Snippet;
125 }
126 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
127}
128
Sam McCall98775c52017-12-04 13:49:59 +0000129/// Get the optional chunk as a string. This function is possibly recursive.
130///
131/// The parameter info for each parameter is appended to the Parameters.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000132std::string getOptionalParameters(const CodeCompletionString &CCS,
133 std::vector<ParameterInformation> &Parameters,
134 SignatureQualitySignals &Signal) {
Sam McCall98775c52017-12-04 13:49:59 +0000135 std::string Result;
136 for (const auto &Chunk : CCS) {
137 switch (Chunk.Kind) {
138 case CodeCompletionString::CK_Optional:
139 assert(Chunk.Optional &&
140 "Expected the optional code completion string to be non-null.");
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000141 Result += getOptionalParameters(*Chunk.Optional, Parameters, Signal);
Sam McCall98775c52017-12-04 13:49:59 +0000142 break;
143 case CodeCompletionString::CK_VerticalSpace:
144 break;
145 case CodeCompletionString::CK_Placeholder:
146 // A string that acts as a placeholder for, e.g., a function call
147 // argument.
148 // Intentional fallthrough here.
149 case CodeCompletionString::CK_CurrentParameter: {
150 // A piece of text that describes the parameter that corresponds to
151 // the code-completion location within a function call, message send,
152 // macro invocation, etc.
153 Result += Chunk.Text;
154 ParameterInformation Info;
155 Info.label = Chunk.Text;
156 Parameters.push_back(std::move(Info));
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000157 Signal.ContainsActiveParameter = true;
158 Signal.NumberOfOptionalParameters++;
Sam McCall98775c52017-12-04 13:49:59 +0000159 break;
160 }
161 default:
162 Result += Chunk.Text;
163 break;
164 }
165 }
166 return Result;
167}
168
Eric Liu63f419a2018-05-15 15:29:32 +0000169/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
170/// include.
171static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
172 llvm::StringRef HintPath) {
173 if (isLiteralInclude(Header))
174 return HeaderFile{Header.str(), /*Verbatim=*/true};
175 auto U = URI::parse(Header);
176 if (!U)
177 return U.takeError();
178
179 auto IncludePath = URI::includeSpelling(*U);
180 if (!IncludePath)
181 return IncludePath.takeError();
182 if (!IncludePath->empty())
183 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
184
185 auto Resolved = URI::resolve(*U, HintPath);
186 if (!Resolved)
187 return Resolved.takeError();
188 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
189}
190
Sam McCall545a20d2018-01-19 14:34:02 +0000191/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000192/// It may be promoted to a CompletionItem if it's among the top-ranked results.
193struct CompletionCandidate {
Sam McCall545a20d2018-01-19 14:34:02 +0000194 llvm::StringRef Name; // Used for filtering and sorting.
195 // We may have a result from Sema, from the index, or both.
196 const CodeCompletionResult *SemaResult = nullptr;
197 const Symbol *IndexResult = nullptr;
Sam McCall98775c52017-12-04 13:49:59 +0000198
Sam McCallc18c2802018-06-15 11:06:29 +0000199 // Returns a token identifying the overload set this is part of.
200 // 0 indicates it's not part of any overload set.
201 size_t overloadSet() const {
202 SmallString<256> Scratch;
203 if (IndexResult) {
204 switch (IndexResult->SymInfo.Kind) {
205 case index::SymbolKind::ClassMethod:
206 case index::SymbolKind::InstanceMethod:
207 case index::SymbolKind::StaticMethod:
208 assert(false && "Don't expect members from index in code completion");
209 // fall through
210 case index::SymbolKind::Function:
211 // We can't group overloads together that need different #includes.
212 // This could break #include insertion.
213 return hash_combine(
214 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
215 headerToInsertIfNotPresent().getValueOr(""));
216 default:
217 return 0;
218 }
219 }
220 assert(SemaResult);
221 // We need to make sure we're consistent with the IndexResult case!
222 const NamedDecl *D = SemaResult->Declaration;
223 if (!D || !D->isFunctionOrFunctionTemplate())
224 return 0;
225 {
226 llvm::raw_svector_ostream OS(Scratch);
227 D->printQualifiedName(OS);
228 }
229 return hash_combine(Scratch, headerToInsertIfNotPresent().getValueOr(""));
230 }
231
232 llvm::Optional<llvm::StringRef> headerToInsertIfNotPresent() const {
233 if (!IndexResult || !IndexResult->Detail ||
234 IndexResult->Detail->IncludeHeader.empty())
235 return llvm::None;
236 if (SemaResult && SemaResult->Declaration) {
237 // Avoid inserting new #include if the declaration is found in the current
238 // file e.g. the symbol is forward declared.
239 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
240 for (const Decl *RD : SemaResult->Declaration->redecls())
Stephen Kelly43465bf2018-08-09 22:42:26 +0000241 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
Sam McCallc18c2802018-06-15 11:06:29 +0000242 return llvm::None;
243 }
244 return IndexResult->Detail->IncludeHeader;
245 }
246
Sam McCallc18c2802018-06-15 11:06:29 +0000247 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
Sam McCall98775c52017-12-04 13:49:59 +0000248};
Sam McCallc18c2802018-06-15 11:06:29 +0000249using ScoredBundle =
Sam McCall27c979a2018-06-29 14:47:57 +0000250 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
Sam McCallc18c2802018-06-15 11:06:29 +0000251struct ScoredBundleGreater {
252 bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
Sam McCall27c979a2018-06-29 14:47:57 +0000253 if (L.second.Total != R.second.Total)
254 return L.second.Total > R.second.Total;
Sam McCallc18c2802018-06-15 11:06:29 +0000255 return L.first.front().Name <
256 R.first.front().Name; // Earlier name is better.
257 }
258};
Sam McCall98775c52017-12-04 13:49:59 +0000259
Sam McCall27c979a2018-06-29 14:47:57 +0000260// Assembles a code completion out of a bundle of >=1 completion candidates.
261// Many of the expensive strings are only computed at this point, once we know
262// the candidate bundle is going to be returned.
263//
264// Many fields are the same for all candidates in a bundle (e.g. name), and are
265// computed from the first candidate, in the constructor.
266// Others vary per candidate, so add() must be called for remaining candidates.
267struct CodeCompletionBuilder {
268 CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
269 CodeCompletionString *SemaCCS,
270 const IncludeInserter &Includes, StringRef FileName,
271 const CodeCompleteOptions &Opts)
272 : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments) {
273 add(C, SemaCCS);
274 if (C.SemaResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000275 Completion.Origin |= SymbolOrigin::AST;
Sam McCall27c979a2018-06-29 14:47:57 +0000276 Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
Eric Liuf433c2d2018-07-18 15:31:14 +0000277 if (Completion.Scope.empty()) {
278 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
279 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
Sam McCall27c979a2018-06-29 14:47:57 +0000280 if (const auto *D = C.SemaResult->getDeclaration())
281 if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
282 Completion.Scope =
283 splitQualifiedName(printQualifiedName(*ND)).first;
Eric Liuf433c2d2018-07-18 15:31:14 +0000284 }
Sam McCall27c979a2018-06-29 14:47:57 +0000285 Completion.Kind =
286 toCompletionItemKind(C.SemaResult->Kind, C.SemaResult->Declaration);
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000287 for (const auto &FixIt : C.SemaResult->FixIts) {
288 Completion.FixIts.push_back(
289 toTextEdit(FixIt, ASTCtx.getSourceManager(), ASTCtx.getLangOpts()));
290 }
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +0000291 std::sort(Completion.FixIts.begin(), Completion.FixIts.end(),
292 [](const TextEdit &X, const TextEdit &Y) {
293 return std::tie(X.range.start.line, X.range.start.character) <
294 std::tie(Y.range.start.line, Y.range.start.character);
295 });
Sam McCall27c979a2018-06-29 14:47:57 +0000296 }
297 if (C.IndexResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000298 Completion.Origin |= C.IndexResult->Origin;
Sam McCall27c979a2018-06-29 14:47:57 +0000299 if (Completion.Scope.empty())
300 Completion.Scope = C.IndexResult->Scope;
301 if (Completion.Kind == CompletionItemKind::Missing)
302 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
303 if (Completion.Name.empty())
304 Completion.Name = C.IndexResult->Name;
305 }
306 if (auto Inserted = C.headerToInsertIfNotPresent()) {
307 // Turn absolute path into a literal string that can be #included.
308 auto Include = [&]() -> Expected<std::pair<std::string, bool>> {
309 auto ResolvedDeclaring =
310 toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
311 if (!ResolvedDeclaring)
312 return ResolvedDeclaring.takeError();
313 auto ResolvedInserted = toHeaderFile(*Inserted, FileName);
314 if (!ResolvedInserted)
315 return ResolvedInserted.takeError();
316 return std::make_pair(Includes.calculateIncludePath(*ResolvedDeclaring,
317 *ResolvedInserted),
318 Includes.shouldInsertInclude(*ResolvedDeclaring,
319 *ResolvedInserted));
320 }();
321 if (Include) {
322 Completion.Header = Include->first;
323 if (Include->second)
324 Completion.HeaderInsertion = Includes.insert(Include->first);
325 } else
Sam McCallbed58852018-07-11 10:35:11 +0000326 log("Failed to generate include insertion edits for adding header "
Sam McCall27c979a2018-06-29 14:47:57 +0000327 "(FileURI='{0}', IncludeHeader='{1}') into {2}",
328 C.IndexResult->CanonicalDeclaration.FileURI,
Sam McCallbed58852018-07-11 10:35:11 +0000329 C.IndexResult->Detail->IncludeHeader, FileName);
Sam McCall27c979a2018-06-29 14:47:57 +0000330 }
331 }
332
333 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {
334 assert(bool(C.SemaResult) == bool(SemaCCS));
335 Bundled.emplace_back();
336 BundledEntry &S = Bundled.back();
337 if (C.SemaResult) {
338 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
339 &Completion.RequiredQualifier);
340 S.ReturnType = getReturnType(*SemaCCS);
341 } else if (C.IndexResult) {
342 S.Signature = C.IndexResult->Signature;
343 S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix;
344 if (auto *D = C.IndexResult->Detail)
345 S.ReturnType = D->ReturnType;
346 }
347 if (ExtractDocumentation && Completion.Documentation.empty()) {
348 if (C.IndexResult && C.IndexResult->Detail)
349 Completion.Documentation = C.IndexResult->Detail->Documentation;
350 else if (C.SemaResult)
351 Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
352 /*CommentsFromHeader=*/false);
353 }
354 }
355
356 CodeCompletion build() {
357 Completion.ReturnType = summarizeReturnType();
358 Completion.Signature = summarizeSignature();
359 Completion.SnippetSuffix = summarizeSnippet();
360 Completion.BundleSize = Bundled.size();
361 return std::move(Completion);
362 }
363
364private:
365 struct BundledEntry {
366 std::string SnippetSuffix;
367 std::string Signature;
368 std::string ReturnType;
369 };
370
371 // If all BundledEntrys have the same value for a property, return it.
372 template <std::string BundledEntry::*Member>
373 const std::string *onlyValue() const {
374 auto B = Bundled.begin(), E = Bundled.end();
375 for (auto I = B + 1; I != E; ++I)
376 if (I->*Member != B->*Member)
377 return nullptr;
378 return &(B->*Member);
379 }
380
381 std::string summarizeReturnType() const {
382 if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
383 return *RT;
384 return "";
385 }
386
387 std::string summarizeSnippet() const {
388 if (auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>())
389 return *Snippet;
390 // All bundles are function calls.
391 return "(${0})";
392 }
393
394 std::string summarizeSignature() const {
395 if (auto *Signature = onlyValue<&BundledEntry::Signature>())
396 return *Signature;
397 // All bundles are function calls.
398 return "(…)";
399 }
400
401 ASTContext &ASTCtx;
402 CodeCompletion Completion;
403 SmallVector<BundledEntry, 1> Bundled;
404 bool ExtractDocumentation;
405};
406
Sam McCall545a20d2018-01-19 14:34:02 +0000407// Determine the symbol ID for a Sema code completion result, if possible.
408llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
409 switch (R.Kind) {
410 case CodeCompletionResult::RK_Declaration:
411 case CodeCompletionResult::RK_Pattern: {
Haojian Wuc6ddb462018-08-07 08:57:52 +0000412 return clang::clangd::getSymbolID(R.Declaration);
Sam McCall545a20d2018-01-19 14:34:02 +0000413 }
414 case CodeCompletionResult::RK_Macro:
415 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
416 case CodeCompletionResult::RK_Keyword:
417 return None;
418 }
419 llvm_unreachable("unknown CodeCompletionResult kind");
420}
421
Haojian Wu061c73e2018-01-23 11:37:26 +0000422// Scopes of the paritial identifier we're trying to complete.
423// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000424struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000425 // The scopes we should look in, determined by Sema.
426 //
427 // If the qualifier was fully resolved, we look for completions in these
428 // scopes; if there is an unresolved part of the qualifier, it should be
429 // resolved within these scopes.
430 //
431 // Examples of qualified completion:
432 //
433 // "::vec" => {""}
434 // "using namespace std; ::vec^" => {"", "std::"}
435 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
436 // "std::vec^" => {""} // "std" unresolved
437 //
438 // Examples of unqualified completion:
439 //
440 // "vec^" => {""}
441 // "using namespace std; vec^" => {"", "std::"}
442 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
443 //
444 // "" for global namespace, "ns::" for normal namespace.
445 std::vector<std::string> AccessibleScopes;
446 // The full scope qualifier as typed by the user (without the leading "::").
447 // Set if the qualifier is not fully resolved by Sema.
448 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000449
Haojian Wu061c73e2018-01-23 11:37:26 +0000450 // Construct scopes being queried in indexes.
451 // This method format the scopes to match the index request representation.
452 std::vector<std::string> scopesForIndexQuery() {
453 std::vector<std::string> Results;
454 for (llvm::StringRef AS : AccessibleScopes) {
455 Results.push_back(AS);
456 if (UnresolvedQualifier)
457 Results.back() += *UnresolvedQualifier;
458 }
459 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000460 }
Eric Liu6f648df2017-12-19 16:50:37 +0000461};
462
Haojian Wu061c73e2018-01-23 11:37:26 +0000463// Get all scopes that will be queried in indexes.
464std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000465 const SourceManager &SM) {
466 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000467 SpecifiedScope Info;
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000468 for (auto *Context : CCContext.getVisitedContexts()) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000469 if (isa<TranslationUnitDecl>(Context))
470 Info.AccessibleScopes.push_back(""); // global namespace
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000471 else if (const auto *NS = dyn_cast<NamespaceDecl>(Context))
Haojian Wu061c73e2018-01-23 11:37:26 +0000472 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
473 }
474 return Info;
475 };
476
477 auto SS = CCContext.getCXXScopeSpecifier();
478
479 // Unqualified completion (e.g. "vec^").
480 if (!SS) {
481 // FIXME: Once we can insert namespace qualifiers and use the in-scope
482 // namespaces for scoring, search in all namespaces.
483 // FIXME: Capture scopes and use for scoring, for example,
484 // "using namespace std; namespace foo {v^}" =>
485 // foo::value > std::vector > boost::variant
486 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
487 }
488
489 // Qualified completion ("std::vec^"), we have two cases depending on whether
490 // the qualifier can be resolved by Sema.
491 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000492 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
493 }
494
495 // Unresolved qualifier.
496 // FIXME: When Sema can resolve part of a scope chain (e.g.
497 // "known::unknown::id"), we should expand the known part ("known::") rather
498 // than treating the whole thing as unknown.
499 SpecifiedScope Info;
500 Info.AccessibleScopes.push_back(""); // global namespace
501
502 Info.UnresolvedQualifier =
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000503 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM,
504 clang::LangOptions())
505 .ltrim("::");
Haojian Wu061c73e2018-01-23 11:37:26 +0000506 // Sema excludes the trailing "::".
507 if (!Info.UnresolvedQualifier->empty())
508 *Info.UnresolvedQualifier += "::";
509
510 return Info.scopesForIndexQuery();
511}
512
Eric Liu42abe412018-05-24 11:20:19 +0000513// Should we perform index-based completion in a context of the specified kind?
514// FIXME: consider allowing completion, but restricting the result types.
515bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
516 switch (K) {
517 case CodeCompletionContext::CCC_TopLevel:
518 case CodeCompletionContext::CCC_ObjCInterface:
519 case CodeCompletionContext::CCC_ObjCImplementation:
520 case CodeCompletionContext::CCC_ObjCIvarList:
521 case CodeCompletionContext::CCC_ClassStructUnion:
522 case CodeCompletionContext::CCC_Statement:
523 case CodeCompletionContext::CCC_Expression:
524 case CodeCompletionContext::CCC_ObjCMessageReceiver:
525 case CodeCompletionContext::CCC_EnumTag:
526 case CodeCompletionContext::CCC_UnionTag:
527 case CodeCompletionContext::CCC_ClassOrStructTag:
528 case CodeCompletionContext::CCC_ObjCProtocolName:
529 case CodeCompletionContext::CCC_Namespace:
530 case CodeCompletionContext::CCC_Type:
531 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
532 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
533 case CodeCompletionContext::CCC_ParenthesizedExpression:
534 case CodeCompletionContext::CCC_ObjCInterfaceName:
535 case CodeCompletionContext::CCC_ObjCCategoryName:
536 return true;
537 case CodeCompletionContext::CCC_Other: // Be conservative.
538 case CodeCompletionContext::CCC_OtherWithMacros:
539 case CodeCompletionContext::CCC_DotMemberAccess:
540 case CodeCompletionContext::CCC_ArrowMemberAccess:
541 case CodeCompletionContext::CCC_ObjCPropertyAccess:
542 case CodeCompletionContext::CCC_MacroName:
543 case CodeCompletionContext::CCC_MacroNameUse:
544 case CodeCompletionContext::CCC_PreprocessorExpression:
545 case CodeCompletionContext::CCC_PreprocessorDirective:
546 case CodeCompletionContext::CCC_NaturalLanguage:
547 case CodeCompletionContext::CCC_SelectorName:
548 case CodeCompletionContext::CCC_TypeQualifiers:
549 case CodeCompletionContext::CCC_ObjCInstanceMessage:
550 case CodeCompletionContext::CCC_ObjCClassMessage:
551 case CodeCompletionContext::CCC_Recovery:
552 return false;
553 }
554 llvm_unreachable("unknown code completion context");
555}
556
Sam McCall4caa8512018-06-07 12:49:17 +0000557// Some member calls are blacklisted because they're so rarely useful.
558static bool isBlacklistedMember(const NamedDecl &D) {
559 // Destructor completion is rarely useful, and works inconsistently.
560 // (s.^ completes ~string, but s.~st^ is an error).
561 if (D.getKind() == Decl::CXXDestructor)
562 return true;
563 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
564 if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
565 if (R->isInjectedClassName())
566 return true;
567 // Explicit calls to operators are also rare.
568 auto NameKind = D.getDeclName().getNameKind();
569 if (NameKind == DeclarationName::CXXOperatorName ||
570 NameKind == DeclarationName::CXXLiteralOperatorName ||
571 NameKind == DeclarationName::CXXConversionFunctionName)
572 return true;
573 return false;
574}
575
Sam McCall545a20d2018-01-19 14:34:02 +0000576// The CompletionRecorder captures Sema code-complete output, including context.
577// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
578// It doesn't do scoring or conversion to CompletionItem yet, as we want to
579// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000580// Generally the fields and methods of this object should only be used from
581// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000582struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000583 CompletionRecorder(const CodeCompleteOptions &Opts,
Benjamin Kramerc36c09f2018-07-03 20:59:33 +0000584 llvm::unique_function<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000585 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000586 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000587 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
588 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000589 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
590 assert(this->ResultsCallback);
591 }
592
Sam McCall545a20d2018-01-19 14:34:02 +0000593 std::vector<CodeCompletionResult> Results;
594 CodeCompletionContext CCContext;
595 Sema *CCSema = nullptr; // Sema that created the results.
596 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000597
Sam McCall545a20d2018-01-19 14:34:02 +0000598 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
599 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000600 unsigned NumResults) override final {
Eric Liu485074f2018-07-11 13:15:31 +0000601 // Results from recovery mode are generally useless, and the callback after
602 // recovery (if any) is usually more interesting. To make sure we handle the
603 // future callback from sema, we just ignore all callbacks in recovery mode,
604 // as taking only results from recovery mode results in poor completion
605 // results.
606 // FIXME: in case there is no future sema completion callback after the
607 // recovery mode, we might still want to provide some results (e.g. trivial
608 // identifier-based completion).
609 if (Context.getKind() == CodeCompletionContext::CCC_Recovery) {
610 log("Code complete: Ignoring sema code complete callback with Recovery "
611 "context.");
612 return;
613 }
Eric Liu42abe412018-05-24 11:20:19 +0000614 // If a callback is called without any sema result and the context does not
615 // support index-based completion, we simply skip it to give way to
616 // potential future callbacks with results.
617 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
618 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000619 if (CCSema) {
Sam McCallbed58852018-07-11 10:35:11 +0000620 log("Multiple code complete callbacks (parser backtracked?). "
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000621 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000622 getCompletionKindString(Context.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +0000623 getCompletionKindString(this->CCContext.getKind()));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000624 return;
625 }
Sam McCall545a20d2018-01-19 14:34:02 +0000626 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000627 CCSema = &S;
628 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000629
Sam McCall545a20d2018-01-19 14:34:02 +0000630 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000631 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000632 auto &Result = InResults[I];
633 // Drop hidden items which cannot be found by lookup after completion.
634 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000635 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
636 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000637 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000638 (Result.Availability == CXAvailability_NotAvailable ||
639 Result.Availability == CXAvailability_NotAccessible))
640 continue;
Sam McCall4caa8512018-06-07 12:49:17 +0000641 if (Result.Declaration &&
642 !Context.getBaseType().isNull() // is this a member-access context?
643 && isBlacklistedMember(*Result.Declaration))
Sam McCalld2a95922018-01-22 21:05:00 +0000644 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000645 // We choose to never append '::' to completion results in clangd.
646 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000647 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000648 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000649 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000650 }
651
Sam McCall545a20d2018-01-19 14:34:02 +0000652 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000653 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
654
Sam McCall545a20d2018-01-19 14:34:02 +0000655 // Returns the filtering/sorting name for Result, which must be from Results.
656 // Returned string is owned by this recorder (or the AST).
657 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000658 switch (Result.Kind) {
659 case CodeCompletionResult::RK_Declaration:
660 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000661 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000662 break;
663 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000664 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000665 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000666 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000667 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000668 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000669 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000670 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000671 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000672 }
673
Sam McCall545a20d2018-01-19 14:34:02 +0000674 // Build a CodeCompletion string for R, which must be from Results.
675 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000676 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000677 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
678 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000679 *CCSema, CCContext, *CCAllocator, CCTUInfo,
680 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000681 }
682
Sam McCall545a20d2018-01-19 14:34:02 +0000683private:
684 CodeCompleteOptions Opts;
685 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000686 CodeCompletionTUInfo CCTUInfo;
Benjamin Kramerc36c09f2018-07-03 20:59:33 +0000687 llvm::unique_function<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000688};
689
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000690using ScoredSignature =
691 std::pair<SignatureQualitySignals, SignatureInformation>;
692
Sam McCall98775c52017-12-04 13:49:59 +0000693class SignatureHelpCollector final : public CodeCompleteConsumer {
694
695public:
696 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
697 SignatureHelp &SigHelp)
698 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
699 SigHelp(SigHelp),
700 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
701 CCTUInfo(Allocator) {}
702
703 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
704 OverloadCandidate *Candidates,
705 unsigned NumCandidates) override {
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000706 std::vector<ScoredSignature> ScoredSignatures;
Sam McCall98775c52017-12-04 13:49:59 +0000707 SigHelp.signatures.reserve(NumCandidates);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000708 ScoredSignatures.reserve(NumCandidates);
Sam McCall98775c52017-12-04 13:49:59 +0000709 // FIXME(rwols): How can we determine the "active overload candidate"?
710 // Right now the overloaded candidates seem to be provided in a "best fit"
711 // order, so I'm not too worried about this.
712 SigHelp.activeSignature = 0;
713 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
714 "too many arguments");
715 SigHelp.activeParameter = static_cast<int>(CurrentArg);
716 for (unsigned I = 0; I < NumCandidates; ++I) {
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +0000717 OverloadCandidate Candidate = Candidates[I];
718 // We want to avoid showing instantiated signatures, because they may be
719 // long in some cases (e.g. when 'T' is substituted with 'std::string', we
720 // would get 'std::basic_string<char>').
721 if (auto *Func = Candidate.getFunction()) {
722 if (auto *Pattern = Func->getTemplateInstantiationPattern())
723 Candidate = OverloadCandidate(Pattern);
724 }
725
Sam McCall98775c52017-12-04 13:49:59 +0000726 const auto *CCS = Candidate.CreateSignatureString(
727 CurrentArg, S, *Allocator, CCTUInfo, true);
728 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000729 // FIXME: for headers, we need to get a comment from the index.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000730 ScoredSignatures.push_back(processOverloadCandidate(
Ilya Biryukov43714502018-05-16 12:32:44 +0000731 Candidate, *CCS,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000732 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000733 /*CommentsFromHeaders=*/false)));
Sam McCall98775c52017-12-04 13:49:59 +0000734 }
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000735 std::sort(ScoredSignatures.begin(), ScoredSignatures.end(),
736 [](const ScoredSignature &L, const ScoredSignature &R) {
737 // Ordering follows:
738 // - Less number of parameters is better.
739 // - Function is better than FunctionType which is better than
740 // Function Template.
741 // - High score is better.
742 // - Shorter signature is better.
743 // - Alphebatically smaller is better.
744 if (L.first.NumberOfParameters != R.first.NumberOfParameters)
745 return L.first.NumberOfParameters <
746 R.first.NumberOfParameters;
747 if (L.first.NumberOfOptionalParameters !=
748 R.first.NumberOfOptionalParameters)
749 return L.first.NumberOfOptionalParameters <
750 R.first.NumberOfOptionalParameters;
751 if (L.first.Kind != R.first.Kind) {
752 using OC = CodeCompleteConsumer::OverloadCandidate;
753 switch (L.first.Kind) {
754 case OC::CK_Function:
755 return true;
756 case OC::CK_FunctionType:
757 return R.first.Kind != OC::CK_Function;
758 case OC::CK_FunctionTemplate:
759 return false;
760 }
761 llvm_unreachable("Unknown overload candidate type.");
762 }
763 if (L.second.label.size() != R.second.label.size())
764 return L.second.label.size() < R.second.label.size();
765 return L.second.label < R.second.label;
766 });
767 for (const auto &SS : ScoredSignatures)
768 SigHelp.signatures.push_back(SS.second);
Sam McCall98775c52017-12-04 13:49:59 +0000769 }
770
771 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
772
773 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
774
775private:
Eric Liu63696e12017-12-20 17:24:31 +0000776 // FIXME(ioeric): consider moving CodeCompletionString logic here to
777 // CompletionString.h.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000778 ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
779 const CodeCompletionString &CCS,
780 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000781 SignatureInformation Result;
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000782 SignatureQualitySignals Signal;
Sam McCall98775c52017-12-04 13:49:59 +0000783 const char *ReturnType = nullptr;
784
Ilya Biryukov43714502018-05-16 12:32:44 +0000785 Result.documentation = formatDocumentation(CCS, DocComment);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000786 Signal.Kind = Candidate.getKind();
Sam McCall98775c52017-12-04 13:49:59 +0000787
788 for (const auto &Chunk : CCS) {
789 switch (Chunk.Kind) {
790 case CodeCompletionString::CK_ResultType:
791 // A piece of text that describes the type of an entity or,
792 // for functions and methods, the return type.
793 assert(!ReturnType && "Unexpected CK_ResultType");
794 ReturnType = Chunk.Text;
795 break;
796 case CodeCompletionString::CK_Placeholder:
797 // A string that acts as a placeholder for, e.g., a function call
798 // argument.
799 // Intentional fallthrough here.
800 case CodeCompletionString::CK_CurrentParameter: {
801 // A piece of text that describes the parameter that corresponds to
802 // the code-completion location within a function call, message send,
803 // macro invocation, etc.
804 Result.label += Chunk.Text;
805 ParameterInformation Info;
806 Info.label = Chunk.Text;
807 Result.parameters.push_back(std::move(Info));
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000808 Signal.NumberOfParameters++;
809 Signal.ContainsActiveParameter = true;
Sam McCall98775c52017-12-04 13:49:59 +0000810 break;
811 }
812 case CodeCompletionString::CK_Optional: {
813 // The rest of the parameters are defaulted/optional.
814 assert(Chunk.Optional &&
815 "Expected the optional code completion string to be non-null.");
816 Result.label +=
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000817 getOptionalParameters(*Chunk.Optional, Result.parameters, Signal);
Sam McCall98775c52017-12-04 13:49:59 +0000818 break;
819 }
820 case CodeCompletionString::CK_VerticalSpace:
821 break;
822 default:
823 Result.label += Chunk.Text;
824 break;
825 }
826 }
827 if (ReturnType) {
828 Result.label += " -> ";
829 Result.label += ReturnType;
830 }
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000831 dlog("Signal for {0}: {1}", Result, Signal);
832 return {Signal, Result};
Sam McCall98775c52017-12-04 13:49:59 +0000833 }
834
835 SignatureHelp &SigHelp;
836 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
837 CodeCompletionTUInfo CCTUInfo;
838
839}; // SignatureHelpCollector
840
Sam McCall545a20d2018-01-19 14:34:02 +0000841struct SemaCompleteInput {
842 PathRef FileName;
843 const tooling::CompileCommand &Command;
844 PrecompiledPreamble const *Preamble;
845 StringRef Contents;
846 Position Pos;
847 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
848 std::shared_ptr<PCHContainerOperations> PCHs;
849};
850
851// Invokes Sema code completion on a file.
Sam McCall3f0243f2018-07-03 08:09:29 +0000852// If \p Includes is set, it will be updated based on the compiler invocation.
Sam McCalld1a7a372018-01-31 13:40:48 +0000853bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000854 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000855 const SemaCompleteInput &Input,
Sam McCall3f0243f2018-07-03 08:09:29 +0000856 IncludeStructure *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000857 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000858 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000859 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000860 ArgStrs.push_back(S.c_str());
861
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000862 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
863 log("Couldn't set working directory");
864 // We run parsing anyway, our lit-tests rely on results for non-existing
865 // working dirs.
866 }
Sam McCall98775c52017-12-04 13:49:59 +0000867
868 IgnoreDiagnostics DummyDiagsConsumer;
869 auto CI = createInvocationFromCommandLine(
870 ArgStrs,
871 CompilerInstance::createDiagnostics(new DiagnosticOptions,
872 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000873 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000874 if (!CI) {
Sam McCallbed58852018-07-11 10:35:11 +0000875 elog("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000876 return false;
877 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000878 auto &FrontendOpts = CI->getFrontendOpts();
879 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000880 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000881 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
882 // Disable typo correction in Sema.
883 CI->getLangOpts()->SpellChecking = false;
884 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +0000885 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000886 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000887 auto Offset = positionToOffset(Input.Contents, Input.Pos);
888 if (!Offset) {
Sam McCallbed58852018-07-11 10:35:11 +0000889 elog("Code completion position was invalid {0}", Offset.takeError());
Sam McCalla4962cc2018-04-27 11:59:28 +0000890 return false;
891 }
892 std::tie(FrontendOpts.CodeCompletionAt.Line,
893 FrontendOpts.CodeCompletionAt.Column) =
894 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000895
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000896 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
897 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
898 // The diagnostic options must be set before creating a CompilerInstance.
899 CI->getDiagnosticOpts().IgnoreWarnings = true;
900 // We reuse the preamble whether it's valid or not. This is a
901 // correctness/performance tradeoff: building without a preamble is slow, and
902 // completion is latency-sensitive.
903 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
904 // the remapped buffers do not get freed.
905 auto Clang = prepareCompilerInstance(
906 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
907 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000908 Clang->setCodeCompletionConsumer(Consumer.release());
909
910 SyntaxOnlyAction Action;
911 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCallbed58852018-07-11 10:35:11 +0000912 log("BeginSourceFile() failed when running codeComplete for {0}",
Sam McCalld1a7a372018-01-31 13:40:48 +0000913 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000914 return false;
915 }
Sam McCall3f0243f2018-07-03 08:09:29 +0000916 if (Includes)
917 Clang->getPreprocessor().addPPCallbacks(
918 collectIncludeStructureCallback(Clang->getSourceManager(), Includes));
Sam McCall98775c52017-12-04 13:49:59 +0000919 if (!Action.Execute()) {
Sam McCallbed58852018-07-11 10:35:11 +0000920 log("Execute() failed when running codeComplete for {0}", Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000921 return false;
922 }
Sam McCall98775c52017-12-04 13:49:59 +0000923 Action.EndSourceFile();
924
925 return true;
926}
927
Ilya Biryukova907ba42018-05-14 10:50:04 +0000928// Should we allow index completions in the specified context?
929bool allowIndex(CodeCompletionContext &CC) {
930 if (!contextAllowsIndex(CC.getKind()))
931 return false;
932 // We also avoid ClassName::bar (but allow namespace::bar).
933 auto Scope = CC.getCXXScopeSpecifier();
934 if (!Scope)
935 return true;
936 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
937 if (!NameSpec)
938 return true;
939 // We only query the index when qualifier is a namespace.
940 // If it's a class, we rely solely on sema completions.
941 switch (NameSpec->getKind()) {
942 case NestedNameSpecifier::Global:
943 case NestedNameSpecifier::Namespace:
944 case NestedNameSpecifier::NamespaceAlias:
945 return true;
946 case NestedNameSpecifier::Super:
947 case NestedNameSpecifier::TypeSpec:
948 case NestedNameSpecifier::TypeSpecWithTemplate:
949 // Unresolved inside a template.
950 case NestedNameSpecifier::Identifier:
951 return false;
952 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000953 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000954}
955
Sam McCall98775c52017-12-04 13:49:59 +0000956} // namespace
957
958clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
959 clang::CodeCompleteOptions Result;
960 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
961 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000962 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000963 // We choose to include full comments and not do doxygen parsing in
964 // completion.
965 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
966 // formatting of the comments.
967 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000968
Sam McCall3d139c52018-01-12 18:30:08 +0000969 // When an is used, Sema is responsible for completing the main file,
970 // the index can provide results from the preamble.
971 // Tell Sema not to deserialize the preamble to look for results.
972 Result.LoadExternal = !Index;
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000973 Result.IncludeFixIts = IncludeFixIts;
Eric Liu6f648df2017-12-19 16:50:37 +0000974
Sam McCall98775c52017-12-04 13:49:59 +0000975 return Result;
976}
977
Sam McCall545a20d2018-01-19 14:34:02 +0000978// Runs Sema-based (AST) and Index-based completion, returns merged results.
979//
980// There are a few tricky considerations:
981// - the AST provides information needed for the index query (e.g. which
982// namespaces to search in). So Sema must start first.
983// - we only want to return the top results (Opts.Limit).
984// Building CompletionItems for everything else is wasteful, so we want to
985// preserve the "native" format until we're done with scoring.
986// - the data underlying Sema completion items is owned by the AST and various
987// other arenas, which must stay alive for us to build CompletionItems.
988// - we may get duplicate results from Sema and the Index, we need to merge.
989//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000990// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000991// We use the Sema context information to query the index.
992// Then we merge the two result sets, producing items that are Sema/Index/Both.
993// These items are scored, and the top N are synthesized into the LSP response.
994// Finally, we can clean up the data structures created by Sema completion.
995//
996// Main collaborators are:
997// - semaCodeComplete sets up the compiler machinery to run code completion.
998// - CompletionRecorder captures Sema completion results, including context.
999// - SymbolIndex (Opts.Index) provides index completion results as Symbols
1000// - CompletionCandidates are the result of merging Sema and Index results.
1001// Each candidate points to an underlying CodeCompletionResult (Sema), a
1002// Symbol (Index), or both. It computes the result quality score.
1003// CompletionCandidate also does conversion to CompletionItem (at the end).
1004// - FuzzyMatcher scores how the candidate matches the partial identifier.
1005// This score is combined with the result quality score for the final score.
1006// - TopN determines the results with the best score.
1007class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +00001008 PathRef FileName;
Sam McCall3f0243f2018-07-03 08:09:29 +00001009 IncludeStructure Includes; // Complete once the compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +00001010 const CodeCompleteOptions &Opts;
1011 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001012 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +00001013 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
1014 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +00001015 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
Eric Liubc25ef72018-07-05 08:29:33 +00001016 std::vector<std::string> QueryScopes; // Initialized once Sema runs.
Sam McCall3f0243f2018-07-03 08:09:29 +00001017 // Include-insertion and proximity scoring rely on the include structure.
1018 // This is available after Sema has run.
1019 llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
1020 llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
Sam McCall545a20d2018-01-19 14:34:02 +00001021
1022public:
1023 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Sam McCall3f0243f2018-07-03 08:09:29 +00001024 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
1025 const CodeCompleteOptions &Opts)
1026 : FileName(FileName), Includes(Includes), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +00001027
Sam McCall27c979a2018-06-29 14:47:57 +00001028 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +00001029 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +00001030
Sam McCall545a20d2018-01-19 14:34:02 +00001031 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001032 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +00001033 // - partial identifier and context. We need these for the index query.
Sam McCall27c979a2018-06-29 14:47:57 +00001034 CodeCompleteResult Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001035 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
1036 assert(Recorder && "Recorder is not set");
Sam McCall3f0243f2018-07-03 08:09:29 +00001037 auto Style =
Eric Liu9338a882018-07-03 14:51:23 +00001038 format::getStyle(format::DefaultFormatStyle, SemaCCInput.FileName,
1039 format::DefaultFallbackStyle, SemaCCInput.Contents,
1040 SemaCCInput.VFS.get());
Sam McCall3f0243f2018-07-03 08:09:29 +00001041 if (!Style) {
Sam McCallbed58852018-07-11 10:35:11 +00001042 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.",
1043 SemaCCInput.FileName, Style.takeError());
Sam McCall3f0243f2018-07-03 08:09:29 +00001044 Style = format::getLLVMStyle();
1045 }
Eric Liu63f419a2018-05-15 15:29:32 +00001046 // If preprocessor was run, inclusions from preprocessor callback should
Sam McCall3f0243f2018-07-03 08:09:29 +00001047 // already be added to Includes.
1048 Inserter.emplace(
1049 SemaCCInput.FileName, SemaCCInput.Contents, *Style,
1050 SemaCCInput.Command.Directory,
1051 Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
1052 for (const auto &Inc : Includes.MainFileIncludes)
1053 Inserter->addExisting(Inc);
1054
1055 // Most of the cost of file proximity is in initializing the FileDistance
1056 // structures based on the observed includes, once per query. Conceptually
1057 // that happens here (though the per-URI-scheme initialization is lazy).
1058 // The per-result proximity scoring is (amortized) very cheap.
1059 FileDistanceOptions ProxOpts{}; // Use defaults.
1060 const auto &SM = Recorder->CCSema->getSourceManager();
1061 llvm::StringMap<SourceParams> ProxSources;
1062 for (auto &Entry : Includes.includeDepth(
1063 SM.getFileEntryForID(SM.getMainFileID())->getName())) {
1064 auto &Source = ProxSources[Entry.getKey()];
1065 Source.Cost = Entry.getValue() * ProxOpts.IncludeCost;
1066 // Symbols near our transitive includes are good, but only consider
1067 // things in the same directory or below it. Otherwise there can be
1068 // many false positives.
1069 if (Entry.getValue() > 0)
1070 Source.MaxUpTraversals = 1;
1071 }
1072 FileProximity.emplace(ProxSources, ProxOpts);
1073
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001074 Output = runWithSema();
Sam McCall3f0243f2018-07-03 08:09:29 +00001075 Inserter.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001076 SPAN_ATTACH(Tracer, "sema_completion_kind",
1077 getCompletionKindString(Recorder->CCContext.getKind()));
Sam McCallbed58852018-07-11 10:35:11 +00001078 log("Code complete: sema context {0}, query scopes [{1}]",
Eric Liubc25ef72018-07-05 08:29:33 +00001079 getCompletionKindString(Recorder->CCContext.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +00001080 llvm::join(QueryScopes.begin(), QueryScopes.end(), ","));
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001081 });
1082
1083 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +00001084 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +00001085 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +00001086
Sam McCall2b780162018-01-30 17:20:54 +00001087 SPAN_ATTACH(Tracer, "sema_results", NSema);
1088 SPAN_ATTACH(Tracer, "index_results", NIndex);
1089 SPAN_ATTACH(Tracer, "merged_results", NBoth);
Sam McCalld20d7982018-07-09 14:25:59 +00001090 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
Sam McCall27c979a2018-06-29 14:47:57 +00001091 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
Sam McCallbed58852018-07-11 10:35:11 +00001092 log("Code complete: {0} results from Sema, {1} from Index, "
1093 "{2} matched, {3} returned{4}.",
1094 NSema, NIndex, NBoth, Output.Completions.size(),
1095 Output.HasMore ? " (incomplete)" : "");
Sam McCall27c979a2018-06-29 14:47:57 +00001096 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +00001097 // We don't assert that isIncomplete means we hit a limit.
1098 // Indexes may choose to impose their own limits even if we don't have one.
1099 return Output;
1100 }
1101
1102private:
1103 // This is called by run() once Sema code completion is done, but before the
1104 // Sema data structures are torn down. It does all the real work.
Sam McCall27c979a2018-06-29 14:47:57 +00001105 CodeCompleteResult runWithSema() {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001106 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1107 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1108 Range TextEditRange;
1109 // When we are getting completions with an empty identifier, for example
1110 // std::vector<int> asdf;
1111 // asdf.^;
1112 // Then the range will be invalid and we will be doing insertion, use
1113 // current cursor position in such cases as range.
1114 if (CodeCompletionRange.isValid()) {
1115 TextEditRange = halfOpenToRange(Recorder->CCSema->getSourceManager(),
1116 CodeCompletionRange);
1117 } else {
1118 const auto &Pos = sourceLocToPosition(
1119 Recorder->CCSema->getSourceManager(),
1120 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1121 TextEditRange.start = TextEditRange.end = Pos;
1122 }
Sam McCall545a20d2018-01-19 14:34:02 +00001123 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001124 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Eric Liubc25ef72018-07-05 08:29:33 +00001125 QueryScopes = getQueryScopes(Recorder->CCContext,
1126 Recorder->CCSema->getSourceManager());
Sam McCall545a20d2018-01-19 14:34:02 +00001127 // Sema provides the needed context to query the index.
1128 // FIXME: in addition to querying for extra/overlapping symbols, we should
1129 // explicitly request symbols corresponding to Sema results.
1130 // We can use their signals even if the index can't suggest them.
1131 // We must copy index results to preserve them, but there are at most Limit.
Eric Liu8f3678d2018-06-15 13:34:18 +00001132 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1133 ? queryIndex()
1134 : SymbolSlab();
Sam McCall545a20d2018-01-19 14:34:02 +00001135 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001136 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall27c979a2018-06-29 14:47:57 +00001137 // Convert the results to final form, assembling the expensive strings.
1138 CodeCompleteResult Output;
1139 for (auto &C : Top) {
1140 Output.Completions.push_back(toCodeCompletion(C.first));
1141 Output.Completions.back().Score = C.second;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001142 Output.Completions.back().CompletionTokenRange = TextEditRange;
Sam McCall27c979a2018-06-29 14:47:57 +00001143 }
1144 Output.HasMore = Incomplete;
Eric Liu5d2a8072018-07-23 10:56:37 +00001145 Output.Context = Recorder->CCContext.getKind();
Sam McCall545a20d2018-01-19 14:34:02 +00001146 return Output;
1147 }
1148
1149 SymbolSlab queryIndex() {
Sam McCalld1a7a372018-01-31 13:40:48 +00001150 trace::Span Tracer("Query index");
Sam McCalld20d7982018-07-09 14:25:59 +00001151 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
Sam McCall2b780162018-01-30 17:20:54 +00001152
Sam McCall545a20d2018-01-19 14:34:02 +00001153 SymbolSlab::Builder ResultsBuilder;
1154 // Build the query.
1155 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +00001156 if (Opts.Limit)
1157 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +00001158 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001159 Req.RestrictForCodeCompletion = true;
Eric Liubc25ef72018-07-05 08:29:33 +00001160 Req.Scopes = QueryScopes;
Sam McCall3f0243f2018-07-03 08:09:29 +00001161 // FIXME: we should send multiple weighted paths here.
Eric Liu6de95ec2018-06-12 08:48:20 +00001162 Req.ProximityPaths.push_back(FileName);
Sam McCallbed58852018-07-11 10:35:11 +00001163 vlog("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])", Req.Query,
1164 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ","));
Sam McCall545a20d2018-01-19 14:34:02 +00001165 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +00001166 if (Opts.Index->fuzzyFind(
1167 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1168 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001169 return std::move(ResultsBuilder).build();
1170 }
1171
Sam McCallc18c2802018-06-15 11:06:29 +00001172 // Merges Sema and Index results where possible, to form CompletionCandidates.
1173 // Groups overloads if desired, to form CompletionCandidate::Bundles.
1174 // The bundles are scored and top results are returned, best to worst.
1175 std::vector<ScoredBundle>
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001176 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1177 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +00001178 trace::Span Tracer("Merge and score results");
Sam McCallc18c2802018-06-15 11:06:29 +00001179 std::vector<CompletionCandidate::Bundle> Bundles;
1180 llvm::DenseMap<size_t, size_t> BundleLookup;
1181 auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
1182 const Symbol *IndexResult) {
1183 CompletionCandidate C;
1184 C.SemaResult = SemaResult;
1185 C.IndexResult = IndexResult;
1186 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1187 if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1188 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1189 if (Ret.second)
1190 Bundles.emplace_back();
1191 Bundles[Ret.first->second].push_back(std::move(C));
1192 } else {
1193 Bundles.emplace_back();
1194 Bundles.back().push_back(std::move(C));
1195 }
1196 };
Sam McCall545a20d2018-01-19 14:34:02 +00001197 llvm::DenseSet<const Symbol *> UsedIndexResults;
1198 auto CorrespondingIndexResult =
1199 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
1200 if (auto SymID = getSymbolID(SemaResult)) {
1201 auto I = IndexResults.find(*SymID);
1202 if (I != IndexResults.end()) {
1203 UsedIndexResults.insert(&*I);
1204 return &*I;
1205 }
1206 }
1207 return nullptr;
1208 };
1209 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001210 for (auto &SemaResult : Recorder->Results)
Sam McCallc18c2802018-06-15 11:06:29 +00001211 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
Sam McCall545a20d2018-01-19 14:34:02 +00001212 // Now emit any Index-only results.
1213 for (const auto &IndexResult : IndexResults) {
1214 if (UsedIndexResults.count(&IndexResult))
1215 continue;
Sam McCallc18c2802018-06-15 11:06:29 +00001216 AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001217 }
Sam McCallc18c2802018-06-15 11:06:29 +00001218 // We only keep the best N results at any time, in "native" format.
1219 TopN<ScoredBundle, ScoredBundleGreater> Top(
1220 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1221 for (auto &Bundle : Bundles)
1222 addCandidate(Top, std::move(Bundle));
Sam McCall545a20d2018-01-19 14:34:02 +00001223 return std::move(Top).items();
1224 }
1225
Sam McCall80ad7072018-06-08 13:32:25 +00001226 Optional<float> fuzzyScore(const CompletionCandidate &C) {
1227 // Macros can be very spammy, so we only support prefix completion.
1228 // We won't end up with underfull index results, as macros are sema-only.
1229 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1230 !C.Name.startswith_lower(Filter->pattern()))
1231 return None;
1232 return Filter->match(C.Name);
1233 }
1234
Sam McCall545a20d2018-01-19 14:34:02 +00001235 // Scores a candidate and adds it to the TopN structure.
Sam McCallc18c2802018-06-15 11:06:29 +00001236 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1237 CompletionCandidate::Bundle Bundle) {
Sam McCallc5707b62018-05-15 17:43:27 +00001238 SymbolQualitySignals Quality;
1239 SymbolRelevanceSignals Relevance;
Eric Liu5d2a8072018-07-23 10:56:37 +00001240 Relevance.Context = Recorder->CCContext.getKind();
Sam McCalld9b54f02018-06-05 16:30:25 +00001241 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Sam McCallf84dd022018-07-05 08:26:53 +00001242 Relevance.FileProximityMatch = FileProximity.getPointer();
Sam McCallc18c2802018-06-15 11:06:29 +00001243 auto &First = Bundle.front();
1244 if (auto FuzzyScore = fuzzyScore(First))
Sam McCallc5707b62018-05-15 17:43:27 +00001245 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001246 else
1247 return;
Sam McCall2161ec72018-07-05 06:20:41 +00001248 SymbolOrigin Origin = SymbolOrigin::Unknown;
Sam McCall4e5742a2018-07-06 11:50:49 +00001249 bool FromIndex = false;
Sam McCallc18c2802018-06-15 11:06:29 +00001250 for (const auto &Candidate : Bundle) {
1251 if (Candidate.IndexResult) {
1252 Quality.merge(*Candidate.IndexResult);
1253 Relevance.merge(*Candidate.IndexResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001254 Origin |= Candidate.IndexResult->Origin;
1255 FromIndex = true;
Sam McCallc18c2802018-06-15 11:06:29 +00001256 }
1257 if (Candidate.SemaResult) {
1258 Quality.merge(*Candidate.SemaResult);
1259 Relevance.merge(*Candidate.SemaResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001260 Origin |= SymbolOrigin::AST;
Sam McCallc18c2802018-06-15 11:06:29 +00001261 }
Sam McCallc5707b62018-05-15 17:43:27 +00001262 }
1263
Sam McCall27c979a2018-06-29 14:47:57 +00001264 CodeCompletion::Scores Scores;
1265 Scores.Quality = Quality.evaluate();
1266 Scores.Relevance = Relevance.evaluate();
1267 Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1268 // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1269 Scores.ExcludingName = Relevance.NameMatch
1270 ? Scores.Total / Relevance.NameMatch
1271 : Scores.Quality;
Sam McCallc5707b62018-05-15 17:43:27 +00001272
Sam McCallbed58852018-07-11 10:35:11 +00001273 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
1274 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
1275 llvm::to_string(Relevance));
Sam McCall545a20d2018-01-19 14:34:02 +00001276
Sam McCall2161ec72018-07-05 06:20:41 +00001277 NSema += bool(Origin & SymbolOrigin::AST);
Sam McCall4e5742a2018-07-06 11:50:49 +00001278 NIndex += FromIndex;
1279 NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
Sam McCallc18c2802018-06-15 11:06:29 +00001280 if (Candidates.push({std::move(Bundle), Scores}))
Sam McCallab8e3932018-02-19 13:04:41 +00001281 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001282 }
1283
Sam McCall27c979a2018-06-29 14:47:57 +00001284 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
1285 llvm::Optional<CodeCompletionBuilder> Builder;
1286 for (const auto &Item : Bundle) {
1287 CodeCompletionString *SemaCCS =
1288 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1289 : nullptr;
1290 if (!Builder)
1291 Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
Sam McCall3f0243f2018-07-03 08:09:29 +00001292 *Inserter, FileName, Opts);
Sam McCall27c979a2018-06-29 14:47:57 +00001293 else
1294 Builder->add(Item, SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +00001295 }
Sam McCall27c979a2018-06-29 14:47:57 +00001296 return Builder->build();
Sam McCall545a20d2018-01-19 14:34:02 +00001297 }
1298};
1299
Sam McCall3f0243f2018-07-03 08:09:29 +00001300CodeCompleteResult codeComplete(PathRef FileName,
1301 const tooling::CompileCommand &Command,
1302 PrecompiledPreamble const *Preamble,
1303 const IncludeStructure &PreambleInclusions,
1304 StringRef Contents, Position Pos,
1305 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1306 std::shared_ptr<PCHContainerOperations> PCHs,
1307 CodeCompleteOptions Opts) {
1308 return CodeCompleteFlow(FileName, PreambleInclusions, Opts)
1309 .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001310}
1311
Sam McCalld1a7a372018-01-31 13:40:48 +00001312SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001313 const tooling::CompileCommand &Command,
1314 PrecompiledPreamble const *Preamble,
1315 StringRef Contents, Position Pos,
1316 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1317 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001318 SignatureHelp Result;
1319 clang::CodeCompleteOptions Options;
1320 Options.IncludeGlobals = false;
1321 Options.IncludeMacros = false;
1322 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001323 Options.IncludeBriefComments = false;
Sam McCall3f0243f2018-07-03 08:09:29 +00001324 IncludeStructure PreambleInclusions; // Unused for signatureHelp
Sam McCalld1a7a372018-01-31 13:40:48 +00001325 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1326 Options,
Sam McCall3f0243f2018-07-03 08:09:29 +00001327 {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1328 std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001329 return Result;
1330}
1331
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001332bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1333 using namespace clang::ast_matchers;
1334 auto InTopLevelScope = hasDeclContext(
1335 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1336 return !match(decl(anyOf(InTopLevelScope,
1337 hasDeclContext(
1338 enumDecl(InTopLevelScope, unless(isScoped()))))),
1339 ND, ASTCtx)
1340 .empty();
1341}
1342
Sam McCall27c979a2018-06-29 14:47:57 +00001343CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1344 CompletionItem LSP;
1345 LSP.label = (HeaderInsertion ? Opts.IncludeIndicator.Insert
1346 : Opts.IncludeIndicator.NoInsert) +
Sam McCall2161ec72018-07-05 06:20:41 +00001347 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
Sam McCall27c979a2018-06-29 14:47:57 +00001348 RequiredQualifier + Name + Signature;
Sam McCall2161ec72018-07-05 06:20:41 +00001349
Sam McCall27c979a2018-06-29 14:47:57 +00001350 LSP.kind = Kind;
1351 LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
1352 : ReturnType;
1353 if (!Header.empty())
1354 LSP.detail += "\n" + Header;
1355 LSP.documentation = Documentation;
1356 LSP.sortText = sortText(Score.Total, Name);
1357 LSP.filterText = Name;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001358 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name};
1359 // Merge continious additionalTextEdits into main edit. The main motivation
1360 // behind this is to help LSP clients, it seems most of them are confused when
1361 // they are provided with additionalTextEdits that are consecutive to main
1362 // edit.
1363 // Note that we store additional text edits from back to front in a line. That
1364 // is mainly to help LSP clients again, so that changes do not effect each
1365 // other.
1366 for (const auto &FixIt : FixIts) {
1367 if (IsRangeConsecutive(FixIt.range, LSP.textEdit->range)) {
1368 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
1369 LSP.textEdit->range.start = FixIt.range.start;
1370 } else {
1371 LSP.additionalTextEdits.push_back(FixIt);
1372 }
1373 }
Sam McCall27c979a2018-06-29 14:47:57 +00001374 if (Opts.EnableSnippets)
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001375 LSP.textEdit->newText += SnippetSuffix;
1376 // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
1377 // compatible with most of the editors.
1378 LSP.insertText = LSP.textEdit->newText;
Sam McCall27c979a2018-06-29 14:47:57 +00001379 LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1380 : InsertTextFormat::PlainText;
1381 if (HeaderInsertion)
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001382 LSP.additionalTextEdits.push_back(*HeaderInsertion);
Sam McCall27c979a2018-06-29 14:47:57 +00001383 return LSP;
1384}
1385
Sam McCalle746a2b2018-07-02 11:13:16 +00001386raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) {
1387 // For now just lean on CompletionItem.
1388 return OS << C.render(CodeCompleteOptions());
1389}
1390
1391raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) {
1392 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
Eric Liu5d2a8072018-07-23 10:56:37 +00001393 << " (" << getCompletionKindString(R.Context) << ")"
Sam McCalle746a2b2018-07-02 11:13:16 +00001394 << " items:\n";
1395 for (const auto &C : R.Completions)
1396 OS << C << "\n";
1397 return OS;
1398}
1399
Sam McCall98775c52017-12-04 13:49:59 +00001400} // namespace clangd
1401} // namespace clang