blob: 12a3d5f48f53aa20fdba13987a08e86f4703d9cf [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) {
717 const auto &Candidate = Candidates[I];
718 const auto *CCS = Candidate.CreateSignatureString(
719 CurrentArg, S, *Allocator, CCTUInfo, true);
720 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000721 // FIXME: for headers, we need to get a comment from the index.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000722 ScoredSignatures.push_back(processOverloadCandidate(
Ilya Biryukov43714502018-05-16 12:32:44 +0000723 Candidate, *CCS,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000724 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000725 /*CommentsFromHeaders=*/false)));
Sam McCall98775c52017-12-04 13:49:59 +0000726 }
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000727 std::sort(ScoredSignatures.begin(), ScoredSignatures.end(),
728 [](const ScoredSignature &L, const ScoredSignature &R) {
729 // Ordering follows:
730 // - Less number of parameters is better.
731 // - Function is better than FunctionType which is better than
732 // Function Template.
733 // - High score is better.
734 // - Shorter signature is better.
735 // - Alphebatically smaller is better.
736 if (L.first.NumberOfParameters != R.first.NumberOfParameters)
737 return L.first.NumberOfParameters <
738 R.first.NumberOfParameters;
739 if (L.first.NumberOfOptionalParameters !=
740 R.first.NumberOfOptionalParameters)
741 return L.first.NumberOfOptionalParameters <
742 R.first.NumberOfOptionalParameters;
743 if (L.first.Kind != R.first.Kind) {
744 using OC = CodeCompleteConsumer::OverloadCandidate;
745 switch (L.first.Kind) {
746 case OC::CK_Function:
747 return true;
748 case OC::CK_FunctionType:
749 return R.first.Kind != OC::CK_Function;
750 case OC::CK_FunctionTemplate:
751 return false;
752 }
753 llvm_unreachable("Unknown overload candidate type.");
754 }
755 if (L.second.label.size() != R.second.label.size())
756 return L.second.label.size() < R.second.label.size();
757 return L.second.label < R.second.label;
758 });
759 for (const auto &SS : ScoredSignatures)
760 SigHelp.signatures.push_back(SS.second);
Sam McCall98775c52017-12-04 13:49:59 +0000761 }
762
763 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
764
765 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
766
767private:
Eric Liu63696e12017-12-20 17:24:31 +0000768 // FIXME(ioeric): consider moving CodeCompletionString logic here to
769 // CompletionString.h.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000770 ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
771 const CodeCompletionString &CCS,
772 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000773 SignatureInformation Result;
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000774 SignatureQualitySignals Signal;
Sam McCall98775c52017-12-04 13:49:59 +0000775 const char *ReturnType = nullptr;
776
Ilya Biryukov43714502018-05-16 12:32:44 +0000777 Result.documentation = formatDocumentation(CCS, DocComment);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000778 Signal.Kind = Candidate.getKind();
Sam McCall98775c52017-12-04 13:49:59 +0000779
780 for (const auto &Chunk : CCS) {
781 switch (Chunk.Kind) {
782 case CodeCompletionString::CK_ResultType:
783 // A piece of text that describes the type of an entity or,
784 // for functions and methods, the return type.
785 assert(!ReturnType && "Unexpected CK_ResultType");
786 ReturnType = Chunk.Text;
787 break;
788 case CodeCompletionString::CK_Placeholder:
789 // A string that acts as a placeholder for, e.g., a function call
790 // argument.
791 // Intentional fallthrough here.
792 case CodeCompletionString::CK_CurrentParameter: {
793 // A piece of text that describes the parameter that corresponds to
794 // the code-completion location within a function call, message send,
795 // macro invocation, etc.
796 Result.label += Chunk.Text;
797 ParameterInformation Info;
798 Info.label = Chunk.Text;
799 Result.parameters.push_back(std::move(Info));
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000800 Signal.NumberOfParameters++;
801 Signal.ContainsActiveParameter = true;
Sam McCall98775c52017-12-04 13:49:59 +0000802 break;
803 }
804 case CodeCompletionString::CK_Optional: {
805 // The rest of the parameters are defaulted/optional.
806 assert(Chunk.Optional &&
807 "Expected the optional code completion string to be non-null.");
808 Result.label +=
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000809 getOptionalParameters(*Chunk.Optional, Result.parameters, Signal);
Sam McCall98775c52017-12-04 13:49:59 +0000810 break;
811 }
812 case CodeCompletionString::CK_VerticalSpace:
813 break;
814 default:
815 Result.label += Chunk.Text;
816 break;
817 }
818 }
819 if (ReturnType) {
820 Result.label += " -> ";
821 Result.label += ReturnType;
822 }
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000823 dlog("Signal for {0}: {1}", Result, Signal);
824 return {Signal, Result};
Sam McCall98775c52017-12-04 13:49:59 +0000825 }
826
827 SignatureHelp &SigHelp;
828 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
829 CodeCompletionTUInfo CCTUInfo;
830
831}; // SignatureHelpCollector
832
Sam McCall545a20d2018-01-19 14:34:02 +0000833struct SemaCompleteInput {
834 PathRef FileName;
835 const tooling::CompileCommand &Command;
836 PrecompiledPreamble const *Preamble;
837 StringRef Contents;
838 Position Pos;
839 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
840 std::shared_ptr<PCHContainerOperations> PCHs;
841};
842
843// Invokes Sema code completion on a file.
Sam McCall3f0243f2018-07-03 08:09:29 +0000844// If \p Includes is set, it will be updated based on the compiler invocation.
Sam McCalld1a7a372018-01-31 13:40:48 +0000845bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000846 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000847 const SemaCompleteInput &Input,
Sam McCall3f0243f2018-07-03 08:09:29 +0000848 IncludeStructure *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000849 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000850 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000851 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000852 ArgStrs.push_back(S.c_str());
853
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000854 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
855 log("Couldn't set working directory");
856 // We run parsing anyway, our lit-tests rely on results for non-existing
857 // working dirs.
858 }
Sam McCall98775c52017-12-04 13:49:59 +0000859
860 IgnoreDiagnostics DummyDiagsConsumer;
861 auto CI = createInvocationFromCommandLine(
862 ArgStrs,
863 CompilerInstance::createDiagnostics(new DiagnosticOptions,
864 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000865 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000866 if (!CI) {
Sam McCallbed58852018-07-11 10:35:11 +0000867 elog("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000868 return false;
869 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000870 auto &FrontendOpts = CI->getFrontendOpts();
871 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000872 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000873 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
874 // Disable typo correction in Sema.
875 CI->getLangOpts()->SpellChecking = false;
876 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +0000877 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000878 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000879 auto Offset = positionToOffset(Input.Contents, Input.Pos);
880 if (!Offset) {
Sam McCallbed58852018-07-11 10:35:11 +0000881 elog("Code completion position was invalid {0}", Offset.takeError());
Sam McCalla4962cc2018-04-27 11:59:28 +0000882 return false;
883 }
884 std::tie(FrontendOpts.CodeCompletionAt.Line,
885 FrontendOpts.CodeCompletionAt.Column) =
886 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000887
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000888 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
889 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
890 // The diagnostic options must be set before creating a CompilerInstance.
891 CI->getDiagnosticOpts().IgnoreWarnings = true;
892 // We reuse the preamble whether it's valid or not. This is a
893 // correctness/performance tradeoff: building without a preamble is slow, and
894 // completion is latency-sensitive.
895 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
896 // the remapped buffers do not get freed.
897 auto Clang = prepareCompilerInstance(
898 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
899 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000900 Clang->setCodeCompletionConsumer(Consumer.release());
901
902 SyntaxOnlyAction Action;
903 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCallbed58852018-07-11 10:35:11 +0000904 log("BeginSourceFile() failed when running codeComplete for {0}",
Sam McCalld1a7a372018-01-31 13:40:48 +0000905 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000906 return false;
907 }
Sam McCall3f0243f2018-07-03 08:09:29 +0000908 if (Includes)
909 Clang->getPreprocessor().addPPCallbacks(
910 collectIncludeStructureCallback(Clang->getSourceManager(), Includes));
Sam McCall98775c52017-12-04 13:49:59 +0000911 if (!Action.Execute()) {
Sam McCallbed58852018-07-11 10:35:11 +0000912 log("Execute() failed when running codeComplete for {0}", Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000913 return false;
914 }
Sam McCall98775c52017-12-04 13:49:59 +0000915 Action.EndSourceFile();
916
917 return true;
918}
919
Ilya Biryukova907ba42018-05-14 10:50:04 +0000920// Should we allow index completions in the specified context?
921bool allowIndex(CodeCompletionContext &CC) {
922 if (!contextAllowsIndex(CC.getKind()))
923 return false;
924 // We also avoid ClassName::bar (but allow namespace::bar).
925 auto Scope = CC.getCXXScopeSpecifier();
926 if (!Scope)
927 return true;
928 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
929 if (!NameSpec)
930 return true;
931 // We only query the index when qualifier is a namespace.
932 // If it's a class, we rely solely on sema completions.
933 switch (NameSpec->getKind()) {
934 case NestedNameSpecifier::Global:
935 case NestedNameSpecifier::Namespace:
936 case NestedNameSpecifier::NamespaceAlias:
937 return true;
938 case NestedNameSpecifier::Super:
939 case NestedNameSpecifier::TypeSpec:
940 case NestedNameSpecifier::TypeSpecWithTemplate:
941 // Unresolved inside a template.
942 case NestedNameSpecifier::Identifier:
943 return false;
944 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000945 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000946}
947
Sam McCall98775c52017-12-04 13:49:59 +0000948} // namespace
949
950clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
951 clang::CodeCompleteOptions Result;
952 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
953 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000954 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000955 // We choose to include full comments and not do doxygen parsing in
956 // completion.
957 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
958 // formatting of the comments.
959 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000960
Sam McCall3d139c52018-01-12 18:30:08 +0000961 // When an is used, Sema is responsible for completing the main file,
962 // the index can provide results from the preamble.
963 // Tell Sema not to deserialize the preamble to look for results.
964 Result.LoadExternal = !Index;
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000965 Result.IncludeFixIts = IncludeFixIts;
Eric Liu6f648df2017-12-19 16:50:37 +0000966
Sam McCall98775c52017-12-04 13:49:59 +0000967 return Result;
968}
969
Sam McCall545a20d2018-01-19 14:34:02 +0000970// Runs Sema-based (AST) and Index-based completion, returns merged results.
971//
972// There are a few tricky considerations:
973// - the AST provides information needed for the index query (e.g. which
974// namespaces to search in). So Sema must start first.
975// - we only want to return the top results (Opts.Limit).
976// Building CompletionItems for everything else is wasteful, so we want to
977// preserve the "native" format until we're done with scoring.
978// - the data underlying Sema completion items is owned by the AST and various
979// other arenas, which must stay alive for us to build CompletionItems.
980// - we may get duplicate results from Sema and the Index, we need to merge.
981//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000982// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000983// We use the Sema context information to query the index.
984// Then we merge the two result sets, producing items that are Sema/Index/Both.
985// These items are scored, and the top N are synthesized into the LSP response.
986// Finally, we can clean up the data structures created by Sema completion.
987//
988// Main collaborators are:
989// - semaCodeComplete sets up the compiler machinery to run code completion.
990// - CompletionRecorder captures Sema completion results, including context.
991// - SymbolIndex (Opts.Index) provides index completion results as Symbols
992// - CompletionCandidates are the result of merging Sema and Index results.
993// Each candidate points to an underlying CodeCompletionResult (Sema), a
994// Symbol (Index), or both. It computes the result quality score.
995// CompletionCandidate also does conversion to CompletionItem (at the end).
996// - FuzzyMatcher scores how the candidate matches the partial identifier.
997// This score is combined with the result quality score for the final score.
998// - TopN determines the results with the best score.
999class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +00001000 PathRef FileName;
Sam McCall3f0243f2018-07-03 08:09:29 +00001001 IncludeStructure Includes; // Complete once the compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +00001002 const CodeCompleteOptions &Opts;
1003 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001004 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +00001005 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
1006 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +00001007 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
Eric Liubc25ef72018-07-05 08:29:33 +00001008 std::vector<std::string> QueryScopes; // Initialized once Sema runs.
Sam McCall3f0243f2018-07-03 08:09:29 +00001009 // Include-insertion and proximity scoring rely on the include structure.
1010 // This is available after Sema has run.
1011 llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
1012 llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
Sam McCall545a20d2018-01-19 14:34:02 +00001013
1014public:
1015 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Sam McCall3f0243f2018-07-03 08:09:29 +00001016 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
1017 const CodeCompleteOptions &Opts)
1018 : FileName(FileName), Includes(Includes), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +00001019
Sam McCall27c979a2018-06-29 14:47:57 +00001020 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +00001021 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +00001022
Sam McCall545a20d2018-01-19 14:34:02 +00001023 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001024 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +00001025 // - partial identifier and context. We need these for the index query.
Sam McCall27c979a2018-06-29 14:47:57 +00001026 CodeCompleteResult Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001027 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
1028 assert(Recorder && "Recorder is not set");
Sam McCall3f0243f2018-07-03 08:09:29 +00001029 auto Style =
Eric Liu9338a882018-07-03 14:51:23 +00001030 format::getStyle(format::DefaultFormatStyle, SemaCCInput.FileName,
1031 format::DefaultFallbackStyle, SemaCCInput.Contents,
1032 SemaCCInput.VFS.get());
Sam McCall3f0243f2018-07-03 08:09:29 +00001033 if (!Style) {
Sam McCallbed58852018-07-11 10:35:11 +00001034 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.",
1035 SemaCCInput.FileName, Style.takeError());
Sam McCall3f0243f2018-07-03 08:09:29 +00001036 Style = format::getLLVMStyle();
1037 }
Eric Liu63f419a2018-05-15 15:29:32 +00001038 // If preprocessor was run, inclusions from preprocessor callback should
Sam McCall3f0243f2018-07-03 08:09:29 +00001039 // already be added to Includes.
1040 Inserter.emplace(
1041 SemaCCInput.FileName, SemaCCInput.Contents, *Style,
1042 SemaCCInput.Command.Directory,
1043 Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
1044 for (const auto &Inc : Includes.MainFileIncludes)
1045 Inserter->addExisting(Inc);
1046
1047 // Most of the cost of file proximity is in initializing the FileDistance
1048 // structures based on the observed includes, once per query. Conceptually
1049 // that happens here (though the per-URI-scheme initialization is lazy).
1050 // The per-result proximity scoring is (amortized) very cheap.
1051 FileDistanceOptions ProxOpts{}; // Use defaults.
1052 const auto &SM = Recorder->CCSema->getSourceManager();
1053 llvm::StringMap<SourceParams> ProxSources;
1054 for (auto &Entry : Includes.includeDepth(
1055 SM.getFileEntryForID(SM.getMainFileID())->getName())) {
1056 auto &Source = ProxSources[Entry.getKey()];
1057 Source.Cost = Entry.getValue() * ProxOpts.IncludeCost;
1058 // Symbols near our transitive includes are good, but only consider
1059 // things in the same directory or below it. Otherwise there can be
1060 // many false positives.
1061 if (Entry.getValue() > 0)
1062 Source.MaxUpTraversals = 1;
1063 }
1064 FileProximity.emplace(ProxSources, ProxOpts);
1065
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001066 Output = runWithSema();
Sam McCall3f0243f2018-07-03 08:09:29 +00001067 Inserter.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001068 SPAN_ATTACH(Tracer, "sema_completion_kind",
1069 getCompletionKindString(Recorder->CCContext.getKind()));
Sam McCallbed58852018-07-11 10:35:11 +00001070 log("Code complete: sema context {0}, query scopes [{1}]",
Eric Liubc25ef72018-07-05 08:29:33 +00001071 getCompletionKindString(Recorder->CCContext.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +00001072 llvm::join(QueryScopes.begin(), QueryScopes.end(), ","));
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001073 });
1074
1075 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +00001076 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +00001077 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +00001078
Sam McCall2b780162018-01-30 17:20:54 +00001079 SPAN_ATTACH(Tracer, "sema_results", NSema);
1080 SPAN_ATTACH(Tracer, "index_results", NIndex);
1081 SPAN_ATTACH(Tracer, "merged_results", NBoth);
Sam McCalld20d7982018-07-09 14:25:59 +00001082 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
Sam McCall27c979a2018-06-29 14:47:57 +00001083 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
Sam McCallbed58852018-07-11 10:35:11 +00001084 log("Code complete: {0} results from Sema, {1} from Index, "
1085 "{2} matched, {3} returned{4}.",
1086 NSema, NIndex, NBoth, Output.Completions.size(),
1087 Output.HasMore ? " (incomplete)" : "");
Sam McCall27c979a2018-06-29 14:47:57 +00001088 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +00001089 // We don't assert that isIncomplete means we hit a limit.
1090 // Indexes may choose to impose their own limits even if we don't have one.
1091 return Output;
1092 }
1093
1094private:
1095 // This is called by run() once Sema code completion is done, but before the
1096 // Sema data structures are torn down. It does all the real work.
Sam McCall27c979a2018-06-29 14:47:57 +00001097 CodeCompleteResult runWithSema() {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001098 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1099 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1100 Range TextEditRange;
1101 // When we are getting completions with an empty identifier, for example
1102 // std::vector<int> asdf;
1103 // asdf.^;
1104 // Then the range will be invalid and we will be doing insertion, use
1105 // current cursor position in such cases as range.
1106 if (CodeCompletionRange.isValid()) {
1107 TextEditRange = halfOpenToRange(Recorder->CCSema->getSourceManager(),
1108 CodeCompletionRange);
1109 } else {
1110 const auto &Pos = sourceLocToPosition(
1111 Recorder->CCSema->getSourceManager(),
1112 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1113 TextEditRange.start = TextEditRange.end = Pos;
1114 }
Sam McCall545a20d2018-01-19 14:34:02 +00001115 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001116 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Eric Liubc25ef72018-07-05 08:29:33 +00001117 QueryScopes = getQueryScopes(Recorder->CCContext,
1118 Recorder->CCSema->getSourceManager());
Sam McCall545a20d2018-01-19 14:34:02 +00001119 // Sema provides the needed context to query the index.
1120 // FIXME: in addition to querying for extra/overlapping symbols, we should
1121 // explicitly request symbols corresponding to Sema results.
1122 // We can use their signals even if the index can't suggest them.
1123 // We must copy index results to preserve them, but there are at most Limit.
Eric Liu8f3678d2018-06-15 13:34:18 +00001124 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1125 ? queryIndex()
1126 : SymbolSlab();
Sam McCall545a20d2018-01-19 14:34:02 +00001127 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001128 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall27c979a2018-06-29 14:47:57 +00001129 // Convert the results to final form, assembling the expensive strings.
1130 CodeCompleteResult Output;
1131 for (auto &C : Top) {
1132 Output.Completions.push_back(toCodeCompletion(C.first));
1133 Output.Completions.back().Score = C.second;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001134 Output.Completions.back().CompletionTokenRange = TextEditRange;
Sam McCall27c979a2018-06-29 14:47:57 +00001135 }
1136 Output.HasMore = Incomplete;
Eric Liu5d2a8072018-07-23 10:56:37 +00001137 Output.Context = Recorder->CCContext.getKind();
Sam McCall545a20d2018-01-19 14:34:02 +00001138 return Output;
1139 }
1140
1141 SymbolSlab queryIndex() {
Sam McCalld1a7a372018-01-31 13:40:48 +00001142 trace::Span Tracer("Query index");
Sam McCalld20d7982018-07-09 14:25:59 +00001143 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
Sam McCall2b780162018-01-30 17:20:54 +00001144
Sam McCall545a20d2018-01-19 14:34:02 +00001145 SymbolSlab::Builder ResultsBuilder;
1146 // Build the query.
1147 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +00001148 if (Opts.Limit)
1149 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +00001150 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001151 Req.RestrictForCodeCompletion = true;
Eric Liubc25ef72018-07-05 08:29:33 +00001152 Req.Scopes = QueryScopes;
Sam McCall3f0243f2018-07-03 08:09:29 +00001153 // FIXME: we should send multiple weighted paths here.
Eric Liu6de95ec2018-06-12 08:48:20 +00001154 Req.ProximityPaths.push_back(FileName);
Sam McCallbed58852018-07-11 10:35:11 +00001155 vlog("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])", Req.Query,
1156 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ","));
Sam McCall545a20d2018-01-19 14:34:02 +00001157 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +00001158 if (Opts.Index->fuzzyFind(
1159 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1160 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001161 return std::move(ResultsBuilder).build();
1162 }
1163
Sam McCallc18c2802018-06-15 11:06:29 +00001164 // Merges Sema and Index results where possible, to form CompletionCandidates.
1165 // Groups overloads if desired, to form CompletionCandidate::Bundles.
1166 // The bundles are scored and top results are returned, best to worst.
1167 std::vector<ScoredBundle>
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001168 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1169 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +00001170 trace::Span Tracer("Merge and score results");
Sam McCallc18c2802018-06-15 11:06:29 +00001171 std::vector<CompletionCandidate::Bundle> Bundles;
1172 llvm::DenseMap<size_t, size_t> BundleLookup;
1173 auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
1174 const Symbol *IndexResult) {
1175 CompletionCandidate C;
1176 C.SemaResult = SemaResult;
1177 C.IndexResult = IndexResult;
1178 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1179 if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1180 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1181 if (Ret.second)
1182 Bundles.emplace_back();
1183 Bundles[Ret.first->second].push_back(std::move(C));
1184 } else {
1185 Bundles.emplace_back();
1186 Bundles.back().push_back(std::move(C));
1187 }
1188 };
Sam McCall545a20d2018-01-19 14:34:02 +00001189 llvm::DenseSet<const Symbol *> UsedIndexResults;
1190 auto CorrespondingIndexResult =
1191 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
1192 if (auto SymID = getSymbolID(SemaResult)) {
1193 auto I = IndexResults.find(*SymID);
1194 if (I != IndexResults.end()) {
1195 UsedIndexResults.insert(&*I);
1196 return &*I;
1197 }
1198 }
1199 return nullptr;
1200 };
1201 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001202 for (auto &SemaResult : Recorder->Results)
Sam McCallc18c2802018-06-15 11:06:29 +00001203 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
Sam McCall545a20d2018-01-19 14:34:02 +00001204 // Now emit any Index-only results.
1205 for (const auto &IndexResult : IndexResults) {
1206 if (UsedIndexResults.count(&IndexResult))
1207 continue;
Sam McCallc18c2802018-06-15 11:06:29 +00001208 AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001209 }
Sam McCallc18c2802018-06-15 11:06:29 +00001210 // We only keep the best N results at any time, in "native" format.
1211 TopN<ScoredBundle, ScoredBundleGreater> Top(
1212 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1213 for (auto &Bundle : Bundles)
1214 addCandidate(Top, std::move(Bundle));
Sam McCall545a20d2018-01-19 14:34:02 +00001215 return std::move(Top).items();
1216 }
1217
Sam McCall80ad7072018-06-08 13:32:25 +00001218 Optional<float> fuzzyScore(const CompletionCandidate &C) {
1219 // Macros can be very spammy, so we only support prefix completion.
1220 // We won't end up with underfull index results, as macros are sema-only.
1221 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1222 !C.Name.startswith_lower(Filter->pattern()))
1223 return None;
1224 return Filter->match(C.Name);
1225 }
1226
Sam McCall545a20d2018-01-19 14:34:02 +00001227 // Scores a candidate and adds it to the TopN structure.
Sam McCallc18c2802018-06-15 11:06:29 +00001228 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1229 CompletionCandidate::Bundle Bundle) {
Sam McCallc5707b62018-05-15 17:43:27 +00001230 SymbolQualitySignals Quality;
1231 SymbolRelevanceSignals Relevance;
Eric Liu5d2a8072018-07-23 10:56:37 +00001232 Relevance.Context = Recorder->CCContext.getKind();
Sam McCalld9b54f02018-06-05 16:30:25 +00001233 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Sam McCallf84dd022018-07-05 08:26:53 +00001234 Relevance.FileProximityMatch = FileProximity.getPointer();
Sam McCallc18c2802018-06-15 11:06:29 +00001235 auto &First = Bundle.front();
1236 if (auto FuzzyScore = fuzzyScore(First))
Sam McCallc5707b62018-05-15 17:43:27 +00001237 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001238 else
1239 return;
Sam McCall2161ec72018-07-05 06:20:41 +00001240 SymbolOrigin Origin = SymbolOrigin::Unknown;
Sam McCall4e5742a2018-07-06 11:50:49 +00001241 bool FromIndex = false;
Sam McCallc18c2802018-06-15 11:06:29 +00001242 for (const auto &Candidate : Bundle) {
1243 if (Candidate.IndexResult) {
1244 Quality.merge(*Candidate.IndexResult);
1245 Relevance.merge(*Candidate.IndexResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001246 Origin |= Candidate.IndexResult->Origin;
1247 FromIndex = true;
Sam McCallc18c2802018-06-15 11:06:29 +00001248 }
1249 if (Candidate.SemaResult) {
1250 Quality.merge(*Candidate.SemaResult);
1251 Relevance.merge(*Candidate.SemaResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001252 Origin |= SymbolOrigin::AST;
Sam McCallc18c2802018-06-15 11:06:29 +00001253 }
Sam McCallc5707b62018-05-15 17:43:27 +00001254 }
1255
Sam McCall27c979a2018-06-29 14:47:57 +00001256 CodeCompletion::Scores Scores;
1257 Scores.Quality = Quality.evaluate();
1258 Scores.Relevance = Relevance.evaluate();
1259 Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1260 // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1261 Scores.ExcludingName = Relevance.NameMatch
1262 ? Scores.Total / Relevance.NameMatch
1263 : Scores.Quality;
Sam McCallc5707b62018-05-15 17:43:27 +00001264
Sam McCallbed58852018-07-11 10:35:11 +00001265 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
1266 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
1267 llvm::to_string(Relevance));
Sam McCall545a20d2018-01-19 14:34:02 +00001268
Sam McCall2161ec72018-07-05 06:20:41 +00001269 NSema += bool(Origin & SymbolOrigin::AST);
Sam McCall4e5742a2018-07-06 11:50:49 +00001270 NIndex += FromIndex;
1271 NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
Sam McCallc18c2802018-06-15 11:06:29 +00001272 if (Candidates.push({std::move(Bundle), Scores}))
Sam McCallab8e3932018-02-19 13:04:41 +00001273 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001274 }
1275
Sam McCall27c979a2018-06-29 14:47:57 +00001276 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
1277 llvm::Optional<CodeCompletionBuilder> Builder;
1278 for (const auto &Item : Bundle) {
1279 CodeCompletionString *SemaCCS =
1280 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1281 : nullptr;
1282 if (!Builder)
1283 Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
Sam McCall3f0243f2018-07-03 08:09:29 +00001284 *Inserter, FileName, Opts);
Sam McCall27c979a2018-06-29 14:47:57 +00001285 else
1286 Builder->add(Item, SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +00001287 }
Sam McCall27c979a2018-06-29 14:47:57 +00001288 return Builder->build();
Sam McCall545a20d2018-01-19 14:34:02 +00001289 }
1290};
1291
Sam McCall3f0243f2018-07-03 08:09:29 +00001292CodeCompleteResult codeComplete(PathRef FileName,
1293 const tooling::CompileCommand &Command,
1294 PrecompiledPreamble const *Preamble,
1295 const IncludeStructure &PreambleInclusions,
1296 StringRef Contents, Position Pos,
1297 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1298 std::shared_ptr<PCHContainerOperations> PCHs,
1299 CodeCompleteOptions Opts) {
1300 return CodeCompleteFlow(FileName, PreambleInclusions, Opts)
1301 .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001302}
1303
Sam McCalld1a7a372018-01-31 13:40:48 +00001304SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001305 const tooling::CompileCommand &Command,
1306 PrecompiledPreamble const *Preamble,
1307 StringRef Contents, Position Pos,
1308 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1309 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001310 SignatureHelp Result;
1311 clang::CodeCompleteOptions Options;
1312 Options.IncludeGlobals = false;
1313 Options.IncludeMacros = false;
1314 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001315 Options.IncludeBriefComments = false;
Sam McCall3f0243f2018-07-03 08:09:29 +00001316 IncludeStructure PreambleInclusions; // Unused for signatureHelp
Sam McCalld1a7a372018-01-31 13:40:48 +00001317 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1318 Options,
Sam McCall3f0243f2018-07-03 08:09:29 +00001319 {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1320 std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001321 return Result;
1322}
1323
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001324bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1325 using namespace clang::ast_matchers;
1326 auto InTopLevelScope = hasDeclContext(
1327 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1328 return !match(decl(anyOf(InTopLevelScope,
1329 hasDeclContext(
1330 enumDecl(InTopLevelScope, unless(isScoped()))))),
1331 ND, ASTCtx)
1332 .empty();
1333}
1334
Sam McCall27c979a2018-06-29 14:47:57 +00001335CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1336 CompletionItem LSP;
1337 LSP.label = (HeaderInsertion ? Opts.IncludeIndicator.Insert
1338 : Opts.IncludeIndicator.NoInsert) +
Sam McCall2161ec72018-07-05 06:20:41 +00001339 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
Sam McCall27c979a2018-06-29 14:47:57 +00001340 RequiredQualifier + Name + Signature;
Sam McCall2161ec72018-07-05 06:20:41 +00001341
Sam McCall27c979a2018-06-29 14:47:57 +00001342 LSP.kind = Kind;
1343 LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
1344 : ReturnType;
1345 if (!Header.empty())
1346 LSP.detail += "\n" + Header;
1347 LSP.documentation = Documentation;
1348 LSP.sortText = sortText(Score.Total, Name);
1349 LSP.filterText = Name;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001350 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name};
1351 // Merge continious additionalTextEdits into main edit. The main motivation
1352 // behind this is to help LSP clients, it seems most of them are confused when
1353 // they are provided with additionalTextEdits that are consecutive to main
1354 // edit.
1355 // Note that we store additional text edits from back to front in a line. That
1356 // is mainly to help LSP clients again, so that changes do not effect each
1357 // other.
1358 for (const auto &FixIt : FixIts) {
1359 if (IsRangeConsecutive(FixIt.range, LSP.textEdit->range)) {
1360 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
1361 LSP.textEdit->range.start = FixIt.range.start;
1362 } else {
1363 LSP.additionalTextEdits.push_back(FixIt);
1364 }
1365 }
Sam McCall27c979a2018-06-29 14:47:57 +00001366 if (Opts.EnableSnippets)
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001367 LSP.textEdit->newText += SnippetSuffix;
1368 // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
1369 // compatible with most of the editors.
1370 LSP.insertText = LSP.textEdit->newText;
Sam McCall27c979a2018-06-29 14:47:57 +00001371 LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1372 : InsertTextFormat::PlainText;
1373 if (HeaderInsertion)
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001374 LSP.additionalTextEdits.push_back(*HeaderInsertion);
Sam McCall27c979a2018-06-29 14:47:57 +00001375 return LSP;
1376}
1377
Sam McCalle746a2b2018-07-02 11:13:16 +00001378raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) {
1379 // For now just lean on CompletionItem.
1380 return OS << C.render(CodeCompleteOptions());
1381}
1382
1383raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) {
1384 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
Eric Liu5d2a8072018-07-23 10:56:37 +00001385 << " (" << getCompletionKindString(R.Context) << ")"
Sam McCalle746a2b2018-07-02 11:13:16 +00001386 << " items:\n";
1387 for (const auto &C : R.Completions)
1388 OS << C << "\n";
1389 return OS;
1390}
1391
Sam McCall98775c52017-12-04 13:49:59 +00001392} // namespace clangd
1393} // namespace clang