blob: be252b52b64d10ca3f6f869d4f6d9ad9edb65dc2 [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());
273 if (Completion.Scope.empty())
274 if (C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
275 if (const auto *D = C.SemaResult->getDeclaration())
276 if (const auto *ND = llvm::dyn_cast<NamedDecl>(D))
277 Completion.Scope =
278 splitQualifiedName(printQualifiedName(*ND)).first;
279 Completion.Kind =
280 toCompletionItemKind(C.SemaResult->Kind, C.SemaResult->Declaration);
281 }
282 if (C.IndexResult) {
Sam McCall4e5742a2018-07-06 11:50:49 +0000283 Completion.Origin |= C.IndexResult->Origin;
Sam McCall27c979a2018-06-29 14:47:57 +0000284 if (Completion.Scope.empty())
285 Completion.Scope = C.IndexResult->Scope;
286 if (Completion.Kind == CompletionItemKind::Missing)
287 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind);
288 if (Completion.Name.empty())
289 Completion.Name = C.IndexResult->Name;
290 }
291 if (auto Inserted = C.headerToInsertIfNotPresent()) {
292 // Turn absolute path into a literal string that can be #included.
293 auto Include = [&]() -> Expected<std::pair<std::string, bool>> {
294 auto ResolvedDeclaring =
295 toHeaderFile(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
296 if (!ResolvedDeclaring)
297 return ResolvedDeclaring.takeError();
298 auto ResolvedInserted = toHeaderFile(*Inserted, FileName);
299 if (!ResolvedInserted)
300 return ResolvedInserted.takeError();
301 return std::make_pair(Includes.calculateIncludePath(*ResolvedDeclaring,
302 *ResolvedInserted),
303 Includes.shouldInsertInclude(*ResolvedDeclaring,
304 *ResolvedInserted));
305 }();
306 if (Include) {
307 Completion.Header = Include->first;
308 if (Include->second)
309 Completion.HeaderInsertion = Includes.insert(Include->first);
310 } else
311 log(llvm::formatv(
312 "Failed to generate include insertion edits for adding header "
313 "(FileURI='{0}', IncludeHeader='{1}') into {2}",
314 C.IndexResult->CanonicalDeclaration.FileURI,
315 C.IndexResult->Detail->IncludeHeader, FileName));
316 }
317 }
318
319 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS) {
320 assert(bool(C.SemaResult) == bool(SemaCCS));
321 Bundled.emplace_back();
322 BundledEntry &S = Bundled.back();
323 if (C.SemaResult) {
324 getSignature(*SemaCCS, &S.Signature, &S.SnippetSuffix,
325 &Completion.RequiredQualifier);
326 S.ReturnType = getReturnType(*SemaCCS);
327 } else if (C.IndexResult) {
328 S.Signature = C.IndexResult->Signature;
329 S.SnippetSuffix = C.IndexResult->CompletionSnippetSuffix;
330 if (auto *D = C.IndexResult->Detail)
331 S.ReturnType = D->ReturnType;
332 }
333 if (ExtractDocumentation && Completion.Documentation.empty()) {
334 if (C.IndexResult && C.IndexResult->Detail)
335 Completion.Documentation = C.IndexResult->Detail->Documentation;
336 else if (C.SemaResult)
337 Completion.Documentation = getDocComment(ASTCtx, *C.SemaResult,
338 /*CommentsFromHeader=*/false);
339 }
340 }
341
342 CodeCompletion build() {
343 Completion.ReturnType = summarizeReturnType();
344 Completion.Signature = summarizeSignature();
345 Completion.SnippetSuffix = summarizeSnippet();
346 Completion.BundleSize = Bundled.size();
347 return std::move(Completion);
348 }
349
350private:
351 struct BundledEntry {
352 std::string SnippetSuffix;
353 std::string Signature;
354 std::string ReturnType;
355 };
356
357 // If all BundledEntrys have the same value for a property, return it.
358 template <std::string BundledEntry::*Member>
359 const std::string *onlyValue() const {
360 auto B = Bundled.begin(), E = Bundled.end();
361 for (auto I = B + 1; I != E; ++I)
362 if (I->*Member != B->*Member)
363 return nullptr;
364 return &(B->*Member);
365 }
366
367 std::string summarizeReturnType() const {
368 if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
369 return *RT;
370 return "";
371 }
372
373 std::string summarizeSnippet() const {
374 if (auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>())
375 return *Snippet;
376 // All bundles are function calls.
377 return "(${0})";
378 }
379
380 std::string summarizeSignature() const {
381 if (auto *Signature = onlyValue<&BundledEntry::Signature>())
382 return *Signature;
383 // All bundles are function calls.
384 return "(…)";
385 }
386
387 ASTContext &ASTCtx;
388 CodeCompletion Completion;
389 SmallVector<BundledEntry, 1> Bundled;
390 bool ExtractDocumentation;
391};
392
Sam McCall545a20d2018-01-19 14:34:02 +0000393// Determine the symbol ID for a Sema code completion result, if possible.
394llvm::Optional<SymbolID> getSymbolID(const CodeCompletionResult &R) {
395 switch (R.Kind) {
396 case CodeCompletionResult::RK_Declaration:
397 case CodeCompletionResult::RK_Pattern: {
398 llvm::SmallString<128> USR;
399 if (/*Ignore=*/clang::index::generateUSRForDecl(R.Declaration, USR))
400 return None;
401 return SymbolID(USR);
402 }
403 case CodeCompletionResult::RK_Macro:
404 // FIXME: Macros do have USRs, but the CCR doesn't contain enough info.
405 case CodeCompletionResult::RK_Keyword:
406 return None;
407 }
408 llvm_unreachable("unknown CodeCompletionResult kind");
409}
410
Haojian Wu061c73e2018-01-23 11:37:26 +0000411// Scopes of the paritial identifier we're trying to complete.
412// It is used when we query the index for more completion results.
Eric Liu6f648df2017-12-19 16:50:37 +0000413struct SpecifiedScope {
Haojian Wu061c73e2018-01-23 11:37:26 +0000414 // The scopes we should look in, determined by Sema.
415 //
416 // If the qualifier was fully resolved, we look for completions in these
417 // scopes; if there is an unresolved part of the qualifier, it should be
418 // resolved within these scopes.
419 //
420 // Examples of qualified completion:
421 //
422 // "::vec" => {""}
423 // "using namespace std; ::vec^" => {"", "std::"}
424 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
425 // "std::vec^" => {""} // "std" unresolved
426 //
427 // Examples of unqualified completion:
428 //
429 // "vec^" => {""}
430 // "using namespace std; vec^" => {"", "std::"}
431 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
432 //
433 // "" for global namespace, "ns::" for normal namespace.
434 std::vector<std::string> AccessibleScopes;
435 // The full scope qualifier as typed by the user (without the leading "::").
436 // Set if the qualifier is not fully resolved by Sema.
437 llvm::Optional<std::string> UnresolvedQualifier;
Sam McCall545a20d2018-01-19 14:34:02 +0000438
Haojian Wu061c73e2018-01-23 11:37:26 +0000439 // Construct scopes being queried in indexes.
440 // This method format the scopes to match the index request representation.
441 std::vector<std::string> scopesForIndexQuery() {
442 std::vector<std::string> Results;
443 for (llvm::StringRef AS : AccessibleScopes) {
444 Results.push_back(AS);
445 if (UnresolvedQualifier)
446 Results.back() += *UnresolvedQualifier;
447 }
448 return Results;
Sam McCall545a20d2018-01-19 14:34:02 +0000449 }
Eric Liu6f648df2017-12-19 16:50:37 +0000450};
451
Haojian Wu061c73e2018-01-23 11:37:26 +0000452// Get all scopes that will be queried in indexes.
453std::vector<std::string> getQueryScopes(CodeCompletionContext &CCContext,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000454 const SourceManager &SM) {
455 auto GetAllAccessibleScopes = [](CodeCompletionContext &CCContext) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000456 SpecifiedScope Info;
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000457 for (auto *Context : CCContext.getVisitedContexts()) {
Haojian Wu061c73e2018-01-23 11:37:26 +0000458 if (isa<TranslationUnitDecl>(Context))
459 Info.AccessibleScopes.push_back(""); // global namespace
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000460 else if (const auto *NS = dyn_cast<NamespaceDecl>(Context))
Haojian Wu061c73e2018-01-23 11:37:26 +0000461 Info.AccessibleScopes.push_back(NS->getQualifiedNameAsString() + "::");
462 }
463 return Info;
464 };
465
466 auto SS = CCContext.getCXXScopeSpecifier();
467
468 // Unqualified completion (e.g. "vec^").
469 if (!SS) {
470 // FIXME: Once we can insert namespace qualifiers and use the in-scope
471 // namespaces for scoring, search in all namespaces.
472 // FIXME: Capture scopes and use for scoring, for example,
473 // "using namespace std; namespace foo {v^}" =>
474 // foo::value > std::vector > boost::variant
475 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
476 }
477
478 // Qualified completion ("std::vec^"), we have two cases depending on whether
479 // the qualifier can be resolved by Sema.
480 if ((*SS)->isValid()) { // Resolved qualifier.
Haojian Wu061c73e2018-01-23 11:37:26 +0000481 return GetAllAccessibleScopes(CCContext).scopesForIndexQuery();
482 }
483
484 // Unresolved qualifier.
485 // FIXME: When Sema can resolve part of a scope chain (e.g.
486 // "known::unknown::id"), we should expand the known part ("known::") rather
487 // than treating the whole thing as unknown.
488 SpecifiedScope Info;
489 Info.AccessibleScopes.push_back(""); // global namespace
490
491 Info.UnresolvedQualifier =
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000492 Lexer::getSourceText(CharSourceRange::getCharRange((*SS)->getRange()), SM,
493 clang::LangOptions())
494 .ltrim("::");
Haojian Wu061c73e2018-01-23 11:37:26 +0000495 // Sema excludes the trailing "::".
496 if (!Info.UnresolvedQualifier->empty())
497 *Info.UnresolvedQualifier += "::";
498
499 return Info.scopesForIndexQuery();
500}
501
Eric Liu42abe412018-05-24 11:20:19 +0000502// Should we perform index-based completion in a context of the specified kind?
503// FIXME: consider allowing completion, but restricting the result types.
504bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
505 switch (K) {
506 case CodeCompletionContext::CCC_TopLevel:
507 case CodeCompletionContext::CCC_ObjCInterface:
508 case CodeCompletionContext::CCC_ObjCImplementation:
509 case CodeCompletionContext::CCC_ObjCIvarList:
510 case CodeCompletionContext::CCC_ClassStructUnion:
511 case CodeCompletionContext::CCC_Statement:
512 case CodeCompletionContext::CCC_Expression:
513 case CodeCompletionContext::CCC_ObjCMessageReceiver:
514 case CodeCompletionContext::CCC_EnumTag:
515 case CodeCompletionContext::CCC_UnionTag:
516 case CodeCompletionContext::CCC_ClassOrStructTag:
517 case CodeCompletionContext::CCC_ObjCProtocolName:
518 case CodeCompletionContext::CCC_Namespace:
519 case CodeCompletionContext::CCC_Type:
520 case CodeCompletionContext::CCC_Name: // FIXME: why does ns::^ give this?
521 case CodeCompletionContext::CCC_PotentiallyQualifiedName:
522 case CodeCompletionContext::CCC_ParenthesizedExpression:
523 case CodeCompletionContext::CCC_ObjCInterfaceName:
524 case CodeCompletionContext::CCC_ObjCCategoryName:
525 return true;
526 case CodeCompletionContext::CCC_Other: // Be conservative.
527 case CodeCompletionContext::CCC_OtherWithMacros:
528 case CodeCompletionContext::CCC_DotMemberAccess:
529 case CodeCompletionContext::CCC_ArrowMemberAccess:
530 case CodeCompletionContext::CCC_ObjCPropertyAccess:
531 case CodeCompletionContext::CCC_MacroName:
532 case CodeCompletionContext::CCC_MacroNameUse:
533 case CodeCompletionContext::CCC_PreprocessorExpression:
534 case CodeCompletionContext::CCC_PreprocessorDirective:
535 case CodeCompletionContext::CCC_NaturalLanguage:
536 case CodeCompletionContext::CCC_SelectorName:
537 case CodeCompletionContext::CCC_TypeQualifiers:
538 case CodeCompletionContext::CCC_ObjCInstanceMessage:
539 case CodeCompletionContext::CCC_ObjCClassMessage:
540 case CodeCompletionContext::CCC_Recovery:
541 return false;
542 }
543 llvm_unreachable("unknown code completion context");
544}
545
Sam McCall4caa8512018-06-07 12:49:17 +0000546// Some member calls are blacklisted because they're so rarely useful.
547static bool isBlacklistedMember(const NamedDecl &D) {
548 // Destructor completion is rarely useful, and works inconsistently.
549 // (s.^ completes ~string, but s.~st^ is an error).
550 if (D.getKind() == Decl::CXXDestructor)
551 return true;
552 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
553 if (auto *R = dyn_cast_or_null<RecordDecl>(&D))
554 if (R->isInjectedClassName())
555 return true;
556 // Explicit calls to operators are also rare.
557 auto NameKind = D.getDeclName().getNameKind();
558 if (NameKind == DeclarationName::CXXOperatorName ||
559 NameKind == DeclarationName::CXXLiteralOperatorName ||
560 NameKind == DeclarationName::CXXConversionFunctionName)
561 return true;
562 return false;
563}
564
Sam McCall545a20d2018-01-19 14:34:02 +0000565// The CompletionRecorder captures Sema code-complete output, including context.
566// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
567// It doesn't do scoring or conversion to CompletionItem yet, as we want to
568// merge with index results first.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000569// Generally the fields and methods of this object should only be used from
570// within the callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000571struct CompletionRecorder : public CodeCompleteConsumer {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000572 CompletionRecorder(const CodeCompleteOptions &Opts,
Benjamin Kramerc36c09f2018-07-03 20:59:33 +0000573 llvm::unique_function<void()> ResultsCallback)
Sam McCall545a20d2018-01-19 14:34:02 +0000574 : CodeCompleteConsumer(Opts.getClangCompleteOpts(),
Sam McCall98775c52017-12-04 13:49:59 +0000575 /*OutputIsBinary=*/false),
Sam McCall545a20d2018-01-19 14:34:02 +0000576 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
577 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000578 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
579 assert(this->ResultsCallback);
580 }
581
Sam McCall545a20d2018-01-19 14:34:02 +0000582 std::vector<CodeCompletionResult> Results;
583 CodeCompletionContext CCContext;
584 Sema *CCSema = nullptr; // Sema that created the results.
585 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
Sam McCall98775c52017-12-04 13:49:59 +0000586
Sam McCall545a20d2018-01-19 14:34:02 +0000587 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
588 CodeCompletionResult *InResults,
Sam McCall98775c52017-12-04 13:49:59 +0000589 unsigned NumResults) override final {
Eric Liu42abe412018-05-24 11:20:19 +0000590 // If a callback is called without any sema result and the context does not
591 // support index-based completion, we simply skip it to give way to
592 // potential future callbacks with results.
593 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
594 return;
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000595 if (CCSema) {
596 log(llvm::formatv(
597 "Multiple code complete callbacks (parser backtracked?). "
598 "Dropping results from context {0}, keeping results from {1}.",
Eric Liu42abe412018-05-24 11:20:19 +0000599 getCompletionKindString(Context.getKind()),
600 getCompletionKindString(this->CCContext.getKind())));
Ilya Biryukov94da7bd2018-03-16 15:23:44 +0000601 return;
602 }
Sam McCall545a20d2018-01-19 14:34:02 +0000603 // Record the completion context.
Sam McCall545a20d2018-01-19 14:34:02 +0000604 CCSema = &S;
605 CCContext = Context;
Eric Liu6f648df2017-12-19 16:50:37 +0000606
Sam McCall545a20d2018-01-19 14:34:02 +0000607 // Retain the results we might want.
Sam McCall98775c52017-12-04 13:49:59 +0000608 for (unsigned I = 0; I < NumResults; ++I) {
Sam McCall545a20d2018-01-19 14:34:02 +0000609 auto &Result = InResults[I];
610 // Drop hidden items which cannot be found by lookup after completion.
611 // Exception: some items can be named by using a qualifier.
Ilya Biryukovf60bf342018-01-10 13:51:09 +0000612 if (Result.Hidden && (!Result.Qualifier || Result.QualifierIsInformative))
613 continue;
Sam McCall545a20d2018-01-19 14:34:02 +0000614 if (!Opts.IncludeIneligibleResults &&
Sam McCall98775c52017-12-04 13:49:59 +0000615 (Result.Availability == CXAvailability_NotAvailable ||
616 Result.Availability == CXAvailability_NotAccessible))
617 continue;
Sam McCall4caa8512018-06-07 12:49:17 +0000618 if (Result.Declaration &&
619 !Context.getBaseType().isNull() // is this a member-access context?
620 && isBlacklistedMember(*Result.Declaration))
Sam McCalld2a95922018-01-22 21:05:00 +0000621 continue;
Ilya Biryukov53d6d932018-03-06 16:45:21 +0000622 // We choose to never append '::' to completion results in clangd.
623 Result.StartsNestedNameSpecifier = false;
Sam McCall545a20d2018-01-19 14:34:02 +0000624 Results.push_back(Result);
Sam McCall98775c52017-12-04 13:49:59 +0000625 }
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000626 ResultsCallback();
Sam McCall98775c52017-12-04 13:49:59 +0000627 }
628
Sam McCall545a20d2018-01-19 14:34:02 +0000629 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
Sam McCall98775c52017-12-04 13:49:59 +0000630 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
631
Sam McCall545a20d2018-01-19 14:34:02 +0000632 // Returns the filtering/sorting name for Result, which must be from Results.
633 // Returned string is owned by this recorder (or the AST).
634 llvm::StringRef getName(const CodeCompletionResult &Result) {
Sam McCall98775c52017-12-04 13:49:59 +0000635 switch (Result.Kind) {
636 case CodeCompletionResult::RK_Declaration:
637 if (auto *ID = Result.Declaration->getIdentifier())
Sam McCall545a20d2018-01-19 14:34:02 +0000638 return ID->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000639 break;
640 case CodeCompletionResult::RK_Keyword:
Sam McCall545a20d2018-01-19 14:34:02 +0000641 return Result.Keyword;
Sam McCall98775c52017-12-04 13:49:59 +0000642 case CodeCompletionResult::RK_Macro:
Sam McCall545a20d2018-01-19 14:34:02 +0000643 return Result.Macro->getName();
Sam McCall98775c52017-12-04 13:49:59 +0000644 case CodeCompletionResult::RK_Pattern:
Sam McCall545a20d2018-01-19 14:34:02 +0000645 return Result.Pattern->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000646 }
Ilya Biryukov43714502018-05-16 12:32:44 +0000647 auto *CCS = codeCompletionString(Result);
Sam McCall545a20d2018-01-19 14:34:02 +0000648 return CCS->getTypedText();
Sam McCall98775c52017-12-04 13:49:59 +0000649 }
650
Sam McCall545a20d2018-01-19 14:34:02 +0000651 // Build a CodeCompletion string for R, which must be from Results.
652 // The CCS will be owned by this recorder.
Ilya Biryukov43714502018-05-16 12:32:44 +0000653 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
Sam McCall545a20d2018-01-19 14:34:02 +0000654 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
655 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
Ilya Biryukov43714502018-05-16 12:32:44 +0000656 *CCSema, CCContext, *CCAllocator, CCTUInfo,
657 /*IncludeBriefComments=*/false);
Sam McCall98775c52017-12-04 13:49:59 +0000658 }
659
Sam McCall545a20d2018-01-19 14:34:02 +0000660private:
661 CodeCompleteOptions Opts;
662 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
Sam McCall98775c52017-12-04 13:49:59 +0000663 CodeCompletionTUInfo CCTUInfo;
Benjamin Kramerc36c09f2018-07-03 20:59:33 +0000664 llvm::unique_function<void()> ResultsCallback;
Sam McCall545a20d2018-01-19 14:34:02 +0000665};
666
Sam McCall98775c52017-12-04 13:49:59 +0000667class SignatureHelpCollector final : public CodeCompleteConsumer {
668
669public:
670 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
671 SignatureHelp &SigHelp)
672 : CodeCompleteConsumer(CodeCompleteOpts, /*OutputIsBinary=*/false),
673 SigHelp(SigHelp),
674 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
675 CCTUInfo(Allocator) {}
676
677 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
678 OverloadCandidate *Candidates,
679 unsigned NumCandidates) override {
680 SigHelp.signatures.reserve(NumCandidates);
681 // FIXME(rwols): How can we determine the "active overload candidate"?
682 // Right now the overloaded candidates seem to be provided in a "best fit"
683 // order, so I'm not too worried about this.
684 SigHelp.activeSignature = 0;
685 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
686 "too many arguments");
687 SigHelp.activeParameter = static_cast<int>(CurrentArg);
688 for (unsigned I = 0; I < NumCandidates; ++I) {
689 const auto &Candidate = Candidates[I];
690 const auto *CCS = Candidate.CreateSignatureString(
691 CurrentArg, S, *Allocator, CCTUInfo, true);
692 assert(CCS && "Expected the CodeCompletionString to be non-null");
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000693 // FIXME: for headers, we need to get a comment from the index.
Ilya Biryukov43714502018-05-16 12:32:44 +0000694 SigHelp.signatures.push_back(ProcessOverloadCandidate(
695 Candidate, *CCS,
Ilya Biryukovbe0eb8f2018-05-24 14:49:23 +0000696 getParameterDocComment(S.getASTContext(), Candidate, CurrentArg,
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000697 /*CommentsFromHeaders=*/false)));
Sam McCall98775c52017-12-04 13:49:59 +0000698 }
699 }
700
701 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
702
703 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
704
705private:
Eric Liu63696e12017-12-20 17:24:31 +0000706 // FIXME(ioeric): consider moving CodeCompletionString logic here to
707 // CompletionString.h.
Sam McCall98775c52017-12-04 13:49:59 +0000708 SignatureInformation
709 ProcessOverloadCandidate(const OverloadCandidate &Candidate,
Ilya Biryukov43714502018-05-16 12:32:44 +0000710 const CodeCompletionString &CCS,
711 llvm::StringRef DocComment) const {
Sam McCall98775c52017-12-04 13:49:59 +0000712 SignatureInformation Result;
713 const char *ReturnType = nullptr;
714
Ilya Biryukov43714502018-05-16 12:32:44 +0000715 Result.documentation = formatDocumentation(CCS, DocComment);
Sam McCall98775c52017-12-04 13:49:59 +0000716
717 for (const auto &Chunk : CCS) {
718 switch (Chunk.Kind) {
719 case CodeCompletionString::CK_ResultType:
720 // A piece of text that describes the type of an entity or,
721 // for functions and methods, the return type.
722 assert(!ReturnType && "Unexpected CK_ResultType");
723 ReturnType = Chunk.Text;
724 break;
725 case CodeCompletionString::CK_Placeholder:
726 // A string that acts as a placeholder for, e.g., a function call
727 // argument.
728 // Intentional fallthrough here.
729 case CodeCompletionString::CK_CurrentParameter: {
730 // A piece of text that describes the parameter that corresponds to
731 // the code-completion location within a function call, message send,
732 // macro invocation, etc.
733 Result.label += Chunk.Text;
734 ParameterInformation Info;
735 Info.label = Chunk.Text;
736 Result.parameters.push_back(std::move(Info));
737 break;
738 }
739 case CodeCompletionString::CK_Optional: {
740 // The rest of the parameters are defaulted/optional.
741 assert(Chunk.Optional &&
742 "Expected the optional code completion string to be non-null.");
743 Result.label +=
744 getOptionalParameters(*Chunk.Optional, Result.parameters);
745 break;
746 }
747 case CodeCompletionString::CK_VerticalSpace:
748 break;
749 default:
750 Result.label += Chunk.Text;
751 break;
752 }
753 }
754 if (ReturnType) {
755 Result.label += " -> ";
756 Result.label += ReturnType;
757 }
758 return Result;
759 }
760
761 SignatureHelp &SigHelp;
762 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
763 CodeCompletionTUInfo CCTUInfo;
764
765}; // SignatureHelpCollector
766
Sam McCall545a20d2018-01-19 14:34:02 +0000767struct SemaCompleteInput {
768 PathRef FileName;
769 const tooling::CompileCommand &Command;
770 PrecompiledPreamble const *Preamble;
771 StringRef Contents;
772 Position Pos;
773 IntrusiveRefCntPtr<vfs::FileSystem> VFS;
774 std::shared_ptr<PCHContainerOperations> PCHs;
775};
776
777// Invokes Sema code completion on a file.
Sam McCall3f0243f2018-07-03 08:09:29 +0000778// If \p Includes is set, it will be updated based on the compiler invocation.
Sam McCalld1a7a372018-01-31 13:40:48 +0000779bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
Sam McCall545a20d2018-01-19 14:34:02 +0000780 const clang::CodeCompleteOptions &Options,
Eric Liu63f419a2018-05-15 15:29:32 +0000781 const SemaCompleteInput &Input,
Sam McCall3f0243f2018-07-03 08:09:29 +0000782 IncludeStructure *Includes = nullptr) {
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000783 trace::Span Tracer("Sema completion");
Sam McCall98775c52017-12-04 13:49:59 +0000784 std::vector<const char *> ArgStrs;
Sam McCall545a20d2018-01-19 14:34:02 +0000785 for (const auto &S : Input.Command.CommandLine)
Sam McCall98775c52017-12-04 13:49:59 +0000786 ArgStrs.push_back(S.c_str());
787
Ilya Biryukova9cf3112018-02-13 17:15:06 +0000788 if (Input.VFS->setCurrentWorkingDirectory(Input.Command.Directory)) {
789 log("Couldn't set working directory");
790 // We run parsing anyway, our lit-tests rely on results for non-existing
791 // working dirs.
792 }
Sam McCall98775c52017-12-04 13:49:59 +0000793
794 IgnoreDiagnostics DummyDiagsConsumer;
795 auto CI = createInvocationFromCommandLine(
796 ArgStrs,
797 CompilerInstance::createDiagnostics(new DiagnosticOptions,
798 &DummyDiagsConsumer, false),
Sam McCall545a20d2018-01-19 14:34:02 +0000799 Input.VFS);
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000800 if (!CI) {
Kirill Bobyrev5a267ed2018-05-29 11:50:51 +0000801 log("Couldn't create CompilerInvocation");
Ilya Biryukovb6ad25c2018-02-09 13:51:57 +0000802 return false;
803 }
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000804 auto &FrontendOpts = CI->getFrontendOpts();
805 FrontendOpts.DisableFree = false;
Sam McCall98775c52017-12-04 13:49:59 +0000806 FrontendOpts.SkipFunctionBodies = true;
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000807 CI->getLangOpts()->CommentOpts.ParseAllComments = true;
808 // Disable typo correction in Sema.
809 CI->getLangOpts()->SpellChecking = false;
810 // Setup code completion.
Sam McCall98775c52017-12-04 13:49:59 +0000811 FrontendOpts.CodeCompleteOpts = Options;
Sam McCall545a20d2018-01-19 14:34:02 +0000812 FrontendOpts.CodeCompletionAt.FileName = Input.FileName;
Sam McCalla4962cc2018-04-27 11:59:28 +0000813 auto Offset = positionToOffset(Input.Contents, Input.Pos);
814 if (!Offset) {
815 log("Code completion position was invalid " +
816 llvm::toString(Offset.takeError()));
817 return false;
818 }
819 std::tie(FrontendOpts.CodeCompletionAt.Line,
820 FrontendOpts.CodeCompletionAt.Column) =
821 offsetToClangLineColumn(Input.Contents, *Offset);
Sam McCall98775c52017-12-04 13:49:59 +0000822
Ilya Biryukov981a35d2018-05-28 12:11:37 +0000823 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
824 llvm::MemoryBuffer::getMemBufferCopy(Input.Contents, Input.FileName);
825 // The diagnostic options must be set before creating a CompilerInstance.
826 CI->getDiagnosticOpts().IgnoreWarnings = true;
827 // We reuse the preamble whether it's valid or not. This is a
828 // correctness/performance tradeoff: building without a preamble is slow, and
829 // completion is latency-sensitive.
830 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
831 // the remapped buffers do not get freed.
832 auto Clang = prepareCompilerInstance(
833 std::move(CI), Input.Preamble, std::move(ContentsBuffer),
834 std::move(Input.PCHs), std::move(Input.VFS), DummyDiagsConsumer);
Sam McCall98775c52017-12-04 13:49:59 +0000835 Clang->setCodeCompletionConsumer(Consumer.release());
836
837 SyntaxOnlyAction Action;
838 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000839 log("BeginSourceFile() failed when running codeComplete for " +
840 Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000841 return false;
842 }
Sam McCall3f0243f2018-07-03 08:09:29 +0000843 if (Includes)
844 Clang->getPreprocessor().addPPCallbacks(
845 collectIncludeStructureCallback(Clang->getSourceManager(), Includes));
Sam McCall98775c52017-12-04 13:49:59 +0000846 if (!Action.Execute()) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000847 log("Execute() failed when running codeComplete for " + Input.FileName);
Sam McCall98775c52017-12-04 13:49:59 +0000848 return false;
849 }
Sam McCall98775c52017-12-04 13:49:59 +0000850 Action.EndSourceFile();
851
852 return true;
853}
854
Ilya Biryukova907ba42018-05-14 10:50:04 +0000855// Should we allow index completions in the specified context?
856bool allowIndex(CodeCompletionContext &CC) {
857 if (!contextAllowsIndex(CC.getKind()))
858 return false;
859 // We also avoid ClassName::bar (but allow namespace::bar).
860 auto Scope = CC.getCXXScopeSpecifier();
861 if (!Scope)
862 return true;
863 NestedNameSpecifier *NameSpec = (*Scope)->getScopeRep();
864 if (!NameSpec)
865 return true;
866 // We only query the index when qualifier is a namespace.
867 // If it's a class, we rely solely on sema completions.
868 switch (NameSpec->getKind()) {
869 case NestedNameSpecifier::Global:
870 case NestedNameSpecifier::Namespace:
871 case NestedNameSpecifier::NamespaceAlias:
872 return true;
873 case NestedNameSpecifier::Super:
874 case NestedNameSpecifier::TypeSpec:
875 case NestedNameSpecifier::TypeSpecWithTemplate:
876 // Unresolved inside a template.
877 case NestedNameSpecifier::Identifier:
878 return false;
879 }
Ilya Biryukova6556e22018-05-14 11:47:30 +0000880 llvm_unreachable("invalid NestedNameSpecifier kind");
Ilya Biryukova907ba42018-05-14 10:50:04 +0000881}
882
Sam McCall98775c52017-12-04 13:49:59 +0000883} // namespace
884
885clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
886 clang::CodeCompleteOptions Result;
887 Result.IncludeCodePatterns = EnableSnippets && IncludeCodePatterns;
888 Result.IncludeMacros = IncludeMacros;
Sam McCalld8169a82018-01-18 15:31:30 +0000889 Result.IncludeGlobals = true;
Ilya Biryukov43714502018-05-16 12:32:44 +0000890 // We choose to include full comments and not do doxygen parsing in
891 // completion.
892 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
893 // formatting of the comments.
894 Result.IncludeBriefComments = false;
Sam McCall98775c52017-12-04 13:49:59 +0000895
Sam McCall3d139c52018-01-12 18:30:08 +0000896 // When an is used, Sema is responsible for completing the main file,
897 // the index can provide results from the preamble.
898 // Tell Sema not to deserialize the preamble to look for results.
899 Result.LoadExternal = !Index;
Eric Liu6f648df2017-12-19 16:50:37 +0000900
Sam McCall98775c52017-12-04 13:49:59 +0000901 return Result;
902}
903
Sam McCall545a20d2018-01-19 14:34:02 +0000904// Runs Sema-based (AST) and Index-based completion, returns merged results.
905//
906// There are a few tricky considerations:
907// - the AST provides information needed for the index query (e.g. which
908// namespaces to search in). So Sema must start first.
909// - we only want to return the top results (Opts.Limit).
910// Building CompletionItems for everything else is wasteful, so we want to
911// preserve the "native" format until we're done with scoring.
912// - the data underlying Sema completion items is owned by the AST and various
913// other arenas, which must stay alive for us to build CompletionItems.
914// - we may get duplicate results from Sema and the Index, we need to merge.
915//
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000916// So we start Sema completion first, and do all our work in its callback.
Sam McCall545a20d2018-01-19 14:34:02 +0000917// We use the Sema context information to query the index.
918// Then we merge the two result sets, producing items that are Sema/Index/Both.
919// These items are scored, and the top N are synthesized into the LSP response.
920// Finally, we can clean up the data structures created by Sema completion.
921//
922// Main collaborators are:
923// - semaCodeComplete sets up the compiler machinery to run code completion.
924// - CompletionRecorder captures Sema completion results, including context.
925// - SymbolIndex (Opts.Index) provides index completion results as Symbols
926// - CompletionCandidates are the result of merging Sema and Index results.
927// Each candidate points to an underlying CodeCompletionResult (Sema), a
928// Symbol (Index), or both. It computes the result quality score.
929// CompletionCandidate also does conversion to CompletionItem (at the end).
930// - FuzzyMatcher scores how the candidate matches the partial identifier.
931// This score is combined with the result quality score for the final score.
932// - TopN determines the results with the best score.
933class CodeCompleteFlow {
Eric Liuc5105f92018-02-16 14:15:55 +0000934 PathRef FileName;
Sam McCall3f0243f2018-07-03 08:09:29 +0000935 IncludeStructure Includes; // Complete once the compiler runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000936 const CodeCompleteOptions &Opts;
937 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000938 CompletionRecorder *Recorder = nullptr;
Sam McCall545a20d2018-01-19 14:34:02 +0000939 int NSema = 0, NIndex = 0, NBoth = 0; // Counters for logging.
940 bool Incomplete = false; // Would more be available with a higher limit?
Eric Liu63f419a2018-05-15 15:29:32 +0000941 llvm::Optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
Eric Liubc25ef72018-07-05 08:29:33 +0000942 std::vector<std::string> QueryScopes; // Initialized once Sema runs.
Sam McCall3f0243f2018-07-03 08:09:29 +0000943 // Include-insertion and proximity scoring rely on the include structure.
944 // This is available after Sema has run.
945 llvm::Optional<IncludeInserter> Inserter; // Available during runWithSema.
946 llvm::Optional<URIDistance> FileProximity; // Initialized once Sema runs.
Sam McCall545a20d2018-01-19 14:34:02 +0000947
948public:
949 // A CodeCompleteFlow object is only useful for calling run() exactly once.
Sam McCall3f0243f2018-07-03 08:09:29 +0000950 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
951 const CodeCompleteOptions &Opts)
952 : FileName(FileName), Includes(Includes), Opts(Opts) {}
Sam McCall545a20d2018-01-19 14:34:02 +0000953
Sam McCall27c979a2018-06-29 14:47:57 +0000954 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
Sam McCalld1a7a372018-01-31 13:40:48 +0000955 trace::Span Tracer("CodeCompleteFlow");
Eric Liu63f419a2018-05-15 15:29:32 +0000956
Sam McCall545a20d2018-01-19 14:34:02 +0000957 // We run Sema code completion first. It builds an AST and calculates:
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000958 // - completion results based on the AST.
Sam McCall545a20d2018-01-19 14:34:02 +0000959 // - partial identifier and context. We need these for the index query.
Sam McCall27c979a2018-06-29 14:47:57 +0000960 CodeCompleteResult Output;
Ilya Biryukovddf6a332018-03-02 12:28:27 +0000961 auto RecorderOwner = llvm::make_unique<CompletionRecorder>(Opts, [&]() {
962 assert(Recorder && "Recorder is not set");
Sam McCall3f0243f2018-07-03 08:09:29 +0000963 auto Style =
Eric Liu9338a882018-07-03 14:51:23 +0000964 format::getStyle(format::DefaultFormatStyle, SemaCCInput.FileName,
965 format::DefaultFallbackStyle, SemaCCInput.Contents,
966 SemaCCInput.VFS.get());
Sam McCall3f0243f2018-07-03 08:09:29 +0000967 if (!Style) {
968 log("Failed to get FormatStyle for file" + SemaCCInput.FileName + ": " +
969 llvm::toString(Style.takeError()) + ". Fallback is LLVM style.");
970 Style = format::getLLVMStyle();
971 }
Eric Liu63f419a2018-05-15 15:29:32 +0000972 // If preprocessor was run, inclusions from preprocessor callback should
Sam McCall3f0243f2018-07-03 08:09:29 +0000973 // already be added to Includes.
974 Inserter.emplace(
975 SemaCCInput.FileName, SemaCCInput.Contents, *Style,
976 SemaCCInput.Command.Directory,
977 Recorder->CCSema->getPreprocessor().getHeaderSearchInfo());
978 for (const auto &Inc : Includes.MainFileIncludes)
979 Inserter->addExisting(Inc);
980
981 // Most of the cost of file proximity is in initializing the FileDistance
982 // structures based on the observed includes, once per query. Conceptually
983 // that happens here (though the per-URI-scheme initialization is lazy).
984 // The per-result proximity scoring is (amortized) very cheap.
985 FileDistanceOptions ProxOpts{}; // Use defaults.
986 const auto &SM = Recorder->CCSema->getSourceManager();
987 llvm::StringMap<SourceParams> ProxSources;
988 for (auto &Entry : Includes.includeDepth(
989 SM.getFileEntryForID(SM.getMainFileID())->getName())) {
990 auto &Source = ProxSources[Entry.getKey()];
991 Source.Cost = Entry.getValue() * ProxOpts.IncludeCost;
992 // Symbols near our transitive includes are good, but only consider
993 // things in the same directory or below it. Otherwise there can be
994 // many false positives.
995 if (Entry.getValue() > 0)
996 Source.MaxUpTraversals = 1;
997 }
998 FileProximity.emplace(ProxSources, ProxOpts);
999
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001000 Output = runWithSema();
Sam McCall3f0243f2018-07-03 08:09:29 +00001001 Inserter.reset(); // Make sure this doesn't out-live Clang.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001002 SPAN_ATTACH(Tracer, "sema_completion_kind",
1003 getCompletionKindString(Recorder->CCContext.getKind()));
Eric Liubc25ef72018-07-05 08:29:33 +00001004 log(llvm::formatv(
1005 "Code complete: sema context {0}, query scopes [{1}]",
1006 getCompletionKindString(Recorder->CCContext.getKind()),
1007 llvm::join(QueryScopes.begin(), QueryScopes.end(), ",")));
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001008 });
1009
1010 Recorder = RecorderOwner.get();
Sam McCalld1a7a372018-01-31 13:40:48 +00001011 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
Eric Liu63f419a2018-05-15 15:29:32 +00001012 SemaCCInput, &Includes);
Sam McCall545a20d2018-01-19 14:34:02 +00001013
Sam McCall2b780162018-01-30 17:20:54 +00001014 SPAN_ATTACH(Tracer, "sema_results", NSema);
1015 SPAN_ATTACH(Tracer, "index_results", NIndex);
1016 SPAN_ATTACH(Tracer, "merged_results", NBoth);
Sam McCall27c979a2018-06-29 14:47:57 +00001017 SPAN_ATTACH(Tracer, "returned_results", Output.Completions.size());
1018 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
Sam McCall0f8df3e2018-06-13 11:31:20 +00001019 log(llvm::formatv("Code complete: {0} results from Sema, {1} from Index, "
1020 "{2} matched, {3} returned{4}.",
Sam McCall27c979a2018-06-29 14:47:57 +00001021 NSema, NIndex, NBoth, Output.Completions.size(),
1022 Output.HasMore ? " (incomplete)" : ""));
1023 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
Sam McCall545a20d2018-01-19 14:34:02 +00001024 // We don't assert that isIncomplete means we hit a limit.
1025 // Indexes may choose to impose their own limits even if we don't have one.
1026 return Output;
1027 }
1028
1029private:
1030 // This is called by run() once Sema code completion is done, but before the
1031 // Sema data structures are torn down. It does all the real work.
Sam McCall27c979a2018-06-29 14:47:57 +00001032 CodeCompleteResult runWithSema() {
Sam McCall545a20d2018-01-19 14:34:02 +00001033 Filter = FuzzyMatcher(
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001034 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
Eric Liubc25ef72018-07-05 08:29:33 +00001035 QueryScopes = getQueryScopes(Recorder->CCContext,
1036 Recorder->CCSema->getSourceManager());
Sam McCall545a20d2018-01-19 14:34:02 +00001037 // Sema provides the needed context to query the index.
1038 // FIXME: in addition to querying for extra/overlapping symbols, we should
1039 // explicitly request symbols corresponding to Sema results.
1040 // We can use their signals even if the index can't suggest them.
1041 // We must copy index results to preserve them, but there are at most Limit.
Eric Liu8f3678d2018-06-15 13:34:18 +00001042 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1043 ? queryIndex()
1044 : SymbolSlab();
Sam McCall545a20d2018-01-19 14:34:02 +00001045 // Merge Sema and Index results, score them, and pick the winners.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001046 auto Top = mergeResults(Recorder->Results, IndexResults);
Sam McCall27c979a2018-06-29 14:47:57 +00001047 // Convert the results to final form, assembling the expensive strings.
1048 CodeCompleteResult Output;
1049 for (auto &C : Top) {
1050 Output.Completions.push_back(toCodeCompletion(C.first));
1051 Output.Completions.back().Score = C.second;
1052 }
1053 Output.HasMore = Incomplete;
Sam McCall545a20d2018-01-19 14:34:02 +00001054 return Output;
1055 }
1056
1057 SymbolSlab queryIndex() {
Sam McCalld1a7a372018-01-31 13:40:48 +00001058 trace::Span Tracer("Query index");
Sam McCall2b780162018-01-30 17:20:54 +00001059 SPAN_ATTACH(Tracer, "limit", Opts.Limit);
1060
Sam McCall545a20d2018-01-19 14:34:02 +00001061 SymbolSlab::Builder ResultsBuilder;
1062 // Build the query.
1063 FuzzyFindRequest Req;
Haojian Wu48b48652018-01-25 09:20:09 +00001064 if (Opts.Limit)
1065 Req.MaxCandidateCount = Opts.Limit;
Sam McCall545a20d2018-01-19 14:34:02 +00001066 Req.Query = Filter->pattern();
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001067 Req.RestrictForCodeCompletion = true;
Eric Liubc25ef72018-07-05 08:29:33 +00001068 Req.Scopes = QueryScopes;
Sam McCall3f0243f2018-07-03 08:09:29 +00001069 // FIXME: we should send multiple weighted paths here.
Eric Liu6de95ec2018-06-12 08:48:20 +00001070 Req.ProximityPaths.push_back(FileName);
Sam McCalld1a7a372018-01-31 13:40:48 +00001071 log(llvm::formatv("Code complete: fuzzyFind(\"{0}\", scopes=[{1}])",
Sam McCall2b780162018-01-30 17:20:54 +00001072 Req.Query,
1073 llvm::join(Req.Scopes.begin(), Req.Scopes.end(), ",")));
Sam McCall545a20d2018-01-19 14:34:02 +00001074 // Run the query against the index.
Sam McCallab8e3932018-02-19 13:04:41 +00001075 if (Opts.Index->fuzzyFind(
1076 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); }))
1077 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001078 return std::move(ResultsBuilder).build();
1079 }
1080
Sam McCallc18c2802018-06-15 11:06:29 +00001081 // Merges Sema and Index results where possible, to form CompletionCandidates.
1082 // Groups overloads if desired, to form CompletionCandidate::Bundles.
1083 // The bundles are scored and top results are returned, best to worst.
1084 std::vector<ScoredBundle>
Sam McCall545a20d2018-01-19 14:34:02 +00001085 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1086 const SymbolSlab &IndexResults) {
Sam McCalld1a7a372018-01-31 13:40:48 +00001087 trace::Span Tracer("Merge and score results");
Sam McCallc18c2802018-06-15 11:06:29 +00001088 std::vector<CompletionCandidate::Bundle> Bundles;
1089 llvm::DenseMap<size_t, size_t> BundleLookup;
1090 auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
1091 const Symbol *IndexResult) {
1092 CompletionCandidate C;
1093 C.SemaResult = SemaResult;
1094 C.IndexResult = IndexResult;
1095 C.Name = IndexResult ? IndexResult->Name : Recorder->getName(*SemaResult);
1096 if (auto OverloadSet = Opts.BundleOverloads ? C.overloadSet() : 0) {
1097 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
1098 if (Ret.second)
1099 Bundles.emplace_back();
1100 Bundles[Ret.first->second].push_back(std::move(C));
1101 } else {
1102 Bundles.emplace_back();
1103 Bundles.back().push_back(std::move(C));
1104 }
1105 };
Sam McCall545a20d2018-01-19 14:34:02 +00001106 llvm::DenseSet<const Symbol *> UsedIndexResults;
1107 auto CorrespondingIndexResult =
1108 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
1109 if (auto SymID = getSymbolID(SemaResult)) {
1110 auto I = IndexResults.find(*SymID);
1111 if (I != IndexResults.end()) {
1112 UsedIndexResults.insert(&*I);
1113 return &*I;
1114 }
1115 }
1116 return nullptr;
1117 };
1118 // Emit all Sema results, merging them with Index results if possible.
Ilya Biryukovddf6a332018-03-02 12:28:27 +00001119 for (auto &SemaResult : Recorder->Results)
Sam McCallc18c2802018-06-15 11:06:29 +00001120 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult));
Sam McCall545a20d2018-01-19 14:34:02 +00001121 // Now emit any Index-only results.
1122 for (const auto &IndexResult : IndexResults) {
1123 if (UsedIndexResults.count(&IndexResult))
1124 continue;
Sam McCallc18c2802018-06-15 11:06:29 +00001125 AddToBundles(/*SemaResult=*/nullptr, &IndexResult);
Sam McCall545a20d2018-01-19 14:34:02 +00001126 }
Sam McCallc18c2802018-06-15 11:06:29 +00001127 // We only keep the best N results at any time, in "native" format.
1128 TopN<ScoredBundle, ScoredBundleGreater> Top(
1129 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
1130 for (auto &Bundle : Bundles)
1131 addCandidate(Top, std::move(Bundle));
Sam McCall545a20d2018-01-19 14:34:02 +00001132 return std::move(Top).items();
1133 }
1134
Sam McCall80ad7072018-06-08 13:32:25 +00001135 Optional<float> fuzzyScore(const CompletionCandidate &C) {
1136 // Macros can be very spammy, so we only support prefix completion.
1137 // We won't end up with underfull index results, as macros are sema-only.
1138 if (C.SemaResult && C.SemaResult->Kind == CodeCompletionResult::RK_Macro &&
1139 !C.Name.startswith_lower(Filter->pattern()))
1140 return None;
1141 return Filter->match(C.Name);
1142 }
1143
Sam McCall545a20d2018-01-19 14:34:02 +00001144 // Scores a candidate and adds it to the TopN structure.
Sam McCallc18c2802018-06-15 11:06:29 +00001145 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
1146 CompletionCandidate::Bundle Bundle) {
Sam McCallc5707b62018-05-15 17:43:27 +00001147 SymbolQualitySignals Quality;
1148 SymbolRelevanceSignals Relevance;
Sam McCalld9b54f02018-06-05 16:30:25 +00001149 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
Sam McCallf84dd022018-07-05 08:26:53 +00001150 Relevance.FileProximityMatch = FileProximity.getPointer();
Sam McCallc18c2802018-06-15 11:06:29 +00001151 auto &First = Bundle.front();
1152 if (auto FuzzyScore = fuzzyScore(First))
Sam McCallc5707b62018-05-15 17:43:27 +00001153 Relevance.NameMatch = *FuzzyScore;
Sam McCall545a20d2018-01-19 14:34:02 +00001154 else
1155 return;
Sam McCall2161ec72018-07-05 06:20:41 +00001156 SymbolOrigin Origin = SymbolOrigin::Unknown;
Sam McCall4e5742a2018-07-06 11:50:49 +00001157 bool FromIndex = false;
Sam McCallc18c2802018-06-15 11:06:29 +00001158 for (const auto &Candidate : Bundle) {
1159 if (Candidate.IndexResult) {
1160 Quality.merge(*Candidate.IndexResult);
1161 Relevance.merge(*Candidate.IndexResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001162 Origin |= Candidate.IndexResult->Origin;
1163 FromIndex = true;
Sam McCallc18c2802018-06-15 11:06:29 +00001164 }
1165 if (Candidate.SemaResult) {
1166 Quality.merge(*Candidate.SemaResult);
1167 Relevance.merge(*Candidate.SemaResult);
Sam McCall4e5742a2018-07-06 11:50:49 +00001168 Origin |= SymbolOrigin::AST;
Sam McCallc18c2802018-06-15 11:06:29 +00001169 }
Sam McCallc5707b62018-05-15 17:43:27 +00001170 }
1171
Sam McCall27c979a2018-06-29 14:47:57 +00001172 CodeCompletion::Scores Scores;
1173 Scores.Quality = Quality.evaluate();
1174 Scores.Relevance = Relevance.evaluate();
1175 Scores.Total = evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
1176 // NameMatch is in fact a multiplier on total score, so rescoring is sound.
1177 Scores.ExcludingName = Relevance.NameMatch
1178 ? Scores.Total / Relevance.NameMatch
1179 : Scores.Quality;
Sam McCallc5707b62018-05-15 17:43:27 +00001180
Sam McCall2161ec72018-07-05 06:20:41 +00001181 LLVM_DEBUG(llvm::dbgs() << "CodeComplete: " << First.Name << " (" << Origin
1182 << ") = " << Scores.Total << "\n"
Sam McCallc18c2802018-06-15 11:06:29 +00001183 << Quality << Relevance << "\n");
Sam McCall545a20d2018-01-19 14:34:02 +00001184
Sam McCall2161ec72018-07-05 06:20:41 +00001185 NSema += bool(Origin & SymbolOrigin::AST);
Sam McCall4e5742a2018-07-06 11:50:49 +00001186 NIndex += FromIndex;
1187 NBoth += bool(Origin & SymbolOrigin::AST) && FromIndex;
Sam McCallc18c2802018-06-15 11:06:29 +00001188 if (Candidates.push({std::move(Bundle), Scores}))
Sam McCallab8e3932018-02-19 13:04:41 +00001189 Incomplete = true;
Sam McCall545a20d2018-01-19 14:34:02 +00001190 }
1191
Sam McCall27c979a2018-06-29 14:47:57 +00001192 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
1193 llvm::Optional<CodeCompletionBuilder> Builder;
1194 for (const auto &Item : Bundle) {
1195 CodeCompletionString *SemaCCS =
1196 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
1197 : nullptr;
1198 if (!Builder)
1199 Builder.emplace(Recorder->CCSema->getASTContext(), Item, SemaCCS,
Sam McCall3f0243f2018-07-03 08:09:29 +00001200 *Inserter, FileName, Opts);
Sam McCall27c979a2018-06-29 14:47:57 +00001201 else
1202 Builder->add(Item, SemaCCS);
Ilya Biryukov43714502018-05-16 12:32:44 +00001203 }
Sam McCall27c979a2018-06-29 14:47:57 +00001204 return Builder->build();
Sam McCall545a20d2018-01-19 14:34:02 +00001205 }
1206};
1207
Sam McCall3f0243f2018-07-03 08:09:29 +00001208CodeCompleteResult codeComplete(PathRef FileName,
1209 const tooling::CompileCommand &Command,
1210 PrecompiledPreamble const *Preamble,
1211 const IncludeStructure &PreambleInclusions,
1212 StringRef Contents, Position Pos,
1213 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1214 std::shared_ptr<PCHContainerOperations> PCHs,
1215 CodeCompleteOptions Opts) {
1216 return CodeCompleteFlow(FileName, PreambleInclusions, Opts)
1217 .run({FileName, Command, Preamble, Contents, Pos, VFS, PCHs});
Sam McCall98775c52017-12-04 13:49:59 +00001218}
1219
Sam McCalld1a7a372018-01-31 13:40:48 +00001220SignatureHelp signatureHelp(PathRef FileName,
Ilya Biryukov940901e2017-12-13 12:51:22 +00001221 const tooling::CompileCommand &Command,
1222 PrecompiledPreamble const *Preamble,
1223 StringRef Contents, Position Pos,
1224 IntrusiveRefCntPtr<vfs::FileSystem> VFS,
1225 std::shared_ptr<PCHContainerOperations> PCHs) {
Sam McCall98775c52017-12-04 13:49:59 +00001226 SignatureHelp Result;
1227 clang::CodeCompleteOptions Options;
1228 Options.IncludeGlobals = false;
1229 Options.IncludeMacros = false;
1230 Options.IncludeCodePatterns = false;
Ilya Biryukov43714502018-05-16 12:32:44 +00001231 Options.IncludeBriefComments = false;
Sam McCall3f0243f2018-07-03 08:09:29 +00001232 IncludeStructure PreambleInclusions; // Unused for signatureHelp
Sam McCalld1a7a372018-01-31 13:40:48 +00001233 semaCodeComplete(llvm::make_unique<SignatureHelpCollector>(Options, Result),
1234 Options,
Sam McCall3f0243f2018-07-03 08:09:29 +00001235 {FileName, Command, Preamble, Contents, Pos, std::move(VFS),
1236 std::move(PCHs)});
Sam McCall98775c52017-12-04 13:49:59 +00001237 return Result;
1238}
1239
Marc-Andre Laperle945b5a32018-06-05 14:01:40 +00001240bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
1241 using namespace clang::ast_matchers;
1242 auto InTopLevelScope = hasDeclContext(
1243 anyOf(namespaceDecl(), translationUnitDecl(), linkageSpecDecl()));
1244 return !match(decl(anyOf(InTopLevelScope,
1245 hasDeclContext(
1246 enumDecl(InTopLevelScope, unless(isScoped()))))),
1247 ND, ASTCtx)
1248 .empty();
1249}
1250
Sam McCall27c979a2018-06-29 14:47:57 +00001251CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
1252 CompletionItem LSP;
1253 LSP.label = (HeaderInsertion ? Opts.IncludeIndicator.Insert
1254 : Opts.IncludeIndicator.NoInsert) +
Sam McCall2161ec72018-07-05 06:20:41 +00001255 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
Sam McCall27c979a2018-06-29 14:47:57 +00001256 RequiredQualifier + Name + Signature;
Sam McCall2161ec72018-07-05 06:20:41 +00001257
Sam McCall27c979a2018-06-29 14:47:57 +00001258 LSP.kind = Kind;
1259 LSP.detail = BundleSize > 1 ? llvm::formatv("[{0} overloads]", BundleSize)
1260 : ReturnType;
1261 if (!Header.empty())
1262 LSP.detail += "\n" + Header;
1263 LSP.documentation = Documentation;
1264 LSP.sortText = sortText(Score.Total, Name);
1265 LSP.filterText = Name;
1266 LSP.insertText = RequiredQualifier + Name;
1267 if (Opts.EnableSnippets)
1268 LSP.insertText += SnippetSuffix;
1269 LSP.insertTextFormat = Opts.EnableSnippets ? InsertTextFormat::Snippet
1270 : InsertTextFormat::PlainText;
1271 if (HeaderInsertion)
1272 LSP.additionalTextEdits = {*HeaderInsertion};
Sam McCall27c979a2018-06-29 14:47:57 +00001273 return LSP;
1274}
1275
Sam McCalle746a2b2018-07-02 11:13:16 +00001276raw_ostream &operator<<(raw_ostream &OS, const CodeCompletion &C) {
1277 // For now just lean on CompletionItem.
1278 return OS << C.render(CodeCompleteOptions());
1279}
1280
1281raw_ostream &operator<<(raw_ostream &OS, const CodeCompleteResult &R) {
1282 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
1283 << " items:\n";
1284 for (const auto &C : R.Completions)
1285 OS << C << "\n";
1286 return OS;
1287}
1288
Sam McCall98775c52017-12-04 13:49:59 +00001289} // namespace clangd
1290} // namespace clang