blob: 254c22be3a9620f0b4ca4e327ab3b2783550e44c [file] [log] [blame]
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00001//===--- CodeComplete.cpp ----------------------------------------*- C++-*-===//
Sam McCall98775c52017-12-04 13:49:59 +00002//
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//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00008//===----------------------------------------------------------------------===//
Sam McCall98775c52017-12-04 13:49:59 +00009//
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//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +000019//===----------------------------------------------------------------------===//
Sam McCall98775c52017-12-04 13:49:59 +000020
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
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000191// First traverses all method definitions inside current class/struct/union
192// definition. Than traverses base classes to find virtual methods that haven't
193// been overriden within current context.
194// FIXME(kadircet): Currently we cannot see declarations below completion point.
195// It is because Sema gets run only upto completion point. Need to find a
196// solution to run it for the whole class/struct/union definition.
197static std::vector<CodeCompletionResult>
198getNonOverridenMethodCompletionResults(const DeclContext *DC, Sema *S) {
199 const auto *CR = llvm::dyn_cast<CXXRecordDecl>(DC);
200 // If not inside a class/struct/union return empty.
201 if (!CR)
202 return {};
203 // First store overrides within current class.
204 // These are stored by name to make querying fast in the later step.
205 llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
206 for (auto *Method : CR->methods()) {
207 if (!Method->isVirtual())
208 continue;
209 Overrides[Method->getName()].push_back(Method);
210 }
211
212 std::vector<CodeCompletionResult> Results;
213 for (const auto &Base : CR->bases()) {
214 const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
215 if (!BR)
216 continue;
217 for (auto *Method : BR->methods()) {
218 if (!Method->isVirtual())
219 continue;
220 const auto it = Overrides.find(Method->getName());
221 bool IsOverriden = false;
222 if (it != Overrides.end()) {
223 for (auto *MD : it->second) {
224 // If the method in current body is not an overload of this virtual
225 // function, that it overrides this one.
226 if (!S->IsOverload(MD, Method, false)) {
227 IsOverriden = true;
228 break;
229 }
230 }
231 }
232 if (!IsOverriden)
233 Results.emplace_back(Method, 0);
234 }
235 }
236
237 return Results;
238}
239
Sam McCall545a20d2018-01-19 14:34:02 +0000240/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000241/// It may be promoted to a CompletionItem if it's among the top-ranked results.
242struct CompletionCandidate {
Sam McCall545a20d2018-01-19 14:34:02 +0000243 llvm::StringRef Name; // Used for filtering and sorting.
244 // We may have a result from Sema, from the index, or both.
245 const CodeCompletionResult *SemaResult = nullptr;
246 const Symbol *IndexResult = nullptr;
Sam McCall98775c52017-12-04 13:49:59 +0000247
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000248 // States whether this item is an override suggestion.
249 bool IsOverride = false;
250
Sam McCallc18c2802018-06-15 11:06:29 +0000251 // Returns a token identifying the overload set this is part of.
252 // 0 indicates it's not part of any overload set.
253 size_t overloadSet() const {
254 SmallString<256> Scratch;
255 if (IndexResult) {
256 switch (IndexResult->SymInfo.Kind) {
257 case index::SymbolKind::ClassMethod:
258 case index::SymbolKind::InstanceMethod:
259 case index::SymbolKind::StaticMethod:
260 assert(false && "Don't expect members from index in code completion");
261 // fall through
262 case index::SymbolKind::Function:
263 // We can't group overloads together that need different #includes.
264 // This could break #include insertion.
265 return hash_combine(
266 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
267 headerToInsertIfNotPresent().getValueOr(""));
268 default:
269 return 0;
270 }
271 }
272 assert(SemaResult);
273 // We need to make sure we're consistent with the IndexResult case!
274 const NamedDecl *D = SemaResult->Declaration;
275 if (!D || !D->isFunctionOrFunctionTemplate())
276 return 0;
277 {
278 llvm::raw_svector_ostream OS(Scratch);
279 D->printQualifiedName(OS);
280 }
281 return hash_combine(Scratch, headerToInsertIfNotPresent().getValueOr(""));
282 }
283
284 llvm::Optional<llvm::StringRef> headerToInsertIfNotPresent() const {
285 if (!IndexResult || !IndexResult->Detail ||
286 IndexResult->Detail->IncludeHeader.empty())
287 return llvm::None;
288 if (SemaResult && SemaResult->Declaration) {
289 // Avoid inserting new #include if the declaration is found in the current
290 // file e.g. the symbol is forward declared.
291 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
292 for (const Decl *RD : SemaResult->Declaration->redecls())
Stephen Kelly43465bf2018-08-09 22:42:26 +0000293 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
Sam McCallc18c2802018-06-15 11:06:29 +0000294 return llvm::None;
295 }
296 return IndexResult->Detail->IncludeHeader;
297 }
298
Sam McCallc18c2802018-06-15 11:06:29 +0000299 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
Sam McCall98775c52017-12-04 13:49:59 +0000300};
Sam McCallc18c2802018-06-15 11:06:29 +0000301using ScoredBundle =
Sam McCall27c979a2018-06-29 14:47:57 +0000302 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
Sam McCallc18c2802018-06-15 11:06:29 +0000303struct ScoredBundleGreater {
304 bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
Sam McCall27c979a2018-06-29 14:47:57 +0000305 if (L.second.Total != R.second.Total)
306 return L.second.Total > R.second.Total;
Sam McCallc18c2802018-06-15 11:06:29 +0000307 return L.first.front().Name <
308 R.first.front().Name; // Earlier name is better.
309 }
310};
Sam McCall98775c52017-12-04 13:49:59 +0000311
Sam McCall27c979a2018-06-29 14:47:57 +0000312// Assembles a code completion out of a bundle of >=1 completion candidates.
313// Many of the expensive strings are only computed at this point, once we know
314// the candidate bundle is going to be returned.
315//
316// Many fields are the same for all candidates in a bundle (e.g. name), and are
317// computed from the first candidate, in the constructor.
318// Others vary per candidate, so add() must be called for remaining candidates.
319struct CodeCompletionBuilder {
320 CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
321 CodeCompletionString *SemaCCS,
322 const IncludeInserter &Includes, StringRef FileName,
323 const CodeCompleteOptions &Opts)
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000324 : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments),
325 EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets) {
Sam McCall27c979a2018-06-29 14:47:57 +0000326 add(C, SemaCCS);
327 if (C.SemaResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000328 Completion.Origin |= SymbolOrigin::AST;
Sam McCall27c979a2018-06-29 14:47:57 +0000329 Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
Eric Liuf433c2d2018-07-18 15:31:14 +0000330 if (Completion.Scope.empty()) {
331 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
332 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
Sam McCall27c979a2018-06-29 14:47:57 +0000333 if (const auto *D = C.SemaResult->getDeclaration())
334 if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
335 Completion.Scope =
336 splitQualifiedName(printQualifiedName(*ND)).first;
Eric Liuf433c2d2018-07-18 15:31:14 +0000337 }
Sam McCall27c979a2018-06-29 14:47:57 +0000338 Completion.Kind =
339 toCompletionItemKind(C.SemaResult->Kind, C.SemaResult->Declaration);
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000340 for (const auto &FixIt : C.SemaResult->FixIts) {
341 Completion.FixIts.push_back(
342 toTextEdit(FixIt, ASTCtx.getSourceManager(), ASTCtx.getLangOpts()));
343 }
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +0000344 std::sort(Completion.FixIts.begin(), Completion.FixIts.end(),
345 [](const TextEdit &X, const TextEdit &Y) {
346 return std::tie(X.range.start.line, X.range.start.character) <
347 std::tie(Y.range.start.line, Y.range.start.character);
348 });
Sam McCall27c979a2018-06-29 14:47:57 +0000349 }
350 if (C.IndexResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000351 Completion.Origin |= C.IndexResult->Origin;
Sam McCall27c979a2018-06-29 14:47:57 +0000352 if (Completion.Scope.empty())
353 Completion.Scope = C.IndexResult->Scope;
354 if (Completion.Kind == CompletionItemKind::Missing)
355 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
356 if (Completion.Name.empty())
357 Completion.Name = C.IndexResult->Name;
358 }
359 if (auto Inserted = C.headerToInsertIfNotPresent()) {
360 // Turn absolute path into a literal string that can be #included.
361 auto Include = [&]() -> Expected<std::pair<std::string, bool>> {
362 auto ResolvedDeclaring =
363 toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
364 if (!ResolvedDeclaring)
365 return ResolvedDeclaring.takeError();
366 auto ResolvedInserted = toHeaderFile(*Inserted, FileName);
367 if (!ResolvedInserted)
368 return ResolvedInserted.takeError();
369 return std::make_pair(Includes.calculateIncludePath(*ResolvedDeclaring,
370 *ResolvedInserted),
371 Includes.shouldInsertInclude(*ResolvedDeclaring,
372 *ResolvedInserted));
373 }();
374 if (Include) {
375 Completion.Header = Include->first;
376 if (Include->second)
377 Completion.HeaderInsertion = Includes.insert(Include->first);
378 } else
Sam McCallbed58852018-07-11 10:35:11 +0000379 log("Failed to generate include insertion edits for adding header "
Sam McCall27c979a2018-06-29 14:47:57 +0000380 "(FileURI='{0}', IncludeHeader='{1}') into {2}",
381 C.IndexResult->CanonicalDeclaration.FileURI,
Sam McCallbed58852018-07-11 10:35:11 +0000382 C.IndexResult->Detail->IncludeHeader, FileName);
Sam McCall27c979a2018-06-29 14:47:57 +0000383 }
384 }
385
386 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {
387 assert(bool(C.SemaResult) == bool(SemaCCS));
388 Bundled.emplace_back();
389 BundledEntry &S = Bundled.back();
390 if (C.SemaResult) {
391 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
392 &Completion.RequiredQualifier);
393 S.ReturnType = getReturnType(*SemaCCS);
394 } else if (C.IndexResult) {
395 S.Signature = C.IndexResult->Signature;
396 S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix;
397 if (auto *D = C.IndexResult->Detail)
398 S.ReturnType = D->ReturnType;
399 }
400 if (ExtractDocumentation && Completion.Documentation.empty()) {
401 if (C.IndexResult && C.IndexResult->Detail)
402 Completion.Documentation = C.IndexResult->Detail->Documentation;
403 else if (C.SemaResult)
404 Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
405 /*CommentsFromHeader=*/false);
406 }
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000407 if (C.IsOverride)
408 S.OverrideSuffix = true;
Sam McCall27c979a2018-06-29 14:47:57 +0000409 }
410
411 CodeCompletion build() {
412 Completion.ReturnType = summarizeReturnType();
413 Completion.Signature = summarizeSignature();
414 Completion.SnippetSuffix = summarizeSnippet();
415 Completion.BundleSize = Bundled.size();
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000416 if (summarizeOverride()) {
417 Completion.Name = Completion.ReturnType + ' ' +
418 std::move(Completion.Name) +
419 std::move(Completion.Signature) + " override";
420 Completion.Signature.clear();
421 }
Sam McCall27c979a2018-06-29 14:47:57 +0000422 return std::move(Completion);
423 }
424
425private:
426 struct BundledEntry {
427 std::string SnippetSuffix;
428 std::string Signature;
429 std::string ReturnType;
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000430 bool OverrideSuffix;
Sam McCall27c979a2018-06-29 14:47:57 +0000431 };
432
433 // If all BundledEntrys have the same value for a property, return it.
434 template <std::string BundledEntry::*Member>
435 const std::string *onlyValue() const {
436 auto B = Bundled.begin(), E = Bundled.end();
437 for (auto I = B + 1; I != E; ++I)
438 if (I->*Member != B->*Member)
439 return nullptr;
440 return &(B->*Member);
441 }
442
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000443 template <bool BundledEntry::*Member> const bool *onlyValue() const {
444 auto B = Bundled.begin(), E = Bundled.end();
445 for (auto I = B + 1; I != E; ++I)
446 if (I->*Member != B->*Member)
447 return nullptr;
448 return &(B->*Member);
449 }
450
Sam McCall27c979a2018-06-29 14:47:57 +0000451 std::string summarizeReturnType() const {
452 if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
453 return *RT;
454 return "";
455 }
456
457 std::string summarizeSnippet() const {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000458 auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
459 if (!Snippet)
460 // All bundles are function calls.
461 return "($0)";
462 if (!Snippet->empty() && !EnableFunctionArgSnippets &&
463 ((Completion.Kind == CompletionItemKind::Function) ||
464 (Completion.Kind == CompletionItemKind::Method)) &&
465 (Snippet->front() == '(') && (Snippet->back() == ')'))
466 // Check whether function has any parameters or not.
467 return Snippet->size() > 2 ? "($0)" : "()";
468 return *Snippet;
Sam McCall27c979a2018-06-29 14:47:57 +0000469 }
470
471 std::string summarizeSignature() const {
472 if (auto *Signature = onlyValue<&BundledEntry::Signature>())
473 return *Signature;
474 // All bundles are function calls.
475 return "(…)";
476 }
477
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000478 bool summarizeOverride() const {
479 if (auto *OverrideSuffix = onlyValue<&BundledEntry::OverrideSuffix>())
480 return *OverrideSuffix;
481 return false;
482 }
483
Sam McCall27c979a2018-06-29 14:47:57 +0000484 ASTContext &ASTCtx;
485 CodeCompletion Completion;
486 SmallVector<BundledEntry, 1> Bundled;
487 bool ExtractDocumentation;
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000488 bool EnableFunctionArgSnippets;
Sam McCall27c979a2018-06-29 14:47:57 +0000489};
490
Sam McCall545a20d2018-01-19 14:34:02 +0000491// Determine the symbol ID for a Sema code completion result, if possible.
492llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
493 switch (R.Kind) {
494 case CodeCompletionResult::RK_Declaration:
495 case CodeCompletionResult::RK_Pattern: {
Haojian Wuc6ddb462018-08-07 08:57:52 +0000496 return clang::clangd::getSymbolID(R.Declaration);
Sam McCall545a20d2018-01-19 14:34:02 +0000497 }
498 case CodeCompletionResult::RK_Macro:
499 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
500 case CodeCompletionResult::RK_Keyword:
501 return None;
502 }
503 llvm_unreachable("unknown CodeCompletionResult kind");
504}
505
Haojian Wu061c73e2018-01-23 11:37:26 +0000506// Scopes of the paritial identifier we're trying to complete.
507// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000508struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000509 // The scopes we should look in, determined by Sema.
510 //
511 // If the qualifier was fully resolved, we look for completions in these
512 // scopes; if there is an unresolved part of the qualifier, it should be
513 // resolved within these scopes.
514 //
515 // Examples of qualified completion:
516 //
517 // "::vec" => {""}
518 // "using namespace std; ::vec^" => {"", "std::"}
519 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
520 // "std::vec^" => {""} // "std" unresolved
521 //
522 // Examples of unqualified completion:
523 //
524 // "vec^" => {""}
525 // "using namespace std; vec^" => {"", "std::"}
526 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
527 //
528 // "" for global namespace, "ns::" for normal namespace.
529 std::vector<std::string> AccessibleScopes;
530 // The full scope qualifier as typed by the user (without the leading "::").
531 // Set if the qualifier is not fully resolved by Sema.
532 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000533
Haojian Wu061c73e2018-01-23 11:37:26 +0000534 // Construct scopes being queried in indexes.
535 // This method format the scopes to match the index request representation.
536 std::vector<std::string> scopesForIndexQuery() {
537 std::vector<std::string> Results;
538 for (llvm::StringRef AS : AccessibleScopes) {
539 Results.push_back(AS);
540 if (UnresolvedQualifier)
541 Results.back() += *UnresolvedQualifier;
542 }
543 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000544 }
Eric Liu6f648df2017-12-19 16:50:37 +0000545};
546
Haojian Wu061c73e2018-01-23 11:37:26 +0000547// Get all scopes that will be queried in indexes.
548std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000549 const SourceManager &SM) {
550 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000551 SpecifiedScope Info;
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000552 for (auto *Context : CCContext.getVisitedContexts()) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000553 if (isa<TranslationUnitDecl>(Context))
554 Info.AccessibleScopes.push_back(""); // global namespace
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000555 else if (const auto *NS = dyn_cast<NamespaceDecl>(Context))
Haojian Wu061c73e2018-01-23 11:37:26 +0000556 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
557 }
558 return Info;
559 };
560
561 auto SS = CCContext.getCXXScopeSpecifier();
562
563 // Unqualified completion (e.g. "vec^").
564 if (!SS) {
565 // FIXME: Once we can insert namespace qualifiers and use the in-scope
566 // namespaces for scoring, search in all namespaces.
567 // FIXME: Capture scopes and use for scoring, for example,
568 // "using namespace std; namespace foo {v^}" =>
569 // foo::value > std::vector > boost::variant
570 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
571 }
572
573 // Qualified completion ("std::vec^"), we have two cases depending on whether
574 // the qualifier can be resolved by Sema.
575 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000576 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
577 }
578
579 // Unresolved qualifier.
580 // FIXME: When Sema can resolve part of a scope chain (e.g.
581 // "known::unknown::id"), we should expand the known part ("known::") rather
582 // than treating the whole thing as unknown.
583 SpecifiedScope Info;
584 Info.AccessibleScopes.push_back(""); // global namespace
585
586 Info.UnresolvedQualifier =
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000587 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM,
588 clang::LangOptions())
589 .ltrim("::");
Haojian Wu061c73e2018-01-23 11:37:26 +0000590 // Sema excludes the trailing "::".
591 if (!Info.UnresolvedQualifier->empty())
592 *Info.UnresolvedQualifier += "::";
593
594 return Info.scopesForIndexQuery();
595}
596
Eric Liu42abe412018-05-24 11:20:19 +0000597// Should we perform index-based completion in a context of the specified kind?
598// FIXME: consider allowing completion, but restricting the result types.
599bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
600 switch (K) {
601 case CodeCompletionContext::CCC_TopLevel:
602 case CodeCompletionContext::CCC_ObjCInterface:
603 case CodeCompletionContext::CCC_ObjCImplementation:
604 case CodeCompletionContext::CCC_ObjCIvarList:
605 case CodeCompletionContext::CCC_ClassStructUnion:
606 case CodeCompletionContext::CCC_Statement:
607 case CodeCompletionContext::CCC_Expression:
608 case CodeCompletionContext::CCC_ObjCMessageReceiver:
609 case CodeCompletionContext::CCC_EnumTag:
610 case CodeCompletionContext::CCC_UnionTag:
611 case CodeCompletionContext::CCC_ClassOrStructTag:
612 case CodeCompletionContext::CCC_ObjCProtocolName:
613 case CodeCompletionContext::CCC_Namespace:
614 case CodeCompletionContext::CCC_Type:
615 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
616 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
617 case CodeCompletionContext::CCC_ParenthesizedExpression:
618 case CodeCompletionContext::CCC_ObjCInterfaceName:
619 case CodeCompletionContext::CCC_ObjCCategoryName:
620 return true;
621 case CodeCompletionContext::CCC_Other: // Be conservative.
622 case CodeCompletionContext::CCC_OtherWithMacros:
623 case CodeCompletionContext::CCC_DotMemberAccess:
624 case CodeCompletionContext::CCC_ArrowMemberAccess:
625 case CodeCompletionContext::CCC_ObjCPropertyAccess:
626 case CodeCompletionContext::CCC_MacroName:
627 case CodeCompletionContext::CCC_MacroNameUse:
628 case CodeCompletionContext::CCC_PreprocessorExpression:
629 case CodeCompletionContext::CCC_PreprocessorDirective:
630 case CodeCompletionContext::CCC_NaturalLanguage:
631 case CodeCompletionContext::CCC_SelectorName:
632 case CodeCompletionContext::CCC_TypeQualifiers:
633 case CodeCompletionContext::CCC_ObjCInstanceMessage:
634 case CodeCompletionContext::CCC_ObjCClassMessage:
635 case CodeCompletionContext::CCC_Recovery:
636 return false;
637 }
638 llvm_unreachable("unknown code completion context");
639}
640
Sam McCall4caa8512018-06-07 12:49:17 +0000641// Some member calls are blacklisted because they're so rarely useful.
642static bool isBlacklistedMember(const NamedDecl &D) {
643 // Destructor completion is rarely useful, and works inconsistently.
644 // (s.^ completes ~string, but s.~st^ is an error).
645 if (D.getKind() == Decl::CXXDestructor)
646 return true;
647 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
648 if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
649 if (R->isInjectedClassName())
650 return true;
651 // Explicit calls to operators are also rare.
652 auto NameKind = D.getDeclName().getNameKind();
653 if (NameKind == DeclarationName::CXXOperatorName ||
654 NameKind == DeclarationName::CXXLiteralOperatorName ||
655 NameKind == DeclarationName::CXXConversionFunctionName)
656 return true;
657 return false;
658}
659
Sam McCall545a20d2018-01-19 14:34:02 +0000660// The CompletionRecorder captures Sema code-complete output, including context.
661// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
662// It doesn't do scoring or conversion to CompletionItem yet, as we want to
663// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000664// Generally the fields and methods of this object should only be used from
665// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000666struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000667 CompletionRecorder(const CodeCompleteOptions &Opts,
Benjamin Kramerc36c09f2018-07-03 20:59:33 +0000668 llvm::unique_function<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000669 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000670 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000671 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
672 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000673 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
674 assert(this->ResultsCallback);
675 }
676
Sam McCall545a20d2018-01-19 14:34:02 +0000677 std::vector<CodeCompletionResult> Results;
678 CodeCompletionContext CCContext;
679 Sema *CCSema = nullptr; // Sema that created the results.
680 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000681
Sam McCall545a20d2018-01-19 14:34:02 +0000682 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
683 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000684 unsigned NumResults) override final {
Eric Liu485074f2018-07-11 13:15:31 +0000685 // Results from recovery mode are generally useless, and the callback after
686 // recovery (if any) is usually more interesting. To make sure we handle the
687 // future callback from sema, we just ignore all callbacks in recovery mode,
688 // as taking only results from recovery mode results in poor completion
689 // results.
690 // FIXME: in case there is no future sema completion callback after the
691 // recovery mode, we might still want to provide some results (e.g. trivial
692 // identifier-based completion).
693 if (Context.getKind() == CodeCompletionContext::CCC_Recovery) {
694 log("Code complete: Ignoring sema code complete callback with Recovery "
695 "context.");
696 return;
697 }
Eric Liu42abe412018-05-24 11:20:19 +0000698 // If a callback is called without any sema result and the context does not
699 // support index-based completion, we simply skip it to give way to
700 // potential future callbacks with results.
701 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
702 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000703 if (CCSema) {
Sam McCallbed58852018-07-11 10:35:11 +0000704 log("Multiple code complete callbacks (parser backtracked?). "
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000705 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000706 getCompletionKindString(Context.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +0000707 getCompletionKindString(this->CCContext.getKind()));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000708 return;
709 }
Sam McCall545a20d2018-01-19 14:34:02 +0000710 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000711 CCSema = &S;
712 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000713
Sam McCall545a20d2018-01-19 14:34:02 +0000714 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000715 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000716 auto &Result = InResults[I];
717 // Drop hidden items which cannot be found by lookup after completion.
718 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000719 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
720 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000721 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000722 (Result.Availability == CXAvailability_NotAvailable ||
723 Result.Availability == CXAvailability_NotAccessible))
724 continue;
Sam McCall4caa8512018-06-07 12:49:17 +0000725 if (Result.Declaration &&
726 !Context.getBaseType().isNull() // is this a member-access context?
727 && isBlacklistedMember(*Result.Declaration))
Sam McCalld2a95922018-01-22 21:05:00 +0000728 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000729 // We choose to never append '::' to completion results in clangd.
730 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000731 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000732 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000733 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000734 }
735
Sam McCall545a20d2018-01-19 14:34:02 +0000736 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000737 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
738
Sam McCall545a20d2018-01-19 14:34:02 +0000739 // Returns the filtering/sorting name for Result, which must be from Results.
740 // Returned string is owned by this recorder (or the AST).
741 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000742 switch (Result.Kind) {
743 case CodeCompletionResult::RK_Declaration:
744 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000745 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000746 break;
747 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000748 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000749 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000750 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000751 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000752 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000753 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000754 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000755 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000756 }
757
Sam McCall545a20d2018-01-19 14:34:02 +0000758 // Build a CodeCompletion string for R, which must be from Results.
759 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000760 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000761 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
762 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000763 *CCSema, CCContext, *CCAllocator, CCTUInfo,
764 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000765 }
766
Sam McCall545a20d2018-01-19 14:34:02 +0000767private:
768 CodeCompleteOptions Opts;
769 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000770 CodeCompletionTUInfo CCTUInfo;
Benjamin Kramerc36c09f2018-07-03 20:59:33 +0000771 llvm::unique_function<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000772};
773
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000774struct ScoredSignature {
775 // When set, requires documentation to be requested from the index with this
776 // ID.
777 llvm::Optional<SymbolID> IDForDoc;
778 SignatureInformation Signature;
779 SignatureQualitySignals Quality;
780};
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000781
Sam McCall98775c52017-12-04 13:49:59 +0000782class SignatureHelpCollector final : public CodeCompleteConsumer {
Sam McCall98775c52017-12-04 13:49:59 +0000783public:
784 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000785 SymbolIndex *Index, SignatureHelp &SigHelp)
786 : CodeCompleteConsumer(CodeCompleteOpts,
787 /*OutputIsBinary=*/false),
Sam McCall98775c52017-12-04 13:49:59 +0000788 SigHelp(SigHelp),
789 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000790 CCTUInfo(Allocator), Index(Index) {}
Sam McCall98775c52017-12-04 13:49:59 +0000791
792 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
793 OverloadCandidate *Candidates,
794 unsigned NumCandidates) override {
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000795 std::vector<ScoredSignature> ScoredSignatures;
Sam McCall98775c52017-12-04 13:49:59 +0000796 SigHelp.signatures.reserve(NumCandidates);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000797 ScoredSignatures.reserve(NumCandidates);
Sam McCall98775c52017-12-04 13:49:59 +0000798 // FIXME(rwols): How can we determine the "active overload candidate"?
799 // Right now the overloaded candidates seem to be provided in a "best fit"
800 // order, so I'm not too worried about this.
801 SigHelp.activeSignature = 0;
802 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
803 "too many arguments");
804 SigHelp.activeParameter = static_cast<int>(CurrentArg);
805 for (unsigned I = 0; I < NumCandidates; ++I) {
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +0000806 OverloadCandidate Candidate = Candidates[I];
807 // We want to avoid showing instantiated signatures, because they may be
808 // long in some cases (e.g. when 'T' is substituted with 'std::string', we
809 // would get 'std::basic_string<char>').
810 if (auto *Func = Candidate.getFunction()) {
811 if (auto *Pattern = Func->getTemplateInstantiationPattern())
812 Candidate = OverloadCandidate(Pattern);
813 }
814
Sam McCall98775c52017-12-04 13:49:59 +0000815 const auto *CCS = Candidate.CreateSignatureString(
816 CurrentArg, S, *Allocator, CCTUInfo, true);
817 assert(CCS && "Expected the CodeCompletionString to be non-null");
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000818 ScoredSignatures.push_back(processOverloadCandidate(
Ilya Biryukov43714502018-05-16 12:32:44 +0000819 Candidate, *CCS,
Ilya Biryukov5f4a3512018-08-17 09:29:38 +0000820 Candidate.getFunction()
821 ? getDeclComment(S.getASTContext(), *Candidate.getFunction())
822 : ""));
Sam McCall98775c52017-12-04 13:49:59 +0000823 }
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000824
825 // Sema does not load the docs from the preamble, so we need to fetch extra
826 // docs from the index instead.
827 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
828 if (Index) {
829 LookupRequest IndexRequest;
830 for (const auto &S : ScoredSignatures) {
831 if (!S.IDForDoc)
832 continue;
833 IndexRequest.IDs.insert(*S.IDForDoc);
834 }
835 Index->lookup(IndexRequest, [&](const Symbol &S) {
836 if (!S.Detail || S.Detail->Documentation.empty())
837 return;
838 FetchedDocs[S.ID] = S.Detail->Documentation;
839 });
840 log("SigHelp: requested docs for {0} symbols from the index, got {1} "
841 "symbols with non-empty docs in the response",
842 IndexRequest.IDs.size(), FetchedDocs.size());
843 }
844
845 std::sort(
846 ScoredSignatures.begin(), ScoredSignatures.end(),
847 [](const ScoredSignature &L, const ScoredSignature &R) {
848 // Ordering follows:
849 // - Less number of parameters is better.
850 // - Function is better than FunctionType which is better than
851 // Function Template.
852 // - High score is better.
853 // - Shorter signature is better.
854 // - Alphebatically smaller is better.
855 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
856 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
857 if (L.Quality.NumberOfOptionalParameters !=
858 R.Quality.NumberOfOptionalParameters)
859 return L.Quality.NumberOfOptionalParameters <
860 R.Quality.NumberOfOptionalParameters;
861 if (L.Quality.Kind != R.Quality.Kind) {
862 using OC = CodeCompleteConsumer::OverloadCandidate;
863 switch (L.Quality.Kind) {
864 case OC::CK_Function:
865 return true;
866 case OC::CK_FunctionType:
867 return R.Quality.Kind != OC::CK_Function;
868 case OC::CK_FunctionTemplate:
869 return false;
870 }
871 llvm_unreachable("Unknown overload candidate type.");
872 }
873 if (L.Signature.label.size() != R.Signature.label.size())
874 return L.Signature.label.size() < R.Signature.label.size();
875 return L.Signature.label < R.Signature.label;
876 });
877
878 for (auto &SS : ScoredSignatures) {
879 auto IndexDocIt =
880 SS.IDForDoc ? FetchedDocs.find(*SS.IDForDoc) : FetchedDocs.end();
881 if (IndexDocIt != FetchedDocs.end())
882 SS.Signature.documentation = IndexDocIt->second;
883
884 SigHelp.signatures.push_back(std::move(SS.Signature));
885 }
Sam McCall98775c52017-12-04 13:49:59 +0000886 }
887
888 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
889
890 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
891
892private:
Eric Liu63696e12017-12-20 17:24:31 +0000893 // FIXME(ioeric): consider moving CodeCompletionString logic here to
894 // CompletionString.h.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000895 ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
896 const CodeCompletionString &CCS,
897 llvm::StringRef DocComment) const {
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000898 SignatureInformation Signature;
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000899 SignatureQualitySignals Signal;
Sam McCall98775c52017-12-04 13:49:59 +0000900 const char *ReturnType = nullptr;
901
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000902 Signature.documentation = formatDocumentation(CCS, DocComment);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000903 Signal.Kind = Candidate.getKind();
Sam McCall98775c52017-12-04 13:49:59 +0000904
905 for (const auto &Chunk : CCS) {
906 switch (Chunk.Kind) {
907 case CodeCompletionString::CK_ResultType:
908 // A piece of text that describes the type of an entity or,
909 // for functions and methods, the return type.
910 assert(!ReturnType && "Unexpected CK_ResultType");
911 ReturnType = Chunk.Text;
912 break;
913 case CodeCompletionString::CK_Placeholder:
914 // A string that acts as a placeholder for, e.g., a function call
915 // argument.
916 // Intentional fallthrough here.
917 case CodeCompletionString::CK_CurrentParameter: {
918 // A piece of text that describes the parameter that corresponds to
919 // the code-completion location within a function call, message send,
920 // macro invocation, etc.
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000921 Signature.label += Chunk.Text;
Sam McCall98775c52017-12-04 13:49:59 +0000922 ParameterInformation Info;
923 Info.label = Chunk.Text;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000924 Signature.parameters.push_back(std::move(Info));
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000925 Signal.NumberOfParameters++;
926 Signal.ContainsActiveParameter = true;
Sam McCall98775c52017-12-04 13:49:59 +0000927 break;
928 }
929 case CodeCompletionString::CK_Optional: {
930 // The rest of the parameters are defaulted/optional.
931 assert(Chunk.Optional &&
932 "Expected the optional code completion string to be non-null.");
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000933 Signature.label += getOptionalParameters(*Chunk.Optional,
934 Signature.parameters, Signal);
Sam McCall98775c52017-12-04 13:49:59 +0000935 break;
936 }
937 case CodeCompletionString::CK_VerticalSpace:
938 break;
939 default:
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000940 Signature.label += Chunk.Text;
Sam McCall98775c52017-12-04 13:49:59 +0000941 break;
942 }
943 }
944 if (ReturnType) {
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000945 Signature.label += " -> ";
946 Signature.label += ReturnType;
Sam McCall98775c52017-12-04 13:49:59 +0000947 }
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000948 dlog("Signal for {0}: {1}", Signature, Signal);
949 ScoredSignature Result;
950 Result.Signature = std::move(Signature);
951 Result.Quality = Signal;
952 Result.IDForDoc =
953 Result.Signature.documentation.empty() && Candidate.getFunction()
954 ? clangd::getSymbolID(Candidate.getFunction())
955 : llvm::None;
956 return Result;
Sam McCall98775c52017-12-04 13:49:59 +0000957 }
958
959 SignatureHelp &SigHelp;
960 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
961 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000962 const SymbolIndex *Index;
Sam McCall98775c52017-12-04 13:49:59 +0000963}; // SignatureHelpCollector
964
Sam McCall545a20d2018-01-19 14:34:02 +0000965struct SemaCompleteInput {
966 PathRef FileName;
967 const tooling::CompileCommand &Command;
968 PrecompiledPreamble const *Preamble;
969 StringRef Contents;
970 Position Pos;
971 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
972 std::shared_ptr<PCHContainerOperations> PCHs;
973};
974
975// Invokes Sema code completion on a file.
Sam McCall3f0243f2018-07-03 08:09:29 +0000976// If \p Includes is set, it will be updated based on the compiler invocation.
Sam McCalld1a7a372018-01-31 13:40:48 +0000977bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000978 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000979 const SemaCompleteInput &Input,
Sam McCall3f0243f2018-07-03 08:09:29 +0000980 IncludeStructure *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000981 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000982 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000983 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000984 ArgStrs.push_back(S.c_str());
985
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000986 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
987 log("Couldn't set working directory");
988 // We run parsing anyway, our lit-tests rely on results for non-existing
989 // working dirs.
990 }
Sam McCall98775c52017-12-04 13:49:59 +0000991
992 IgnoreDiagnostics DummyDiagsConsumer;
993 auto CI = createInvocationFromCommandLine(
994 ArgStrs,
995 CompilerInstance::createDiagnostics(new DiagnosticOptions,
996 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000997 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000998 if (!CI) {
Sam McCallbed58852018-07-11 10:35:11 +0000999 elog("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +00001000 return false;
1001 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001002 auto &FrontendOpts = CI->getFrontendOpts();
1003 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +00001004 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001005 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
1006 // Disable typo correction in Sema.
1007 CI->getLangOpts()->SpellChecking = false;
1008 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +00001009 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +00001010 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +00001011 auto Offset = positionToOffset(Input.Contents, Input.Pos);
1012 if (!Offset) {
Sam McCallbed58852018-07-11 10:35:11 +00001013 elog("Code completion position was invalid {0}", Offset.takeError());
Sam McCalla4962cc2018-04-27 11:59:28 +00001014 return false;
1015 }
1016 std::tie(FrontendOpts.CodeCompletionAt.Line,
1017 FrontendOpts.CodeCompletionAt.Column) =
1018 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +00001019
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001020 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1021 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
1022 // The diagnostic options must be set before creating a CompilerInstance.
1023 CI->getDiagnosticOpts().IgnoreWarnings = true;
1024 // We reuse the preamble whether it's valid or not. This is a
1025 // correctness/performance tradeoff: building without a preamble is slow, and
1026 // completion is latency-sensitive.
1027 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
1028 // the remapped buffers do not get freed.
1029 auto Clang = prepareCompilerInstance(
1030 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
1031 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +00001032 Clang->setCodeCompletionConsumer(Consumer.release());
1033
1034 SyntaxOnlyAction Action;
1035 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCallbed58852018-07-11 10:35:11 +00001036 log("BeginSourceFile() failed when running codeComplete for {0}",
Sam McCalld1a7a372018-01-31 13:40:48 +00001037 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +00001038 return false;
1039 }
Sam McCall3f0243f2018-07-03 08:09:29 +00001040 if (Includes)
1041 Clang->getPreprocessor().addPPCallbacks(
1042 collectIncludeStructureCallback(Clang->getSourceManager(), Includes));
Sam McCall98775c52017-12-04 13:49:59 +00001043 if (!Action.Execute()) {
Sam McCallbed58852018-07-11 10:35:11 +00001044 log("Execute() failed when running codeComplete for {0}", Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +00001045 return false;
1046 }
Sam McCall98775c52017-12-04 13:49:59 +00001047 Action.EndSourceFile();
1048
1049 return true;
1050}
1051
Ilya Biryukova907ba42018-05-14 10:50:04 +00001052// Should we allow index completions in the specified context?
1053bool allowIndex(CodeCompletionContext &CC) {
1054 if (!contextAllowsIndex(CC.getKind()))
1055 return false;
1056 // We also avoid ClassName::bar (but allow namespace::bar).
1057 auto Scope = CC.getCXXScopeSpecifier();
1058 if (!Scope)
1059 return true;
1060 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
1061 if (!NameSpec)
1062 return true;
1063 // We only query the index when qualifier is a namespace.
1064 // If it's a class, we rely solely on sema completions.
1065 switch (NameSpec->getKind()) {
1066 case NestedNameSpecifier::Global:
1067 case NestedNameSpecifier::Namespace:
1068 case NestedNameSpecifier::NamespaceAlias:
1069 return true;
1070 case NestedNameSpecifier::Super:
1071 case NestedNameSpecifier::TypeSpec:
1072 case NestedNameSpecifier::TypeSpecWithTemplate:
1073 // Unresolved inside a template.
1074 case NestedNameSpecifier::Identifier:
1075 return false;
1076 }
Ilya Biryukova6556e22018-05-14 11:47:30 +00001077 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +00001078}
1079
Sam McCall98775c52017-12-04 13:49:59 +00001080} // namespace
1081
1082clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
1083 clang::CodeCompleteOptions Result;
1084 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
1085 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +00001086 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +00001087 // We choose to include full comments and not do doxygen parsing in
1088 // completion.
1089 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
1090 // formatting of the comments.
1091 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +00001092
Sam McCall3d139c52018-01-12 18:30:08 +00001093 // When an is used, Sema is responsible for completing the main file,
1094 // the index can provide results from the preamble.
1095 // Tell Sema not to deserialize the preamble to look for results.
1096 Result.LoadExternal = !Index;
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001097 Result.IncludeFixIts = IncludeFixIts;
Eric Liu6f648df2017-12-19 16:50:37 +00001098
Sam McCall98775c52017-12-04 13:49:59 +00001099 return Result;
1100}
1101
Sam McCall545a20d2018-01-19 14:34:02 +00001102// Runs Sema-based (AST) and Index-based completion, returns merged results.
1103//
1104// There are a few tricky considerations:
1105// - the AST provides information needed for the index query (e.g. which
1106// namespaces to search in). So Sema must start first.
1107// - we only want to return the top results (Opts.Limit).
1108// Building CompletionItems for everything else is wasteful, so we want to
1109// preserve the "native" format until we're done with scoring.
1110// - the data underlying Sema completion items is owned by the AST and various
1111// other arenas, which must stay alive for us to build CompletionItems.
1112// - we may get duplicate results from Sema and the Index, we need to merge.
1113//
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001114// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +00001115// We use the Sema context information to query the index.
1116// Then we merge the two result sets, producing items that are Sema/Index/Both.
1117// These items are scored, and the top N are synthesized into the LSP response.
1118// Finally, we can clean up the data structures created by Sema completion.
1119//
1120// Main collaborators are:
1121// - semaCodeComplete sets up the compiler machinery to run code completion.
1122// - CompletionRecorder captures Sema completion results, including context.
1123// - SymbolIndex (Opts.Index) provides index completion results as Symbols
1124// - CompletionCandidates are the result of merging Sema and Index results.
1125// Each candidate points to an underlying CodeCompletionResult (Sema), a
1126// Symbol (Index), or both. It computes the result quality score.
1127// CompletionCandidate also does conversion to CompletionItem (at the end).
1128// - FuzzyMatcher scores how the candidate matches the partial identifier.
1129// This score is combined with the result quality score for the final score.
1130// - TopN determines the results with the best score.
1131class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +00001132 PathRef FileName;
Sam McCall3f0243f2018-07-03 08:09:29 +00001133 IncludeStructure Includes; // Complete once the compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +00001134 const CodeCompleteOptions &Opts;
1135 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001136 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +00001137 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
1138 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +00001139 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
Eric Liubc25ef72018-07-05 08:29:33 +00001140 std::vector<std::string> QueryScopes; // Initialized once Sema runs.
Sam McCall3f0243f2018-07-03 08:09:29 +00001141 // Include-insertion and proximity scoring rely on the include structure.
1142 // This is available after Sema has run.
1143 llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
1144 llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
Sam McCall545a20d2018-01-19 14:34:02 +00001145
1146public:
1147 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Sam McCall3f0243f2018-07-03 08:09:29 +00001148 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
1149 const CodeCompleteOptions &Opts)
1150 : FileName(FileName), Includes(Includes), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +00001151
Sam McCall27c979a2018-06-29 14:47:57 +00001152 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +00001153 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +00001154
Sam McCall545a20d2018-01-19 14:34:02 +00001155 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001156 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +00001157 // - partial identifier and context. We need these for the index query.
Sam McCall27c979a2018-06-29 14:47:57 +00001158 CodeCompleteResult Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001159 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
1160 assert(Recorder && "Recorder is not set");
Sam McCall3f0243f2018-07-03 08:09:29 +00001161 auto Style =
Eric Liu9338a882018-07-03 14:51:23 +00001162 format::getStyle(format::DefaultFormatStyle, SemaCCInput.FileName,
1163 format::DefaultFallbackStyle, SemaCCInput.Contents,
1164 SemaCCInput.VFS.get());
Sam McCall3f0243f2018-07-03 08:09:29 +00001165 if (!Style) {
Sam McCallbed58852018-07-11 10:35:11 +00001166 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.",
1167 SemaCCInput.FileName, Style.takeError());
Sam McCall3f0243f2018-07-03 08:09:29 +00001168 Style = format::getLLVMStyle();
1169 }
Eric Liu63f419a2018-05-15 15:29:32 +00001170 // If preprocessor was run, inclusions from preprocessor callback should
Sam McCall3f0243f2018-07-03 08:09:29 +00001171 // already be added to Includes.
1172 Inserter.emplace(
1173 SemaCCInput.FileName, SemaCCInput.Contents, *Style,
1174 SemaCCInput.Command.Directory,
1175 Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
1176 for (const auto &Inc : Includes.MainFileIncludes)
1177 Inserter->addExisting(Inc);
1178
1179 // Most of the cost of file proximity is in initializing the FileDistance
1180 // structures based on the observed includes, once per query. Conceptually
1181 // that happens here (though the per-URI-scheme initialization is lazy).
1182 // The per-result proximity scoring is (amortized) very cheap.
1183 FileDistanceOptions ProxOpts{}; // Use defaults.
1184 const auto &SM = Recorder->CCSema->getSourceManager();
1185 llvm::StringMap<SourceParams> ProxSources;
1186 for (auto &Entry : Includes.includeDepth(
1187 SM.getFileEntryForID(SM.getMainFileID())->getName())) {
1188 auto &Source = ProxSources[Entry.getKey()];
1189 Source.Cost = Entry.getValue() * ProxOpts.IncludeCost;
1190 // Symbols near our transitive includes are good, but only consider
1191 // things in the same directory or below it. Otherwise there can be
1192 // many false positives.
1193 if (Entry.getValue() > 0)
1194 Source.MaxUpTraversals = 1;
1195 }
1196 FileProximity.emplace(ProxSources, ProxOpts);
1197
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001198 Output = runWithSema();
Sam McCall3f0243f2018-07-03 08:09:29 +00001199 Inserter.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001200 SPAN_ATTACH(Tracer, "sema_completion_kind",
1201 getCompletionKindString(Recorder->CCContext.getKind()));
Sam McCallbed58852018-07-11 10:35:11 +00001202 log("Code complete: sema context {0}, query scopes [{1}]",
Eric Liubc25ef72018-07-05 08:29:33 +00001203 getCompletionKindString(Recorder->CCContext.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +00001204 llvm::join(QueryScopes.begin(), QueryScopes.end(), ","));
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001205 });
1206
1207 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +00001208 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +00001209 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +00001210
Sam McCall2b780162018-01-30 17:20:54 +00001211 SPAN_ATTACH(Tracer, "sema_results", NSema);
1212 SPAN_ATTACH(Tracer, "index_results", NIndex);
1213 SPAN_ATTACH(Tracer, "merged_results", NBoth);
Sam McCalld20d7982018-07-09 14:25:59 +00001214 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
Sam McCall27c979a2018-06-29 14:47:57 +00001215 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
Sam McCallbed58852018-07-11 10:35:11 +00001216 log("Code complete: {0} results from Sema, {1} from Index, "
1217 "{2} matched, {3} returned{4}.",
1218 NSema, NIndex, NBoth, Output.Completions.size(),
1219 Output.HasMore ? " (incomplete)" : "");
Sam McCall27c979a2018-06-29 14:47:57 +00001220 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +00001221 // We don't assert that isIncomplete means we hit a limit.
1222 // Indexes may choose to impose their own limits even if we don't have one.
1223 return Output;
1224 }
1225
1226private:
1227 // This is called by run() once Sema code completion is done, but before the
1228 // Sema data structures are torn down. It does all the real work.
Sam McCall27c979a2018-06-29 14:47:57 +00001229 CodeCompleteResult runWithSema() {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001230 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1231 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1232 Range TextEditRange;
1233 // When we are getting completions with an empty identifier, for example
1234 // std::vector<int> asdf;
1235 // asdf.^;
1236 // Then the range will be invalid and we will be doing insertion, use
1237 // current cursor position in such cases as range.
1238 if (CodeCompletionRange.isValid()) {
1239 TextEditRange = halfOpenToRange(Recorder->CCSema->getSourceManager(),
1240 CodeCompletionRange);
1241 } else {
1242 const auto &Pos = sourceLocToPosition(
1243 Recorder->CCSema->getSourceManager(),
1244 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1245 TextEditRange.start = TextEditRange.end = Pos;
1246 }
Sam McCall545a20d2018-01-19 14:34:02 +00001247 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001248 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Eric Liubc25ef72018-07-05 08:29:33 +00001249 QueryScopes = getQueryScopes(Recorder->CCContext,
1250 Recorder->CCSema->getSourceManager());
Sam McCall545a20d2018-01-19 14:34:02 +00001251 // Sema provides the needed context to query the index.
1252 // FIXME: in addition to querying for extra/overlapping symbols, we should
1253 // explicitly request symbols corresponding to Sema results.
1254 // We can use their signals even if the index can't suggest them.
1255 // We must copy index results to preserve them, but there are at most Limit.
Eric Liu8f3678d2018-06-15 13:34:18 +00001256 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1257 ? queryIndex()
1258 : SymbolSlab();
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001259 // Merge Sema, Index and Override results, score them, and pick the
1260 // winners.
1261 const auto Overrides = getNonOverridenMethodCompletionResults(
1262 Recorder->CCSema->CurContext, Recorder->CCSema);
1263 auto Top = mergeResults(Recorder->Results, IndexResults, Overrides);
Sam McCall27c979a2018-06-29 14:47:57 +00001264 CodeCompleteResult Output;
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001265
1266 // Convert the results to final form, assembling the expensive strings.
Sam McCall27c979a2018-06-29 14:47:57 +00001267 for (auto &C : Top) {
1268 Output.Completions.push_back(toCodeCompletion(C.first));
1269 Output.Completions.back().Score = C.second;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001270 Output.Completions.back().CompletionTokenRange = TextEditRange;
Sam McCall27c979a2018-06-29 14:47:57 +00001271 }
1272 Output.HasMore = Incomplete;
Eric Liu5d2a8072018-07-23 10:56:37 +00001273 Output.Context = Recorder->CCContext.getKind();
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001274
Sam McCall545a20d2018-01-19 14:34:02 +00001275 return Output;
1276 }
1277
1278 SymbolSlab queryIndex() {
Sam McCalld1a7a372018-01-31 13:40:48 +00001279 trace::Span Tracer("Query index");
Sam McCalld20d7982018-07-09 14:25:59 +00001280 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
Sam McCall2b780162018-01-30 17:20:54 +00001281
Sam McCall545a20d2018-01-19 14:34:02 +00001282 SymbolSlab::Builder ResultsBuilder;
1283 // Build the query.
1284 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +00001285 if (Opts.Limit)
1286 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +00001287 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001288 Req.RestrictForCodeCompletion = true;
Eric Liubc25ef72018-07-05 08:29:33 +00001289 Req.Scopes = QueryScopes;
Sam McCall3f0243f2018-07-03 08:09:29 +00001290 // FIXME: we should send multiple weighted paths here.
Eric Liu6de95ec2018-06-12 08:48:20 +00001291 Req.ProximityPaths.push_back(FileName);
Sam McCallbed58852018-07-11 10:35:11 +00001292 vlog("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])", Req.Query,
1293 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ","));
Sam McCall545a20d2018-01-19 14:34:02 +00001294 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +00001295 if (Opts.Index->fuzzyFind(
1296 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1297 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001298 return std::move(ResultsBuilder).build();
1299 }
1300
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001301 // Merges Sema, Index and Override results where possible, to form
1302 // CompletionCandidates. Groups overloads if desired, to form
1303 // CompletionCandidate::Bundles. The bundles are scored and top results are
1304 // returned, best to worst.
Sam McCallc18c2802018-06-15 11:06:29 +00001305 std::vector<ScoredBundle>
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001306 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1307 const SymbolSlab &IndexResults,
1308 const std::vector<CodeCompletionResult> &OverrideResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +00001309 trace::Span Tracer("Merge and score results");
Sam McCallc18c2802018-06-15 11:06:29 +00001310 std::vector<CompletionCandidate::Bundle> Bundles;
1311 llvm::DenseMap<size_t, size_t> BundleLookup;
1312 auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001313 const Symbol *IndexResult,
1314 bool IsOverride = false) {
Sam McCallc18c2802018-06-15 11:06:29 +00001315 CompletionCandidate C;
1316 C.SemaResult = SemaResult;
1317 C.IndexResult = IndexResult;
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001318 C.IsOverride = IsOverride;
Sam McCallc18c2802018-06-15 11:06:29 +00001319 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1320 if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1321 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1322 if (Ret.second)
1323 Bundles.emplace_back();
1324 Bundles[Ret.first->second].push_back(std::move(C));
1325 } else {
1326 Bundles.emplace_back();
1327 Bundles.back().push_back(std::move(C));
1328 }
1329 };
Sam McCall545a20d2018-01-19 14:34:02 +00001330 llvm::DenseSet<const Symbol *> UsedIndexResults;
1331 auto CorrespondingIndexResult =
1332 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
1333 if (auto SymID = getSymbolID(SemaResult)) {
1334 auto I = IndexResults.find(*SymID);
1335 if (I != IndexResults.end()) {
1336 UsedIndexResults.insert(&*I);
1337 return &*I;
1338 }
1339 }
1340 return nullptr;
1341 };
1342 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001343 for (auto &SemaResult : Recorder->Results)
Sam McCallc18c2802018-06-15 11:06:29 +00001344 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001345 // Handle OverrideResults the same way we deal with SemaResults. Since these
1346 // results use the same structs as a SemaResult it is safe to do that, but
1347 // we need to make sure we dont' duplicate things in future if Sema starts
1348 // to provide them as well.
1349 for (auto &OverrideResult : OverrideResults)
1350 AddToBundles(&OverrideResult, CorrespondingIndexResult(OverrideResult),
1351 true);
Sam McCall545a20d2018-01-19 14:34:02 +00001352 // Now emit any Index-only results.
1353 for (const auto &IndexResult : IndexResults) {
1354 if (UsedIndexResults.count(&IndexResult))
1355 continue;
Sam McCallc18c2802018-06-15 11:06:29 +00001356 AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001357 }
Sam McCallc18c2802018-06-15 11:06:29 +00001358 // We only keep the best N results at any time, in "native" format.
1359 TopN<ScoredBundle, ScoredBundleGreater> Top(
1360 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1361 for (auto &Bundle : Bundles)
1362 addCandidate(Top, std::move(Bundle));
Sam McCall545a20d2018-01-19 14:34:02 +00001363 return std::move(Top).items();
1364 }
1365
Sam McCall80ad7072018-06-08 13:32:25 +00001366 Optional<float> fuzzyScore(const CompletionCandidate &C) {
1367 // Macros can be very spammy, so we only support prefix completion.
1368 // We won't end up with underfull index results, as macros are sema-only.
1369 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1370 !C.Name.startswith_lower(Filter->pattern()))
1371 return None;
1372 return Filter->match(C.Name);
1373 }
1374
Sam McCall545a20d2018-01-19 14:34:02 +00001375 // Scores a candidate and adds it to the TopN structure.
Sam McCallc18c2802018-06-15 11:06:29 +00001376 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1377 CompletionCandidate::Bundle Bundle) {
Sam McCallc5707b62018-05-15 17:43:27 +00001378 SymbolQualitySignals Quality;
1379 SymbolRelevanceSignals Relevance;
Eric Liu5d2a8072018-07-23 10:56:37 +00001380 Relevance.Context = Recorder->CCContext.getKind();
Sam McCalld9b54f02018-06-05 16:30:25 +00001381 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Sam McCallf84dd022018-07-05 08:26:53 +00001382 Relevance.FileProximityMatch = FileProximity.getPointer();
Sam McCallc18c2802018-06-15 11:06:29 +00001383 auto &First = Bundle.front();
1384 if (auto FuzzyScore = fuzzyScore(First))
Sam McCallc5707b62018-05-15 17:43:27 +00001385 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001386 else
1387 return;
Sam McCall2161ec72018-07-05 06:20:41 +00001388 SymbolOrigin Origin = SymbolOrigin::Unknown;
Sam McCall4e5742a2018-07-06 11:50:49 +00001389 bool FromIndex = false;
Sam McCallc18c2802018-06-15 11:06:29 +00001390 for (const auto &Candidate : Bundle) {
1391 if (Candidate.IndexResult) {
1392 Quality.merge(*Candidate.IndexResult);
1393 Relevance.merge(*Candidate.IndexResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001394 Origin |= Candidate.IndexResult->Origin;
1395 FromIndex = true;
Sam McCallc18c2802018-06-15 11:06:29 +00001396 }
1397 if (Candidate.SemaResult) {
1398 Quality.merge(*Candidate.SemaResult);
1399 Relevance.merge(*Candidate.SemaResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001400 Origin |= SymbolOrigin::AST;
Sam McCallc18c2802018-06-15 11:06:29 +00001401 }
Sam McCallc5707b62018-05-15 17:43:27 +00001402 }
1403
Sam McCall27c979a2018-06-29 14:47:57 +00001404 CodeCompletion::Scores Scores;
1405 Scores.Quality = Quality.evaluate();
1406 Scores.Relevance = Relevance.evaluate();
1407 Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1408 // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1409 Scores.ExcludingName = Relevance.NameMatch
1410 ? Scores.Total / Relevance.NameMatch
1411 : Scores.Quality;
Sam McCallc5707b62018-05-15 17:43:27 +00001412
Sam McCallbed58852018-07-11 10:35:11 +00001413 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
1414 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
1415 llvm::to_string(Relevance));
Sam McCall545a20d2018-01-19 14:34:02 +00001416
Sam McCall2161ec72018-07-05 06:20:41 +00001417 NSema += bool(Origin & SymbolOrigin::AST);
Sam McCall4e5742a2018-07-06 11:50:49 +00001418 NIndex += FromIndex;
1419 NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
Sam McCallc18c2802018-06-15 11:06:29 +00001420 if (Candidates.push({std::move(Bundle), Scores}))
Sam McCallab8e3932018-02-19 13:04:41 +00001421 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001422 }
1423
Sam McCall27c979a2018-06-29 14:47:57 +00001424 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
1425 llvm::Optional<CodeCompletionBuilder> Builder;
1426 for (const auto &Item : Bundle) {
1427 CodeCompletionString *SemaCCS =
1428 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1429 : nullptr;
1430 if (!Builder)
1431 Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
Sam McCall3f0243f2018-07-03 08:09:29 +00001432 *Inserter, FileName, Opts);
Sam McCall27c979a2018-06-29 14:47:57 +00001433 else
1434 Builder->add(Item, SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +00001435 }
Sam McCall27c979a2018-06-29 14:47:57 +00001436 return Builder->build();
Sam McCall545a20d2018-01-19 14:34:02 +00001437 }
1438};
1439
Sam McCall3f0243f2018-07-03 08:09:29 +00001440CodeCompleteResult codeComplete(PathRef FileName,
1441 const tooling::CompileCommand &Command,
1442 PrecompiledPreamble const *Preamble,
1443 const IncludeStructure &PreambleInclusions,
1444 StringRef Contents, Position Pos,
1445 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1446 std::shared_ptr<PCHContainerOperations> PCHs,
1447 CodeCompleteOptions Opts) {
1448 return CodeCompleteFlow(FileName, PreambleInclusions, Opts)
1449 .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001450}
1451
Sam McCalld1a7a372018-01-31 13:40:48 +00001452SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001453 const tooling::CompileCommand &Command,
1454 PrecompiledPreamble const *Preamble,
1455 StringRef Contents, Position Pos,
1456 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001457 std::shared_ptr<PCHContainerOperations> PCHs,
1458 SymbolIndex *Index) {
Sam McCall98775c52017-12-04 13:49:59 +00001459 SignatureHelp Result;
1460 clang::CodeCompleteOptions Options;
1461 Options.IncludeGlobals = false;
1462 Options.IncludeMacros = false;
1463 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001464 Options.IncludeBriefComments = false;
Sam McCall3f0243f2018-07-03 08:09:29 +00001465 IncludeStructure PreambleInclusions; // Unused for signatureHelp
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001466 semaCodeComplete(
1467 llvm::make_unique<SignatureHelpCollector>(Options, Index, Result),
1468 Options,
1469 {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1470 std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001471 return Result;
1472}
1473
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001474bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1475 using namespace clang::ast_matchers;
1476 auto InTopLevelScope = hasDeclContext(
1477 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1478 return !match(decl(anyOf(InTopLevelScope,
1479 hasDeclContext(
1480 enumDecl(InTopLevelScope, unless(isScoped()))))),
1481 ND, ASTCtx)
1482 .empty();
1483}
1484
Sam McCall27c979a2018-06-29 14:47:57 +00001485CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1486 CompletionItem LSP;
1487 LSP.label = (HeaderInsertion ? Opts.IncludeIndicator.Insert
1488 : Opts.IncludeIndicator.NoInsert) +
Sam McCall2161ec72018-07-05 06:20:41 +00001489 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
Sam McCall27c979a2018-06-29 14:47:57 +00001490 RequiredQualifier + Name + Signature;
Sam McCall2161ec72018-07-05 06:20:41 +00001491
Sam McCall27c979a2018-06-29 14:47:57 +00001492 LSP.kind = Kind;
1493 LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
1494 : ReturnType;
1495 if (!Header.empty())
1496 LSP.detail += "\n" + Header;
1497 LSP.documentation = Documentation;
1498 LSP.sortText = sortText(Score.Total, Name);
1499 LSP.filterText = Name;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001500 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name};
1501 // Merge continious additionalTextEdits into main edit. The main motivation
1502 // behind this is to help LSP clients, it seems most of them are confused when
1503 // they are provided with additionalTextEdits that are consecutive to main
1504 // edit.
1505 // Note that we store additional text edits from back to front in a line. That
1506 // is mainly to help LSP clients again, so that changes do not effect each
1507 // other.
1508 for (const auto &FixIt : FixIts) {
1509 if (IsRangeConsecutive(FixIt.range, LSP.textEdit->range)) {
1510 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
1511 LSP.textEdit->range.start = FixIt.range.start;
1512 } else {
1513 LSP.additionalTextEdits.push_back(FixIt);
1514 }
1515 }
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001516 if (Opts.EnableSnippets)
1517 LSP.textEdit->newText += SnippetSuffix;
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001518
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001519 // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
1520 // compatible with most of the editors.
1521 LSP.insertText = LSP.textEdit->newText;
Sam McCall27c979a2018-06-29 14:47:57 +00001522 LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1523 : InsertTextFormat::PlainText;
1524 if (HeaderInsertion)
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001525 LSP.additionalTextEdits.push_back(*HeaderInsertion);
Sam McCall27c979a2018-06-29 14:47:57 +00001526 return LSP;
1527}
1528
Sam McCalle746a2b2018-07-02 11:13:16 +00001529raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) {
1530 // For now just lean on CompletionItem.
1531 return OS << C.render(CodeCompleteOptions());
1532}
1533
1534raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) {
1535 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
Eric Liu5d2a8072018-07-23 10:56:37 +00001536 << " (" << getCompletionKindString(R.Context) << ")"
Sam McCalle746a2b2018-07-02 11:13:16 +00001537 << " items:\n";
1538 for (const auto &C : R.Completions)
1539 OS << C << "\n";
1540 return OS;
1541}
1542
Sam McCall98775c52017-12-04 13:49:59 +00001543} // namespace clangd
1544} // namespace clang