blob: c0725fa633aaddcc578f166c46ab151062c6f771 [file] [log] [blame]
Sam McCall98775c52017-12-04 13:49:59 +00001//===--- CodeComplete.cpp ---------------------------------------*- C++-*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===---------------------------------------------------------------------===//
9//
Sam McCallc18c2802018-06-15 11:06:29 +000010// Code completion has several moving parts:
11// - AST-based completions are provided using the completion hooks in Sema.
12// - external completions are retrieved from the index (using hints from Sema)
13// - the two sources overlap, and must be merged and overloads bundled
14// - results must be scored and ranked (see Quality.h) before rendering
Sam McCall98775c52017-12-04 13:49:59 +000015//
Sam McCallc18c2802018-06-15 11:06:29 +000016// Signature help works in a similar way as code completion, but it is simpler:
17// it's purely AST-based, and there are few candidates.
Sam McCall98775c52017-12-04 13:49:59 +000018//
19//===---------------------------------------------------------------------===//
20
21#include "CodeComplete.h"
Eric Liu7ad16962018-06-22 10:46:59 +000022#include "AST.h"
Eric Liu63696e12017-12-20 17:24:31 +000023#include "CodeCompletionStrings.h"
Sam McCall98775c52017-12-04 13:49:59 +000024#include "Compiler.h"
Sam McCall3f0243f2018-07-03 08:09:29 +000025#include "FileDistance.h"
Sam McCall84652cc2018-01-12 16:16:09 +000026#include "FuzzyMatch.h"
Eric Liu63f419a2018-05-15 15:29:32 +000027#include "Headers.h"
Eric Liu6f648df2017-12-19 16:50:37 +000028#include "Logger.h"
Sam McCallc5707b62018-05-15 17:43:27 +000029#include "Quality.h"
Eric Liuc5105f92018-02-16 14:15:55 +000030#include "SourceCode.h"
Sam McCall2b780162018-01-30 17:20:54 +000031#include "Trace.h"
Eric Liu63f419a2018-05-15 15:29:32 +000032#include "URI.h"
Eric Liu6f648df2017-12-19 16:50:37 +000033#include "index/Index.h"
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +000034#include "clang/ASTMatchers/ASTMatchFinder.h"
Ilya Biryukovc22d3442018-05-16 12:32:49 +000035#include "clang/Basic/LangOptions.h"
Eric Liuc5105f92018-02-16 14:15:55 +000036#include "clang/Format/Format.h"
Sam McCall98775c52017-12-04 13:49:59 +000037#include "clang/Frontend/CompilerInstance.h"
38#include "clang/Frontend/FrontendActions.h"
Sam McCall545a20d2018-01-19 14:34:02 +000039#include "clang/Index/USRGeneration.h"
Sam McCall98775c52017-12-04 13:49:59 +000040#include "clang/Sema/CodeCompleteConsumer.h"
41#include "clang/Sema/Sema.h"
Eric Liuc5105f92018-02-16 14:15:55 +000042#include "clang/Tooling/Core/Replacement.h"
Haojian Wuba28e9a2018-01-10 14:44:34 +000043#include "llvm/Support/Format.h"
Eric Liubc25ef72018-07-05 08:29:33 +000044#include "llvm/Support/FormatVariadic.h"
Sam McCall2161ec72018-07-05 06:20:41 +000045#include "llvm/Support/ScopedPrinter.h"
Sam McCall98775c52017-12-04 13:49:59 +000046#include <queue>
47
Sam McCallc5707b62018-05-15 17:43:27 +000048// We log detailed candidate here if you run with -debug-only=codecomplete.
Sam McCall27c979a2018-06-29 14:47:57 +000049#define DEBUG_TYPE "CodeComplete"
Sam McCallc5707b62018-05-15 17:43:27 +000050
Sam McCall98775c52017-12-04 13:49:59 +000051namespace clang {
52namespace clangd {
53namespace {
54
Eric Liu6f648df2017-12-19 16:50:37 +000055CompletionItemKind toCompletionItemKind(index::SymbolKind Kind) {
56 using SK = index::SymbolKind;
57 switch (Kind) {
58 case SK::Unknown:
59 return CompletionItemKind::Missing;
60 case SK::Module:
61 case SK::Namespace:
62 case SK::NamespaceAlias:
63 return CompletionItemKind::Module;
64 case SK::Macro:
65 return CompletionItemKind::Text;
66 case SK::Enum:
67 return CompletionItemKind::Enum;
68 // FIXME(ioeric): use LSP struct instead of class when it is suppoted in the
69 // protocol.
70 case SK::Struct:
71 case SK::Class:
72 case SK::Protocol:
73 case SK::Extension:
74 case SK::Union:
75 return CompletionItemKind::Class;
76 // FIXME(ioeric): figure out whether reference is the right type for aliases.
77 case SK::TypeAlias:
78 case SK::Using:
79 return CompletionItemKind::Reference;
80 case SK::Function:
81 // FIXME(ioeric): this should probably be an operator. This should be fixed
82 // when `Operator` is support type in the protocol.
83 case SK::ConversionFunction:
84 return CompletionItemKind::Function;
85 case SK::Variable:
86 case SK::Parameter:
87 return CompletionItemKind::Variable;
88 case SK::Field:
89 return CompletionItemKind::Field;
90 // FIXME(ioeric): use LSP enum constant when it is supported in the protocol.
91 case SK::EnumConstant:
92 return CompletionItemKind::Value;
93 case SK::InstanceMethod:
94 case SK::ClassMethod:
95 case SK::StaticMethod:
96 case SK::Destructor:
97 return CompletionItemKind::Method;
98 case SK::InstanceProperty:
99 case SK::ClassProperty:
100 case SK::StaticProperty:
101 return CompletionItemKind::Property;
102 case SK::Constructor:
103 return CompletionItemKind::Constructor;
104 }
105 llvm_unreachable("Unhandled clang::index::SymbolKind.");
106}
107
Sam McCall83305892018-06-08 21:17:19 +0000108CompletionItemKind
109toCompletionItemKind(CodeCompletionResult::ResultKind ResKind,
110 const NamedDecl *Decl) {
111 if (Decl)
112 return toCompletionItemKind(index::getSymbolInfo(Decl).Kind);
113 switch (ResKind) {
114 case CodeCompletionResult::RK_Declaration:
115 llvm_unreachable("RK_Declaration without Decl");
116 case CodeCompletionResult::RK_Keyword:
117 return CompletionItemKind::Keyword;
118 case CodeCompletionResult::RK_Macro:
119 return CompletionItemKind::Text; // unfortunately, there's no 'Macro'
120 // completion items in LSP.
121 case CodeCompletionResult::RK_Pattern:
122 return CompletionItemKind::Snippet;
123 }
124 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
125}
126
Sam McCall98775c52017-12-04 13:49:59 +0000127/// Get the optional chunk as a string. This function is possibly recursive.
128///
129/// The parameter info for each parameter is appended to the Parameters.
130std::string
131getOptionalParameters(const CodeCompletionString &CCS,
132 std::vector<ParameterInformation> &Parameters) {
133 std::string Result;
134 for (const auto &Chunk : CCS) {
135 switch (Chunk.Kind) {
136 case CodeCompletionString::CK_Optional:
137 assert(Chunk.Optional &&
138 "Expected the optional code completion string to be non-null.");
139 Result += getOptionalParameters(*Chunk.Optional, Parameters);
140 break;
141 case CodeCompletionString::CK_VerticalSpace:
142 break;
143 case CodeCompletionString::CK_Placeholder:
144 // A string that acts as a placeholder for, e.g., a function call
145 // argument.
146 // Intentional fallthrough here.
147 case CodeCompletionString::CK_CurrentParameter: {
148 // A piece of text that describes the parameter that corresponds to
149 // the code-completion location within a function call, message send,
150 // macro invocation, etc.
151 Result += Chunk.Text;
152 ParameterInformation Info;
153 Info.label = Chunk.Text;
154 Parameters.push_back(std::move(Info));
155 break;
156 }
157 default:
158 Result += Chunk.Text;
159 break;
160 }
161 }
162 return Result;
163}
164
Eric Liu63f419a2018-05-15 15:29:32 +0000165/// Creates a `HeaderFile` from \p Header which can be either a URI or a literal
166/// include.
167static llvm::Expected<HeaderFile> toHeaderFile(StringRef Header,
168 llvm::StringRef HintPath) {
169 if (isLiteralInclude(Header))
170 return HeaderFile{Header.str(), /*Verbatim=*/true};
171 auto U = URI::parse(Header);
172 if (!U)
173 return U.takeError();
174
175 auto IncludePath = URI::includeSpelling(*U);
176 if (!IncludePath)
177 return IncludePath.takeError();
178 if (!IncludePath->empty())
179 return HeaderFile{std::move(*IncludePath), /*Verbatim=*/true};
180
181 auto Resolved = URI::resolve(*U, HintPath);
182 if (!Resolved)
183 return Resolved.takeError();
184 return HeaderFile{std::move(*Resolved), /*Verbatim=*/false};
185}
186
Sam McCall545a20d2018-01-19 14:34:02 +0000187/// A code completion result, in clang-native form.
Sam McCall98775c52017-12-04 13:49:59 +0000188/// It may be promoted to a CompletionItem if it's among the top-ranked results.
189struct CompletionCandidate {
Sam McCall545a20d2018-01-19 14:34:02 +0000190 llvm::StringRef Name; // Used for filtering and sorting.
191 // We may have a result from Sema, from the index, or both.
192 const CodeCompletionResult *SemaResult = nullptr;
193 const Symbol *IndexResult = nullptr;
Sam McCall98775c52017-12-04 13:49:59 +0000194
Sam McCallc18c2802018-06-15 11:06:29 +0000195 // Returns a token identifying the overload set this is part of.
196 // 0 indicates it's not part of any overload set.
197 size_t overloadSet() const {
198 SmallString<256> Scratch;
199 if (IndexResult) {
200 switch (IndexResult->SymInfo.Kind) {
201 case index::SymbolKind::ClassMethod:
202 case index::SymbolKind::InstanceMethod:
203 case index::SymbolKind::StaticMethod:
204 assert(false && "Don't expect members from index in code completion");
205 // fall through
206 case index::SymbolKind::Function:
207 // We can't group overloads together that need different #includes.
208 // This could break #include insertion.
209 return hash_combine(
210 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
211 headerToInsertIfNotPresent().getValueOr(""));
212 default:
213 return 0;
214 }
215 }
216 assert(SemaResult);
217 // We need to make sure we're consistent with the IndexResult case!
218 const NamedDecl *D = SemaResult->Declaration;
219 if (!D || !D->isFunctionOrFunctionTemplate())
220 return 0;
221 {
222 llvm::raw_svector_ostream OS(Scratch);
223 D->printQualifiedName(OS);
224 }
225 return hash_combine(Scratch, headerToInsertIfNotPresent().getValueOr(""));
226 }
227
228 llvm::Optional<llvm::StringRef> headerToInsertIfNotPresent() const {
229 if (!IndexResult || !IndexResult->Detail ||
230 IndexResult->Detail->IncludeHeader.empty())
231 return llvm::None;
232 if (SemaResult && SemaResult->Declaration) {
233 // Avoid inserting new #include if the declaration is found in the current
234 // file e.g. the symbol is forward declared.
235 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
236 for (const Decl *RD : SemaResult->Declaration->redecls())
237 if (SM.isInMainFile(SM.getExpansionLoc(RD->getLocStart())))
238 return llvm::None;
239 }
240 return IndexResult->Detail->IncludeHeader;
241 }
242
Sam McCallc18c2802018-06-15 11:06:29 +0000243 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
Sam McCall98775c52017-12-04 13:49:59 +0000244};
Sam McCallc18c2802018-06-15 11:06:29 +0000245using ScoredBundle =
Sam McCall27c979a2018-06-29 14:47:57 +0000246 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
Sam McCallc18c2802018-06-15 11:06:29 +0000247struct ScoredBundleGreater {
248 bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
Sam McCall27c979a2018-06-29 14:47:57 +0000249 if (L.second.Total != R.second.Total)
250 return L.second.Total > R.second.Total;
Sam McCallc18c2802018-06-15 11:06:29 +0000251 return L.first.front().Name <
252 R.first.front().Name; // Earlier name is better.
253 }
254};
Sam McCall98775c52017-12-04 13:49:59 +0000255
Sam McCall27c979a2018-06-29 14:47:57 +0000256// Assembles a code completion out of a bundle of >=1 completion candidates.
257// Many of the expensive strings are only computed at this point, once we know
258// the candidate bundle is going to be returned.
259//
260// Many fields are the same for all candidates in a bundle (e.g. name), and are
261// computed from the first candidate, in the constructor.
262// Others vary per candidate, so add() must be called for remaining candidates.
263struct CodeCompletionBuilder {
264 CodeCompletionBuilder(ASTContext &ASTCtx, const CompletionCandidate &C,
265 CodeCompletionString *SemaCCS,
266 const IncludeInserter &Includes, StringRef FileName,
267 const CodeCompleteOptions &Opts)
268 : ASTCtx(ASTCtx), ExtractDocumentation(Opts.IncludeComments) {
269 add(C, SemaCCS);
270 if (C.SemaResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000271 Completion.Origin |= SymbolOrigin::AST;
Sam McCall27c979a2018-06-29 14:47:57 +0000272 Completion.Name = llvm::StringRef(SemaCCS->getTypedText());
Eric Liuf433c2d2018-07-18 15:31:14 +0000273 if (Completion.Scope.empty()) {
274 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
275 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
Sam McCall27c979a2018-06-29 14:47:57 +0000276 if (const auto *D = C.SemaResult->getDeclaration())
277 if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
278 Completion.Scope =
279 splitQualifiedName(printQualifiedName(*ND)).first;
Eric Liuf433c2d2018-07-18 15:31:14 +0000280 }
Sam McCall27c979a2018-06-29 14:47:57 +0000281 Completion.Kind =
282 toCompletionItemKind(C.SemaResult->Kind, C.SemaResult->Declaration);
283 }
284 if (C.IndexResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000285 Completion.Origin |= C.IndexResult->Origin;
Sam McCall27c979a2018-06-29 14:47:57 +0000286 if (Completion.Scope.empty())
287 Completion.Scope = C.IndexResult->Scope;
288 if (Completion.Kind == CompletionItemKind::Missing)
289 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
290 if (Completion.Name.empty())
291 Completion.Name = C.IndexResult->Name;
292 }
293 if (auto Inserted = C.headerToInsertIfNotPresent()) {
294 // Turn absolute path into a literal string that can be #included.
295 auto Include = [&]() -> Expected<std::pair<std::string, bool>> {
296 auto ResolvedDeclaring =
297 toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
298 if (!ResolvedDeclaring)
299 return ResolvedDeclaring.takeError();
300 auto ResolvedInserted = toHeaderFile(*Inserted, FileName);
301 if (!ResolvedInserted)
302 return ResolvedInserted.takeError();
303 return std::make_pair(Includes.calculateIncludePath(*ResolvedDeclaring,
304 *ResolvedInserted),
305 Includes.shouldInsertInclude(*ResolvedDeclaring,
306 *ResolvedInserted));
307 }();
308 if (Include) {
309 Completion.Header = Include->first;
310 if (Include->second)
311 Completion.HeaderInsertion = Includes.insert(Include->first);
312 } else
Sam McCallbed58852018-07-11 10:35:11 +0000313 log("Failed to generate include insertion edits for adding header "
Sam McCall27c979a2018-06-29 14:47:57 +0000314 "(FileURI='{0}', IncludeHeader='{1}') into {2}",
315 C.IndexResult->CanonicalDeclaration.FileURI,
Sam McCallbed58852018-07-11 10:35:11 +0000316 C.IndexResult->Detail->IncludeHeader, FileName);
Sam McCall27c979a2018-06-29 14:47:57 +0000317 }
318 }
319
320 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {
321 assert(bool(C.SemaResult) == bool(SemaCCS));
322 Bundled.emplace_back();
323 BundledEntry &S = Bundled.back();
324 if (C.SemaResult) {
325 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
326 &Completion.RequiredQualifier);
327 S.ReturnType = getReturnType(*SemaCCS);
328 } else if (C.IndexResult) {
329 S.Signature = C.IndexResult->Signature;
330 S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix;
331 if (auto *D = C.IndexResult->Detail)
332 S.ReturnType = D->ReturnType;
333 }
334 if (ExtractDocumentation && Completion.Documentation.empty()) {
335 if (C.IndexResult && C.IndexResult->Detail)
336 Completion.Documentation = C.IndexResult->Detail->Documentation;
337 else if (C.SemaResult)
338 Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
339 /*CommentsFromHeader=*/false);
340 }
341 }
342
343 CodeCompletion build() {
344 Completion.ReturnType = summarizeReturnType();
345 Completion.Signature = summarizeSignature();
346 Completion.SnippetSuffix = summarizeSnippet();
347 Completion.BundleSize = Bundled.size();
348 return std::move(Completion);
349 }
350
351private:
352 struct BundledEntry {
353 std::string SnippetSuffix;
354 std::string Signature;
355 std::string ReturnType;
356 };
357
358 // If all BundledEntrys have the same value for a property, return it.
359 template <std::string BundledEntry::*Member>
360 const std::string *onlyValue() const {
361 auto B = Bundled.begin(), E = Bundled.end();
362 for (auto I = B + 1; I != E; ++I)
363 if (I->*Member != B->*Member)
364 return nullptr;
365 return &(B->*Member);
366 }
367
368 std::string summarizeReturnType() const {
369 if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
370 return *RT;
371 return "";
372 }
373
374 std::string summarizeSnippet() const {
375 if (auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>())
376 return *Snippet;
377 // All bundles are function calls.
378 return "(${0})";
379 }
380
381 std::string summarizeSignature() const {
382 if (auto *Signature = onlyValue<&BundledEntry::Signature>())
383 return *Signature;
384 // All bundles are function calls.
385 return "(…)";
386 }
387
388 ASTContext &ASTCtx;
389 CodeCompletion Completion;
390 SmallVector<BundledEntry, 1> Bundled;
391 bool ExtractDocumentation;
392};
393
Sam McCall545a20d2018-01-19 14:34:02 +0000394// Determine the symbol ID for a Sema code completion result, if possible.
395llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
396 switch (R.Kind) {
397 case CodeCompletionResult::RK_Declaration:
398 case CodeCompletionResult::RK_Pattern: {
399 llvm::SmallString<128> USR;
400 if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
401 return None;
402 return SymbolID(USR);
403 }
404 case CodeCompletionResult::RK_Macro:
405 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
406 case CodeCompletionResult::RK_Keyword:
407 return None;
408 }
409 llvm_unreachable("unknown CodeCompletionResult kind");
410}
411
Haojian Wu061c73e2018-01-23 11:37:26 +0000412// Scopes of the paritial identifier we're trying to complete.
413// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000414struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000415 // The scopes we should look in, determined by Sema.
416 //
417 // If the qualifier was fully resolved, we look for completions in these
418 // scopes; if there is an unresolved part of the qualifier, it should be
419 // resolved within these scopes.
420 //
421 // Examples of qualified completion:
422 //
423 // "::vec" => {""}
424 // "using namespace std; ::vec^" => {"", "std::"}
425 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
426 // "std::vec^" => {""} // "std" unresolved
427 //
428 // Examples of unqualified completion:
429 //
430 // "vec^" => {""}
431 // "using namespace std; vec^" => {"", "std::"}
432 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
433 //
434 // "" for global namespace, "ns::" for normal namespace.
435 std::vector<std::string> AccessibleScopes;
436 // The full scope qualifier as typed by the user (without the leading "::").
437 // Set if the qualifier is not fully resolved by Sema.
438 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000439
Haojian Wu061c73e2018-01-23 11:37:26 +0000440 // Construct scopes being queried in indexes.
441 // This method format the scopes to match the index request representation.
442 std::vector<std::string> scopesForIndexQuery() {
443 std::vector<std::string> Results;
444 for (llvm::StringRef AS : AccessibleScopes) {
445 Results.push_back(AS);
446 if (UnresolvedQualifier)
447 Results.back() += *UnresolvedQualifier;
448 }
449 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000450 }
Eric Liu6f648df2017-12-19 16:50:37 +0000451};
452
Haojian Wu061c73e2018-01-23 11:37:26 +0000453// Get all scopes that will be queried in indexes.
454std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000455 const SourceManager &SM) {
456 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000457 SpecifiedScope Info;
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000458 for (auto *Context : CCContext.getVisitedContexts()) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000459 if (isa<TranslationUnitDecl>(Context))
460 Info.AccessibleScopes.push_back(""); // global namespace
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000461 else if (const auto *NS = dyn_cast<NamespaceDecl>(Context))
Haojian Wu061c73e2018-01-23 11:37:26 +0000462 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
463 }
464 return Info;
465 };
466
467 auto SS = CCContext.getCXXScopeSpecifier();
468
469 // Unqualified completion (e.g. "vec^").
470 if (!SS) {
471 // FIXME: Once we can insert namespace qualifiers and use the in-scope
472 // namespaces for scoring, search in all namespaces.
473 // FIXME: Capture scopes and use for scoring, for example,
474 // "using namespace std; namespace foo {v^}" =>
475 // foo::value > std::vector > boost::variant
476 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
477 }
478
479 // Qualified completion ("std::vec^"), we have two cases depending on whether
480 // the qualifier can be resolved by Sema.
481 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000482 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
483 }
484
485 // Unresolved qualifier.
486 // FIXME: When Sema can resolve part of a scope chain (e.g.
487 // "known::unknown::id"), we should expand the known part ("known::") rather
488 // than treating the whole thing as unknown.
489 SpecifiedScope Info;
490 Info.AccessibleScopes.push_back(""); // global namespace
491
492 Info.UnresolvedQualifier =
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000493 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM,
494 clang::LangOptions())
495 .ltrim("::");
Haojian Wu061c73e2018-01-23 11:37:26 +0000496 // Sema excludes the trailing "::".
497 if (!Info.UnresolvedQualifier->empty())
498 *Info.UnresolvedQualifier += "::";
499
500 return Info.scopesForIndexQuery();
501}
502
Eric Liu42abe412018-05-24 11:20:19 +0000503// Should we perform index-based completion in a context of the specified kind?
504// FIXME: consider allowing completion, but restricting the result types.
505bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
506 switch (K) {
507 case CodeCompletionContext::CCC_TopLevel:
508 case CodeCompletionContext::CCC_ObjCInterface:
509 case CodeCompletionContext::CCC_ObjCImplementation:
510 case CodeCompletionContext::CCC_ObjCIvarList:
511 case CodeCompletionContext::CCC_ClassStructUnion:
512 case CodeCompletionContext::CCC_Statement:
513 case CodeCompletionContext::CCC_Expression:
514 case CodeCompletionContext::CCC_ObjCMessageReceiver:
515 case CodeCompletionContext::CCC_EnumTag:
516 case CodeCompletionContext::CCC_UnionTag:
517 case CodeCompletionContext::CCC_ClassOrStructTag:
518 case CodeCompletionContext::CCC_ObjCProtocolName:
519 case CodeCompletionContext::CCC_Namespace:
520 case CodeCompletionContext::CCC_Type:
521 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
522 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
523 case CodeCompletionContext::CCC_ParenthesizedExpression:
524 case CodeCompletionContext::CCC_ObjCInterfaceName:
525 case CodeCompletionContext::CCC_ObjCCategoryName:
526 return true;
527 case CodeCompletionContext::CCC_Other: // Be conservative.
528 case CodeCompletionContext::CCC_OtherWithMacros:
529 case CodeCompletionContext::CCC_DotMemberAccess:
530 case CodeCompletionContext::CCC_ArrowMemberAccess:
531 case CodeCompletionContext::CCC_ObjCPropertyAccess:
532 case CodeCompletionContext::CCC_MacroName:
533 case CodeCompletionContext::CCC_MacroNameUse:
534 case CodeCompletionContext::CCC_PreprocessorExpression:
535 case CodeCompletionContext::CCC_PreprocessorDirective:
536 case CodeCompletionContext::CCC_NaturalLanguage:
537 case CodeCompletionContext::CCC_SelectorName:
538 case CodeCompletionContext::CCC_TypeQualifiers:
539 case CodeCompletionContext::CCC_ObjCInstanceMessage:
540 case CodeCompletionContext::CCC_ObjCClassMessage:
541 case CodeCompletionContext::CCC_Recovery:
542 return false;
543 }
544 llvm_unreachable("unknown code completion context");
545}
546
Sam McCall4caa8512018-06-07 12:49:17 +0000547// Some member calls are blacklisted because they're so rarely useful.
548static bool isBlacklistedMember(const NamedDecl &D) {
549 // Destructor completion is rarely useful, and works inconsistently.
550 // (s.^ completes ~string, but s.~st^ is an error).
551 if (D.getKind() == Decl::CXXDestructor)
552 return true;
553 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
554 if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
555 if (R->isInjectedClassName())
556 return true;
557 // Explicit calls to operators are also rare.
558 auto NameKind = D.getDeclName().getNameKind();
559 if (NameKind == DeclarationName::CXXOperatorName ||
560 NameKind == DeclarationName::CXXLiteralOperatorName ||
561 NameKind == DeclarationName::CXXConversionFunctionName)
562 return true;
563 return false;
564}
565
Sam McCall545a20d2018-01-19 14:34:02 +0000566// The CompletionRecorder captures Sema code-complete output, including context.
567// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
568// It doesn't do scoring or conversion to CompletionItem yet, as we want to
569// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000570// Generally the fields and methods of this object should only be used from
571// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000572struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000573 CompletionRecorder(const CodeCompleteOptions &Opts,
Benjamin Kramerc36c09f2018-07-03 20:59:33 +0000574 llvm::unique_function<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000575 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000576 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000577 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
578 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000579 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
580 assert(this->ResultsCallback);
581 }
582
Sam McCall545a20d2018-01-19 14:34:02 +0000583 std::vector<CodeCompletionResult> Results;
584 CodeCompletionContext CCContext;
585 Sema *CCSema = nullptr; // Sema that created the results.
586 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000587
Sam McCall545a20d2018-01-19 14:34:02 +0000588 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
589 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000590 unsigned NumResults) override final {
Eric Liu485074f2018-07-11 13:15:31 +0000591 // Results from recovery mode are generally useless, and the callback after
592 // recovery (if any) is usually more interesting. To make sure we handle the
593 // future callback from sema, we just ignore all callbacks in recovery mode,
594 // as taking only results from recovery mode results in poor completion
595 // results.
596 // FIXME: in case there is no future sema completion callback after the
597 // recovery mode, we might still want to provide some results (e.g. trivial
598 // identifier-based completion).
599 if (Context.getKind() == CodeCompletionContext::CCC_Recovery) {
600 log("Code complete: Ignoring sema code complete callback with Recovery "
601 "context.");
602 return;
603 }
Eric Liu42abe412018-05-24 11:20:19 +0000604 // If a callback is called without any sema result and the context does not
605 // support index-based completion, we simply skip it to give way to
606 // potential future callbacks with results.
607 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
608 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000609 if (CCSema) {
Sam McCallbed58852018-07-11 10:35:11 +0000610 log("Multiple code complete callbacks (parser backtracked?). "
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000611 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000612 getCompletionKindString(Context.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +0000613 getCompletionKindString(this->CCContext.getKind()));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000614 return;
615 }
Sam McCall545a20d2018-01-19 14:34:02 +0000616 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000617 CCSema = &S;
618 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000619
Sam McCall545a20d2018-01-19 14:34:02 +0000620 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000621 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000622 auto &Result = InResults[I];
623 // Drop hidden items which cannot be found by lookup after completion.
624 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000625 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
626 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000627 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000628 (Result.Availability == CXAvailability_NotAvailable ||
629 Result.Availability == CXAvailability_NotAccessible))
630 continue;
Sam McCall4caa8512018-06-07 12:49:17 +0000631 if (Result.Declaration &&
632 !Context.getBaseType().isNull() // is this a member-access context?
633 && isBlacklistedMember(*Result.Declaration))
Sam McCalld2a95922018-01-22 21:05:00 +0000634 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000635 // We choose to never append '::' to completion results in clangd.
636 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000637 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000638 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000639 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000640 }
641
Sam McCall545a20d2018-01-19 14:34:02 +0000642 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000643 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
644
Sam McCall545a20d2018-01-19 14:34:02 +0000645 // Returns the filtering/sorting name for Result, which must be from Results.
646 // Returned string is owned by this recorder (or the AST).
647 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000648 switch (Result.Kind) {
649 case CodeCompletionResult::RK_Declaration:
650 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000651 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000652 break;
653 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000654 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000655 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000656 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000657 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000658 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000659 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000660 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000661 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000662 }
663
Sam McCall545a20d2018-01-19 14:34:02 +0000664 // Build a CodeCompletion string for R, which must be from Results.
665 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000666 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000667 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
668 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000669 *CCSema, CCContext, *CCAllocator, CCTUInfo,
670 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000671 }
672
Sam McCall545a20d2018-01-19 14:34:02 +0000673private:
674 CodeCompleteOptions Opts;
675 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000676 CodeCompletionTUInfo CCTUInfo;
Benjamin Kramerc36c09f2018-07-03 20:59:33 +0000677 llvm::unique_function<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000678};
679
Sam McCall98775c52017-12-04 13:49:59 +0000680class SignatureHelpCollector final : public CodeCompleteConsumer {
681
682public:
683 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
684 SignatureHelp &SigHelp)
685 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
686 SigHelp(SigHelp),
687 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
688 CCTUInfo(Allocator) {}
689
690 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
691 OverloadCandidate *Candidates,
692 unsigned NumCandidates) override {
693 SigHelp.signatures.reserve(NumCandidates);
694 // FIXME(rwols): How can we determine the "active overload candidate"?
695 // Right now the overloaded candidates seem to be provided in a "best fit"
696 // order, so I'm not too worried about this.
697 SigHelp.activeSignature = 0;
698 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
699 "too many arguments");
700 SigHelp.activeParameter = static_cast<int>(CurrentArg);
701 for (unsigned I = 0; I < NumCandidates; ++I) {
702 const auto &Candidate = Candidates[I];
703 const auto *CCS = Candidate.CreateSignatureString(
704 CurrentArg, S, *Allocator, CCTUInfo, true);
705 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000706 // FIXME: for headers, we need to get a comment from the index.
Ilya Biryukov43714502018-05-16 12:32:44 +0000707 SigHelp.signatures.push_back(ProcessOverloadCandidate(
708 Candidate, *CCS,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000709 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000710 /*CommentsFromHeaders=*/false)));
Sam McCall98775c52017-12-04 13:49:59 +0000711 }
712 }
713
714 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
715
716 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
717
718private:
Eric Liu63696e12017-12-20 17:24:31 +0000719 // FIXME(ioeric): consider moving CodeCompletionString logic here to
720 // CompletionString.h.
Sam McCall98775c52017-12-04 13:49:59 +0000721 SignatureInformation
722 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
Ilya Biryukov43714502018-05-16 12:32:44 +0000723 const CodeCompletionString &CCS,
724 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000725 SignatureInformation Result;
726 const char *ReturnType = nullptr;
727
Ilya Biryukov43714502018-05-16 12:32:44 +0000728 Result.documentation = formatDocumentation(CCS, DocComment);
Sam McCall98775c52017-12-04 13:49:59 +0000729
730 for (const auto &Chunk : CCS) {
731 switch (Chunk.Kind) {
732 case CodeCompletionString::CK_ResultType:
733 // A piece of text that describes the type of an entity or,
734 // for functions and methods, the return type.
735 assert(!ReturnType && "Unexpected CK_ResultType");
736 ReturnType = Chunk.Text;
737 break;
738 case CodeCompletionString::CK_Placeholder:
739 // A string that acts as a placeholder for, e.g., a function call
740 // argument.
741 // Intentional fallthrough here.
742 case CodeCompletionString::CK_CurrentParameter: {
743 // A piece of text that describes the parameter that corresponds to
744 // the code-completion location within a function call, message send,
745 // macro invocation, etc.
746 Result.label += Chunk.Text;
747 ParameterInformation Info;
748 Info.label = Chunk.Text;
749 Result.parameters.push_back(std::move(Info));
750 break;
751 }
752 case CodeCompletionString::CK_Optional: {
753 // The rest of the parameters are defaulted/optional.
754 assert(Chunk.Optional &&
755 "Expected the optional code completion string to be non-null.");
756 Result.label +=
757 getOptionalParameters(*Chunk.Optional, Result.parameters);
758 break;
759 }
760 case CodeCompletionString::CK_VerticalSpace:
761 break;
762 default:
763 Result.label += Chunk.Text;
764 break;
765 }
766 }
767 if (ReturnType) {
768 Result.label += " -> ";
769 Result.label += ReturnType;
770 }
771 return Result;
772 }
773
774 SignatureHelp &SigHelp;
775 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
776 CodeCompletionTUInfo CCTUInfo;
777
778}; // SignatureHelpCollector
779
Sam McCall545a20d2018-01-19 14:34:02 +0000780struct SemaCompleteInput {
781 PathRef FileName;
782 const tooling::CompileCommand &Command;
783 PrecompiledPreamble const *Preamble;
784 StringRef Contents;
785 Position Pos;
786 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
787 std::shared_ptr<PCHContainerOperations> PCHs;
788};
789
790// Invokes Sema code completion on a file.
Sam McCall3f0243f2018-07-03 08:09:29 +0000791// If \p Includes is set, it will be updated based on the compiler invocation.
Sam McCalld1a7a372018-01-31 13:40:48 +0000792bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000793 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000794 const SemaCompleteInput &Input,
Sam McCall3f0243f2018-07-03 08:09:29 +0000795 IncludeStructure *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000796 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000797 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000798 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000799 ArgStrs.push_back(S.c_str());
800
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000801 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
802 log("Couldn't set working directory");
803 // We run parsing anyway, our lit-tests rely on results for non-existing
804 // working dirs.
805 }
Sam McCall98775c52017-12-04 13:49:59 +0000806
807 IgnoreDiagnostics DummyDiagsConsumer;
808 auto CI = createInvocationFromCommandLine(
809 ArgStrs,
810 CompilerInstance::createDiagnostics(new DiagnosticOptions,
811 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000812 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000813 if (!CI) {
Sam McCallbed58852018-07-11 10:35:11 +0000814 elog("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000815 return false;
816 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000817 auto &FrontendOpts = CI->getFrontendOpts();
818 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000819 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000820 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
821 // Disable typo correction in Sema.
822 CI->getLangOpts()->SpellChecking = false;
823 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +0000824 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000825 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000826 auto Offset = positionToOffset(Input.Contents, Input.Pos);
827 if (!Offset) {
Sam McCallbed58852018-07-11 10:35:11 +0000828 elog("Code completion position was invalid {0}", Offset.takeError());
Sam McCalla4962cc2018-04-27 11:59:28 +0000829 return false;
830 }
831 std::tie(FrontendOpts.CodeCompletionAt.Line,
832 FrontendOpts.CodeCompletionAt.Column) =
833 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000834
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000835 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
836 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
837 // The diagnostic options must be set before creating a CompilerInstance.
838 CI->getDiagnosticOpts().IgnoreWarnings = true;
839 // We reuse the preamble whether it's valid or not. This is a
840 // correctness/performance tradeoff: building without a preamble is slow, and
841 // completion is latency-sensitive.
842 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
843 // the remapped buffers do not get freed.
844 auto Clang = prepareCompilerInstance(
845 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
846 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000847 Clang->setCodeCompletionConsumer(Consumer.release());
848
849 SyntaxOnlyAction Action;
850 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCallbed58852018-07-11 10:35:11 +0000851 log("BeginSourceFile() failed when running codeComplete for {0}",
Sam McCalld1a7a372018-01-31 13:40:48 +0000852 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000853 return false;
854 }
Sam McCall3f0243f2018-07-03 08:09:29 +0000855 if (Includes)
856 Clang->getPreprocessor().addPPCallbacks(
857 collectIncludeStructureCallback(Clang->getSourceManager(), Includes));
Sam McCall98775c52017-12-04 13:49:59 +0000858 if (!Action.Execute()) {
Sam McCallbed58852018-07-11 10:35:11 +0000859 log("Execute() failed when running codeComplete for {0}", Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000860 return false;
861 }
Sam McCall98775c52017-12-04 13:49:59 +0000862 Action.EndSourceFile();
863
864 return true;
865}
866
Ilya Biryukova907ba42018-05-14 10:50:04 +0000867// Should we allow index completions in the specified context?
868bool allowIndex(CodeCompletionContext &CC) {
869 if (!contextAllowsIndex(CC.getKind()))
870 return false;
871 // We also avoid ClassName::bar (but allow namespace::bar).
872 auto Scope = CC.getCXXScopeSpecifier();
873 if (!Scope)
874 return true;
875 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
876 if (!NameSpec)
877 return true;
878 // We only query the index when qualifier is a namespace.
879 // If it's a class, we rely solely on sema completions.
880 switch (NameSpec->getKind()) {
881 case NestedNameSpecifier::Global:
882 case NestedNameSpecifier::Namespace:
883 case NestedNameSpecifier::NamespaceAlias:
884 return true;
885 case NestedNameSpecifier::Super:
886 case NestedNameSpecifier::TypeSpec:
887 case NestedNameSpecifier::TypeSpecWithTemplate:
888 // Unresolved inside a template.
889 case NestedNameSpecifier::Identifier:
890 return false;
891 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000892 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000893}
894
Sam McCall98775c52017-12-04 13:49:59 +0000895} // namespace
896
897clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
898 clang::CodeCompleteOptions Result;
899 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
900 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000901 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000902 // We choose to include full comments and not do doxygen parsing in
903 // completion.
904 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
905 // formatting of the comments.
906 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000907
Sam McCall3d139c52018-01-12 18:30:08 +0000908 // When an is used, Sema is responsible for completing the main file,
909 // the index can provide results from the preamble.
910 // Tell Sema not to deserialize the preamble to look for results.
911 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000912
Sam McCall98775c52017-12-04 13:49:59 +0000913 return Result;
914}
915
Sam McCall545a20d2018-01-19 14:34:02 +0000916// Runs Sema-based (AST) and Index-based completion, returns merged results.
917//
918// There are a few tricky considerations:
919// - the AST provides information needed for the index query (e.g. which
920// namespaces to search in). So Sema must start first.
921// - we only want to return the top results (Opts.Limit).
922// Building CompletionItems for everything else is wasteful, so we want to
923// preserve the "native" format until we're done with scoring.
924// - the data underlying Sema completion items is owned by the AST and various
925// other arenas, which must stay alive for us to build CompletionItems.
926// - we may get duplicate results from Sema and the Index, we need to merge.
927//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000928// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000929// We use the Sema context information to query the index.
930// Then we merge the two result sets, producing items that are Sema/Index/Both.
931// These items are scored, and the top N are synthesized into the LSP response.
932// Finally, we can clean up the data structures created by Sema completion.
933//
934// Main collaborators are:
935// - semaCodeComplete sets up the compiler machinery to run code completion.
936// - CompletionRecorder captures Sema completion results, including context.
937// - SymbolIndex (Opts.Index) provides index completion results as Symbols
938// - CompletionCandidates are the result of merging Sema and Index results.
939// Each candidate points to an underlying CodeCompletionResult (Sema), a
940// Symbol (Index), or both. It computes the result quality score.
941// CompletionCandidate also does conversion to CompletionItem (at the end).
942// - FuzzyMatcher scores how the candidate matches the partial identifier.
943// This score is combined with the result quality score for the final score.
944// - TopN determines the results with the best score.
945class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000946 PathRef FileName;
Sam McCall3f0243f2018-07-03 08:09:29 +0000947 IncludeStructure Includes; // Complete once the compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000948 const CodeCompleteOptions &Opts;
949 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000950 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000951 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
952 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000953 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
Eric Liubc25ef72018-07-05 08:29:33 +0000954 std::vector<std::string> QueryScopes; // Initialized once Sema runs.
Sam McCall3f0243f2018-07-03 08:09:29 +0000955 // Include-insertion and proximity scoring rely on the include structure.
956 // This is available after Sema has run.
957 llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
958 llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000959
960public:
961 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Sam McCall3f0243f2018-07-03 08:09:29 +0000962 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
963 const CodeCompleteOptions &Opts)
964 : FileName(FileName), Includes(Includes), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000965
Sam McCall27c979a2018-06-29 14:47:57 +0000966 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000967 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000968
Sam McCall545a20d2018-01-19 14:34:02 +0000969 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000970 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000971 // - partial identifier and context. We need these for the index query.
Sam McCall27c979a2018-06-29 14:47:57 +0000972 CodeCompleteResult Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000973 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
974 assert(Recorder && "Recorder is not set");
Sam McCall3f0243f2018-07-03 08:09:29 +0000975 auto Style =
Eric Liu9338a882018-07-03 14:51:23 +0000976 format::getStyle(format::DefaultFormatStyle, SemaCCInput.FileName,
977 format::DefaultFallbackStyle, SemaCCInput.Contents,
978 SemaCCInput.VFS.get());
Sam McCall3f0243f2018-07-03 08:09:29 +0000979 if (!Style) {
Sam McCallbed58852018-07-11 10:35:11 +0000980 log("getStyle() failed for file {0}: {1}. Fallback is LLVM style.",
981 SemaCCInput.FileName, Style.takeError());
Sam McCall3f0243f2018-07-03 08:09:29 +0000982 Style = format::getLLVMStyle();
983 }
Eric Liu63f419a2018-05-15 15:29:32 +0000984 // If preprocessor was run, inclusions from preprocessor callback should
Sam McCall3f0243f2018-07-03 08:09:29 +0000985 // already be added to Includes.
986 Inserter.emplace(
987 SemaCCInput.FileName, SemaCCInput.Contents, *Style,
988 SemaCCInput.Command.Directory,
989 Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
990 for (const auto &Inc : Includes.MainFileIncludes)
991 Inserter->addExisting(Inc);
992
993 // Most of the cost of file proximity is in initializing the FileDistance
994 // structures based on the observed includes, once per query. Conceptually
995 // that happens here (though the per-URI-scheme initialization is lazy).
996 // The per-result proximity scoring is (amortized) very cheap.
997 FileDistanceOptions ProxOpts{}; // Use defaults.
998 const auto &SM = Recorder->CCSema->getSourceManager();
999 llvm::StringMap<SourceParams> ProxSources;
1000 for (auto &Entry : Includes.includeDepth(
1001 SM.getFileEntryForID(SM.getMainFileID())->getName())) {
1002 auto &Source = ProxSources[Entry.getKey()];
1003 Source.Cost = Entry.getValue() * ProxOpts.IncludeCost;
1004 // Symbols near our transitive includes are good, but only consider
1005 // things in the same directory or below it. Otherwise there can be
1006 // many false positives.
1007 if (Entry.getValue() > 0)
1008 Source.MaxUpTraversals = 1;
1009 }
1010 FileProximity.emplace(ProxSources, ProxOpts);
1011
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001012 Output = runWithSema();
Sam McCall3f0243f2018-07-03 08:09:29 +00001013 Inserter.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001014 SPAN_ATTACH(Tracer, "sema_completion_kind",
1015 getCompletionKindString(Recorder->CCContext.getKind()));
Sam McCallbed58852018-07-11 10:35:11 +00001016 log("Code complete: sema context {0}, query scopes [{1}]",
Eric Liubc25ef72018-07-05 08:29:33 +00001017 getCompletionKindString(Recorder->CCContext.getKind()),
Sam McCallbed58852018-07-11 10:35:11 +00001018 llvm::join(QueryScopes.begin(), QueryScopes.end(), ","));
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001019 });
1020
1021 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +00001022 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +00001023 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +00001024
Sam McCall2b780162018-01-30 17:20:54 +00001025 SPAN_ATTACH(Tracer, "sema_results", NSema);
1026 SPAN_ATTACH(Tracer, "index_results", NIndex);
1027 SPAN_ATTACH(Tracer, "merged_results", NBoth);
Sam McCalld20d7982018-07-09 14:25:59 +00001028 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
Sam McCall27c979a2018-06-29 14:47:57 +00001029 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
Sam McCallbed58852018-07-11 10:35:11 +00001030 log("Code complete: {0} results from Sema, {1} from Index, "
1031 "{2} matched, {3} returned{4}.",
1032 NSema, NIndex, NBoth, Output.Completions.size(),
1033 Output.HasMore ? " (incomplete)" : "");
Sam McCall27c979a2018-06-29 14:47:57 +00001034 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +00001035 // We don't assert that isIncomplete means we hit a limit.
1036 // Indexes may choose to impose their own limits even if we don't have one.
1037 return Output;
1038 }
1039
1040private:
1041 // This is called by run() once Sema code completion is done, but before the
1042 // Sema data structures are torn down. It does all the real work.
Sam McCall27c979a2018-06-29 14:47:57 +00001043 CodeCompleteResult runWithSema() {
Sam McCall545a20d2018-01-19 14:34:02 +00001044 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001045 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Eric Liubc25ef72018-07-05 08:29:33 +00001046 QueryScopes = getQueryScopes(Recorder->CCContext,
1047 Recorder->CCSema->getSourceManager());
Sam McCall545a20d2018-01-19 14:34:02 +00001048 // Sema provides the needed context to query the index.
1049 // FIXME: in addition to querying for extra/overlapping symbols, we should
1050 // explicitly request symbols corresponding to Sema results.
1051 // We can use their signals even if the index can't suggest them.
1052 // We must copy index results to preserve them, but there are at most Limit.
Eric Liu8f3678d2018-06-15 13:34:18 +00001053 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1054 ? queryIndex()
1055 : SymbolSlab();
Sam McCall545a20d2018-01-19 14:34:02 +00001056 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001057 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall27c979a2018-06-29 14:47:57 +00001058 // Convert the results to final form, assembling the expensive strings.
1059 CodeCompleteResult Output;
1060 for (auto &C : Top) {
1061 Output.Completions.push_back(toCodeCompletion(C.first));
1062 Output.Completions.back().Score = C.second;
1063 }
1064 Output.HasMore = Incomplete;
Sam McCall545a20d2018-01-19 14:34:02 +00001065 return Output;
1066 }
1067
1068 SymbolSlab queryIndex() {
Sam McCalld1a7a372018-01-31 13:40:48 +00001069 trace::Span Tracer("Query index");
Sam McCalld20d7982018-07-09 14:25:59 +00001070 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
Sam McCall2b780162018-01-30 17:20:54 +00001071
Sam McCall545a20d2018-01-19 14:34:02 +00001072 SymbolSlab::Builder ResultsBuilder;
1073 // Build the query.
1074 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +00001075 if (Opts.Limit)
1076 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +00001077 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001078 Req.RestrictForCodeCompletion = true;
Eric Liubc25ef72018-07-05 08:29:33 +00001079 Req.Scopes = QueryScopes;
Sam McCall3f0243f2018-07-03 08:09:29 +00001080 // FIXME: we should send multiple weighted paths here.
Eric Liu6de95ec2018-06-12 08:48:20 +00001081 Req.ProximityPaths.push_back(FileName);
Sam McCallbed58852018-07-11 10:35:11 +00001082 vlog("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])", Req.Query,
1083 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ","));
Sam McCall545a20d2018-01-19 14:34:02 +00001084 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +00001085 if (Opts.Index->fuzzyFind(
1086 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1087 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001088 return std::move(ResultsBuilder).build();
1089 }
1090
Sam McCallc18c2802018-06-15 11:06:29 +00001091 // Merges Sema and Index results where possible, to form CompletionCandidates.
1092 // Groups overloads if desired, to form CompletionCandidate::Bundles.
1093 // The bundles are scored and top results are returned, best to worst.
1094 std::vector<ScoredBundle>
Sam McCall545a20d2018-01-19 14:34:02 +00001095 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1096 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +00001097 trace::Span Tracer("Merge and score results");
Sam McCallc18c2802018-06-15 11:06:29 +00001098 std::vector<CompletionCandidate::Bundle> Bundles;
1099 llvm::DenseMap<size_t, size_t> BundleLookup;
1100 auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
1101 const Symbol *IndexResult) {
1102 CompletionCandidate C;
1103 C.SemaResult = SemaResult;
1104 C.IndexResult = IndexResult;
1105 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1106 if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1107 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1108 if (Ret.second)
1109 Bundles.emplace_back();
1110 Bundles[Ret.first->second].push_back(std::move(C));
1111 } else {
1112 Bundles.emplace_back();
1113 Bundles.back().push_back(std::move(C));
1114 }
1115 };
Sam McCall545a20d2018-01-19 14:34:02 +00001116 llvm::DenseSet<const Symbol *> UsedIndexResults;
1117 auto CorrespondingIndexResult =
1118 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
1119 if (auto SymID = getSymbolID(SemaResult)) {
1120 auto I = IndexResults.find(*SymID);
1121 if (I != IndexResults.end()) {
1122 UsedIndexResults.insert(&*I);
1123 return &*I;
1124 }
1125 }
1126 return nullptr;
1127 };
1128 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001129 for (auto &SemaResult : Recorder->Results)
Sam McCallc18c2802018-06-15 11:06:29 +00001130 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
Sam McCall545a20d2018-01-19 14:34:02 +00001131 // Now emit any Index-only results.
1132 for (const auto &IndexResult : IndexResults) {
1133 if (UsedIndexResults.count(&IndexResult))
1134 continue;
Sam McCallc18c2802018-06-15 11:06:29 +00001135 AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001136 }
Sam McCallc18c2802018-06-15 11:06:29 +00001137 // We only keep the best N results at any time, in "native" format.
1138 TopN<ScoredBundle, ScoredBundleGreater> Top(
1139 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1140 for (auto &Bundle : Bundles)
1141 addCandidate(Top, std::move(Bundle));
Sam McCall545a20d2018-01-19 14:34:02 +00001142 return std::move(Top).items();
1143 }
1144
Sam McCall80ad7072018-06-08 13:32:25 +00001145 Optional<float> fuzzyScore(const CompletionCandidate &C) {
1146 // Macros can be very spammy, so we only support prefix completion.
1147 // We won't end up with underfull index results, as macros are sema-only.
1148 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1149 !C.Name.startswith_lower(Filter->pattern()))
1150 return None;
1151 return Filter->match(C.Name);
1152 }
1153
Sam McCall545a20d2018-01-19 14:34:02 +00001154 // Scores a candidate and adds it to the TopN structure.
Sam McCallc18c2802018-06-15 11:06:29 +00001155 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1156 CompletionCandidate::Bundle Bundle) {
Sam McCallc5707b62018-05-15 17:43:27 +00001157 SymbolQualitySignals Quality;
1158 SymbolRelevanceSignals Relevance;
Sam McCalld9b54f02018-06-05 16:30:25 +00001159 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Sam McCallf84dd022018-07-05 08:26:53 +00001160 Relevance.FileProximityMatch = FileProximity.getPointer();
Sam McCallc18c2802018-06-15 11:06:29 +00001161 auto &First = Bundle.front();
1162 if (auto FuzzyScore = fuzzyScore(First))
Sam McCallc5707b62018-05-15 17:43:27 +00001163 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001164 else
1165 return;
Sam McCall2161ec72018-07-05 06:20:41 +00001166 SymbolOrigin Origin = SymbolOrigin::Unknown;
Sam McCall4e5742a2018-07-06 11:50:49 +00001167 bool FromIndex = false;
Sam McCallc18c2802018-06-15 11:06:29 +00001168 for (const auto &Candidate : Bundle) {
1169 if (Candidate.IndexResult) {
1170 Quality.merge(*Candidate.IndexResult);
1171 Relevance.merge(*Candidate.IndexResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001172 Origin |= Candidate.IndexResult->Origin;
1173 FromIndex = true;
Sam McCallc18c2802018-06-15 11:06:29 +00001174 }
1175 if (Candidate.SemaResult) {
1176 Quality.merge(*Candidate.SemaResult);
1177 Relevance.merge(*Candidate.SemaResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001178 Origin |= SymbolOrigin::AST;
Sam McCallc18c2802018-06-15 11:06:29 +00001179 }
Sam McCallc5707b62018-05-15 17:43:27 +00001180 }
1181
Sam McCall27c979a2018-06-29 14:47:57 +00001182 CodeCompletion::Scores Scores;
1183 Scores.Quality = Quality.evaluate();
1184 Scores.Relevance = Relevance.evaluate();
1185 Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1186 // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1187 Scores.ExcludingName = Relevance.NameMatch
1188 ? Scores.Total / Relevance.NameMatch
1189 : Scores.Quality;
Sam McCallc5707b62018-05-15 17:43:27 +00001190
Sam McCallbed58852018-07-11 10:35:11 +00001191 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
1192 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
1193 llvm::to_string(Relevance));
Sam McCall545a20d2018-01-19 14:34:02 +00001194
Sam McCall2161ec72018-07-05 06:20:41 +00001195 NSema += bool(Origin & SymbolOrigin::AST);
Sam McCall4e5742a2018-07-06 11:50:49 +00001196 NIndex += FromIndex;
1197 NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
Sam McCallc18c2802018-06-15 11:06:29 +00001198 if (Candidates.push({std::move(Bundle), Scores}))
Sam McCallab8e3932018-02-19 13:04:41 +00001199 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001200 }
1201
Sam McCall27c979a2018-06-29 14:47:57 +00001202 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
1203 llvm::Optional<CodeCompletionBuilder> Builder;
1204 for (const auto &Item : Bundle) {
1205 CodeCompletionString *SemaCCS =
1206 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1207 : nullptr;
1208 if (!Builder)
1209 Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
Sam McCall3f0243f2018-07-03 08:09:29 +00001210 *Inserter, FileName, Opts);
Sam McCall27c979a2018-06-29 14:47:57 +00001211 else
1212 Builder->add(Item, SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +00001213 }
Sam McCall27c979a2018-06-29 14:47:57 +00001214 return Builder->build();
Sam McCall545a20d2018-01-19 14:34:02 +00001215 }
1216};
1217
Sam McCall3f0243f2018-07-03 08:09:29 +00001218CodeCompleteResult codeComplete(PathRef FileName,
1219 const tooling::CompileCommand &Command,
1220 PrecompiledPreamble const *Preamble,
1221 const IncludeStructure &PreambleInclusions,
1222 StringRef Contents, Position Pos,
1223 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1224 std::shared_ptr<PCHContainerOperations> PCHs,
1225 CodeCompleteOptions Opts) {
1226 return CodeCompleteFlow(FileName, PreambleInclusions, Opts)
1227 .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001228}
1229
Sam McCalld1a7a372018-01-31 13:40:48 +00001230SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001231 const tooling::CompileCommand &Command,
1232 PrecompiledPreamble const *Preamble,
1233 StringRef Contents, Position Pos,
1234 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1235 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001236 SignatureHelp Result;
1237 clang::CodeCompleteOptions Options;
1238 Options.IncludeGlobals = false;
1239 Options.IncludeMacros = false;
1240 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001241 Options.IncludeBriefComments = false;
Sam McCall3f0243f2018-07-03 08:09:29 +00001242 IncludeStructure PreambleInclusions; // Unused for signatureHelp
Sam McCalld1a7a372018-01-31 13:40:48 +00001243 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1244 Options,
Sam McCall3f0243f2018-07-03 08:09:29 +00001245 {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1246 std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001247 return Result;
1248}
1249
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001250bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1251 using namespace clang::ast_matchers;
1252 auto InTopLevelScope = hasDeclContext(
1253 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1254 return !match(decl(anyOf(InTopLevelScope,
1255 hasDeclContext(
1256 enumDecl(InTopLevelScope, unless(isScoped()))))),
1257 ND, ASTCtx)
1258 .empty();
1259}
1260
Sam McCall27c979a2018-06-29 14:47:57 +00001261CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1262 CompletionItem LSP;
1263 LSP.label = (HeaderInsertion ? Opts.IncludeIndicator.Insert
1264 : Opts.IncludeIndicator.NoInsert) +
Sam McCall2161ec72018-07-05 06:20:41 +00001265 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
Sam McCall27c979a2018-06-29 14:47:57 +00001266 RequiredQualifier + Name + Signature;
Sam McCall2161ec72018-07-05 06:20:41 +00001267
Sam McCall27c979a2018-06-29 14:47:57 +00001268 LSP.kind = Kind;
1269 LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
1270 : ReturnType;
1271 if (!Header.empty())
1272 LSP.detail += "\n" + Header;
1273 LSP.documentation = Documentation;
1274 LSP.sortText = sortText(Score.Total, Name);
1275 LSP.filterText = Name;
1276 LSP.insertText = RequiredQualifier + Name;
1277 if (Opts.EnableSnippets)
1278 LSP.insertText += SnippetSuffix;
1279 LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1280 : InsertTextFormat::PlainText;
1281 if (HeaderInsertion)
1282 LSP.additionalTextEdits = {*HeaderInsertion};
Sam McCall27c979a2018-06-29 14:47:57 +00001283 return LSP;
1284}
1285
Sam McCalle746a2b2018-07-02 11:13:16 +00001286raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) {
1287 // For now just lean on CompletionItem.
1288 return OS << C.render(CodeCompleteOptions());
1289}
1290
1291raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) {
1292 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
1293 << " items:\n";
1294 for (const auto &C : R.Completions)
1295 OS << C << "\n";
1296 return OS;
1297}
1298
Sam McCall98775c52017-12-04 13:49:59 +00001299} // namespace clangd
1300} // namespace clang