blob: eda6dfde7fa7b00c5dca5dc32bdef982a0ddc900 [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"
Eric Liu25d74e92018-08-24 11:23:56 +000032#include "TUScheduler.h"
Sam McCall2b780162018-01-30 17:20:54 +000033#include "Trace.h"
Eric Liu63f419a2018-05-15 15:29:32 +000034#include "URI.h"
Eric Liu6f648df2017-12-19 16:50:37 +000035#include "index/Index.h"
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +000036#include "clang/ASTMatchers/ASTMatchFinder.h"
Ilya Biryukovc22d3442018-05-16 12:32:49 +000037#include "clang/Basic/LangOptions.h"
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +000038#include "clang/Basic/SourceLocation.h"
Eric Liuc5105f92018-02-16 14:15:55 +000039#include "clang/Format/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000040#include "clang/Frontend/CompilerInstance.h"
41#include "clang/Frontend/FrontendActions.h"
Sam McCall545a20d2018-01-19 14:34:02 +000042#include "clang/Index/USRGeneration.h"
Sam McCall98775c52017-12-04 13:49:59 +000043#include "clang/Sema/CodeCompleteConsumer.h"
44#include "clang/Sema/Sema.h"
Eric Liuc5105f92018-02-16 14:15:55 +000045#include "clang/Tooling/Core/Replacement.h"
Eric Liu25d74e92018-08-24 11:23:56 +000046#include "llvm/ADT/Optional.h"
Eric Liu83f63e42018-09-03 10:18:21 +000047#include "llvm/ADT/SmallVector.h"
Eric Liu25d74e92018-08-24 11:23:56 +000048#include "llvm/Support/Error.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000049#include "llvm/Support/Format.h"
Eric Liubc25ef72018-07-05 08:29:33 +000050#include "llvm/Support/FormatVariadic.h"
Sam McCall2161ec72018-07-05 06:20:41 +000051#include "llvm/Support/ScopedPrinter.h"
Eric Liu83f63e42018-09-03 10:18:21 +000052#include <algorithm>
53#include <iterator>
Sam McCall98775c52017-12-04 13:49:59 +000054#include <queue>
55
Sam McCallc5707b62018-05-15 17:43:27 +000056// We log detailed candidate here if you run with -debug-only=codecomplete.
Sam McCall27c979a2018-06-29 14:47:57 +000057#define DEBUG_TYPE "CodeComplete"
Sam McCallc5707b62018-05-15 17:43:27 +000058
Sam McCall98775c52017-12-04 13:49:59 +000059namespace clang {
60namespace clangd {
61namespace {
62
Eric Liu6f648df2017-12-19 16:50:37 +000063CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
64 using SK = index::SymbolKind;
65 switch (Kind) {
66 case SK::Unknown:
67 return CompletionItemKind::Missing;
68 case SK::Module:
69 case SK::Namespace:
70 case SK::NamespaceAlias:
71 return CompletionItemKind::Module;
72 case SK::Macro:
73 return CompletionItemKind::Text;
74 case SK::Enum:
75 return CompletionItemKind::Enum;
76 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
77 // protocol.
78 case SK::Struct:
79 case SK::Class:
80 case SK::Protocol:
81 case SK::Extension:
82 case SK::Union:
83 return CompletionItemKind::Class;
84 // FIXME(ioeric): figure out whether reference is the right type for aliases.
85 case SK::TypeAlias:
86 case SK::Using:
87 return CompletionItemKind::Reference;
88 case SK::Function:
89 // FIXME(ioeric): this should probably be an operator. This should be fixed
90 // when `Operator` is support type in the protocol.
91 case SK::ConversionFunction:
92 return CompletionItemKind::Function;
93 case SK::Variable:
94 case SK::Parameter:
95 return CompletionItemKind::Variable;
96 case SK::Field:
97 return CompletionItemKind::Field;
98 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
99 case SK::EnumConstant:
100 return CompletionItemKind::Value;
101 case SK::InstanceMethod:
102 case SK::ClassMethod:
103 case SK::StaticMethod:
104 case SK::Destructor:
105 return CompletionItemKind::Method;
106 case SK::InstanceProperty:
107 case SK::ClassProperty:
108 case SK::StaticProperty:
109 return CompletionItemKind::Property;
110 case SK::Constructor:
111 return CompletionItemKind::Constructor;
112 }
113 llvm_unreachable("Unhandled clang::index::SymbolKind.");
114}
115
Sam McCall83305892018-06-08 21:17:19 +0000116CompletionItemKind
117toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
118 const NamedDecl *Decl) {
119 if (Decl)
120 return toCompletionItemKind(index::getSymbolInfo(Decl).Kind);
121 switch (ResKind) {
122 case CodeCompletionResult::RK_Declaration:
123 llvm_unreachable("RK_Declaration without Decl");
124 case CodeCompletionResult::RK_Keyword:
125 return CompletionItemKind::Keyword;
126 case CodeCompletionResult::RK_Macro:
127 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
128 // completion items in LSP.
129 case CodeCompletionResult::RK_Pattern:
130 return CompletionItemKind::Snippet;
131 }
132 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
133}
134
Sam McCall98775c52017-12-04 13:49:59 +0000135/// Get the optional chunk as a string. This function is possibly recursive.
136///
137/// The parameter info for each parameter is appended to the Parameters.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000138std::string getOptionalParameters(const CodeCompletionString &CCS,
139 std::vector<ParameterInformation> &Parameters,
140 SignatureQualitySignals &Signal) {
Sam McCall98775c52017-12-04 13:49:59 +0000141 std::string Result;
142 for (const auto &Chunk : CCS) {
143 switch (Chunk.Kind) {
144 case CodeCompletionString::CK_Optional:
145 assert(Chunk.Optional &&
146 "Expected the optional code completion string to be non-null.");
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000147 Result += getOptionalParameters(*Chunk.Optional, Parameters, Signal);
Sam McCall98775c52017-12-04 13:49:59 +0000148 break;
149 case CodeCompletionString::CK_VerticalSpace:
150 break;
151 case CodeCompletionString::CK_Placeholder:
152 // A string that acts as a placeholder for, e.g., a function call
153 // argument.
154 // Intentional fallthrough here.
155 case CodeCompletionString::CK_CurrentParameter: {
156 // A piece of text that describes the parameter that corresponds to
157 // the code-completion location within a function call, message send,
158 // macro invocation, etc.
159 Result += Chunk.Text;
160 ParameterInformation Info;
161 Info.label = Chunk.Text;
162 Parameters.push_back(std::move(Info));
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000163 Signal.ContainsActiveParameter = true;
164 Signal.NumberOfOptionalParameters++;
Sam McCall98775c52017-12-04 13:49:59 +0000165 break;
166 }
167 default:
168 Result += Chunk.Text;
169 break;
170 }
171 }
172 return Result;
173}
174
Eric Liu63f419a2018-05-15 15:29:32 +0000175/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
176/// include.
177static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
178 llvm::StringRef HintPath) {
179 if (isLiteralInclude(Header))
180 return HeaderFile{Header.str(), /*Verbatim=*/true};
181 auto U = URI::parse(Header);
182 if (!U)
183 return U.takeError();
184
185 auto IncludePath = URI::includeSpelling(*U);
186 if (!IncludePath)
187 return IncludePath.takeError();
188 if (!IncludePath->empty())
189 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
190
191 auto Resolved = URI::resolve(*U, HintPath);
192 if (!Resolved)
193 return Resolved.takeError();
194 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
195}
196
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000197// First traverses all method definitions inside current class/struct/union
198// definition. Than traverses base classes to find virtual methods that haven't
199// been overriden within current context.
200// FIXME(kadircet): Currently we cannot see declarations below completion point.
201// It is because Sema gets run only upto completion point. Need to find a
202// solution to run it for the whole class/struct/union definition.
203static std::vector<CodeCompletionResult>
204getNonOverridenMethodCompletionResults(const DeclContext *DC, Sema *S) {
205 const auto *CR = llvm::dyn_cast<CXXRecordDecl>(DC);
206 // If not inside a class/struct/union return empty.
207 if (!CR)
208 return {};
209 // First store overrides within current class.
210 // These are stored by name to make querying fast in the later step.
211 llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
212 for (auto *Method : CR->methods()) {
Ilya Biryukov5a79d1e2018-09-03 15:25:27 +0000213 if (!Method->isVirtual() || !Method->getIdentifier())
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000214 continue;
215 Overrides[Method->getName()].push_back(Method);
216 }
217
218 std::vector<CodeCompletionResult> Results;
219 for (const auto &Base : CR->bases()) {
220 const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
221 if (!BR)
222 continue;
223 for (auto *Method : BR->methods()) {
Ilya Biryukov5a79d1e2018-09-03 15:25:27 +0000224 if (!Method->isVirtual() || !Method->getIdentifier())
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000225 continue;
226 const auto it = Overrides.find(Method->getName());
227 bool IsOverriden = false;
228 if (it != Overrides.end()) {
229 for (auto *MD : it->second) {
230 // If the method in current body is not an overload of this virtual
Ilya Biryukov5a79d1e2018-09-03 15:25:27 +0000231 // function, then it overrides this one.
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000232 if (!S->IsOverload(MD, Method, false)) {
233 IsOverriden = true;
234 break;
235 }
236 }
237 }
238 if (!IsOverriden)
239 Results.emplace_back(Method, 0);
240 }
241 }
242
243 return Results;
244}
245
Sam McCall545a20d2018-01-19 14:34:02 +0000246/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000247/// It may be promoted to a CompletionItem if it's among the top-ranked results.
248struct CompletionCandidate {
Sam McCall545a20d2018-01-19 14:34:02 +0000249 llvm::StringRef Name; // Used for filtering and sorting.
250 // We may have a result from Sema, from the index, or both.
251 const CodeCompletionResult *SemaResult = nullptr;
252 const Symbol *IndexResult = nullptr;
Eric Liu83f63e42018-09-03 10:18:21 +0000253 llvm::SmallVector<StringRef, 1> RankedIncludeHeaders;
Sam McCall98775c52017-12-04 13:49:59 +0000254
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000255 // States whether this item is an override suggestion.
256 bool IsOverride = false;
257
Sam McCallc18c2802018-06-15 11:06:29 +0000258 // Returns a token identifying the overload set this is part of.
259 // 0 indicates it's not part of any overload set.
260 size_t overloadSet() const {
261 SmallString<256> Scratch;
262 if (IndexResult) {
263 switch (IndexResult->SymInfo.Kind) {
264 case index::SymbolKind::ClassMethod:
265 case index::SymbolKind::InstanceMethod:
266 case index::SymbolKind::StaticMethod:
267 assert(false && "Don't expect members from index in code completion");
268 // fall through
269 case index::SymbolKind::Function:
270 // We can't group overloads together that need different #includes.
271 // This could break #include insertion.
272 return hash_combine(
273 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
Eric Liu83f63e42018-09-03 10:18:21 +0000274 headerToInsertIfAllowed().getValueOr(""));
Sam McCallc18c2802018-06-15 11:06:29 +0000275 default:
276 return 0;
277 }
278 }
279 assert(SemaResult);
280 // We need to make sure we're consistent with the IndexResult case!
281 const NamedDecl *D = SemaResult->Declaration;
282 if (!D || !D->isFunctionOrFunctionTemplate())
283 return 0;
284 {
285 llvm::raw_svector_ostream OS(Scratch);
286 D->printQualifiedName(OS);
287 }
Eric Liu83f63e42018-09-03 10:18:21 +0000288 return hash_combine(Scratch, headerToInsertIfAllowed().getValueOr(""));
Sam McCallc18c2802018-06-15 11:06:29 +0000289 }
290
Eric Liu83f63e42018-09-03 10:18:21 +0000291 // The best header to include if include insertion is allowed.
292 llvm::Optional<llvm::StringRef> headerToInsertIfAllowed() const {
293 if (RankedIncludeHeaders.empty())
Sam McCallc18c2802018-06-15 11:06:29 +0000294 return llvm::None;
295 if (SemaResult && SemaResult->Declaration) {
296 // Avoid inserting new #include if the declaration is found in the current
297 // file e.g. the symbol is forward declared.
298 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
299 for (const Decl *RD : SemaResult->Declaration->redecls())
Stephen Kelly43465bf2018-08-09 22:42:26 +0000300 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
Sam McCallc18c2802018-06-15 11:06:29 +0000301 return llvm::None;
302 }
Eric Liu83f63e42018-09-03 10:18:21 +0000303 return RankedIncludeHeaders[0];
Sam McCallc18c2802018-06-15 11:06:29 +0000304 }
305
Sam McCallc18c2802018-06-15 11:06:29 +0000306 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
Sam McCall98775c52017-12-04 13:49:59 +0000307};
Sam McCallc18c2802018-06-15 11:06:29 +0000308using ScoredBundle =
Sam McCall27c979a2018-06-29 14:47:57 +0000309 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
Sam McCallc18c2802018-06-15 11:06:29 +0000310struct ScoredBundleGreater {
311 bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
Sam McCall27c979a2018-06-29 14:47:57 +0000312 if (L.second.Total != R.second.Total)
313 return L.second.Total > R.second.Total;
Sam McCallc18c2802018-06-15 11:06:29 +0000314 return L.first.front().Name <
315 R.first.front().Name; // Earlier name is better.
316 }
317};
Sam McCall98775c52017-12-04 13:49:59 +0000318
Sam McCall27c979a2018-06-29 14:47:57 +0000319// Assembles a code completion out of a bundle of >=1 completion candidates.
320// Many of the expensive strings are only computed at this point, once we know
321// the candidate bundle is going to be returned.
322//
323// Many fields are the same for all candidates in a bundle (e.g. name), and are
324// computed from the first candidate, in the constructor.
325// Others vary per candidate, so add() must be called for remaining candidates.
326struct CodeCompletionBuilder {
327 CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
328 CodeCompletionString *SemaCCS,
329 const IncludeInserter &Includes, StringRef FileName,
330 const CodeCompleteOptions &Opts)
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000331 : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments),
332 EnableFunctionArgSnippets(Opts.EnableFunctionArgSnippets) {
Sam McCall27c979a2018-06-29 14:47:57 +0000333 add(C, SemaCCS);
334 if (C.SemaResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000335 Completion.Origin |= SymbolOrigin::AST;
Sam McCall27c979a2018-06-29 14:47:57 +0000336 Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
Eric Liuf433c2d2018-07-18 15:31:14 +0000337 if (Completion.Scope.empty()) {
338 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
339 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
Sam McCall27c979a2018-06-29 14:47:57 +0000340 if (const auto *D = C.SemaResult->getDeclaration())
341 if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
342 Completion.Scope =
343 splitQualifiedName(printQualifiedName(*ND)).first;
Eric Liuf433c2d2018-07-18 15:31:14 +0000344 }
Sam McCall27c979a2018-06-29 14:47:57 +0000345 Completion.Kind =
346 toCompletionItemKind(C.SemaResult->Kind, C.SemaResult->Declaration);
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +0000347 for (const auto &FixIt : C.SemaResult->FixIts) {
348 Completion.FixIts.push_back(
349 toTextEdit(FixIt, ASTCtx.getSourceManager(), ASTCtx.getLangOpts()));
350 }
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +0000351 std::sort(Completion.FixIts.begin(), Completion.FixIts.end(),
352 [](const TextEdit &X, const TextEdit &Y) {
353 return std::tie(X.range.start.line, X.range.start.character) <
354 std::tie(Y.range.start.line, Y.range.start.character);
355 });
Sam McCall27c979a2018-06-29 14:47:57 +0000356 }
357 if (C.IndexResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000358 Completion.Origin |= C.IndexResult->Origin;
Sam McCall27c979a2018-06-29 14:47:57 +0000359 if (Completion.Scope.empty())
360 Completion.Scope = C.IndexResult->Scope;
361 if (Completion.Kind == CompletionItemKind::Missing)
362 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
363 if (Completion.Name.empty())
364 Completion.Name = C.IndexResult->Name;
365 }
Eric Liu83f63e42018-09-03 10:18:21 +0000366
367 // Turn absolute path into a literal string that can be #included.
368 auto Inserted =
369 [&](StringRef Header) -> Expected<std::pair<std::string, bool>> {
370 auto ResolvedDeclaring =
371 toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
372 if (!ResolvedDeclaring)
373 return ResolvedDeclaring.takeError();
374 auto ResolvedInserted = toHeaderFile(Header, FileName);
375 if (!ResolvedInserted)
376 return ResolvedInserted.takeError();
377 return std::make_pair(
378 Includes.calculateIncludePath(*ResolvedDeclaring, *ResolvedInserted),
379 Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
380 };
381 bool ShouldInsert = C.headerToInsertIfAllowed().hasValue();
382 // Calculate include paths and edits for all possible headers.
383 for (const auto &Inc : C.RankedIncludeHeaders) {
384 if (auto ToInclude = Inserted(Inc)) {
385 CodeCompletion::IncludeCandidate Include;
386 Include.Header = ToInclude->first;
387 if (ToInclude->second && ShouldInsert)
388 Include.Insertion = Includes.insert(ToInclude->first);
389 Completion.Includes.push_back(std::move(Include));
Sam McCall27c979a2018-06-29 14:47:57 +0000390 } else
Sam McCallbed58852018-07-11 10:35:11 +0000391 log("Failed to generate include insertion edits for adding header "
Sam McCall27c979a2018-06-29 14:47:57 +0000392 "(FileURI='{0}', IncludeHeader='{1}') into {2}",
Eric Liu83f63e42018-09-03 10:18:21 +0000393 C.IndexResult->CanonicalDeclaration.FileURI, Inc, FileName);
Sam McCall27c979a2018-06-29 14:47:57 +0000394 }
Eric Liu83f63e42018-09-03 10:18:21 +0000395 // Prefer includes that do not need edits (i.e. already exist).
396 std::stable_partition(Completion.Includes.begin(),
397 Completion.Includes.end(),
398 [](const CodeCompletion::IncludeCandidate &I) {
399 return !I.Insertion.hasValue();
400 });
Sam McCall27c979a2018-06-29 14:47:57 +0000401 }
402
403 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {
404 assert(bool(C.SemaResult) == bool(SemaCCS));
405 Bundled.emplace_back();
406 BundledEntry &S = Bundled.back();
407 if (C.SemaResult) {
408 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
409 &Completion.RequiredQualifier);
410 S.ReturnType = getReturnType(*SemaCCS);
411 } else if (C.IndexResult) {
412 S.Signature = C.IndexResult->Signature;
413 S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix;
Sam McCall2e5700f2018-08-31 13:55:01 +0000414 S.ReturnType = C.IndexResult->ReturnType;
Sam McCall27c979a2018-06-29 14:47:57 +0000415 }
416 if (ExtractDocumentation && Completion.Documentation.empty()) {
Sam McCall2e5700f2018-08-31 13:55:01 +0000417 if (C.IndexResult)
418 Completion.Documentation = C.IndexResult->Documentation;
Sam McCall27c979a2018-06-29 14:47:57 +0000419 else if (C.SemaResult)
420 Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
421 /*CommentsFromHeader=*/false);
422 }
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000423 if (C.IsOverride)
424 S.OverrideSuffix = true;
Sam McCall27c979a2018-06-29 14:47:57 +0000425 }
426
427 CodeCompletion build() {
428 Completion.ReturnType = summarizeReturnType();
429 Completion.Signature = summarizeSignature();
430 Completion.SnippetSuffix = summarizeSnippet();
431 Completion.BundleSize = Bundled.size();
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000432 if (summarizeOverride()) {
433 Completion.Name = Completion.ReturnType + ' ' +
434 std::move(Completion.Name) +
435 std::move(Completion.Signature) + " override";
436 Completion.Signature.clear();
437 }
Sam McCall27c979a2018-06-29 14:47:57 +0000438 return std::move(Completion);
439 }
440
441private:
442 struct BundledEntry {
443 std::string SnippetSuffix;
444 std::string Signature;
445 std::string ReturnType;
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000446 bool OverrideSuffix;
Sam McCall27c979a2018-06-29 14:47:57 +0000447 };
448
449 // If all BundledEntrys have the same value for a property, return it.
450 template <std::string BundledEntry::*Member>
451 const std::string *onlyValue() const {
452 auto B = Bundled.begin(), E = Bundled.end();
453 for (auto I = B + 1; I != E; ++I)
454 if (I->*Member != B->*Member)
455 return nullptr;
456 return &(B->*Member);
457 }
458
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000459 template <bool BundledEntry::*Member> const bool *onlyValue() const {
460 auto B = Bundled.begin(), E = Bundled.end();
461 for (auto I = B + 1; I != E; ++I)
462 if (I->*Member != B->*Member)
463 return nullptr;
464 return &(B->*Member);
465 }
466
Sam McCall27c979a2018-06-29 14:47:57 +0000467 std::string summarizeReturnType() const {
468 if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
469 return *RT;
470 return "";
471 }
472
473 std::string summarizeSnippet() const {
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000474 auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
475 if (!Snippet)
476 // All bundles are function calls.
477 return "($0)";
478 if (!Snippet->empty() && !EnableFunctionArgSnippets &&
479 ((Completion.Kind == CompletionItemKind::Function) ||
480 (Completion.Kind == CompletionItemKind::Method)) &&
481 (Snippet->front() == '(') && (Snippet->back() == ')'))
482 // Check whether function has any parameters or not.
483 return Snippet->size() > 2 ? "($0)" : "()";
484 return *Snippet;
Sam McCall27c979a2018-06-29 14:47:57 +0000485 }
486
487 std::string summarizeSignature() const {
488 if (auto *Signature = onlyValue<&BundledEntry::Signature>())
489 return *Signature;
490 // All bundles are function calls.
491 return "(…)";
492 }
493
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +0000494 bool summarizeOverride() const {
495 if (auto *OverrideSuffix = onlyValue<&BundledEntry::OverrideSuffix>())
496 return *OverrideSuffix;
497 return false;
498 }
499
Sam McCall27c979a2018-06-29 14:47:57 +0000500 ASTContext &ASTCtx;
501 CodeCompletion Completion;
502 SmallVector<BundledEntry, 1> Bundled;
503 bool ExtractDocumentation;
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +0000504 bool EnableFunctionArgSnippets;
Sam McCall27c979a2018-06-29 14:47:57 +0000505};
506
Sam McCall545a20d2018-01-19 14:34:02 +0000507// Determine the symbol ID for a Sema code completion result, if possible.
508llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
509 switch (R.Kind) {
510 case CodeCompletionResult::RK_Declaration:
511 case CodeCompletionResult::RK_Pattern: {
Haojian Wuc6ddb462018-08-07 08:57:52 +0000512 return clang::clangd::getSymbolID(R.Declaration);
Sam McCall545a20d2018-01-19 14:34:02 +0000513 }
514 case CodeCompletionResult::RK_Macro:
515 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
516 case CodeCompletionResult::RK_Keyword:
517 return None;
518 }
519 llvm_unreachable("unknown CodeCompletionResult kind");
520}
521
Haojian Wu061c73e2018-01-23 11:37:26 +0000522// Scopes of the paritial identifier we're trying to complete.
523// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000524struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000525 // The scopes we should look in, determined by Sema.
526 //
527 // If the qualifier was fully resolved, we look for completions in these
528 // scopes; if there is an unresolved part of the qualifier, it should be
529 // resolved within these scopes.
530 //
531 // Examples of qualified completion:
532 //
533 // "::vec" => {""}
534 // "using namespace std; ::vec^" => {"", "std::"}
535 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
536 // "std::vec^" => {""} // "std" unresolved
537 //
538 // Examples of unqualified completion:
539 //
540 // "vec^" => {""}
541 // "using namespace std; vec^" => {"", "std::"}
542 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
543 //
544 // "" for global namespace, "ns::" for normal namespace.
545 std::vector<std::string> AccessibleScopes;
546 // The full scope qualifier as typed by the user (without the leading "::").
547 // Set if the qualifier is not fully resolved by Sema.
548 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000549
Haojian Wu061c73e2018-01-23 11:37:26 +0000550 // Construct scopes being queried in indexes.
551 // This method format the scopes to match the index request representation.
552 std::vector<std::string> scopesForIndexQuery() {
553 std::vector<std::string> Results;
554 for (llvm::StringRef AS : AccessibleScopes) {
555 Results.push_back(AS);
556 if (UnresolvedQualifier)
557 Results.back() += *UnresolvedQualifier;
558 }
559 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000560 }
Eric Liu6f648df2017-12-19 16:50:37 +0000561};
562
Haojian Wu061c73e2018-01-23 11:37:26 +0000563// Get all scopes that will be queried in indexes.
564std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000565 const SourceManager &SM) {
566 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000567 SpecifiedScope Info;
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000568 for (auto *Context : CCContext.getVisitedContexts()) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000569 if (isa<TranslationUnitDecl>(Context))
570 Info.AccessibleScopes.push_back(""); // global namespace
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000571 else if (const auto *NS = dyn_cast<NamespaceDecl>(Context))
Haojian Wu061c73e2018-01-23 11:37:26 +0000572 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
573 }
574 return Info;
575 };
576
577 auto SS = CCContext.getCXXScopeSpecifier();
578
579 // Unqualified completion (e.g. "vec^").
580 if (!SS) {
581 // FIXME: Once we can insert namespace qualifiers and use the in-scope
582 // namespaces for scoring, search in all namespaces.
583 // FIXME: Capture scopes and use for scoring, for example,
584 // "using namespace std; namespace foo {v^}" =>
585 // foo::value > std::vector > boost::variant
586 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
587 }
588
589 // Qualified completion ("std::vec^"), we have two cases depending on whether
590 // the qualifier can be resolved by Sema.
591 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000592 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
593 }
594
595 // Unresolved qualifier.
596 // FIXME: When Sema can resolve part of a scope chain (e.g.
597 // "known::unknown::id"), we should expand the known part ("known::") rather
598 // than treating the whole thing as unknown.
599 SpecifiedScope Info;
600 Info.AccessibleScopes.push_back(""); // global namespace
601
602 Info.UnresolvedQualifier =
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000603 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM,
604 clang::LangOptions())
605 .ltrim("::");
Haojian Wu061c73e2018-01-23 11:37:26 +0000606 // Sema excludes the trailing "::".
607 if (!Info.UnresolvedQualifier->empty())
608 *Info.UnresolvedQualifier += "::";
609
610 return Info.scopesForIndexQuery();
611}
612
Eric Liu42abe412018-05-24 11:20:19 +0000613// Should we perform index-based completion in a context of the specified kind?
614// FIXME: consider allowing completion, but restricting the result types.
615bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
616 switch (K) {
617 case CodeCompletionContext::CCC_TopLevel:
618 case CodeCompletionContext::CCC_ObjCInterface:
619 case CodeCompletionContext::CCC_ObjCImplementation:
620 case CodeCompletionContext::CCC_ObjCIvarList:
621 case CodeCompletionContext::CCC_ClassStructUnion:
622 case CodeCompletionContext::CCC_Statement:
623 case CodeCompletionContext::CCC_Expression:
624 case CodeCompletionContext::CCC_ObjCMessageReceiver:
625 case CodeCompletionContext::CCC_EnumTag:
626 case CodeCompletionContext::CCC_UnionTag:
627 case CodeCompletionContext::CCC_ClassOrStructTag:
628 case CodeCompletionContext::CCC_ObjCProtocolName:
629 case CodeCompletionContext::CCC_Namespace:
630 case CodeCompletionContext::CCC_Type:
631 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
632 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
633 case CodeCompletionContext::CCC_ParenthesizedExpression:
634 case CodeCompletionContext::CCC_ObjCInterfaceName:
635 case CodeCompletionContext::CCC_ObjCCategoryName:
636 return true;
637 case CodeCompletionContext::CCC_Other: // Be conservative.
638 case CodeCompletionContext::CCC_OtherWithMacros:
639 case CodeCompletionContext::CCC_DotMemberAccess:
640 case CodeCompletionContext::CCC_ArrowMemberAccess:
641 case CodeCompletionContext::CCC_ObjCPropertyAccess:
642 case CodeCompletionContext::CCC_MacroName:
643 case CodeCompletionContext::CCC_MacroNameUse:
644 case CodeCompletionContext::CCC_PreprocessorExpression:
645 case CodeCompletionContext::CCC_PreprocessorDirective:
646 case CodeCompletionContext::CCC_NaturalLanguage:
647 case CodeCompletionContext::CCC_SelectorName:
648 case CodeCompletionContext::CCC_TypeQualifiers:
649 case CodeCompletionContext::CCC_ObjCInstanceMessage:
650 case CodeCompletionContext::CCC_ObjCClassMessage:
651 case CodeCompletionContext::CCC_Recovery:
652 return false;
653 }
654 llvm_unreachable("unknown code completion context");
655}
656
Sam McCall4caa8512018-06-07 12:49:17 +0000657// Some member calls are blacklisted because they're so rarely useful.
658static bool isBlacklistedMember(const NamedDecl &D) {
659 // Destructor completion is rarely useful, and works inconsistently.
660 // (s.^ completes ~string, but s.~st^ is an error).
661 if (D.getKind() == Decl::CXXDestructor)
662 return true;
663 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
664 if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
665 if (R->isInjectedClassName())
666 return true;
667 // Explicit calls to operators are also rare.
668 auto NameKind = D.getDeclName().getNameKind();
669 if (NameKind == DeclarationName::CXXOperatorName ||
670 NameKind == DeclarationName::CXXLiteralOperatorName ||
671 NameKind == DeclarationName::CXXConversionFunctionName)
672 return true;
673 return false;
674}
675
Sam McCall545a20d2018-01-19 14:34:02 +0000676// The CompletionRecorder captures Sema code-complete output, including context.
677// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
678// It doesn't do scoring or conversion to CompletionItem yet, as we want to
679// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000680// Generally the fields and methods of this object should only be used from
681// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000682struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000683 CompletionRecorder(const CodeCompleteOptions &Opts,
Benjamin Kramerc36c09f2018-07-03 20:59:33 +0000684 llvm::unique_function<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000685 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000686 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000687 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
688 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000689 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
690 assert(this->ResultsCallback);
691 }
692
Sam McCall545a20d2018-01-19 14:34:02 +0000693 std::vector<CodeCompletionResult> Results;
694 CodeCompletionContext CCContext;
695 Sema *CCSema = nullptr; // Sema that created the results.
696 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000697
Sam McCall545a20d2018-01-19 14:34:02 +0000698 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
699 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000700 unsigned NumResults) override final {
Eric Liu485074f2018-07-11 13:15:31 +0000701 // Results from recovery mode are generally useless, and the callback after
702 // recovery (if any) is usually more interesting. To make sure we handle the
703 // future callback from sema, we just ignore all callbacks in recovery mode,
704 // as taking only results from recovery mode results in poor completion
705 // results.
706 // FIXME: in case there is no future sema completion callback after the
707 // recovery mode, we might still want to provide some results (e.g. trivial
708 // identifier-based completion).
709 if (Context.getKind() == CodeCompletionContext::CCC_Recovery) {
710 log("Code complete: Ignoring sema code complete callback with Recovery "
711 "context.");
712 return;
713 }
Eric Liu42abe412018-05-24 11:20:19 +0000714 // If a callback is called without any sema result and the context does not
715 // support index-based completion, we simply skip it to give way to
716 // potential future callbacks with results.
717 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
718 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000719 if (CCSema) {
Sam McCallbed58852018-07-11 10:35:11 +0000720 log("Multiple code complete callbacks (parser backtracked?). "
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000721 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000722 getCompletionKindString(Context.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +0000723 getCompletionKindString(this->CCContext.getKind()));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000724 return;
725 }
Sam McCall545a20d2018-01-19 14:34:02 +0000726 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000727 CCSema = &S;
728 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000729
Sam McCall545a20d2018-01-19 14:34:02 +0000730 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000731 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000732 auto &Result = InResults[I];
733 // Drop hidden items which cannot be found by lookup after completion.
734 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000735 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
736 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000737 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000738 (Result.Availability == CXAvailability_NotAvailable ||
739 Result.Availability == CXAvailability_NotAccessible))
740 continue;
Sam McCall4caa8512018-06-07 12:49:17 +0000741 if (Result.Declaration &&
742 !Context.getBaseType().isNull() // is this a member-access context?
743 && isBlacklistedMember(*Result.Declaration))
Sam McCalld2a95922018-01-22 21:05:00 +0000744 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000745 // We choose to never append '::' to completion results in clangd.
746 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000747 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000748 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000749 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000750 }
751
Sam McCall545a20d2018-01-19 14:34:02 +0000752 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000753 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
754
Sam McCall545a20d2018-01-19 14:34:02 +0000755 // Returns the filtering/sorting name for Result, which must be from Results.
756 // Returned string is owned by this recorder (or the AST).
757 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000758 switch (Result.Kind) {
759 case CodeCompletionResult::RK_Declaration:
760 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000761 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000762 break;
763 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000764 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000765 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000766 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000767 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000768 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000769 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000770 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000771 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000772 }
773
Sam McCall545a20d2018-01-19 14:34:02 +0000774 // Build a CodeCompletion string for R, which must be from Results.
775 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000776 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000777 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
778 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000779 *CCSema, CCContext, *CCAllocator, CCTUInfo,
780 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000781 }
782
Sam McCall545a20d2018-01-19 14:34:02 +0000783private:
784 CodeCompleteOptions Opts;
785 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000786 CodeCompletionTUInfo CCTUInfo;
Benjamin Kramerc36c09f2018-07-03 20:59:33 +0000787 llvm::unique_function<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000788};
789
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000790struct ScoredSignature {
791 // When set, requires documentation to be requested from the index with this
792 // ID.
793 llvm::Optional<SymbolID> IDForDoc;
794 SignatureInformation Signature;
795 SignatureQualitySignals Quality;
796};
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000797
Sam McCall98775c52017-12-04 13:49:59 +0000798class SignatureHelpCollector final : public CodeCompleteConsumer {
Sam McCall98775c52017-12-04 13:49:59 +0000799public:
800 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000801 SymbolIndex *Index, SignatureHelp &SigHelp)
802 : CodeCompleteConsumer(CodeCompleteOpts,
803 /*OutputIsBinary=*/false),
Sam McCall98775c52017-12-04 13:49:59 +0000804 SigHelp(SigHelp),
805 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000806 CCTUInfo(Allocator), Index(Index) {}
Sam McCall98775c52017-12-04 13:49:59 +0000807
808 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
809 OverloadCandidate *Candidates,
Ilya Biryukov43c292c2018-08-30 13:14:31 +0000810 unsigned NumCandidates,
811 SourceLocation OpenParLoc) override {
812 assert(!OpenParLoc.isInvalid());
813 SourceManager &SrcMgr = S.getSourceManager();
814 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
815 if (SrcMgr.isInMainFile(OpenParLoc))
816 SigHelp.argListStart = sourceLocToPosition(SrcMgr, OpenParLoc);
817 else
818 elog("Location oustide main file in signature help: {0}",
819 OpenParLoc.printToString(SrcMgr));
820
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000821 std::vector<ScoredSignature> ScoredSignatures;
Sam McCall98775c52017-12-04 13:49:59 +0000822 SigHelp.signatures.reserve(NumCandidates);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000823 ScoredSignatures.reserve(NumCandidates);
Sam McCall98775c52017-12-04 13:49:59 +0000824 // FIXME(rwols): How can we determine the "active overload candidate"?
825 // Right now the overloaded candidates seem to be provided in a "best fit"
826 // order, so I'm not too worried about this.
827 SigHelp.activeSignature = 0;
828 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
829 "too many arguments");
830 SigHelp.activeParameter = static_cast<int>(CurrentArg);
831 for (unsigned I = 0; I < NumCandidates; ++I) {
Ilya Biryukov8fd44bb2018-08-14 09:36:32 +0000832 OverloadCandidate Candidate = Candidates[I];
833 // We want to avoid showing instantiated signatures, because they may be
834 // long in some cases (e.g. when 'T' is substituted with 'std::string', we
835 // would get 'std::basic_string<char>').
836 if (auto *Func = Candidate.getFunction()) {
837 if (auto *Pattern = Func->getTemplateInstantiationPattern())
838 Candidate = OverloadCandidate(Pattern);
839 }
840
Sam McCall98775c52017-12-04 13:49:59 +0000841 const auto *CCS = Candidate.CreateSignatureString(
842 CurrentArg, S, *Allocator, CCTUInfo, true);
843 assert(CCS && "Expected the CodeCompletionString to be non-null");
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000844 ScoredSignatures.push_back(processOverloadCandidate(
Ilya Biryukov43714502018-05-16 12:32:44 +0000845 Candidate, *CCS,
Ilya Biryukov5f4a3512018-08-17 09:29:38 +0000846 Candidate.getFunction()
847 ? getDeclComment(S.getASTContext(), *Candidate.getFunction())
848 : ""));
Sam McCall98775c52017-12-04 13:49:59 +0000849 }
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000850
851 // Sema does not load the docs from the preamble, so we need to fetch extra
852 // docs from the index instead.
853 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
854 if (Index) {
855 LookupRequest IndexRequest;
856 for (const auto &S : ScoredSignatures) {
857 if (!S.IDForDoc)
858 continue;
859 IndexRequest.IDs.insert(*S.IDForDoc);
860 }
861 Index->lookup(IndexRequest, [&](const Symbol &S) {
Sam McCall2e5700f2018-08-31 13:55:01 +0000862 if (!S.Documentation.empty())
863 FetchedDocs[S.ID] = S.Documentation;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000864 });
865 log("SigHelp: requested docs for {0} symbols from the index, got {1} "
866 "symbols with non-empty docs in the response",
867 IndexRequest.IDs.size(), FetchedDocs.size());
868 }
869
870 std::sort(
871 ScoredSignatures.begin(), ScoredSignatures.end(),
872 [](const ScoredSignature &L, const ScoredSignature &R) {
873 // Ordering follows:
874 // - Less number of parameters is better.
875 // - Function is better than FunctionType which is better than
876 // Function Template.
877 // - High score is better.
878 // - Shorter signature is better.
879 // - Alphebatically smaller is better.
880 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
881 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
882 if (L.Quality.NumberOfOptionalParameters !=
883 R.Quality.NumberOfOptionalParameters)
884 return L.Quality.NumberOfOptionalParameters <
885 R.Quality.NumberOfOptionalParameters;
886 if (L.Quality.Kind != R.Quality.Kind) {
887 using OC = CodeCompleteConsumer::OverloadCandidate;
888 switch (L.Quality.Kind) {
889 case OC::CK_Function:
890 return true;
891 case OC::CK_FunctionType:
892 return R.Quality.Kind != OC::CK_Function;
893 case OC::CK_FunctionTemplate:
894 return false;
895 }
896 llvm_unreachable("Unknown overload candidate type.");
897 }
898 if (L.Signature.label.size() != R.Signature.label.size())
899 return L.Signature.label.size() < R.Signature.label.size();
900 return L.Signature.label < R.Signature.label;
901 });
902
903 for (auto &SS : ScoredSignatures) {
904 auto IndexDocIt =
905 SS.IDForDoc ? FetchedDocs.find(*SS.IDForDoc) : FetchedDocs.end();
906 if (IndexDocIt != FetchedDocs.end())
907 SS.Signature.documentation = IndexDocIt->second;
908
909 SigHelp.signatures.push_back(std::move(SS.Signature));
910 }
Sam McCall98775c52017-12-04 13:49:59 +0000911 }
912
913 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
914
915 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
916
917private:
Eric Liu63696e12017-12-20 17:24:31 +0000918 // FIXME(ioeric): consider moving CodeCompletionString logic here to
919 // CompletionString.h.
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000920 ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
921 const CodeCompletionString &CCS,
922 llvm::StringRef DocComment) const {
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000923 SignatureInformation Signature;
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000924 SignatureQualitySignals Signal;
Sam McCall98775c52017-12-04 13:49:59 +0000925 const char *ReturnType = nullptr;
926
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000927 Signature.documentation = formatDocumentation(CCS, DocComment);
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000928 Signal.Kind = Candidate.getKind();
Sam McCall98775c52017-12-04 13:49:59 +0000929
930 for (const auto &Chunk : CCS) {
931 switch (Chunk.Kind) {
932 case CodeCompletionString::CK_ResultType:
933 // A piece of text that describes the type of an entity or,
934 // for functions and methods, the return type.
935 assert(!ReturnType && "Unexpected CK_ResultType");
936 ReturnType = Chunk.Text;
937 break;
938 case CodeCompletionString::CK_Placeholder:
939 // A string that acts as a placeholder for, e.g., a function call
940 // argument.
941 // Intentional fallthrough here.
942 case CodeCompletionString::CK_CurrentParameter: {
943 // A piece of text that describes the parameter that corresponds to
944 // the code-completion location within a function call, message send,
945 // macro invocation, etc.
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000946 Signature.label += Chunk.Text;
Sam McCall98775c52017-12-04 13:49:59 +0000947 ParameterInformation Info;
948 Info.label = Chunk.Text;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000949 Signature.parameters.push_back(std::move(Info));
Kadir Cetinkayae486e372018-08-13 08:40:05 +0000950 Signal.NumberOfParameters++;
951 Signal.ContainsActiveParameter = true;
Sam McCall98775c52017-12-04 13:49:59 +0000952 break;
953 }
954 case CodeCompletionString::CK_Optional: {
955 // The rest of the parameters are defaulted/optional.
956 assert(Chunk.Optional &&
957 "Expected the optional code completion string to be non-null.");
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000958 Signature.label += getOptionalParameters(*Chunk.Optional,
959 Signature.parameters, Signal);
Sam McCall98775c52017-12-04 13:49:59 +0000960 break;
961 }
962 case CodeCompletionString::CK_VerticalSpace:
963 break;
964 default:
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000965 Signature.label += Chunk.Text;
Sam McCall98775c52017-12-04 13:49:59 +0000966 break;
967 }
968 }
969 if (ReturnType) {
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000970 Signature.label += " -> ";
971 Signature.label += ReturnType;
Sam McCall98775c52017-12-04 13:49:59 +0000972 }
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000973 dlog("Signal for {0}: {1}", Signature, Signal);
974 ScoredSignature Result;
975 Result.Signature = std::move(Signature);
976 Result.Quality = Signal;
977 Result.IDForDoc =
978 Result.Signature.documentation.empty() && Candidate.getFunction()
979 ? clangd::getSymbolID(Candidate.getFunction())
980 : llvm::None;
981 return Result;
Sam McCall98775c52017-12-04 13:49:59 +0000982 }
983
984 SignatureHelp &SigHelp;
985 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
986 CodeCompletionTUInfo CCTUInfo;
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +0000987 const SymbolIndex *Index;
Sam McCall98775c52017-12-04 13:49:59 +0000988}; // SignatureHelpCollector
989
Sam McCall545a20d2018-01-19 14:34:02 +0000990struct SemaCompleteInput {
991 PathRef FileName;
992 const tooling::CompileCommand &Command;
993 PrecompiledPreamble const *Preamble;
994 StringRef Contents;
995 Position Pos;
996 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
997 std::shared_ptr<PCHContainerOperations> PCHs;
998};
999
1000// Invokes Sema code completion on a file.
Sam McCall3f0243f2018-07-03 08:09:29 +00001001// If \p Includes is set, it will be updated based on the compiler invocation.
Sam McCalld1a7a372018-01-31 13:40:48 +00001002bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +00001003 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +00001004 const SemaCompleteInput &Input,
Sam McCall3f0243f2018-07-03 08:09:29 +00001005 IncludeStructure *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001006 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +00001007 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +00001008 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +00001009 ArgStrs.push_back(S.c_str());
1010
Ilya Biryukova9cf3112018-02-13 17:15:06 +00001011 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
1012 log("Couldn't set working directory");
1013 // We run parsing anyway, our lit-tests rely on results for non-existing
1014 // working dirs.
1015 }
Sam McCall98775c52017-12-04 13:49:59 +00001016
1017 IgnoreDiagnostics DummyDiagsConsumer;
1018 auto CI = createInvocationFromCommandLine(
1019 ArgStrs,
1020 CompilerInstance::createDiagnostics(new DiagnosticOptions,
1021 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +00001022 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +00001023 if (!CI) {
Sam McCallbed58852018-07-11 10:35:11 +00001024 elog("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +00001025 return false;
1026 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001027 auto &FrontendOpts = CI->getFrontendOpts();
1028 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +00001029 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001030 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
1031 // Disable typo correction in Sema.
1032 CI->getLangOpts()->SpellChecking = false;
1033 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +00001034 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +00001035 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +00001036 auto Offset = positionToOffset(Input.Contents, Input.Pos);
1037 if (!Offset) {
Sam McCallbed58852018-07-11 10:35:11 +00001038 elog("Code completion position was invalid {0}", Offset.takeError());
Sam McCalla4962cc2018-04-27 11:59:28 +00001039 return false;
1040 }
1041 std::tie(FrontendOpts.CodeCompletionAt.Line,
1042 FrontendOpts.CodeCompletionAt.Column) =
1043 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +00001044
Ilya Biryukov981a35d2018-05-28 12:11:37 +00001045 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1046 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
1047 // The diagnostic options must be set before creating a CompilerInstance.
1048 CI->getDiagnosticOpts().IgnoreWarnings = true;
1049 // We reuse the preamble whether it's valid or not. This is a
1050 // correctness/performance tradeoff: building without a preamble is slow, and
1051 // completion is latency-sensitive.
1052 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
1053 // the remapped buffers do not get freed.
1054 auto Clang = prepareCompilerInstance(
1055 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
1056 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +00001057 Clang->setCodeCompletionConsumer(Consumer.release());
1058
1059 SyntaxOnlyAction Action;
1060 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCallbed58852018-07-11 10:35:11 +00001061 log("BeginSourceFile() failed when running codeComplete for {0}",
Sam McCalld1a7a372018-01-31 13:40:48 +00001062 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +00001063 return false;
1064 }
Sam McCall3f0243f2018-07-03 08:09:29 +00001065 if (Includes)
1066 Clang->getPreprocessor().addPPCallbacks(
1067 collectIncludeStructureCallback(Clang->getSourceManager(), Includes));
Sam McCall98775c52017-12-04 13:49:59 +00001068 if (!Action.Execute()) {
Sam McCallbed58852018-07-11 10:35:11 +00001069 log("Execute() failed when running codeComplete for {0}", Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +00001070 return false;
1071 }
Sam McCall98775c52017-12-04 13:49:59 +00001072 Action.EndSourceFile();
1073
1074 return true;
1075}
1076
Ilya Biryukova907ba42018-05-14 10:50:04 +00001077// Should we allow index completions in the specified context?
1078bool allowIndex(CodeCompletionContext &CC) {
1079 if (!contextAllowsIndex(CC.getKind()))
1080 return false;
1081 // We also avoid ClassName::bar (but allow namespace::bar).
1082 auto Scope = CC.getCXXScopeSpecifier();
1083 if (!Scope)
1084 return true;
1085 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
1086 if (!NameSpec)
1087 return true;
1088 // We only query the index when qualifier is a namespace.
1089 // If it's a class, we rely solely on sema completions.
1090 switch (NameSpec->getKind()) {
1091 case NestedNameSpecifier::Global:
1092 case NestedNameSpecifier::Namespace:
1093 case NestedNameSpecifier::NamespaceAlias:
1094 return true;
1095 case NestedNameSpecifier::Super:
1096 case NestedNameSpecifier::TypeSpec:
1097 case NestedNameSpecifier::TypeSpecWithTemplate:
1098 // Unresolved inside a template.
1099 case NestedNameSpecifier::Identifier:
1100 return false;
1101 }
Ilya Biryukova6556e22018-05-14 11:47:30 +00001102 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +00001103}
1104
Eric Liu25d74e92018-08-24 11:23:56 +00001105std::future<SymbolSlab> startAsyncFuzzyFind(const SymbolIndex &Index,
1106 const FuzzyFindRequest &Req) {
1107 return runAsync<SymbolSlab>([&Index, Req]() {
1108 trace::Span Tracer("Async fuzzyFind");
1109 SymbolSlab::Builder Syms;
1110 Index.fuzzyFind(Req, [&Syms](const Symbol &Sym) { Syms.insert(Sym); });
1111 return std::move(Syms).build();
1112 });
1113}
1114
1115// Creates a `FuzzyFindRequest` based on the cached index request from the
1116// last completion, if any, and the speculated completion filter text in the
1117// source code.
1118llvm::Optional<FuzzyFindRequest> speculativeFuzzyFindRequestForCompletion(
1119 FuzzyFindRequest CachedReq, PathRef File, StringRef Content, Position Pos) {
1120 auto Filter = speculateCompletionFilter(Content, Pos);
1121 if (!Filter) {
1122 elog("Failed to speculate filter text for code completion at Pos "
1123 "{0}:{1}: {2}",
1124 Pos.line, Pos.character, Filter.takeError());
1125 return llvm::None;
1126 }
1127 CachedReq.Query = *Filter;
1128 return CachedReq;
1129}
1130
Sam McCall98775c52017-12-04 13:49:59 +00001131} // namespace
1132
1133clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
1134 clang::CodeCompleteOptions Result;
1135 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
1136 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +00001137 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +00001138 // We choose to include full comments and not do doxygen parsing in
1139 // completion.
1140 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
1141 // formatting of the comments.
1142 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +00001143
Sam McCall3d139c52018-01-12 18:30:08 +00001144 // When an is used, Sema is responsible for completing the main file,
1145 // the index can provide results from the preamble.
1146 // Tell Sema not to deserialize the preamble to look for results.
1147 Result.LoadExternal = !Index;
Kadir Cetinkaya2f84d912018-08-08 08:59:29 +00001148 Result.IncludeFixIts = IncludeFixIts;
Eric Liu6f648df2017-12-19 16:50:37 +00001149
Sam McCall98775c52017-12-04 13:49:59 +00001150 return Result;
1151}
1152
Eric Liu83f63e42018-09-03 10:18:21 +00001153// Returns the most popular include header for \p Sym. If two headers are
1154// equally popular, prefer the shorter one. Returns empty string if \p Sym has
1155// no include header.
1156llvm::SmallVector<StringRef, 1>
1157getRankedIncludes(const Symbol &Sym) {
1158 auto Includes = Sym.IncludeHeaders;
1159 // Sort in descending order by reference count and header length.
1160 std::sort(Includes.begin(), Includes.end(),
1161 [](const Symbol::IncludeHeaderWithReferences &LHS,
1162 const Symbol::IncludeHeaderWithReferences &RHS) {
1163 if (LHS.References == RHS.References)
1164 return LHS.IncludeHeader.size() < RHS.IncludeHeader.size();
1165 return LHS.References > RHS.References;
1166 });
1167 llvm::SmallVector<StringRef, 1> Headers;
1168 for (const auto &Include : Includes)
1169 Headers.push_back(Include.IncludeHeader);
1170 return Headers;
1171}
1172
Sam McCall545a20d2018-01-19 14:34:02 +00001173// Runs Sema-based (AST) and Index-based completion, returns merged results.
1174//
1175// There are a few tricky considerations:
1176// - the AST provides information needed for the index query (e.g. which
1177// namespaces to search in). So Sema must start first.
1178// - we only want to return the top results (Opts.Limit).
1179// Building CompletionItems for everything else is wasteful, so we want to
1180// preserve the "native" format until we're done with scoring.
1181// - the data underlying Sema completion items is owned by the AST and various
1182// other arenas, which must stay alive for us to build CompletionItems.
1183// - we may get duplicate results from Sema and the Index, we need to merge.
1184//
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001185// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +00001186// We use the Sema context information to query the index.
1187// Then we merge the two result sets, producing items that are Sema/Index/Both.
1188// These items are scored, and the top N are synthesized into the LSP response.
1189// Finally, we can clean up the data structures created by Sema completion.
1190//
1191// Main collaborators are:
1192// - semaCodeComplete sets up the compiler machinery to run code completion.
1193// - CompletionRecorder captures Sema completion results, including context.
1194// - SymbolIndex (Opts.Index) provides index completion results as Symbols
1195// - CompletionCandidates are the result of merging Sema and Index results.
1196// Each candidate points to an underlying CodeCompletionResult (Sema), a
1197// Symbol (Index), or both. It computes the result quality score.
1198// CompletionCandidate also does conversion to CompletionItem (at the end).
1199// - FuzzyMatcher scores how the candidate matches the partial identifier.
1200// This score is combined with the result quality score for the final score.
1201// - TopN determines the results with the best score.
1202class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +00001203 PathRef FileName;
Sam McCall3f0243f2018-07-03 08:09:29 +00001204 IncludeStructure Includes; // Complete once the compiler runs.
Eric Liu25d74e92018-08-24 11:23:56 +00001205 SpeculativeFuzzyFind *SpecFuzzyFind; // Can be nullptr.
Sam McCall545a20d2018-01-19 14:34:02 +00001206 const CodeCompleteOptions &Opts;
Eric Liu25d74e92018-08-24 11:23:56 +00001207
Sam McCall545a20d2018-01-19 14:34:02 +00001208 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001209 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +00001210 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
1211 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +00001212 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
Eric Liubc25ef72018-07-05 08:29:33 +00001213 std::vector<std::string> QueryScopes; // Initialized once Sema runs.
Sam McCall3f0243f2018-07-03 08:09:29 +00001214 // Include-insertion and proximity scoring rely on the include structure.
1215 // This is available after Sema has run.
1216 llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
1217 llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
Eric Liu25d74e92018-08-24 11:23:56 +00001218 /// Speculative request based on the cached request and the filter text before
1219 /// the cursor.
1220 /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
1221 /// set and contains a cached request.
1222 llvm::Optional<FuzzyFindRequest> SpecReq;
Sam McCall545a20d2018-01-19 14:34:02 +00001223
1224public:
1225 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Sam McCall3f0243f2018-07-03 08:09:29 +00001226 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
Eric Liu25d74e92018-08-24 11:23:56 +00001227 SpeculativeFuzzyFind *SpecFuzzyFind,
Sam McCall3f0243f2018-07-03 08:09:29 +00001228 const CodeCompleteOptions &Opts)
Eric Liu25d74e92018-08-24 11:23:56 +00001229 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1230 Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +00001231
Sam McCall27c979a2018-06-29 14:47:57 +00001232 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +00001233 trace::Span Tracer("CodeCompleteFlow");
Eric Liu25d74e92018-08-24 11:23:56 +00001234 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq.hasValue()) {
1235 assert(!SpecFuzzyFind->Result.valid());
1236 if ((SpecReq = speculativeFuzzyFindRequestForCompletion(
1237 *SpecFuzzyFind->CachedReq, SemaCCInput.FileName,
1238 SemaCCInput.Contents, SemaCCInput.Pos)))
1239 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1240 }
Eric Liu63f419a2018-05-15 15:29:32 +00001241
Sam McCall545a20d2018-01-19 14:34:02 +00001242 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001243 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +00001244 // - partial identifier and context. We need these for the index query.
Sam McCall27c979a2018-06-29 14:47:57 +00001245 CodeCompleteResult Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001246 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
1247 assert(Recorder && "Recorder is not set");
Sam McCall3f0243f2018-07-03 08:09:29 +00001248 auto Style =
Eric Liu9338a882018-07-03 14:51:23 +00001249 format::getStyle(format::DefaultFormatStyle, SemaCCInput.FileName,
1250 format::DefaultFallbackStyle, SemaCCInput.Contents,
1251 SemaCCInput.VFS.get());
Sam McCall3f0243f2018-07-03 08:09:29 +00001252 if (!Style) {
Sam McCallbed58852018-07-11 10:35:11 +00001253 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.",
1254 SemaCCInput.FileName, Style.takeError());
Sam McCall3f0243f2018-07-03 08:09:29 +00001255 Style = format::getLLVMStyle();
1256 }
Eric Liu63f419a2018-05-15 15:29:32 +00001257 // If preprocessor was run, inclusions from preprocessor callback should
Sam McCall3f0243f2018-07-03 08:09:29 +00001258 // already be added to Includes.
1259 Inserter.emplace(
1260 SemaCCInput.FileName, SemaCCInput.Contents, *Style,
1261 SemaCCInput.Command.Directory,
1262 Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
1263 for (const auto &Inc : Includes.MainFileIncludes)
1264 Inserter->addExisting(Inc);
1265
1266 // Most of the cost of file proximity is in initializing the FileDistance
1267 // structures based on the observed includes, once per query. Conceptually
1268 // that happens here (though the per-URI-scheme initialization is lazy).
1269 // The per-result proximity scoring is (amortized) very cheap.
1270 FileDistanceOptions ProxOpts{}; // Use defaults.
1271 const auto &SM = Recorder->CCSema->getSourceManager();
1272 llvm::StringMap<SourceParams> ProxSources;
1273 for (auto &Entry : Includes.includeDepth(
1274 SM.getFileEntryForID(SM.getMainFileID())->getName())) {
1275 auto &Source = ProxSources[Entry.getKey()];
1276 Source.Cost = Entry.getValue() * ProxOpts.IncludeCost;
1277 // Symbols near our transitive includes are good, but only consider
1278 // things in the same directory or below it. Otherwise there can be
1279 // many false positives.
1280 if (Entry.getValue() > 0)
1281 Source.MaxUpTraversals = 1;
1282 }
1283 FileProximity.emplace(ProxSources, ProxOpts);
1284
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001285 Output = runWithSema();
Sam McCall3f0243f2018-07-03 08:09:29 +00001286 Inserter.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001287 SPAN_ATTACH(Tracer, "sema_completion_kind",
1288 getCompletionKindString(Recorder->CCContext.getKind()));
Sam McCallbed58852018-07-11 10:35:11 +00001289 log("Code complete: sema context {0}, query scopes [{1}]",
Eric Liubc25ef72018-07-05 08:29:33 +00001290 getCompletionKindString(Recorder->CCContext.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +00001291 llvm::join(QueryScopes.begin(), QueryScopes.end(), ","));
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001292 });
1293
1294 Recorder = RecorderOwner.get();
Eric Liu25d74e92018-08-24 11:23:56 +00001295
Sam McCalld1a7a372018-01-31 13:40:48 +00001296 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +00001297 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +00001298
Sam McCall2b780162018-01-30 17:20:54 +00001299 SPAN_ATTACH(Tracer, "sema_results", NSema);
1300 SPAN_ATTACH(Tracer, "index_results", NIndex);
1301 SPAN_ATTACH(Tracer, "merged_results", NBoth);
Sam McCalld20d7982018-07-09 14:25:59 +00001302 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
Sam McCall27c979a2018-06-29 14:47:57 +00001303 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
Sam McCallbed58852018-07-11 10:35:11 +00001304 log("Code complete: {0} results from Sema, {1} from Index, "
1305 "{2} matched, {3} returned{4}.",
1306 NSema, NIndex, NBoth, Output.Completions.size(),
1307 Output.HasMore ? " (incomplete)" : "");
Sam McCall27c979a2018-06-29 14:47:57 +00001308 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +00001309 // We don't assert that isIncomplete means we hit a limit.
1310 // Indexes may choose to impose their own limits even if we don't have one.
1311 return Output;
1312 }
1313
1314private:
1315 // This is called by run() once Sema code completion is done, but before the
1316 // Sema data structures are torn down. It does all the real work.
Sam McCall27c979a2018-06-29 14:47:57 +00001317 CodeCompleteResult runWithSema() {
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001318 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1319 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1320 Range TextEditRange;
1321 // When we are getting completions with an empty identifier, for example
1322 // std::vector<int> asdf;
1323 // asdf.^;
1324 // Then the range will be invalid and we will be doing insertion, use
1325 // current cursor position in such cases as range.
1326 if (CodeCompletionRange.isValid()) {
1327 TextEditRange = halfOpenToRange(Recorder->CCSema->getSourceManager(),
1328 CodeCompletionRange);
1329 } else {
1330 const auto &Pos = sourceLocToPosition(
1331 Recorder->CCSema->getSourceManager(),
1332 Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1333 TextEditRange.start = TextEditRange.end = Pos;
1334 }
Sam McCall545a20d2018-01-19 14:34:02 +00001335 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001336 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Eric Liubc25ef72018-07-05 08:29:33 +00001337 QueryScopes = getQueryScopes(Recorder->CCContext,
1338 Recorder->CCSema->getSourceManager());
Sam McCall545a20d2018-01-19 14:34:02 +00001339 // Sema provides the needed context to query the index.
1340 // FIXME: in addition to querying for extra/overlapping symbols, we should
1341 // explicitly request symbols corresponding to Sema results.
1342 // We can use their signals even if the index can't suggest them.
1343 // We must copy index results to preserve them, but there are at most Limit.
Eric Liu8f3678d2018-06-15 13:34:18 +00001344 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1345 ? queryIndex()
1346 : SymbolSlab();
Eric Liu25d74e92018-08-24 11:23:56 +00001347 trace::Span Tracer("Populate CodeCompleteResult");
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001348 // Merge Sema, Index and Override results, score them, and pick the
1349 // winners.
1350 const auto Overrides = getNonOverridenMethodCompletionResults(
1351 Recorder->CCSema->CurContext, Recorder->CCSema);
1352 auto Top = mergeResults(Recorder->Results, IndexResults, Overrides);
Sam McCall27c979a2018-06-29 14:47:57 +00001353 CodeCompleteResult Output;
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001354
1355 // Convert the results to final form, assembling the expensive strings.
Sam McCall27c979a2018-06-29 14:47:57 +00001356 for (auto &C : Top) {
1357 Output.Completions.push_back(toCodeCompletion(C.first));
1358 Output.Completions.back().Score = C.second;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001359 Output.Completions.back().CompletionTokenRange = TextEditRange;
Sam McCall27c979a2018-06-29 14:47:57 +00001360 }
1361 Output.HasMore = Incomplete;
Eric Liu5d2a8072018-07-23 10:56:37 +00001362 Output.Context = Recorder->CCContext.getKind();
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001363
Sam McCall545a20d2018-01-19 14:34:02 +00001364 return Output;
1365 }
1366
1367 SymbolSlab queryIndex() {
Sam McCalld1a7a372018-01-31 13:40:48 +00001368 trace::Span Tracer("Query index");
Sam McCalld20d7982018-07-09 14:25:59 +00001369 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
Sam McCall2b780162018-01-30 17:20:54 +00001370
Sam McCall545a20d2018-01-19 14:34:02 +00001371 // Build the query.
1372 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +00001373 if (Opts.Limit)
1374 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +00001375 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001376 Req.RestrictForCodeCompletion = true;
Eric Liubc25ef72018-07-05 08:29:33 +00001377 Req.Scopes = QueryScopes;
Sam McCall3f0243f2018-07-03 08:09:29 +00001378 // FIXME: we should send multiple weighted paths here.
Eric Liu6de95ec2018-06-12 08:48:20 +00001379 Req.ProximityPaths.push_back(FileName);
Sam McCallbed58852018-07-11 10:35:11 +00001380 vlog("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])", Req.Query,
1381 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ","));
Eric Liu25d74e92018-08-24 11:23:56 +00001382
1383 if (SpecFuzzyFind)
1384 SpecFuzzyFind->NewReq = Req;
1385 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1386 vlog("Code complete: speculative fuzzy request matches the actual index "
1387 "request. Waiting for the speculative index results.");
1388 SPAN_ATTACH(Tracer, "Speculative results", true);
1389
1390 trace::Span WaitSpec("Wait speculative results");
1391 return SpecFuzzyFind->Result.get();
1392 }
1393
1394 SPAN_ATTACH(Tracer, "Speculative results", false);
1395
Sam McCall545a20d2018-01-19 14:34:02 +00001396 // Run the query against the index.
Eric Liu25d74e92018-08-24 11:23:56 +00001397 SymbolSlab::Builder ResultsBuilder;
Sam McCallab8e3932018-02-19 13:04:41 +00001398 if (Opts.Index->fuzzyFind(
1399 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1400 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001401 return std::move(ResultsBuilder).build();
1402 }
1403
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001404 // Merges Sema, Index and Override results where possible, to form
1405 // CompletionCandidates. Groups overloads if desired, to form
1406 // CompletionCandidate::Bundles. The bundles are scored and top results are
1407 // returned, best to worst.
Sam McCallc18c2802018-06-15 11:06:29 +00001408 std::vector<ScoredBundle>
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001409 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1410 const SymbolSlab &IndexResults,
1411 const std::vector<CodeCompletionResult> &OverrideResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +00001412 trace::Span Tracer("Merge and score results");
Sam McCallc18c2802018-06-15 11:06:29 +00001413 std::vector<CompletionCandidate::Bundle> Bundles;
1414 llvm::DenseMap<size_t, size_t> BundleLookup;
1415 auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001416 const Symbol *IndexResult,
1417 bool IsOverride = false) {
Sam McCallc18c2802018-06-15 11:06:29 +00001418 CompletionCandidate C;
1419 C.SemaResult = SemaResult;
1420 C.IndexResult = IndexResult;
Eric Liu83f63e42018-09-03 10:18:21 +00001421 if (C.IndexResult)
1422 C.RankedIncludeHeaders = getRankedIncludes(*C.IndexResult);
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001423 C.IsOverride = IsOverride;
Sam McCallc18c2802018-06-15 11:06:29 +00001424 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1425 if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1426 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1427 if (Ret.second)
1428 Bundles.emplace_back();
1429 Bundles[Ret.first->second].push_back(std::move(C));
1430 } else {
1431 Bundles.emplace_back();
1432 Bundles.back().push_back(std::move(C));
1433 }
1434 };
Sam McCall545a20d2018-01-19 14:34:02 +00001435 llvm::DenseSet<const Symbol *> UsedIndexResults;
1436 auto CorrespondingIndexResult =
1437 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
1438 if (auto SymID = getSymbolID(SemaResult)) {
1439 auto I = IndexResults.find(*SymID);
1440 if (I != IndexResults.end()) {
1441 UsedIndexResults.insert(&*I);
1442 return &*I;
1443 }
1444 }
1445 return nullptr;
1446 };
1447 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001448 for (auto &SemaResult : Recorder->Results)
Sam McCallc18c2802018-06-15 11:06:29 +00001449 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
Kadir Cetinkayaf8b85a32018-08-23 13:14:50 +00001450 // Handle OverrideResults the same way we deal with SemaResults. Since these
1451 // results use the same structs as a SemaResult it is safe to do that, but
1452 // we need to make sure we dont' duplicate things in future if Sema starts
1453 // to provide them as well.
1454 for (auto &OverrideResult : OverrideResults)
1455 AddToBundles(&OverrideResult, CorrespondingIndexResult(OverrideResult),
1456 true);
Sam McCall545a20d2018-01-19 14:34:02 +00001457 // Now emit any Index-only results.
1458 for (const auto &IndexResult : IndexResults) {
1459 if (UsedIndexResults.count(&IndexResult))
1460 continue;
Sam McCallc18c2802018-06-15 11:06:29 +00001461 AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001462 }
Sam McCallc18c2802018-06-15 11:06:29 +00001463 // We only keep the best N results at any time, in "native" format.
1464 TopN<ScoredBundle, ScoredBundleGreater> Top(
1465 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1466 for (auto &Bundle : Bundles)
1467 addCandidate(Top, std::move(Bundle));
Sam McCall545a20d2018-01-19 14:34:02 +00001468 return std::move(Top).items();
1469 }
1470
Sam McCall80ad7072018-06-08 13:32:25 +00001471 Optional<float> fuzzyScore(const CompletionCandidate &C) {
1472 // Macros can be very spammy, so we only support prefix completion.
1473 // We won't end up with underfull index results, as macros are sema-only.
1474 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1475 !C.Name.startswith_lower(Filter->pattern()))
1476 return None;
1477 return Filter->match(C.Name);
1478 }
1479
Sam McCall545a20d2018-01-19 14:34:02 +00001480 // Scores a candidate and adds it to the TopN structure.
Sam McCallc18c2802018-06-15 11:06:29 +00001481 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1482 CompletionCandidate::Bundle Bundle) {
Sam McCallc5707b62018-05-15 17:43:27 +00001483 SymbolQualitySignals Quality;
1484 SymbolRelevanceSignals Relevance;
Eric Liu5d2a8072018-07-23 10:56:37 +00001485 Relevance.Context = Recorder->CCContext.getKind();
Sam McCalld9b54f02018-06-05 16:30:25 +00001486 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Sam McCallf84dd022018-07-05 08:26:53 +00001487 Relevance.FileProximityMatch = FileProximity.getPointer();
Sam McCallc18c2802018-06-15 11:06:29 +00001488 auto &First = Bundle.front();
1489 if (auto FuzzyScore = fuzzyScore(First))
Sam McCallc5707b62018-05-15 17:43:27 +00001490 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001491 else
1492 return;
Sam McCall2161ec72018-07-05 06:20:41 +00001493 SymbolOrigin Origin = SymbolOrigin::Unknown;
Sam McCall4e5742a2018-07-06 11:50:49 +00001494 bool FromIndex = false;
Sam McCallc18c2802018-06-15 11:06:29 +00001495 for (const auto &Candidate : Bundle) {
1496 if (Candidate.IndexResult) {
1497 Quality.merge(*Candidate.IndexResult);
1498 Relevance.merge(*Candidate.IndexResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001499 Origin |= Candidate.IndexResult->Origin;
1500 FromIndex = true;
Sam McCallc18c2802018-06-15 11:06:29 +00001501 }
1502 if (Candidate.SemaResult) {
1503 Quality.merge(*Candidate.SemaResult);
1504 Relevance.merge(*Candidate.SemaResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001505 Origin |= SymbolOrigin::AST;
Sam McCallc18c2802018-06-15 11:06:29 +00001506 }
Sam McCallc5707b62018-05-15 17:43:27 +00001507 }
1508
Sam McCall27c979a2018-06-29 14:47:57 +00001509 CodeCompletion::Scores Scores;
1510 Scores.Quality = Quality.evaluate();
1511 Scores.Relevance = Relevance.evaluate();
1512 Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1513 // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1514 Scores.ExcludingName = Relevance.NameMatch
1515 ? Scores.Total / Relevance.NameMatch
1516 : Scores.Quality;
Sam McCallc5707b62018-05-15 17:43:27 +00001517
Sam McCallbed58852018-07-11 10:35:11 +00001518 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
1519 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
1520 llvm::to_string(Relevance));
Sam McCall545a20d2018-01-19 14:34:02 +00001521
Sam McCall2161ec72018-07-05 06:20:41 +00001522 NSema += bool(Origin & SymbolOrigin::AST);
Sam McCall4e5742a2018-07-06 11:50:49 +00001523 NIndex += FromIndex;
1524 NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
Sam McCallc18c2802018-06-15 11:06:29 +00001525 if (Candidates.push({std::move(Bundle), Scores}))
Sam McCallab8e3932018-02-19 13:04:41 +00001526 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001527 }
1528
Sam McCall27c979a2018-06-29 14:47:57 +00001529 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
1530 llvm::Optional<CodeCompletionBuilder> Builder;
1531 for (const auto &Item : Bundle) {
1532 CodeCompletionString *SemaCCS =
1533 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1534 : nullptr;
1535 if (!Builder)
1536 Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
Sam McCall3f0243f2018-07-03 08:09:29 +00001537 *Inserter, FileName, Opts);
Sam McCall27c979a2018-06-29 14:47:57 +00001538 else
1539 Builder->add(Item, SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +00001540 }
Sam McCall27c979a2018-06-29 14:47:57 +00001541 return Builder->build();
Sam McCall545a20d2018-01-19 14:34:02 +00001542 }
1543};
1544
Eric Liu25d74e92018-08-24 11:23:56 +00001545llvm::Expected<llvm::StringRef>
1546speculateCompletionFilter(llvm::StringRef Content, Position Pos) {
1547 auto Offset = positionToOffset(Content, Pos);
1548 if (!Offset)
1549 return llvm::make_error<llvm::StringError>(
1550 "Failed to convert position to offset in content.",
1551 llvm::inconvertibleErrorCode());
1552 if (*Offset == 0)
1553 return "";
1554
1555 // Start from the character before the cursor.
1556 int St = *Offset - 1;
1557 // FIXME(ioeric): consider UTF characters?
1558 auto IsValidIdentifierChar = [](char c) {
1559 return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
1560 (c >= '0' && c <= '9') || (c == '_'));
1561 };
1562 size_t Len = 0;
1563 for (; (St >= 0) && IsValidIdentifierChar(Content[St]); --St, ++Len) {
1564 }
1565 if (Len > 0)
1566 St++; // Shift to the first valid character.
1567 return Content.substr(St, Len);
1568}
1569
1570CodeCompleteResult
1571codeComplete(PathRef FileName, const tooling::CompileCommand &Command,
1572 PrecompiledPreamble const *Preamble,
1573 const IncludeStructure &PreambleInclusions, StringRef Contents,
1574 Position Pos, IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1575 std::shared_ptr<PCHContainerOperations> PCHs,
1576 CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind) {
1577 return CodeCompleteFlow(FileName, PreambleInclusions, SpecFuzzyFind, Opts)
Sam McCall3f0243f2018-07-03 08:09:29 +00001578 .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001579}
1580
Sam McCalld1a7a372018-01-31 13:40:48 +00001581SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001582 const tooling::CompileCommand &Command,
1583 PrecompiledPreamble const *Preamble,
1584 StringRef Contents, Position Pos,
1585 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001586 std::shared_ptr<PCHContainerOperations> PCHs,
1587 SymbolIndex *Index) {
Sam McCall98775c52017-12-04 13:49:59 +00001588 SignatureHelp Result;
1589 clang::CodeCompleteOptions Options;
1590 Options.IncludeGlobals = false;
1591 Options.IncludeMacros = false;
1592 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001593 Options.IncludeBriefComments = false;
Sam McCall3f0243f2018-07-03 08:09:29 +00001594 IncludeStructure PreambleInclusions; // Unused for signatureHelp
Ilya Biryukov8a0f76b2018-08-17 09:32:30 +00001595 semaCodeComplete(
1596 llvm::make_unique<SignatureHelpCollector>(Options, Index, Result),
1597 Options,
1598 {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1599 std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001600 return Result;
1601}
1602
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001603bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1604 using namespace clang::ast_matchers;
1605 auto InTopLevelScope = hasDeclContext(
1606 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1607 return !match(decl(anyOf(InTopLevelScope,
1608 hasDeclContext(
1609 enumDecl(InTopLevelScope, unless(isScoped()))))),
1610 ND, ASTCtx)
1611 .empty();
1612}
1613
Sam McCall27c979a2018-06-29 14:47:57 +00001614CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1615 CompletionItem LSP;
Eric Liu83f63e42018-09-03 10:18:21 +00001616 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
1617 LSP.label = ((InsertInclude && InsertInclude->Insertion)
1618 ? Opts.IncludeIndicator.Insert
1619 : Opts.IncludeIndicator.NoInsert) +
Sam McCall2161ec72018-07-05 06:20:41 +00001620 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
Sam McCall27c979a2018-06-29 14:47:57 +00001621 RequiredQualifier + Name + Signature;
Sam McCall2161ec72018-07-05 06:20:41 +00001622
Sam McCall27c979a2018-06-29 14:47:57 +00001623 LSP.kind = Kind;
1624 LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
1625 : ReturnType;
Eric Liu83f63e42018-09-03 10:18:21 +00001626 if (InsertInclude)
1627 LSP.detail += "\n" + InsertInclude->Header;
Sam McCall27c979a2018-06-29 14:47:57 +00001628 LSP.documentation = Documentation;
1629 LSP.sortText = sortText(Score.Total, Name);
1630 LSP.filterText = Name;
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001631 LSP.textEdit = {CompletionTokenRange, RequiredQualifier + Name};
1632 // Merge continious additionalTextEdits into main edit. The main motivation
1633 // behind this is to help LSP clients, it seems most of them are confused when
1634 // they are provided with additionalTextEdits that are consecutive to main
1635 // edit.
1636 // Note that we store additional text edits from back to front in a line. That
1637 // is mainly to help LSP clients again, so that changes do not effect each
1638 // other.
1639 for (const auto &FixIt : FixIts) {
1640 if (IsRangeConsecutive(FixIt.range, LSP.textEdit->range)) {
1641 LSP.textEdit->newText = FixIt.newText + LSP.textEdit->newText;
1642 LSP.textEdit->range.start = FixIt.range.start;
1643 } else {
1644 LSP.additionalTextEdits.push_back(FixIt);
1645 }
1646 }
Kadir Cetinkaya516fcda2018-08-23 12:19:39 +00001647 if (Opts.EnableSnippets)
1648 LSP.textEdit->newText += SnippetSuffix;
Kadir Cetinkaya6c9f15c2018-08-17 15:42:54 +00001649
Kadir Cetinkayaa9c9d002018-08-13 08:23:01 +00001650 // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
1651 // compatible with most of the editors.
1652 LSP.insertText = LSP.textEdit->newText;
Sam McCall27c979a2018-06-29 14:47:57 +00001653 LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1654 : InsertTextFormat::PlainText;
Eric Liu83f63e42018-09-03 10:18:21 +00001655 if (InsertInclude && InsertInclude->Insertion)
1656 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
Sam McCall27c979a2018-06-29 14:47:57 +00001657 return LSP;
1658}
1659
Sam McCalle746a2b2018-07-02 11:13:16 +00001660raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) {
1661 // For now just lean on CompletionItem.
1662 return OS << C.render(CodeCompleteOptions());
1663}
1664
1665raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) {
1666 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
Eric Liu5d2a8072018-07-23 10:56:37 +00001667 << " (" << getCompletionKindString(R.Context) << ")"
Sam McCalle746a2b2018-07-02 11:13:16 +00001668 << " items:\n";
1669 for (const auto &C : R.Completions)
1670 OS << C << "\n";
1671 return OS;
1672}
1673
Sam McCall98775c52017-12-04 13:49:59 +00001674} // namespace clangd
1675} // namespace clang