clang-tools 23.0.0git
CodeComplete.cpp
Go to the documentation of this file.
1//===--- CodeComplete.cpp ----------------------------------------*- C++-*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Code completion has several moving parts:
10// - AST-based completions are provided using the completion hooks in Sema.
11// - external completions are retrieved from the index (using hints from Sema)
12// - the two sources overlap, and must be merged and overloads bundled
13// - results must be scored and ranked (see Quality.h) before rendering
14//
15// Signature help works in a similar way as code completion, but it is simpler:
16// it's purely AST-based, and there are few candidates.
17//
18//===----------------------------------------------------------------------===//
19
20#include "CodeComplete.h"
21#include "AST.h"
23#include "Compiler.h"
24#include "Config.h"
25#include "ExpectedTypes.h"
26#include "Feature.h"
27#include "FileDistance.h"
28#include "FuzzyMatch.h"
29#include "Headers.h"
30#include "Hover.h"
31#include "Preamble.h"
32#include "Protocol.h"
33#include "Quality.h"
34#include "SourceCode.h"
35#include "URI.h"
36#include "index/Index.h"
37#include "index/Symbol.h"
38#include "index/SymbolOrigin.h"
39#include "support/Logger.h"
40#include "support/Markup.h"
41#include "support/Threading.h"
43#include "support/Trace.h"
44#include "clang/AST/Decl.h"
45#include "clang/AST/DeclBase.h"
46#include "clang/AST/DeclTemplate.h"
47#include "clang/Basic/CharInfo.h"
48#include "clang/Basic/LangOptions.h"
49#include "clang/Basic/SourceLocation.h"
50#include "clang/Basic/TokenKinds.h"
51#include "clang/Format/Format.h"
52#include "clang/Frontend/CompilerInstance.h"
53#include "clang/Frontend/FrontendActions.h"
54#include "clang/Lex/ExternalPreprocessorSource.h"
55#include "clang/Lex/Lexer.h"
56#include "clang/Lex/Preprocessor.h"
57#include "clang/Lex/PreprocessorOptions.h"
58#include "clang/Sema/CodeCompleteConsumer.h"
59#include "clang/Sema/DeclSpec.h"
60#include "clang/Sema/Sema.h"
61#include "llvm/ADT/ArrayRef.h"
62#include "llvm/ADT/SmallVector.h"
63#include "llvm/ADT/StringExtras.h"
64#include "llvm/ADT/StringRef.h"
65#include "llvm/Support/Casting.h"
66#include "llvm/Support/Compiler.h"
67#include "llvm/Support/Debug.h"
68#include "llvm/Support/Error.h"
69#include "llvm/Support/FormatVariadic.h"
70#include "llvm/Support/ScopedPrinter.h"
71#include <algorithm>
72#include <iterator>
73#include <limits>
74#include <optional>
75#include <utility>
76
77// We log detailed candidate here if you run with -debug-only=codecomplete.
78#define DEBUG_TYPE "CodeComplete"
79
80namespace clang {
81namespace clangd {
82
83#if CLANGD_DECISION_FOREST
84const CodeCompleteOptions::CodeCompletionRankingModel
85 CodeCompleteOptions::DefaultRankingModel =
86 CodeCompleteOptions::DecisionForest;
87#else
88const CodeCompleteOptions::CodeCompletionRankingModel
89 CodeCompleteOptions::DefaultRankingModel = CodeCompleteOptions::Heuristics;
90#endif
91
92namespace {
93
94// Note: changes to this function should also be reflected in the
95// CodeCompletionResult overload where appropriate.
96CompletionItemKind
97toCompletionItemKind(index::SymbolKind Kind,
98 const llvm::StringRef *Signature = nullptr) {
99 using SK = index::SymbolKind;
100 switch (Kind) {
101 // FIXME: for backwards compatibility, the include directive kind is treated
102 // the same as Unknown
103 case SK::IncludeDirective:
104 case SK::Unknown:
106 case SK::Module:
107 case SK::Namespace:
108 case SK::NamespaceAlias:
110 case SK::Macro:
111 // Use macro signature (if provided) to tell apart function-like and
112 // object-like macros.
113 return Signature && Signature->contains('(') ? CompletionItemKind::Function
115 case SK::Enum:
117 case SK::Struct:
119 case SK::Class:
120 case SK::Extension:
121 case SK::Union:
123 case SK::Protocol:
124 // Use interface instead of class for differentiation of classes and
125 // protocols with the same name (e.g. @interface NSObject vs. @protocol
126 // NSObject).
128 case SK::TypeAlias:
129 // We use the same kind as the VSCode C++ extension.
130 // FIXME: pick a better option when we have one.
132 case SK::Using:
134 case SK::Function:
135 case SK::ConversionFunction:
137 case SK::Variable:
138 case SK::Parameter:
139 case SK::NonTypeTemplateParm:
141 case SK::Field:
143 case SK::EnumConstant:
145 case SK::InstanceMethod:
146 case SK::ClassMethod:
147 case SK::StaticMethod:
148 case SK::Destructor:
150 case SK::InstanceProperty:
151 case SK::ClassProperty:
152 case SK::StaticProperty:
154 case SK::Constructor:
156 case SK::TemplateTypeParm:
157 case SK::TemplateTemplateParm:
159 case SK::Concept:
161 }
162 llvm_unreachable("Unhandled clang::index::SymbolKind.");
163}
164
165// Note: changes to this function should also be reflected in the
166// index::SymbolKind overload where appropriate.
167CompletionItemKind toCompletionItemKind(const CodeCompletionResult &Res,
168 CodeCompletionContext::Kind CtxKind) {
169 if (Res.Declaration)
170 return toCompletionItemKind(index::getSymbolInfo(Res.Declaration).Kind);
171 if (CtxKind == CodeCompletionContext::CCC_IncludedFile)
173 switch (Res.Kind) {
174 case CodeCompletionResult::RK_Declaration:
175 llvm_unreachable("RK_Declaration without Decl");
176 case CodeCompletionResult::RK_Keyword:
178 case CodeCompletionResult::RK_Macro:
179 // There is no 'Macro' kind in LSP.
180 // Avoid using 'Text' to avoid confusion with client-side word-based
181 // completion proposals.
182 return Res.MacroDefInfo && Res.MacroDefInfo->isFunctionLike()
185 case CodeCompletionResult::RK_Pattern:
187 }
188 llvm_unreachable("Unhandled CodeCompletionResult::ResultKind.");
189}
190
191// FIXME: find a home for this (that can depend on both markup and Protocol).
192MarkupContent renderDoc(const markup::Document &Doc, MarkupKind Kind) {
193 MarkupContent Result;
194 Result.kind = Kind;
195 switch (Kind) {
197 Result.value.append(Doc.asPlainText());
198 break;
200 if (Config::current().Documentation.CommentFormat ==
202 Result.value.append(Doc.asEscapedMarkdown());
203 else
204 Result.value.append(Doc.asMarkdown());
205 break;
206 }
207 return Result;
208}
209
210Symbol::IncludeDirective insertionDirective(const CodeCompleteOptions &Opts) {
211 if (!Opts.ImportInsertions || !Opts.MainFileSignals)
213 return Opts.MainFileSignals->InsertionDirective;
214}
215
216// Identifier code completion result.
217struct RawIdentifier {
218 llvm::StringRef Name;
219 unsigned References; // # of usages in file.
220};
221
222/// A code completion result, in clang-native form.
223/// It may be promoted to a CompletionItem if it's among the top-ranked results.
224struct CompletionCandidate {
225 llvm::StringRef Name; // Used for filtering and sorting.
226 // We may have a result from Sema, from the index, or both.
227 const CodeCompletionResult *SemaResult = nullptr;
228 const Symbol *IndexResult = nullptr;
229 const RawIdentifier *IdentifierResult = nullptr;
230 llvm::SmallVector<SymbolInclude, 1> RankedIncludeHeaders;
231
232 // Returns a token identifying the overload set this is part of.
233 // 0 indicates it's not part of any overload set.
234 size_t overloadSet(const CodeCompleteOptions &Opts, llvm::StringRef FileName,
235 IncludeInserter *Inserter,
236 CodeCompletionContext::Kind CCContextKind) const {
237 if (!Opts.BundleOverloads)
238 return 0;
239
240 // Depending on the index implementation, we can see different header
241 // strings (literal or URI) mapping to the same file. We still want to
242 // bundle those, so we must resolve the header to be included here.
243 std::string HeaderForHash;
244 if (Inserter) {
245 if (auto Header = headerToInsertIfAllowed(Opts, CCContextKind)) {
246 if (auto HeaderFile = toHeaderFile(*Header, FileName)) {
247 if (auto Spelled =
248 Inserter->calculateIncludePath(*HeaderFile, FileName))
249 HeaderForHash = *Spelled;
250 } else {
251 vlog("Code completion header path manipulation failed {0}",
252 HeaderFile.takeError());
253 }
254 }
255 }
256
257 llvm::SmallString<256> Scratch;
258 if (IndexResult) {
259 switch (IndexResult->SymInfo.Kind) {
260 case index::SymbolKind::ClassMethod:
261 case index::SymbolKind::InstanceMethod:
262 case index::SymbolKind::StaticMethod:
263#ifndef NDEBUG
264 llvm_unreachable("Don't expect members from index in code completion");
265#else
266 [[fallthrough]];
267#endif
268 case index::SymbolKind::Function:
269 // We can't group overloads together that need different #includes.
270 // This could break #include insertion.
271 return llvm::hash_combine(
272 (IndexResult->Scope + IndexResult->Name).toStringRef(Scratch),
273 HeaderForHash);
274 default:
275 return 0;
276 }
277 }
278 if (SemaResult) {
279 // We need to make sure we're consistent with the IndexResult case!
280 const NamedDecl *D = SemaResult->Declaration;
281 if (!D || !D->isFunctionOrFunctionTemplate())
282 return 0;
283 {
284 llvm::raw_svector_ostream OS(Scratch);
285 D->printQualifiedName(OS);
286 }
287 return llvm::hash_combine(Scratch, HeaderForHash);
288 }
289 assert(IdentifierResult);
290 return 0;
291 }
292
293 bool contextAllowsHeaderInsertion(CodeCompletionContext::Kind Kind) const {
294 // Explicitly disable insertions for forward declarations since they don't
295 // reference the declaration.
296 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
297 return false;
298 return true;
299 }
300
301 // The best header to include if include insertion is allowed.
302 std::optional<llvm::StringRef>
303 headerToInsertIfAllowed(const CodeCompleteOptions &Opts,
304 CodeCompletionContext::Kind ContextKind) const {
305 if (Opts.InsertIncludes == Config::HeaderInsertionPolicy::NeverInsert ||
306 RankedIncludeHeaders.empty() ||
307 !contextAllowsHeaderInsertion(ContextKind))
308 return std::nullopt;
309 if (SemaResult && SemaResult->Declaration) {
310 // Avoid inserting new #include if the declaration is found in the current
311 // file e.g. the symbol is forward declared.
312 auto &SM = SemaResult->Declaration->getASTContext().getSourceManager();
313 for (const Decl *RD : SemaResult->Declaration->redecls())
314 if (SM.isInMainFile(SM.getExpansionLoc(RD->getBeginLoc())))
315 return std::nullopt;
316 }
317 Symbol::IncludeDirective Directive = insertionDirective(Opts);
318 for (const auto &Inc : RankedIncludeHeaders)
319 if ((Inc.Directive & Directive) != 0)
320 return Inc.Header;
321 return std::nullopt;
322 }
323
324 using Bundle = llvm::SmallVector<CompletionCandidate, 4>;
325};
326using ScoredBundle =
327 std::pair<CompletionCandidate::Bundle, CodeCompletion::Scores>;
328struct ScoredBundleGreater {
329 bool operator()(const ScoredBundle &L, const ScoredBundle &R) {
330 if (L.second.Total != R.second.Total)
331 return L.second.Total > R.second.Total;
332 return L.first.front().Name <
333 R.first.front().Name; // Earlier name is better.
334 }
335};
336
337// Remove the first template argument from Signature.
338// If Signature only contains a single argument an empty string is returned.
339std::string removeFirstTemplateArg(llvm::StringRef Signature) {
340 auto Rest = Signature.split(",").second;
341 if (Rest.empty())
342 return "";
343 return ("<" + Rest.ltrim()).str();
344}
345
346// Assembles a code completion out of a bundle of >=1 completion candidates.
347// Many of the expensive strings are only computed at this point, once we know
348// the candidate bundle is going to be returned.
349//
350// Many fields are the same for all candidates in a bundle (e.g. name), and are
351// computed from the first candidate, in the constructor.
352// Others vary per candidate, so add() must be called for remaining candidates.
353struct CodeCompletionBuilder {
354 CodeCompletionBuilder(ASTContext *ASTCtx, const CompletionCandidate &C,
355 CodeCompletionString *SemaCCS,
356 llvm::ArrayRef<std::string> AccessibleScopes,
357 const IncludeInserter &Includes,
358 llvm::StringRef FileName,
359 CodeCompletionContext::Kind ContextKind,
360 const CodeCompleteOptions &Opts,
361 bool IsUsingDeclaration, tok::TokenKind NextTokenKind)
362 : ASTCtx(ASTCtx), ArgumentLists(Opts.ArgumentLists),
363 IsUsingDeclaration(IsUsingDeclaration), NextTokenKind(NextTokenKind) {
364 Completion.Deprecated = true; // cleared by any non-deprecated overload.
365 add(C, SemaCCS, ContextKind);
366 if (C.SemaResult) {
367 assert(ASTCtx);
368 Completion.Origin |= SymbolOrigin::AST;
369 Completion.Name = std::string(llvm::StringRef(SemaCCS->getTypedText()));
370 Completion.FilterText = SemaCCS->getAllTypedText();
371 if (Completion.Scope.empty()) {
372 if ((C.SemaResult->Kind == CodeCompletionResult::RK_Declaration) ||
373 (C.SemaResult->Kind == CodeCompletionResult::RK_Pattern))
374 if (const auto *D = C.SemaResult->getDeclaration())
375 if (const auto *ND = dyn_cast<NamedDecl>(D))
376 Completion.Scope = std::string(
378 }
379 Completion.Kind = toCompletionItemKind(*C.SemaResult, ContextKind);
380 // Sema could provide more info on whether the completion was a file or
381 // folder.
382 if (Completion.Kind == CompletionItemKind::File &&
383 Completion.Name.back() == '/')
384 Completion.Kind = CompletionItemKind::Folder;
385 for (const auto &FixIt : C.SemaResult->FixIts) {
386 Completion.FixIts.push_back(toTextEdit(
387 FixIt, ASTCtx->getSourceManager(), ASTCtx->getLangOpts()));
388 }
389 llvm::sort(Completion.FixIts, [](const TextEdit &X, const TextEdit &Y) {
390 return std::tie(X.range.start.line, X.range.start.character) <
391 std::tie(Y.range.start.line, Y.range.start.character);
392 });
393 }
394 if (C.IndexResult) {
395 Completion.Origin |= C.IndexResult->Origin;
396 if (Completion.Scope.empty())
397 Completion.Scope = std::string(C.IndexResult->Scope);
398 if (Completion.Kind == CompletionItemKind::Missing)
399 Completion.Kind = toCompletionItemKind(C.IndexResult->SymInfo.Kind,
400 &C.IndexResult->Signature);
401 if (Completion.Name.empty())
402 Completion.Name = std::string(C.IndexResult->Name);
403 if (Completion.FilterText.empty())
404 Completion.FilterText = Completion.Name;
405 // If the completion was visible to Sema, no qualifier is needed. This
406 // avoids unneeded qualifiers in cases like with `using ns::X`.
407 if (Completion.RequiredQualifier.empty() && !C.SemaResult) {
408 llvm::StringRef ShortestQualifier = C.IndexResult->Scope;
409 for (llvm::StringRef Scope : AccessibleScopes) {
410 llvm::StringRef Qualifier = C.IndexResult->Scope;
411 if (Qualifier.consume_front(Scope) &&
412 Qualifier.size() < ShortestQualifier.size())
413 ShortestQualifier = Qualifier;
414 }
415 Completion.RequiredQualifier = std::string(ShortestQualifier);
416 }
417 }
418 if (C.IdentifierResult) {
419 Completion.Origin |= SymbolOrigin::Identifier;
420 Completion.Kind = CompletionItemKind::Text;
421 Completion.Name = std::string(C.IdentifierResult->Name);
422 Completion.FilterText = Completion.Name;
423 }
424
425 // Turn absolute path into a literal string that can be #included.
426 auto Inserted = [&](llvm::StringRef Header)
427 -> llvm::Expected<std::pair<std::string, bool>> {
428 auto ResolvedDeclaring =
429 URI::resolve(C.IndexResult->CanonicalDeclaration.FileURI, FileName);
430 if (!ResolvedDeclaring)
431 return ResolvedDeclaring.takeError();
432 auto ResolvedInserted = toHeaderFile(Header, FileName);
433 if (!ResolvedInserted)
434 return ResolvedInserted.takeError();
435 auto Spelled = Includes.calculateIncludePath(*ResolvedInserted, FileName);
436 if (!Spelled)
437 return error("Header not on include path");
438 return std::make_pair(
439 std::move(*Spelled),
440 Includes.shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
441 };
442 bool ShouldInsert =
443 C.headerToInsertIfAllowed(Opts, ContextKind).has_value();
444 Symbol::IncludeDirective Directive = insertionDirective(Opts);
445 // Calculate include paths and edits for all possible headers.
446 for (const auto &Inc : C.RankedIncludeHeaders) {
447 if ((Inc.Directive & Directive) == 0)
448 continue;
449
450 if (auto ToInclude = Inserted(Inc.Header)) {
451 CodeCompletion::IncludeCandidate Include;
452 Include.Header = ToInclude->first;
453 if (ToInclude->second && ShouldInsert)
454 Include.Insertion = Includes.insert(
455 ToInclude->first, Directive == Symbol::Import
456 ? tooling::IncludeDirective::Import
457 : tooling::IncludeDirective::Include);
458 Completion.Includes.push_back(std::move(Include));
459 } else
460 log("Failed to generate include insertion edits for adding header "
461 "(FileURI='{0}', IncludeHeader='{1}') into {2}: {3}",
462 C.IndexResult->CanonicalDeclaration.FileURI, Inc.Header, FileName,
463 ToInclude.takeError());
464 }
465 // Prefer includes that do not need edits (i.e. already exist).
466 std::stable_partition(Completion.Includes.begin(),
467 Completion.Includes.end(),
468 [](const CodeCompletion::IncludeCandidate &I) {
469 return !I.Insertion.has_value();
470 });
471 }
472
473 void add(const CompletionCandidate &C, CodeCompletionString *SemaCCS,
474 CodeCompletionContext::Kind ContextKind) {
475 assert(bool(C.SemaResult) == bool(SemaCCS));
476 Bundled.emplace_back();
477 BundledEntry &S = Bundled.back();
478 bool IsConcept = false;
479 if (C.SemaResult) {
481 *SemaCCS, &S.Signature, &S.SnippetSuffix, C.SemaResult->Kind,
482 C.SemaResult->CursorKind,
483 /*IncludeFunctionArguments=*/C.SemaResult->FunctionCanBeCall ||
484 C.SemaResult->DeclaringEntity,
485 /*RequiredQualifiers=*/&Completion.RequiredQualifier);
486 S.ReturnType = getReturnType(*SemaCCS);
487 if (C.SemaResult->Kind == CodeCompletionResult::RK_Declaration)
488 if (const auto *D = C.SemaResult->getDeclaration())
489 if (isa<ConceptDecl>(D))
490 IsConcept = true;
491 } else if (C.IndexResult) {
492 S.Signature = std::string(C.IndexResult->Signature);
493 S.SnippetSuffix = std::string(C.IndexResult->CompletionSnippetSuffix);
494 S.ReturnType = std::string(C.IndexResult->ReturnType);
495 if (C.IndexResult->SymInfo.Kind == index::SymbolKind::Concept)
496 IsConcept = true;
497 }
498
499 /// When a concept is used as a type-constraint (e.g. `Iterator auto x`),
500 /// and in some other contexts, its first type argument is not written.
501 /// Drop the parameter from the signature.
502 if (IsConcept && ContextKind == CodeCompletionContext::CCC_TopLevel) {
503 S.Signature = removeFirstTemplateArg(S.Signature);
504 // Dropping the first placeholder from the suffix will leave a $2
505 // with no $1.
506 S.SnippetSuffix = removeFirstTemplateArg(S.SnippetSuffix);
507 }
508
509 if (!Completion.Documentation) {
510 auto SetDoc = [&](llvm::StringRef Doc) {
511 if (!Doc.empty()) {
512 Completion.Documentation.emplace();
513 parseDocumentation(Doc, *Completion.Documentation);
514 }
515 };
516 if (C.IndexResult) {
517 SetDoc(C.IndexResult->Documentation);
518 } else if (C.SemaResult) {
519 const auto DocComment = getDocComment(*ASTCtx, *C.SemaResult,
520 /*CommentsFromHeaders=*/false);
521 SetDoc(formatDocumentation(*SemaCCS, DocComment));
522 }
523 }
524 if (Completion.Deprecated) {
525 if (C.SemaResult)
526 Completion.Deprecated &=
527 C.SemaResult->Availability == CXAvailability_Deprecated;
528 if (C.IndexResult)
529 Completion.Deprecated &=
530 bool(C.IndexResult->Flags & Symbol::Deprecated);
531 }
532 }
533
534 CodeCompletion build() {
535 Completion.ReturnType = summarizeReturnType();
536 Completion.Signature = summarizeSignature();
537 Completion.SnippetSuffix = summarizeSnippet();
538 Completion.BundleSize = Bundled.size();
539 return std::move(Completion);
540 }
541
542private:
543 struct BundledEntry {
544 std::string SnippetSuffix;
545 std::string Signature;
546 std::string ReturnType;
547 };
548
549 // If all BundledEntries have the same value for a property, return it.
550 template <std::string BundledEntry::*Member>
551 const std::string *onlyValue() const {
552 auto B = Bundled.begin(), E = Bundled.end();
553 for (auto *I = B + 1; I != E; ++I)
554 if (I->*Member != B->*Member)
555 return nullptr;
556 return &(B->*Member);
557 }
558
559 template <bool BundledEntry::*Member> const bool *onlyValue() const {
560 auto B = Bundled.begin(), E = Bundled.end();
561 for (auto *I = B + 1; I != E; ++I)
562 if (I->*Member != B->*Member)
563 return nullptr;
564 return &(B->*Member);
565 }
566
567 std::string summarizeReturnType() const {
568 if (auto *RT = onlyValue<&BundledEntry::ReturnType>())
569 return *RT;
570 return "";
571 }
572
573 std::string summarizeSnippet() const {
574 /// localize ArgumentLists tests for better readability
575 const bool None = ArgumentLists == Config::ArgumentListsPolicy::None;
576 const bool Open =
578 const bool Delim = ArgumentLists == Config::ArgumentListsPolicy::Delimiters;
579 const bool Full =
581 (!None && !Open && !Delim); // <-- failsafe: Full is default
582
583 if (IsUsingDeclaration)
584 return "";
585 auto *Snippet = onlyValue<&BundledEntry::SnippetSuffix>();
586 if (!Snippet)
587 // All bundles are function calls.
588 // FIXME(ibiryukov): sometimes add template arguments to a snippet, e.g.
589 // we need to complete 'forward<$1>($0)'.
590 return None ? "" : (Open ? "(" : "($0)");
591
592 if (Snippet->empty())
593 return "";
594
595 bool MayHaveArgList =
596 Completion.Kind == CompletionItemKind::Function ||
597 Completion.Kind == CompletionItemKind::Method ||
598 Completion.Kind == CompletionItemKind::Constructor ||
599 Completion.Kind == CompletionItemKind::Text /*Macro*/ ||
600 Completion.Kind == CompletionItemKind::Variable /*Lambda*/;
601 // If likely arg list already exists, don't add new parens & placeholders.
602 // Snippet: function(int x, int y)
603 // func^(1,2) -> function(1, 2)
604 // NOT function(int x, int y)(1, 2)
605 if (MayHaveArgList) {
606 // Check for a template argument list in the code.
607 // Snippet: function<class T>(int x)
608 // fu^<int>(1) -> function<int>(1)
609 if (NextTokenKind == tok::less && Snippet->front() == '<')
610 return "";
611 // Potentially followed by regular argument list.
612 if (NextTokenKind == tok::l_paren) {
613 // Snippet: function<class T>(int x)
614 // fu^(1,2) -> function<class T>(1, 2)
615 if (Snippet->front() == '<') {
616 // Find matching '>', handling nested brackets.
617 int Balance = 0;
618 size_t I = 0;
619 do {
620 if (Snippet->at(I) == '>')
621 --Balance;
622 else if (Snippet->at(I) == '<')
623 ++Balance;
624 ++I;
625 } while (Balance > 0);
626 return Snippet->substr(0, I);
627 }
628 return "";
629 }
630 }
631 if (Full)
632 return *Snippet;
633
634 // Replace argument snippets with a simplified pattern.
635 if (MayHaveArgList && llvm::StringRef(*Snippet).contains("(")) {
636 // Functions snippets can be of 2 types:
637 // - containing only function arguments, e.g.
638 // foo(${1:int p1}, ${2:int p2});
639 // We transform this pattern to '($0)' or '()'.
640 // - template arguments and function arguments, e.g.
641 // foo<${1:class}>(${2:int p1}).
642 // We transform this pattern to '<$1>()$0' or '<$0>()'.
643
644 bool EmptyArgs = llvm::StringRef(*Snippet).ends_with("()");
645 if (Snippet->front() == '<')
646 return None ? "" : (Open ? "<" : (EmptyArgs ? "<$1>()$0" : "<$1>($0)"));
647 if (Snippet->front() == '(')
648 return None ? "" : (Open ? "(" : (EmptyArgs ? "()" : "($0)"));
649 return *Snippet; // Not an arg snippet?
650 }
651 // 'CompletionItemKind::Interface' matches template type aliases.
652 if (Completion.Kind == CompletionItemKind::Interface ||
653 Completion.Kind == CompletionItemKind::Class ||
654 Completion.Kind == CompletionItemKind::Variable) {
655 if (Snippet->front() != '<')
656 return *Snippet; // Not an arg snippet?
657
658 // Classes and template using aliases can only have template arguments,
659 // e.g. Foo<${1:class}>.
660 if (llvm::StringRef(*Snippet).ends_with("<>"))
661 return "<>"; // can happen with defaulted template arguments.
662 return None ? "" : (Open ? "<" : "<$0>");
663 }
664 return *Snippet;
665 }
666
667 std::string summarizeSignature() const {
668 if (auto *Signature = onlyValue<&BundledEntry::Signature>())
669 return *Signature;
670 // All bundles are function calls.
671 return "(…)";
672 }
673
674 // ASTCtx can be nullptr if not run with sema.
675 ASTContext *ASTCtx;
676 CodeCompletion Completion;
677 llvm::SmallVector<BundledEntry, 1> Bundled;
678 /// the way argument lists are handled.
679 Config::ArgumentListsPolicy ArgumentLists;
680 // No snippets will be generated for using declarations and when the function
681 // arguments are already present.
682 bool IsUsingDeclaration;
683 tok::TokenKind NextTokenKind;
684};
685
686// Determine the symbol ID for a Sema code completion result, if possible.
687SymbolID getSymbolID(const CodeCompletionResult &R, const SourceManager &SM) {
688 switch (R.Kind) {
689 case CodeCompletionResult::RK_Declaration:
690 case CodeCompletionResult::RK_Pattern: {
691 // Computing USR caches linkage, which may change after code completion.
692 if (hasUnstableLinkage(R.Declaration))
693 return {};
694 return clang::clangd::getSymbolID(R.Declaration);
695 }
696 case CodeCompletionResult::RK_Macro:
697 return clang::clangd::getSymbolID(R.Macro->getName(), R.MacroDefInfo, SM);
698 case CodeCompletionResult::RK_Keyword:
699 return {};
700 }
701 llvm_unreachable("unknown CodeCompletionResult kind");
702}
703
704// Scopes of the partial identifier we're trying to complete.
705// It is used when we query the index for more completion results.
706struct SpecifiedScope {
707 // The scopes we should look in, determined by Sema.
708 //
709 // If the qualifier was fully resolved, we look for completions in these
710 // scopes; if there is an unresolved part of the qualifier, it should be
711 // resolved within these scopes.
712 //
713 // Examples of qualified completion:
714 //
715 // "::vec" => {""}
716 // "using namespace std; ::vec^" => {"", "std::"}
717 // "namespace ns {using namespace std;} ns::^" => {"ns::", "std::"}
718 // "std::vec^" => {""} // "std" unresolved
719 //
720 // Examples of unqualified completion:
721 //
722 // "vec^" => {""}
723 // "using namespace std; vec^" => {"", "std::"}
724 // "namespace ns {inline namespace ni { struct Foo {}}}
725 // using namespace ns::ni; Fo^ " => {"", "ns::ni::"}
726 // "using namespace std; namespace ns { vec^ }" => {"ns::", "std::", ""}
727 //
728 // "" for global namespace, "ns::" for normal namespace.
729 std::vector<std::string> AccessibleScopes;
730 // This is an overestimate of AccessibleScopes, e.g. it ignores inline
731 // namespaces, to fetch more relevant symbols from index.
732 std::vector<std::string> QueryScopes;
733 // The full scope qualifier as typed by the user (without the leading "::").
734 // Set if the qualifier is not fully resolved by Sema.
735 std::optional<std::string> UnresolvedQualifier;
736
737 std::optional<std::string> EnclosingNamespace;
738
739 bool AllowAllScopes = false;
740
741 // Scopes that are accessible from current context. Used for dropping
742 // unnecessary namespecifiers.
743 std::vector<std::string> scopesForQualification() {
744 std::set<std::string> Results;
745 for (llvm::StringRef AS : AccessibleScopes)
746 Results.insert(
747 (AS + (UnresolvedQualifier ? *UnresolvedQualifier : "")).str());
748 return {Results.begin(), Results.end()};
749 }
750
751 // Construct scopes being queried in indexes. The results are deduplicated.
752 // This method formats the scopes to match the index request representation.
753 std::vector<std::string> scopesForIndexQuery() {
754 // The enclosing namespace must be first, it gets a quality boost.
755 std::vector<std::string> EnclosingAtFront;
756 if (EnclosingNamespace.has_value())
757 EnclosingAtFront.push_back(*EnclosingNamespace);
758 std::set<std::string> Deduplicated;
759 for (llvm::StringRef S : QueryScopes)
760 if (S != EnclosingNamespace)
761 Deduplicated.insert((S + UnresolvedQualifier.value_or("")).str());
762
763 EnclosingAtFront.reserve(EnclosingAtFront.size() + Deduplicated.size());
764 llvm::copy(Deduplicated, std::back_inserter(EnclosingAtFront));
765
766 return EnclosingAtFront;
767 }
768};
769
770// Get all scopes that will be queried in indexes and whether symbols from
771// any scope is allowed. The first scope in the list is the preferred scope
772// (e.g. enclosing namespace).
773SpecifiedScope getQueryScopes(CodeCompletionContext &CCContext,
774 const Sema &CCSema,
775 const CompletionPrefix &HeuristicPrefix,
776 const CodeCompleteOptions &Opts) {
777 SpecifiedScope Scopes;
778 for (auto *Context : CCContext.getVisitedContexts()) {
779 if (isa<TranslationUnitDecl>(Context)) {
780 Scopes.QueryScopes.push_back("");
781 Scopes.AccessibleScopes.push_back("");
782 } else if (const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
783 Scopes.QueryScopes.push_back(printNamespaceScope(*Context));
784 Scopes.AccessibleScopes.push_back(printQualifiedName(*ND) + "::");
785 }
786 }
787
788 const CXXScopeSpec *SemaSpecifier =
789 CCContext.getCXXScopeSpecifier().value_or(nullptr);
790 // Case 1: unqualified completion.
791 if (!SemaSpecifier) {
792 // Case 2 (exception): sema saw no qualifier, but there appears to be one!
793 // This can happen e.g. in incomplete macro expansions. Use heuristics.
794 if (!HeuristicPrefix.Qualifier.empty()) {
795 vlog("Sema said no scope specifier, but we saw {0} in the source code",
796 HeuristicPrefix.Qualifier);
797 StringRef SpelledSpecifier = HeuristicPrefix.Qualifier;
798 if (SpelledSpecifier.consume_front("::")) {
799 Scopes.AccessibleScopes = {""};
800 Scopes.QueryScopes = {""};
801 }
802 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
803 return Scopes;
804 }
805 /// FIXME: When the enclosing namespace contains an inline namespace,
806 /// it's dropped here. This leads to a behavior similar to
807 /// https://github.com/clangd/clangd/issues/1451
808 Scopes.EnclosingNamespace = printNamespaceScope(*CCSema.CurContext);
809 // Allow AllScopes completion as there is no explicit scope qualifier.
810 Scopes.AllowAllScopes = Opts.AllScopes;
811 return Scopes;
812 }
813 // Case 3: sema saw and resolved a scope qualifier.
814 if (SemaSpecifier && SemaSpecifier->isValid())
815 return Scopes;
816
817 // Case 4: There was a qualifier, and Sema didn't resolve it.
818 Scopes.QueryScopes.push_back(""); // Make sure global scope is included.
819 llvm::StringRef SpelledSpecifier = Lexer::getSourceText(
820 CharSourceRange::getCharRange(SemaSpecifier->getRange()),
821 CCSema.SourceMgr, clang::LangOptions());
822 if (SpelledSpecifier.consume_front("::"))
823 Scopes.QueryScopes = {""};
824 Scopes.UnresolvedQualifier = std::string(SpelledSpecifier);
825 // Sema excludes the trailing "::".
826 if (!Scopes.UnresolvedQualifier->empty())
827 *Scopes.UnresolvedQualifier += "::";
828
829 Scopes.AccessibleScopes = Scopes.QueryScopes;
830
831 return Scopes;
832}
833
834// Should we perform index-based completion in a context of the specified kind?
835// FIXME: consider allowing completion, but restricting the result types.
836bool contextAllowsIndex(enum CodeCompletionContext::Kind K) {
837 switch (K) {
838 case CodeCompletionContext::CCC_TopLevel:
839 case CodeCompletionContext::CCC_ObjCInterface:
840 case CodeCompletionContext::CCC_ObjCImplementation:
841 case CodeCompletionContext::CCC_ObjCIvarList:
842 case CodeCompletionContext::CCC_ClassStructUnion:
843 case CodeCompletionContext::CCC_Statement:
844 case CodeCompletionContext::CCC_Expression:
845 case CodeCompletionContext::CCC_ObjCMessageReceiver:
846 case CodeCompletionContext::CCC_EnumTag:
847 case CodeCompletionContext::CCC_UnionTag:
848 case CodeCompletionContext::CCC_ClassOrStructTag:
849 case CodeCompletionContext::CCC_ObjCProtocolName:
850 case CodeCompletionContext::CCC_Namespace:
851 case CodeCompletionContext::CCC_Type:
852 case CodeCompletionContext::CCC_ParenthesizedExpression:
853 case CodeCompletionContext::CCC_ObjCInterfaceName:
854 case CodeCompletionContext::CCC_Symbol:
855 case CodeCompletionContext::CCC_SymbolOrNewName:
856 case CodeCompletionContext::CCC_ObjCClassForwardDecl:
857 case CodeCompletionContext::CCC_TopLevelOrExpression:
858 return true;
859 case CodeCompletionContext::CCC_OtherWithMacros:
860 case CodeCompletionContext::CCC_DotMemberAccess:
861 case CodeCompletionContext::CCC_ArrowMemberAccess:
862 case CodeCompletionContext::CCC_ObjCCategoryName:
863 case CodeCompletionContext::CCC_ObjCPropertyAccess:
864 case CodeCompletionContext::CCC_MacroName:
865 case CodeCompletionContext::CCC_MacroNameUse:
866 case CodeCompletionContext::CCC_PreprocessorExpression:
867 case CodeCompletionContext::CCC_PreprocessorDirective:
868 case CodeCompletionContext::CCC_SelectorName:
869 case CodeCompletionContext::CCC_TypeQualifiers:
870 case CodeCompletionContext::CCC_ObjCInstanceMessage:
871 case CodeCompletionContext::CCC_ObjCClassMessage:
872 case CodeCompletionContext::CCC_IncludedFile:
873 case CodeCompletionContext::CCC_Attribute:
874 // FIXME: Provide identifier based completions for the following contexts:
875 case CodeCompletionContext::CCC_Other: // Be conservative.
876 case CodeCompletionContext::CCC_NaturalLanguage:
877 case CodeCompletionContext::CCC_Recovery:
878 case CodeCompletionContext::CCC_NewName:
879 return false;
880 }
881 llvm_unreachable("unknown code completion context");
882}
883
884static bool isInjectedClass(const NamedDecl &D) {
885 if (auto *R = dyn_cast_or_null<CXXRecordDecl>(&D))
886 if (R->isInjectedClassName())
887 return true;
888 return false;
889}
890
891// Some member calls are excluded because they're so rarely useful.
892static bool isExcludedMember(const NamedDecl &D) {
893 // Destructor completion is rarely useful, and works inconsistently.
894 // (s.^ completes ~string, but s.~st^ is an error).
895 if (D.getKind() == Decl::CXXDestructor)
896 return true;
897 // Injected name may be useful for A::foo(), but who writes A::A::foo()?
898 if (isInjectedClass(D))
899 return true;
900 // Explicit calls to operators are also rare.
901 auto NameKind = D.getDeclName().getNameKind();
902 if (NameKind == DeclarationName::CXXOperatorName ||
903 NameKind == DeclarationName::CXXLiteralOperatorName ||
904 NameKind == DeclarationName::CXXConversionFunctionName)
905 return true;
906 return false;
907}
908
909// The CompletionRecorder captures Sema code-complete output, including context.
910// It filters out ignored results (but doesn't apply fuzzy-filtering yet).
911// It doesn't do scoring or conversion to CompletionItem yet, as we want to
912// merge with index results first.
913// Generally the fields and methods of this object should only be used from
914// within the callback.
915struct CompletionRecorder : public CodeCompleteConsumer {
916 CompletionRecorder(const CodeCompleteOptions &Opts,
917 llvm::unique_function<void()> ResultsCallback)
918 : CodeCompleteConsumer(Opts.getClangCompleteOpts()),
919 CCContext(CodeCompletionContext::CCC_Other), Opts(Opts),
920 CCAllocator(std::make_shared<GlobalCodeCompletionAllocator>()),
921 CCTUInfo(CCAllocator), ResultsCallback(std::move(ResultsCallback)) {
922 assert(this->ResultsCallback);
923 }
924
925 std::vector<CodeCompletionResult> Results;
926 CodeCompletionContext CCContext;
927 Sema *CCSema = nullptr; // Sema that created the results.
928 // FIXME: Sema is scary. Can we store ASTContext and Preprocessor, instead?
929
930 void ProcessCodeCompleteResults(class Sema &S, CodeCompletionContext Context,
931 CodeCompletionResult *InResults,
932 unsigned NumResults) final {
933 // Results from recovery mode are generally useless, and the callback after
934 // recovery (if any) is usually more interesting. To make sure we handle the
935 // future callback from sema, we just ignore all callbacks in recovery mode,
936 // as taking only results from recovery mode results in poor completion
937 // results.
938 // FIXME: in case there is no future sema completion callback after the
939 // recovery mode, we might still want to provide some results (e.g. trivial
940 // identifier-based completion).
941 CodeCompletionContext::Kind ContextKind = Context.getKind();
942 if (ContextKind == CodeCompletionContext::CCC_Recovery) {
943 log("Code complete: Ignoring sema code complete callback with Recovery "
944 "context.");
945 return;
946 }
947 // If a callback is called without any sema result and the context does not
948 // support index-based completion, we simply skip it to give way to
949 // potential future callbacks with results.
950 if (NumResults == 0 && !contextAllowsIndex(Context.getKind()))
951 return;
952 if (CCSema) {
953 log("Multiple code complete callbacks (parser backtracked?). "
954 "Dropping results from context {0}, keeping results from {1}.",
955 getCompletionKindString(Context.getKind()),
956 getCompletionKindString(this->CCContext.getKind()));
957 return;
958 }
959 // Record the completion context.
960 CCSema = &S;
961 CCContext = Context;
962
963 // Retain the results we might want.
964 for (unsigned I = 0; I < NumResults; ++I) {
965 auto &Result = InResults[I];
966 if (Config::current().Completion.CodePatterns ==
968 Result.Kind == CodeCompletionResult::RK_Pattern &&
969 // keep allowing the include files autocomplete suggestions
970 ContextKind != CodeCompletionContext::CCC_IncludedFile)
971 continue;
972 // Class members that are shadowed by subclasses are usually noise.
973 if (Result.Hidden && Result.Declaration &&
974 Result.Declaration->isCXXClassMember())
975 continue;
976 if (!Opts.IncludeIneligibleResults &&
977 (Result.Availability == CXAvailability_NotAvailable ||
978 Result.Availability == CXAvailability_NotAccessible))
979 continue;
980 if (Result.Declaration &&
981 !Context.getBaseType().isNull() // is this a member-access context?
982 && isExcludedMember(*Result.Declaration))
983 continue;
984 // Skip injected class name when no class scope is not explicitly set.
985 // E.g. show injected A::A in `using A::A^` but not in "A^".
986 if (Result.Declaration && !Context.getCXXScopeSpecifier() &&
987 isInjectedClass(*Result.Declaration))
988 continue;
989 // We choose to never append '::' to completion results in clangd.
990 Result.StartsNestedNameSpecifier = false;
991 Results.push_back(Result);
992 }
993 ResultsCallback();
994 }
995
996 CodeCompletionAllocator &getAllocator() override { return *CCAllocator; }
997 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
998
999 // Returns the filtering/sorting name for Result, which must be from Results.
1000 // Returned string is owned by this recorder (or the AST).
1001 llvm::StringRef getName(const CodeCompletionResult &Result) {
1002 switch (Result.Kind) {
1003 case CodeCompletionResult::RK_Declaration:
1004 if (auto *ID = Result.Declaration->getIdentifier())
1005 return ID->getName();
1006 break;
1007 case CodeCompletionResult::RK_Keyword:
1008 return Result.Keyword;
1009 case CodeCompletionResult::RK_Macro:
1010 return Result.Macro->getName();
1011 case CodeCompletionResult::RK_Pattern:
1012 break;
1013 }
1014 auto *CCS = codeCompletionString(Result);
1015 const CodeCompletionString::Chunk *OnlyText = nullptr;
1016 for (auto &C : *CCS) {
1017 if (C.Kind != CodeCompletionString::CK_TypedText)
1018 continue;
1019 if (OnlyText)
1020 return CCAllocator->CopyString(CCS->getAllTypedText());
1021 OnlyText = &C;
1022 }
1023 return OnlyText ? OnlyText->Text : llvm::StringRef();
1024 }
1025
1026 // Build a CodeCompletion string for R, which must be from Results.
1027 // The CCS will be owned by this recorder.
1028 CodeCompletionString *codeCompletionString(const CodeCompletionResult &R) {
1029 // CodeCompletionResult doesn't seem to be const-correct. We own it, anyway.
1030 return const_cast<CodeCompletionResult &>(R).CreateCodeCompletionString(
1031 *CCSema, CCContext, *CCAllocator, CCTUInfo,
1032 /*IncludeBriefComments=*/false);
1033 }
1034
1035private:
1036 CodeCompleteOptions Opts;
1037 std::shared_ptr<GlobalCodeCompletionAllocator> CCAllocator;
1038 CodeCompletionTUInfo CCTUInfo;
1039 llvm::unique_function<void()> ResultsCallback;
1040};
1041
1042struct ScoredSignature {
1043 // When not null, requires documentation to be requested from the index with
1044 // this ID.
1045 SymbolID IDForDoc;
1046 SignatureInformation Signature;
1047 SignatureQualitySignals Quality;
1048};
1049
1050// Returns the index of the parameter matching argument number "Arg.
1051// This is usually just "Arg", except for variadic functions/templates, where
1052// "Arg" might be higher than the number of parameters. When that happens, we
1053// assume the last parameter is variadic and assume all further args are
1054// part of it.
1055int paramIndexForArg(const CodeCompleteConsumer::OverloadCandidate &Candidate,
1056 int Arg) {
1057 int NumParams = Candidate.getNumParams();
1058 if (auto *T = Candidate.getFunctionType()) {
1059 if (auto *Proto = T->getAs<FunctionProtoType>()) {
1060 if (Proto->isVariadic())
1061 ++NumParams;
1062 }
1063 }
1064 return std::min(Arg, std::max(NumParams - 1, 0));
1065}
1066
1067class SignatureHelpCollector final : public CodeCompleteConsumer {
1068public:
1069 SignatureHelpCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
1070 MarkupKind DocumentationFormat,
1071 const SymbolIndex *Index, SignatureHelp &SigHelp)
1072 : CodeCompleteConsumer(CodeCompleteOpts), SigHelp(SigHelp),
1073 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1074 CCTUInfo(Allocator), Index(Index),
1075 DocumentationFormat(DocumentationFormat) {}
1076
1077 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1078 OverloadCandidate *Candidates,
1079 unsigned NumCandidates,
1080 SourceLocation OpenParLoc,
1081 bool Braced) override {
1082 assert(!OpenParLoc.isInvalid());
1083 SourceManager &SrcMgr = S.getSourceManager();
1084 OpenParLoc = SrcMgr.getFileLoc(OpenParLoc);
1085 if (SrcMgr.isInMainFile(OpenParLoc))
1086 SigHelp.argListStart = sourceLocToPosition(SrcMgr, OpenParLoc);
1087 else
1088 elog("Location oustide main file in signature help: {0}",
1089 OpenParLoc.printToString(SrcMgr));
1090
1091 std::vector<ScoredSignature> ScoredSignatures;
1092 SigHelp.signatures.reserve(NumCandidates);
1093 ScoredSignatures.reserve(NumCandidates);
1094 // FIXME(rwols): How can we determine the "active overload candidate"?
1095 // Right now the overloaded candidates seem to be provided in a "best fit"
1096 // order, so I'm not too worried about this.
1097 SigHelp.activeSignature = 0;
1098 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
1099 "too many arguments");
1100
1101 SigHelp.activeParameter = static_cast<int>(CurrentArg);
1102
1103 for (unsigned I = 0; I < NumCandidates; ++I) {
1104 OverloadCandidate Candidate = Candidates[I];
1105 // We want to avoid showing instantiated signatures, because they may be
1106 // long in some cases (e.g. when 'T' is substituted with 'std::string', we
1107 // would get 'std::basic_string<char>').
1108 if (auto *Func = Candidate.getFunction()) {
1109 if (auto *Pattern = Func->getTemplateInstantiationPattern())
1110 Candidate = OverloadCandidate(Pattern);
1111 }
1112 if (static_cast<int>(I) == SigHelp.activeSignature) {
1113 // The activeParameter in LSP relates to the activeSignature. There is
1114 // another, per-signature field, but we currently do not use it and not
1115 // all clients might support it.
1116 // FIXME: Add support for per-signature activeParameter field.
1117 SigHelp.activeParameter =
1118 paramIndexForArg(Candidate, SigHelp.activeParameter);
1119 }
1120
1121 const auto *CCS = Candidate.CreateSignatureString(
1122 CurrentArg, S, *Allocator, CCTUInfo,
1123 /*IncludeBriefComments=*/true, Braced);
1124 assert(CCS && "Expected the CodeCompletionString to be non-null");
1125 ScoredSignatures.push_back(processOverloadCandidate(
1126 Candidate, *CCS,
1127 Candidate.getFunction()
1128 ? getDeclComment(S.getASTContext(), *Candidate.getFunction())
1129 : ""));
1130 }
1131
1132 // Sema does not load the docs from the preamble, so we need to fetch extra
1133 // docs from the index instead.
1134 llvm::DenseMap<SymbolID, std::string> FetchedDocs;
1135 if (Index) {
1136 LookupRequest IndexRequest;
1137 for (const auto &S : ScoredSignatures) {
1138 if (!S.IDForDoc)
1139 continue;
1140 IndexRequest.IDs.insert(S.IDForDoc);
1141 }
1142 Index->lookup(IndexRequest, [&](const Symbol &S) {
1143 if (!S.Documentation.empty())
1144 FetchedDocs[S.ID] = std::string(S.Documentation);
1145 });
1146 vlog("SigHelp: requested docs for {0} symbols from the index, got {1} "
1147 "symbols with non-empty docs in the response",
1148 IndexRequest.IDs.size(), FetchedDocs.size());
1149 }
1150
1151 llvm::sort(ScoredSignatures, [](const ScoredSignature &L,
1152 const ScoredSignature &R) {
1153 // Ordering follows:
1154 // - Less number of parameters is better.
1155 // - Aggregate > Function > FunctionType > FunctionTemplate
1156 // - High score is better.
1157 // - Shorter signature is better.
1158 // - Alphabetically smaller is better.
1159 if (L.Quality.NumberOfParameters != R.Quality.NumberOfParameters)
1160 return L.Quality.NumberOfParameters < R.Quality.NumberOfParameters;
1161 if (L.Quality.NumberOfOptionalParameters !=
1162 R.Quality.NumberOfOptionalParameters)
1163 return L.Quality.NumberOfOptionalParameters <
1164 R.Quality.NumberOfOptionalParameters;
1165 if (L.Quality.Kind != R.Quality.Kind) {
1166 using OC = CodeCompleteConsumer::OverloadCandidate;
1167 auto KindPriority = [&](OC::CandidateKind K) {
1168 switch (K) {
1169 case OC::CK_Aggregate:
1170 return 0;
1171 case OC::CK_Function:
1172 return 1;
1173 case OC::CK_FunctionType:
1174 return 2;
1175 case OC::CK_FunctionProtoTypeLoc:
1176 return 3;
1177 case OC::CK_FunctionTemplate:
1178 return 4;
1179 case OC::CK_Template:
1180 return 5;
1181 }
1182 llvm_unreachable("Unknown overload candidate type.");
1183 };
1184 return KindPriority(L.Quality.Kind) < KindPriority(R.Quality.Kind);
1185 }
1186 if (L.Signature.label.size() != R.Signature.label.size())
1187 return L.Signature.label.size() < R.Signature.label.size();
1188 return L.Signature.label < R.Signature.label;
1189 });
1190
1191 for (auto &SS : ScoredSignatures) {
1192 auto IndexDocIt =
1193 SS.IDForDoc ? FetchedDocs.find(SS.IDForDoc) : FetchedDocs.end();
1194 if (IndexDocIt != FetchedDocs.end()) {
1195 markup::Document SignatureComment;
1196 parseDocumentation(IndexDocIt->second, SignatureComment);
1197 SS.Signature.documentation =
1198 renderDoc(SignatureComment, DocumentationFormat);
1199 }
1200
1201 SigHelp.signatures.push_back(std::move(SS.Signature));
1202 }
1203 }
1204
1205 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
1206
1207 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1208
1209private:
1210 void processParameterChunk(llvm::StringRef ChunkText,
1211 SignatureInformation &Signature) const {
1212 // (!) this is O(n), should still be fast compared to building ASTs.
1213 unsigned ParamStartOffset = lspLength(Signature.label);
1214 unsigned ParamEndOffset = ParamStartOffset + lspLength(ChunkText);
1215 // A piece of text that describes the parameter that corresponds to
1216 // the code-completion location within a function call, message send,
1217 // macro invocation, etc.
1218 Signature.label += ChunkText;
1219 ParameterInformation Info;
1220 Info.labelOffsets.emplace(ParamStartOffset, ParamEndOffset);
1221 // FIXME: only set 'labelOffsets' when all clients migrate out of it.
1222 Info.labelString = std::string(ChunkText);
1223
1224 Signature.parameters.push_back(std::move(Info));
1225 }
1226
1227 void processOptionalChunk(const CodeCompletionString &CCS,
1228 SignatureInformation &Signature,
1229 SignatureQualitySignals &Signal) const {
1230 for (const auto &Chunk : CCS) {
1231 switch (Chunk.Kind) {
1232 case CodeCompletionString::CK_Optional:
1233 assert(Chunk.Optional &&
1234 "Expected the optional code completion string to be non-null.");
1235 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1236 break;
1237 case CodeCompletionString::CK_VerticalSpace:
1238 break;
1239 case CodeCompletionString::CK_CurrentParameter:
1240 case CodeCompletionString::CK_Placeholder:
1241 processParameterChunk(Chunk.Text, Signature);
1242 Signal.NumberOfOptionalParameters++;
1243 break;
1244 default:
1245 Signature.label += Chunk.Text;
1246 break;
1247 }
1248 }
1249 }
1250
1251 // FIXME(ioeric): consider moving CodeCompletionString logic here to
1252 // CompletionString.h.
1253 ScoredSignature processOverloadCandidate(const OverloadCandidate &Candidate,
1254 const CodeCompletionString &CCS,
1255 llvm::StringRef DocComment) const {
1256 SignatureInformation Signature;
1257 SignatureQualitySignals Signal;
1258 const char *ReturnType = nullptr;
1259
1260 markup::Document OverloadComment;
1261 parseDocumentation(formatDocumentation(CCS, DocComment), OverloadComment);
1262 Signature.documentation = renderDoc(OverloadComment, DocumentationFormat);
1263 Signal.Kind = Candidate.getKind();
1264
1265 for (const auto &Chunk : CCS) {
1266 switch (Chunk.Kind) {
1267 case CodeCompletionString::CK_ResultType:
1268 // A piece of text that describes the type of an entity or,
1269 // for functions and methods, the return type.
1270 assert(!ReturnType && "Unexpected CK_ResultType");
1271 ReturnType = Chunk.Text;
1272 break;
1273 case CodeCompletionString::CK_CurrentParameter:
1274 case CodeCompletionString::CK_Placeholder:
1275 processParameterChunk(Chunk.Text, Signature);
1276 Signal.NumberOfParameters++;
1277 break;
1278 case CodeCompletionString::CK_Optional: {
1279 // The rest of the parameters are defaulted/optional.
1280 assert(Chunk.Optional &&
1281 "Expected the optional code completion string to be non-null.");
1282 processOptionalChunk(*Chunk.Optional, Signature, Signal);
1283 break;
1284 }
1285 case CodeCompletionString::CK_VerticalSpace:
1286 break;
1287 default:
1288 Signature.label += Chunk.Text;
1289 break;
1290 }
1291 }
1292 if (ReturnType) {
1293 Signature.label += " -> ";
1294 Signature.label += ReturnType;
1295 }
1296 dlog("Signal for {0}: {1}", Signature, Signal);
1297 ScoredSignature Result;
1298 Result.Signature = std::move(Signature);
1299 Result.Quality = Signal;
1300 const FunctionDecl *Func = Candidate.getFunction();
1301 if (Func && Result.Signature.documentation.value.empty()) {
1302 // Computing USR caches linkage, which may change after code completion.
1303 if (!hasUnstableLinkage(Func))
1304 Result.IDForDoc = clangd::getSymbolID(Func);
1305 }
1306 return Result;
1307 }
1308
1309 SignatureHelp &SigHelp;
1310 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1311 CodeCompletionTUInfo CCTUInfo;
1312 const SymbolIndex *Index;
1313 MarkupKind DocumentationFormat;
1314}; // SignatureHelpCollector
1315
1316// Used only for completion of C-style comments in function call (i.e.
1317// /*foo=*/7). Similar to SignatureHelpCollector, but needs to do less work.
1318class ParamNameCollector final : public CodeCompleteConsumer {
1319public:
1320 ParamNameCollector(const clang::CodeCompleteOptions &CodeCompleteOpts,
1321 std::set<std::string> &ParamNames)
1322 : CodeCompleteConsumer(CodeCompleteOpts),
1323 Allocator(std::make_shared<clang::GlobalCodeCompletionAllocator>()),
1324 CCTUInfo(Allocator), ParamNames(ParamNames) {}
1325
1326 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1327 OverloadCandidate *Candidates,
1328 unsigned NumCandidates,
1329 SourceLocation OpenParLoc,
1330 bool Braced) override {
1331 assert(CurrentArg <= (unsigned)std::numeric_limits<int>::max() &&
1332 "too many arguments");
1333
1334 for (unsigned I = 0; I < NumCandidates; ++I) {
1335 if (const NamedDecl *ND = Candidates[I].getParamDecl(CurrentArg))
1336 if (const auto *II = ND->getIdentifier())
1337 ParamNames.emplace(II->getName());
1338 }
1339 }
1340
1341private:
1342 GlobalCodeCompletionAllocator &getAllocator() override { return *Allocator; }
1343
1344 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1345
1346 std::shared_ptr<clang::GlobalCodeCompletionAllocator> Allocator;
1347 CodeCompletionTUInfo CCTUInfo;
1348 std::set<std::string> &ParamNames;
1349};
1350
1351struct SemaCompleteInput {
1352 PathRef FileName;
1353 size_t Offset;
1354 const PreambleData &Preamble;
1355 const std::optional<PreamblePatch> Patch;
1356 const ParseInputs &ParseInput;
1357};
1358
1359void loadMainFilePreambleMacros(const Preprocessor &PP,
1360 const PreambleData &Preamble) {
1361 // The ExternalPreprocessorSource has our macros, if we know where to look.
1362 // We can read all the macros using PreambleMacros->ReadDefinedMacros(),
1363 // but this includes transitively included files, so may deserialize a lot.
1364 ExternalPreprocessorSource *PreambleMacros = PP.getExternalSource();
1365 // As we have the names of the macros, we can look up their IdentifierInfo
1366 // and then use this to load just the macros we want.
1367 const auto &ITable = PP.getIdentifierTable();
1368 IdentifierInfoLookup *PreambleIdentifiers =
1369 ITable.getExternalIdentifierLookup();
1370
1371 if (!PreambleIdentifiers || !PreambleMacros)
1372 return;
1373 for (const auto &MacroName : Preamble.Macros.Names) {
1374 if (ITable.find(MacroName.getKey()) != ITable.end())
1375 continue;
1376 if (auto *II = PreambleIdentifiers->get(MacroName.getKey()))
1377 if (II->isOutOfDate())
1378 PreambleMacros->updateOutOfDateIdentifier(*II);
1379 }
1380}
1381
1382// Invokes Sema code completion on a file.
1383// If \p Includes is set, it will be updated based on the compiler invocation.
1384bool semaCodeComplete(std::unique_ptr<CodeCompleteConsumer> Consumer,
1385 const clang::CodeCompleteOptions &Options,
1386 const SemaCompleteInput &Input,
1387 IncludeStructure *Includes = nullptr,
1388 std::unique_ptr<CompilerInvocation> CI = nullptr) {
1389 trace::Span Tracer("Sema completion");
1390
1391 IgnoreDiagnostics IgnoreDiags;
1392 if (!CI) {
1393 CI = buildCompilerInvocation(Input.ParseInput, IgnoreDiags);
1394 if (!CI) {
1395 elog("Couldn't create CompilerInvocation");
1396 return false;
1397 }
1398 }
1399 auto &FrontendOpts = CI->getFrontendOpts();
1400 FrontendOpts.SkipFunctionBodies = true;
1401 // Disable typo correction in Sema.
1402 CI->getLangOpts().SpellChecking = false;
1403 // Code completion won't trigger in delayed template bodies.
1404 // This is on-by-default in windows to allow parsing SDK headers; we're only
1405 // disabling it for the main-file (not preamble).
1406 CI->getLangOpts().DelayedTemplateParsing = false;
1407 // Setup code completion.
1408 FrontendOpts.CodeCompleteOpts = Options;
1409 FrontendOpts.CodeCompletionAt.FileName = std::string(Input.FileName);
1410 std::tie(FrontendOpts.CodeCompletionAt.Line,
1411 FrontendOpts.CodeCompletionAt.Column) =
1412 offsetToClangLineColumn(Input.ParseInput.Contents, Input.Offset);
1413
1414 std::unique_ptr<llvm::MemoryBuffer> ContentsBuffer =
1415 llvm::MemoryBuffer::getMemBuffer(Input.ParseInput.Contents,
1416 Input.FileName);
1417 // The diagnostic options must be set before creating a CompilerInstance.
1418 CI->getDiagnosticOpts().IgnoreWarnings = true;
1419 // We reuse the preamble whether it's valid or not. This is a
1420 // correctness/performance tradeoff: building without a preamble is slow, and
1421 // completion is latency-sensitive.
1422 // However, if we're completing *inside* the preamble section of the draft,
1423 // overriding the preamble will break sema completion. Fortunately we can just
1424 // skip all includes in this case; these completions are really simple.
1425 PreambleBounds PreambleRegion =
1426 computePreambleBounds(CI->getLangOpts(), *ContentsBuffer,
1427 Input.ParseInput.Opts.SkipPreambleBuild);
1428 bool CompletingInPreamble = Input.Offset < PreambleRegion.Size ||
1429 (!PreambleRegion.PreambleEndsAtStartOfLine &&
1430 Input.Offset == PreambleRegion.Size);
1431 if (Input.Patch)
1432 Input.Patch->apply(*CI);
1433 // NOTE: we must call BeginSourceFile after prepareCompilerInstance. Otherwise
1434 // the remapped buffers do not get freed.
1435 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS =
1436 Input.ParseInput.TFS->view(Input.ParseInput.CompileCommand.Directory);
1437 if (Input.Preamble.StatCache)
1438 VFS = Input.Preamble.StatCache->getConsumingFS(std::move(VFS));
1439 auto Clang = prepareCompilerInstance(
1440 std::move(CI),
1441 (!CompletingInPreamble && !Input.ParseInput.Opts.SkipPreambleBuild)
1442 ? &Input.Preamble.Preamble
1443 : nullptr,
1444 std::move(ContentsBuffer), std::move(VFS), IgnoreDiags);
1445 Clang->getPreprocessorOpts().SingleFileParseMode = CompletingInPreamble;
1446 Clang->setCodeCompletionConsumer(Consumer.release());
1447
1448 if (Input.Preamble.RequiredModules)
1449 Input.Preamble.RequiredModules->adjustHeaderSearchOptions(
1450 Clang->getHeaderSearchOpts());
1451
1452 SyntaxOnlyAction Action;
1453 if (!Action.BeginSourceFile(*Clang, Clang->getFrontendOpts().Inputs[0])) {
1454 log("BeginSourceFile() failed when running codeComplete for {0}",
1455 Input.FileName);
1456 return false;
1457 }
1458 // Macros can be defined within the preamble region of the main file.
1459 // They don't fall nicely into our index/Sema dichotomy:
1460 // - they're not indexed for completion (they're not available across files)
1461 // - but Sema code complete won't see them: as part of the preamble, they're
1462 // deserialized only when mentioned.
1463 // Force them to be deserialized so SemaCodeComplete sees them.
1464 loadMainFilePreambleMacros(Clang->getPreprocessor(), Input.Preamble);
1465 if (Includes)
1466 Includes->collect(*Clang);
1467 if (llvm::Error Err = Action.Execute()) {
1468 log("Execute() failed when running codeComplete for {0}: {1}",
1469 Input.FileName, toString(std::move(Err)));
1470 return false;
1471 }
1472 Action.EndSourceFile();
1473
1474 return true;
1475}
1476
1477// Should we allow index completions in the specified context?
1478bool allowIndex(CodeCompletionContext &CC) {
1479 if (!contextAllowsIndex(CC.getKind()))
1480 return false;
1481 // We also avoid ClassName::bar (but allow namespace::bar).
1482 auto Scope = CC.getCXXScopeSpecifier();
1483 if (!Scope)
1484 return true;
1485 // We only query the index when qualifier is a namespace.
1486 // If it's a class, we rely solely on sema completions.
1487 switch ((*Scope)->getScopeRep().getKind()) {
1488 case NestedNameSpecifier::Kind::Null:
1489 case NestedNameSpecifier::Kind::Global:
1490 case NestedNameSpecifier::Kind::Namespace:
1491 return true;
1492 case NestedNameSpecifier::Kind::MicrosoftSuper:
1493 case NestedNameSpecifier::Kind::Type:
1494 return false;
1495 }
1496 llvm_unreachable("invalid NestedNameSpecifier kind");
1497}
1498
1499// Should we include a symbol from the index given the completion kind?
1500// FIXME: Ideally we can filter in the fuzzy find request itself.
1501bool includeSymbolFromIndex(CodeCompletionContext::Kind Kind,
1502 const Symbol &Sym) {
1503 // Objective-C protocols are only useful in ObjC protocol completions,
1504 // in other places they're confusing, especially when they share the same
1505 // identifier with a class.
1506 if (Sym.SymInfo.Kind == index::SymbolKind::Protocol &&
1507 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC)
1508 return Kind == CodeCompletionContext::CCC_ObjCProtocolName;
1509 else if (Kind == CodeCompletionContext::CCC_ObjCProtocolName)
1510 // Don't show anything else in ObjC protocol completions.
1511 return false;
1512
1513 if (Kind == CodeCompletionContext::CCC_ObjCClassForwardDecl)
1514 return Sym.SymInfo.Kind == index::SymbolKind::Class &&
1515 Sym.SymInfo.Lang == index::SymbolLanguage::ObjC;
1516 return true;
1517}
1518
1519std::future<std::pair<bool, SymbolSlab>>
1520startAsyncFuzzyFind(const SymbolIndex &Index, const FuzzyFindRequest &Req) {
1521 return runAsync<std::pair<bool, SymbolSlab>>([&Index, Req]() {
1522 trace::Span Tracer("Async fuzzyFind");
1523 SymbolSlab::Builder Syms;
1524 bool Incomplete =
1525 Index.fuzzyFind(Req, [&Syms](const Symbol &Sym) { Syms.insert(Sym); });
1526 return std::make_pair(Incomplete, std::move(Syms).build());
1527 });
1528}
1529
1530// Creates a `FuzzyFindRequest` based on the cached index request from the
1531// last completion, if any, and the speculated completion filter text in the
1532// source code.
1533FuzzyFindRequest speculativeFuzzyFindRequestForCompletion(
1534 FuzzyFindRequest CachedReq, const CompletionPrefix &HeuristicPrefix) {
1535 CachedReq.Query = std::string(HeuristicPrefix.Name);
1536 return CachedReq;
1537}
1538
1539// Runs Sema-based (AST) and Index-based completion, returns merged results.
1540//
1541// There are a few tricky considerations:
1542// - the AST provides information needed for the index query (e.g. which
1543// namespaces to search in). So Sema must start first.
1544// - we only want to return the top results (Opts.Limit).
1545// Building CompletionItems for everything else is wasteful, so we want to
1546// preserve the "native" format until we're done with scoring.
1547// - the data underlying Sema completion items is owned by the AST and various
1548// other arenas, which must stay alive for us to build CompletionItems.
1549// - we may get duplicate results from Sema and the Index, we need to merge.
1550//
1551// So we start Sema completion first, and do all our work in its callback.
1552// We use the Sema context information to query the index.
1553// Then we merge the two result sets, producing items that are Sema/Index/Both.
1554// These items are scored, and the top N are synthesized into the LSP response.
1555// Finally, we can clean up the data structures created by Sema completion.
1556//
1557// Main collaborators are:
1558// - semaCodeComplete sets up the compiler machinery to run code completion.
1559// - CompletionRecorder captures Sema completion results, including context.
1560// - SymbolIndex (Opts.Index) provides index completion results as Symbols
1561// - CompletionCandidates are the result of merging Sema and Index results.
1562// Each candidate points to an underlying CodeCompletionResult (Sema), a
1563// Symbol (Index), or both. It computes the result quality score.
1564// CompletionCandidate also does conversion to CompletionItem (at the end).
1565// - FuzzyMatcher scores how the candidate matches the partial identifier.
1566// This score is combined with the result quality score for the final score.
1567// - TopN determines the results with the best score.
1568class CodeCompleteFlow {
1569 PathRef FileName;
1570 IncludeStructure Includes; // Complete once the compiler runs.
1571 SpeculativeFuzzyFind *SpecFuzzyFind; // Can be nullptr.
1572 const CodeCompleteOptions &Opts;
1573
1574 // Sema takes ownership of Recorder. Recorder is valid until Sema cleanup.
1575 CompletionRecorder *Recorder = nullptr;
1576 CodeCompletionContext::Kind CCContextKind = CodeCompletionContext::CCC_Other;
1577 bool IsUsingDeclaration = false;
1578 // The snippets will not be generated if the token following completion
1579 // location is an opening parenthesis (tok::l_paren) because this would add
1580 // extra parenthesis.
1581 tok::TokenKind NextTokenKind = tok::eof;
1582 // End of the identifier suffix after the completion cursor.
1583 // Shared by NextTokenKind detection and replace-range calculation.
1584 SourceLocation IdentifierSuffixEnd;
1585 // Counters for logging.
1586 int NSema = 0, NIndex = 0, NSemaAndIndex = 0, NIdent = 0;
1587 bool Incomplete = false; // Would more be available with a higher limit?
1588 CompletionPrefix HeuristicPrefix;
1589 std::optional<FuzzyMatcher> Filter; // Initialized once Sema runs.
1590 Range InsertRange;
1591 std::optional<Range> ReplaceRange;
1592 std::vector<std::string> QueryScopes; // Initialized once Sema runs.
1593 std::vector<std::string> AccessibleScopes; // Initialized once Sema runs.
1594 // Initialized once QueryScopes is initialized, if there are scopes.
1595 std::optional<ScopeDistance> ScopeProximity;
1596 std::optional<OpaqueType> PreferredType; // Initialized once Sema runs.
1597 // Whether to query symbols from any scope. Initialized once Sema runs.
1598 bool AllScopes = false;
1599 llvm::StringSet<> ContextWords;
1600 // Include-insertion and proximity scoring rely on the include structure.
1601 // This is available after Sema has run.
1602 std::optional<IncludeInserter> Inserter; // Available during runWithSema.
1603 std::optional<URIDistance> FileProximity; // Initialized once Sema runs.
1604 /// Speculative request based on the cached request and the filter text before
1605 /// the cursor.
1606 /// Initialized right before sema run. This is only set if `SpecFuzzyFind` is
1607 /// set and contains a cached request.
1608 std::optional<FuzzyFindRequest> SpecReq;
1609
1610public:
1611 // A CodeCompleteFlow object is only useful for calling run() exactly once.
1612 CodeCompleteFlow(PathRef FileName, const IncludeStructure &Includes,
1613 SpeculativeFuzzyFind *SpecFuzzyFind,
1614 const CodeCompleteOptions &Opts)
1615 : FileName(FileName), Includes(Includes), SpecFuzzyFind(SpecFuzzyFind),
1616 Opts(Opts) {}
1617
1618 CodeCompleteResult run(const SemaCompleteInput &SemaCCInput) && {
1619 trace::Span Tracer("CodeCompleteFlow");
1620 HeuristicPrefix = guessCompletionPrefix(SemaCCInput.ParseInput.Contents,
1621 SemaCCInput.Offset);
1622 populateContextWords(SemaCCInput.ParseInput.Contents);
1623 if (Opts.Index && SpecFuzzyFind && SpecFuzzyFind->CachedReq) {
1624 assert(!SpecFuzzyFind->Result.valid());
1625 SpecReq = speculativeFuzzyFindRequestForCompletion(
1626 *SpecFuzzyFind->CachedReq, HeuristicPrefix);
1627 SpecFuzzyFind->Result = startAsyncFuzzyFind(*Opts.Index, *SpecReq);
1628 }
1629
1630 // We run Sema code completion first. It builds an AST and calculates:
1631 // - completion results based on the AST.
1632 // - partial identifier and context. We need these for the index query.
1633 CodeCompleteResult Output;
1634 auto RecorderOwner = std::make_unique<CompletionRecorder>(Opts, [&]() {
1635 assert(Recorder && "Recorder is not set");
1636 CCContextKind = Recorder->CCContext.getKind();
1637 IsUsingDeclaration = Recorder->CCContext.isUsingDeclaration();
1638 auto Style = getFormatStyleForFile(SemaCCInput.FileName,
1639 SemaCCInput.ParseInput.Contents,
1640 *SemaCCInput.ParseInput.TFS, false);
1641 const auto &SM = Recorder->CCSema->getSourceManager();
1642 const LangOptions &LangOpts = Recorder->CCSema->getLangOpts();
1643 // Skip past the NUL byte inserted at the cursor, then scan through any
1644 // identifier continuation characters to find where the suffix ends.
1645 IdentifierSuffixEnd = Lexer::findEndOfIdentifierContinuation(
1646 Recorder->CCSema->getPreprocessor()
1647 .getCodeCompletionLoc()
1648 .getLocWithOffset(1),
1649 SM, LangOpts);
1650 // Lex the token after the identifier suffix to determine NextTokenKind.
1651 if (Token NextToken;
1652 !Lexer::getRawToken(IdentifierSuffixEnd, NextToken, SM, LangOpts,
1653 /*IgnoreWhiteSpace=*/true))
1654 NextTokenKind = NextToken.getKind();
1655 // If preprocessor was run, inclusions from preprocessor callback should
1656 // already be added to Includes.
1657 Inserter.emplace(
1658 SemaCCInput.FileName, SemaCCInput.ParseInput.Contents, Style,
1659 SemaCCInput.ParseInput.CompileCommand.Directory,
1660 &Recorder->CCSema->getPreprocessor().getHeaderSearchInfo(),
1663 for (const auto &Inc : Includes.MainFileIncludes)
1664 Inserter->addExisting(Inc);
1665
1666 // Most of the cost of file proximity is in initializing the FileDistance
1667 // structures based on the observed includes, once per query. Conceptually
1668 // that happens here (though the per-URI-scheme initialization is lazy).
1669 // The per-result proximity scoring is (amortized) very cheap.
1670 FileDistanceOptions ProxOpts{}; // Use defaults.
1671 llvm::StringMap<SourceParams> ProxSources;
1672 auto MainFileID =
1673 Includes.getID(SM.getFileEntryForID(SM.getMainFileID()));
1674 assert(MainFileID);
1675 for (auto &HeaderIDAndDepth : Includes.includeDepth(*MainFileID)) {
1676 auto &Source =
1677 ProxSources[Includes.getRealPath(HeaderIDAndDepth.getFirst())];
1678 Source.Cost = HeaderIDAndDepth.getSecond() * ProxOpts.IncludeCost;
1679 // Symbols near our transitive includes are good, but only consider
1680 // things in the same directory or below it. Otherwise there can be
1681 // many false positives.
1682 if (HeaderIDAndDepth.getSecond() > 0)
1683 Source.MaxUpTraversals = 1;
1684 }
1685 FileProximity.emplace(ProxSources, ProxOpts);
1686
1687 Output = runWithSema();
1688 Inserter.reset(); // Make sure this doesn't out-live Clang.
1689 SPAN_ATTACH(Tracer, "sema_completion_kind",
1690 getCompletionKindString(CCContextKind));
1691 log("Code complete: sema context {0}, query scopes [{1}] (AnyScope={2}), "
1692 "expected type {3}{4}",
1693 getCompletionKindString(CCContextKind),
1694 llvm::join(QueryScopes.begin(), QueryScopes.end(), ","), AllScopes,
1695 PreferredType ? Recorder->CCContext.getPreferredType().getAsString()
1696 : "<none>",
1697 IsUsingDeclaration ? ", inside using declaration" : "");
1698 });
1699
1700 Recorder = RecorderOwner.get();
1701
1702 semaCodeComplete(std::move(RecorderOwner), Opts.getClangCompleteOpts(),
1703 SemaCCInput, &Includes);
1704 logResults(Output, Tracer);
1705 return Output;
1706 }
1707
1708 void logResults(const CodeCompleteResult &Output, const trace::Span &Tracer) {
1709 SPAN_ATTACH(Tracer, "sema_results", NSema);
1710 SPAN_ATTACH(Tracer, "index_results", NIndex);
1711 SPAN_ATTACH(Tracer, "merged_results", NSemaAndIndex);
1712 SPAN_ATTACH(Tracer, "identifier_results", NIdent);
1713 SPAN_ATTACH(Tracer, "returned_results", int64_t(Output.Completions.size()));
1714 SPAN_ATTACH(Tracer, "incomplete", Output.HasMore);
1715 log("Code complete: {0} results from Sema, {1} from Index, "
1716 "{2} matched, {3} from identifiers, {4} returned{5}.",
1717 NSema, NIndex, NSemaAndIndex, NIdent, Output.Completions.size(),
1718 Output.HasMore ? " (incomplete)" : "");
1719 assert(!Opts.Limit || Output.Completions.size() <= Opts.Limit);
1720 // We don't assert that isIncomplete means we hit a limit.
1721 // Indexes may choose to impose their own limits even if we don't have one.
1722 }
1723
1724 CodeCompleteResult runWithoutSema(llvm::StringRef Content, size_t Offset,
1725 const ThreadsafeFS &TFS) && {
1726 trace::Span Tracer("CodeCompleteWithoutSema");
1727 // Fill in fields normally set by runWithSema()
1728 HeuristicPrefix = guessCompletionPrefix(Content, Offset);
1729 populateContextWords(Content);
1730 CCContextKind = CodeCompletionContext::CCC_Recovery;
1731 IsUsingDeclaration = false;
1732 Filter = FuzzyMatcher(HeuristicPrefix.Name);
1733 auto Pos = offsetToPosition(Content, Offset);
1734 InsertRange.start = InsertRange.end = Pos;
1735 InsertRange.start.character -= HeuristicPrefix.Name.size();
1736
1737 if (Opts.EnableInsertReplace) {
1738 ReplaceRange.emplace();
1739 ReplaceRange->start = InsertRange.start;
1740 // Scan forward past ASCII identifier characters to find replace end.
1741 size_t ReplaceEnd = Offset;
1742 while (ReplaceEnd < Content.size() &&
1743 isAsciiIdentifierContinue(Content[ReplaceEnd]))
1744 ++ReplaceEnd;
1745 ReplaceRange->end = offsetToPosition(Content, ReplaceEnd);
1746 }
1747
1748 llvm::StringMap<SourceParams> ProxSources;
1749 ProxSources[FileName].Cost = 0;
1750 FileProximity.emplace(ProxSources);
1751
1752 auto Style = getFormatStyleForFile(FileName, Content, TFS, false);
1753 // This will only insert verbatim headers.
1754 Inserter.emplace(FileName, Content, Style,
1755 /*BuildDir=*/"", /*HeaderSearchInfo=*/nullptr,
1756 Config::current().Style.QuotedHeaders,
1758
1759 auto Identifiers = collectIdentifiers(Content, Style);
1760 std::vector<RawIdentifier> IdentifierResults;
1761 for (const auto &IDAndCount : Identifiers) {
1762 RawIdentifier ID;
1763 ID.Name = IDAndCount.first();
1764 ID.References = IDAndCount.second;
1765 // Avoid treating typed filter as an identifier.
1766 if (ID.Name == HeuristicPrefix.Name)
1767 --ID.References;
1768 if (ID.References > 0)
1769 IdentifierResults.push_back(std::move(ID));
1770 }
1771
1772 // Simplified version of getQueryScopes():
1773 // - accessible scopes are determined heuristically.
1774 // - all-scopes query if no qualifier was typed (and it's allowed).
1775 SpecifiedScope Scopes;
1776 Scopes.QueryScopes = visibleNamespaces(
1777 Content.take_front(Offset), format::getFormattingLangOpts(Style));
1778 for (std::string &S : Scopes.QueryScopes)
1779 if (!S.empty())
1780 S.append("::"); // visibleNamespaces doesn't include trailing ::.
1781 if (HeuristicPrefix.Qualifier.empty())
1782 AllScopes = Opts.AllScopes;
1783 else if (HeuristicPrefix.Qualifier.starts_with("::")) {
1784 Scopes.QueryScopes = {""};
1785 Scopes.UnresolvedQualifier =
1786 std::string(HeuristicPrefix.Qualifier.drop_front(2));
1787 } else
1788 Scopes.UnresolvedQualifier = std::string(HeuristicPrefix.Qualifier);
1789 // First scope is the (modified) enclosing scope.
1790 QueryScopes = Scopes.scopesForIndexQuery();
1791 AccessibleScopes = QueryScopes;
1792 ScopeProximity.emplace(QueryScopes);
1793
1794 SymbolSlab IndexResults = Opts.Index ? queryIndex() : SymbolSlab();
1795
1796 CodeCompleteResult Output = toCodeCompleteResult(mergeResults(
1797 /*SemaResults=*/{}, IndexResults, IdentifierResults));
1798 Output.RanParser = false;
1799 logResults(Output, Tracer);
1800 return Output;
1801 }
1802
1803private:
1804 void populateContextWords(llvm::StringRef Content) {
1805 // Take last 3 lines before the completion point.
1806 unsigned RangeEnd = HeuristicPrefix.Qualifier.begin() - Content.data(),
1807 RangeBegin = RangeEnd;
1808 for (size_t I = 0; I < 3 && RangeBegin > 0; ++I) {
1809 auto PrevNL = Content.rfind('\n', RangeBegin);
1810 if (PrevNL == StringRef::npos) {
1811 RangeBegin = 0;
1812 break;
1813 }
1814 RangeBegin = PrevNL;
1815 }
1816
1817 ContextWords = collectWords(Content.slice(RangeBegin, RangeEnd));
1818 dlog("Completion context words: {0}",
1819 llvm::join(ContextWords.keys(), ", "));
1820 }
1821
1822 // This is called by run() once Sema code completion is done, but before the
1823 // Sema data structures are torn down. It does all the real work.
1824 CodeCompleteResult runWithSema() {
1825 const auto &CodeCompletionRange = CharSourceRange::getCharRange(
1826 Recorder->CCSema->getPreprocessor().getCodeCompletionTokenRange());
1827
1828 const SourceManager &SM = Recorder->CCSema->getSourceManager();
1829
1830 // When we are getting completions with an empty identifier, for example
1831 // std::vector<int> asdf;
1832 // asdf.^;
1833 // Then the range will be invalid and we will be doing insertion, use
1834 // current cursor position in such cases as range.
1835 if (CodeCompletionRange.isValid()) {
1836 InsertRange = halfOpenToRange(SM, CodeCompletionRange);
1837 } else {
1838 const auto &Pos = sourceLocToPosition(
1839 SM, Recorder->CCSema->getPreprocessor().getCodeCompletionLoc());
1840 InsertRange.start = InsertRange.end = Pos;
1841 }
1842
1843 if (Opts.EnableInsertReplace) {
1844 ReplaceRange.emplace();
1845 ReplaceRange->start = InsertRange.start;
1846 ReplaceRange->end = getEndOfCodeCompletionReplace(SM);
1847 }
1848 Filter = FuzzyMatcher(
1849 Recorder->CCSema->getPreprocessor().getCodeCompletionFilter());
1850 auto SpecifiedScopes = getQueryScopes(
1851 Recorder->CCContext, *Recorder->CCSema, HeuristicPrefix, Opts);
1852
1853 QueryScopes = SpecifiedScopes.scopesForIndexQuery();
1854 AccessibleScopes = SpecifiedScopes.scopesForQualification();
1855 AllScopes = SpecifiedScopes.AllowAllScopes;
1856 if (!QueryScopes.empty())
1857 ScopeProximity.emplace(QueryScopes);
1858 PreferredType =
1859 OpaqueType::fromType(Recorder->CCSema->getASTContext(),
1860 Recorder->CCContext.getPreferredType());
1861 // Sema provides the needed context to query the index.
1862 // FIXME: in addition to querying for extra/overlapping symbols, we should
1863 // explicitly request symbols corresponding to Sema results.
1864 // We can use their signals even if the index can't suggest them.
1865 // We must copy index results to preserve them, but there are at most Limit.
1866 auto IndexResults = (Opts.Index && allowIndex(Recorder->CCContext))
1867 ? queryIndex()
1868 : SymbolSlab();
1869 trace::Span Tracer("Populate CodeCompleteResult");
1870 // Merge Sema and Index results, score them, and pick the winners.
1871 auto Top =
1872 mergeResults(Recorder->Results, IndexResults, /*Identifiers*/ {});
1873 return toCodeCompleteResult(Top);
1874 }
1875
1876 // Returns the LSP position at the end of the identifier suffix after the
1877 // code completion cursor.
1878 Position getEndOfCodeCompletionReplace(const SourceManager &SM) {
1879 Position End = sourceLocToPosition(SM, IdentifierSuffixEnd);
1880 // Adjust for the NUL byte inserted at the cursor by code completion,
1881 // which inflates the column by 1.
1882 End.character--;
1883 return End;
1884 }
1885
1886 CodeCompleteResult
1887 toCodeCompleteResult(const std::vector<ScoredBundle> &Scored) {
1888 CodeCompleteResult Output;
1889
1890 // Convert the results to final form, assembling the expensive strings.
1891 // If necessary, search the index for documentation comments.
1892 LookupRequest Req;
1893 llvm::DenseMap<SymbolID, uint32_t> SymbolToCompletion;
1894 for (auto &C : Scored) {
1895 Output.Completions.push_back(toCodeCompletion(C.first));
1896 Output.Completions.back().Score = C.second;
1897 Output.Completions.back().CompletionInsertRange = InsertRange;
1898 Output.Completions.back().CompletionReplaceRange = ReplaceRange;
1899 if (Opts.Index && !Output.Completions.back().Documentation) {
1900 for (auto &Cand : C.first) {
1901 if (Cand.SemaResult &&
1902 Cand.SemaResult->Kind == CodeCompletionResult::RK_Declaration) {
1903 const NamedDecl *DeclToLookup = Cand.SemaResult->getDeclaration();
1904 // For instantiations of members of class templates, the
1905 // documentation will be stored at the member's original
1906 // declaration.
1907 if (const NamedDecl *Adjusted =
1908 dyn_cast<NamedDecl>(&adjustDeclToTemplate(*DeclToLookup))) {
1909 DeclToLookup = Adjusted;
1910 }
1911 auto ID = clangd::getSymbolID(DeclToLookup);
1912 if (!ID)
1913 continue;
1914 Req.IDs.insert(ID);
1915 SymbolToCompletion[ID] = Output.Completions.size() - 1;
1916 }
1917 }
1918 }
1919 }
1920 Output.HasMore = Incomplete;
1921 Output.Context = CCContextKind;
1922 Output.InsertRange = InsertRange;
1923 Output.ReplaceRange = ReplaceRange;
1924
1925 // Look up documentation from the index.
1926 if (Opts.Index) {
1927 Opts.Index->lookup(Req, [&](const Symbol &S) {
1928 if (S.Documentation.empty())
1929 return;
1930 auto &C = Output.Completions[SymbolToCompletion.at(S.ID)];
1931 C.Documentation.emplace();
1932 parseDocumentation(S.Documentation, *C.Documentation);
1933 });
1934 }
1935
1936 return Output;
1937 }
1938
1939 SymbolSlab queryIndex() {
1940 trace::Span Tracer("Query index");
1941 SPAN_ATTACH(Tracer, "limit", int64_t(Opts.Limit));
1942
1943 // Build the query.
1944 FuzzyFindRequest Req;
1945 if (Opts.Limit)
1946 Req.Limit = Opts.Limit;
1947 Req.Query = std::string(Filter->pattern());
1948 Req.RestrictForCodeCompletion = true;
1949 Req.Scopes = QueryScopes;
1950 Req.AnyScope = AllScopes;
1951 // FIXME: we should send multiple weighted paths here.
1952 Req.ProximityPaths.push_back(std::string(FileName));
1953 if (PreferredType)
1954 Req.PreferredTypes.push_back(std::string(PreferredType->raw()));
1955 vlog("Code complete: fuzzyFind({0:2})", toJSON(Req));
1956
1957 if (SpecFuzzyFind)
1958 SpecFuzzyFind->NewReq = Req;
1959 if (SpecFuzzyFind && SpecFuzzyFind->Result.valid() && (*SpecReq == Req)) {
1960 vlog("Code complete: speculative fuzzy request matches the actual index "
1961 "request. Waiting for the speculative index results.");
1962 SPAN_ATTACH(Tracer, "Speculative results", true);
1963
1964 trace::Span WaitSpec("Wait speculative results");
1965 auto SpecRes = SpecFuzzyFind->Result.get();
1966 Incomplete |= SpecRes.first;
1967 return std::move(SpecRes.second);
1968 }
1969
1970 SPAN_ATTACH(Tracer, "Speculative results", false);
1971
1972 // Run the query against the index.
1973 SymbolSlab::Builder ResultsBuilder;
1974 Incomplete |= Opts.Index->fuzzyFind(
1975 Req, [&](const Symbol &Sym) { ResultsBuilder.insert(Sym); });
1976 return std::move(ResultsBuilder).build();
1977 }
1978
1979 // Merges Sema and Index results where possible, to form CompletionCandidates.
1980 // \p Identifiers is raw identifiers that can also be completion candidates.
1981 // Identifiers are not merged with results from index or sema.
1982 // Groups overloads if desired, to form CompletionCandidate::Bundles. The
1983 // bundles are scored and top results are returned, best to worst.
1984 std::vector<ScoredBundle>
1985 mergeResults(const std::vector<CodeCompletionResult> &SemaResults,
1986 const SymbolSlab &IndexResults,
1987 const std::vector<RawIdentifier> &IdentifierResults) {
1988 trace::Span Tracer("Merge and score results");
1989 std::vector<CompletionCandidate::Bundle> Bundles;
1990 llvm::DenseMap<size_t, size_t> BundleLookup;
1991 auto AddToBundles = [&](const CodeCompletionResult *SemaResult,
1992 const Symbol *IndexResult,
1993 const RawIdentifier *IdentifierResult) {
1994 CompletionCandidate C;
1995 C.SemaResult = SemaResult;
1996 C.IndexResult = IndexResult;
1997 C.IdentifierResult = IdentifierResult;
1998 if (C.IndexResult) {
1999 C.Name = IndexResult->Name;
2000 C.RankedIncludeHeaders = getRankedIncludes(*C.IndexResult);
2001 } else if (C.SemaResult) {
2002 C.Name = Recorder->getName(*SemaResult);
2003 } else {
2004 assert(IdentifierResult);
2005 C.Name = IdentifierResult->Name;
2006 }
2007 if (auto OverloadSet = C.overloadSet(
2008 Opts, FileName, Inserter ? &*Inserter : nullptr, CCContextKind)) {
2009 auto Ret = BundleLookup.try_emplace(OverloadSet, Bundles.size());
2010 if (Ret.second)
2011 Bundles.emplace_back();
2012 Bundles[Ret.first->second].push_back(std::move(C));
2013 } else {
2014 Bundles.emplace_back();
2015 Bundles.back().push_back(std::move(C));
2016 }
2017 };
2018 llvm::DenseSet<const Symbol *> UsedIndexResults;
2019 auto CorrespondingIndexResult =
2020 [&](const CodeCompletionResult &SemaResult) -> const Symbol * {
2021 if (auto SymID =
2022 getSymbolID(SemaResult, Recorder->CCSema->getSourceManager())) {
2023 auto I = IndexResults.find(SymID);
2024 if (I != IndexResults.end()) {
2025 UsedIndexResults.insert(&*I);
2026 return &*I;
2027 }
2028 }
2029 return nullptr;
2030 };
2031 // Emit all Sema results, merging them with Index results if possible.
2032 for (auto &SemaResult : SemaResults)
2033 AddToBundles(&SemaResult, CorrespondingIndexResult(SemaResult), nullptr);
2034 // Now emit any Index-only results.
2035 for (const auto &IndexResult : IndexResults) {
2036 if (UsedIndexResults.count(&IndexResult))
2037 continue;
2038 if (!includeSymbolFromIndex(CCContextKind, IndexResult))
2039 continue;
2040 AddToBundles(/*SemaResult=*/nullptr, &IndexResult, nullptr);
2041 }
2042 // Emit identifier results.
2043 for (const auto &Ident : IdentifierResults)
2044 AddToBundles(/*SemaResult=*/nullptr, /*IndexResult=*/nullptr, &Ident);
2045 // We only keep the best N results at any time, in "native" format.
2046 TopN<ScoredBundle, ScoredBundleGreater> Top(
2047 Opts.Limit == 0 ? std::numeric_limits<size_t>::max() : Opts.Limit);
2048 for (auto &Bundle : Bundles)
2049 addCandidate(Top, std::move(Bundle));
2050 return std::move(Top).items();
2051 }
2052
2053 std::optional<float> fuzzyScore(const CompletionCandidate &C) {
2054 using MacroFilterPolicy = Config::MacroFilterPolicy;
2055
2056 const auto IsMacroResult =
2057 ((C.SemaResult &&
2058 C.SemaResult->Kind == CodeCompletionResult::RK_Macro) ||
2059 (C.IndexResult &&
2060 C.IndexResult->SymInfo.Kind == index::SymbolKind::Macro));
2061
2062 if (!IsMacroResult)
2063 return Filter->match(C.Name);
2064
2065 // macros with underscores are probably noisy, so don't suggest them
2066 bool RequireExactPrefix =
2067 Opts.MacroFilter == MacroFilterPolicy::ExactPrefix ||
2068 C.Name.starts_with_insensitive("_") ||
2069 C.Name.ends_with_insensitive("_");
2070
2071 if (RequireExactPrefix &&
2072 !C.Name.starts_with_insensitive(Filter->pattern())) {
2073 return std::nullopt;
2074 }
2075
2076 return Filter->match(C.Name);
2077 }
2078
2079 CodeCompletion::Scores
2080 evaluateCompletion(const SymbolQualitySignals &Quality,
2081 const SymbolRelevanceSignals &Relevance) {
2082 using RM = CodeCompleteOptions::CodeCompletionRankingModel;
2083 CodeCompletion::Scores Scores;
2084 switch (Opts.RankingModel) {
2085 case RM::Heuristics:
2086 Scores.Quality = Quality.evaluateHeuristics();
2087 Scores.Relevance = Relevance.evaluateHeuristics();
2088 Scores.Total =
2089 evaluateSymbolAndRelevance(Scores.Quality, Scores.Relevance);
2090 // NameMatch is in fact a multiplier on total score, so rescoring is
2091 // sound.
2092 Scores.ExcludingName =
2093 Relevance.NameMatch > std::numeric_limits<float>::epsilon()
2094 ? Scores.Total / Relevance.NameMatch
2095 : Scores.Quality;
2096 return Scores;
2097
2098 case RM::DecisionForest:
2099 DecisionForestScores DFScores = Opts.DecisionForestScorer(
2100 Quality, Relevance, Opts.DecisionForestBase);
2101 Scores.ExcludingName = DFScores.ExcludingName;
2102 Scores.Total = DFScores.Total;
2103 return Scores;
2104 }
2105 llvm_unreachable("Unhandled CodeCompletion ranking model.");
2106 }
2107
2108 // Scores a candidate and adds it to the TopN structure.
2109 void addCandidate(TopN<ScoredBundle, ScoredBundleGreater> &Candidates,
2110 CompletionCandidate::Bundle Bundle) {
2111 SymbolQualitySignals Quality;
2112 SymbolRelevanceSignals Relevance;
2113 Relevance.Context = CCContextKind;
2114 Relevance.Name = Bundle.front().Name;
2115 Relevance.FilterLength = HeuristicPrefix.Name.size();
2116 Relevance.Query = SymbolRelevanceSignals::CodeComplete;
2117 Relevance.FileProximityMatch = &*FileProximity;
2118 if (ScopeProximity)
2119 Relevance.ScopeProximityMatch = &*ScopeProximity;
2120 if (PreferredType)
2121 Relevance.HadContextType = true;
2122 Relevance.ContextWords = &ContextWords;
2123 Relevance.MainFileSignals = Opts.MainFileSignals;
2124
2125 auto &First = Bundle.front();
2126 if (auto FuzzyScore = fuzzyScore(First))
2127 Relevance.NameMatch = *FuzzyScore;
2128 else
2129 return;
2130 SymbolOrigin Origin = SymbolOrigin::Unknown;
2131 bool FromIndex = false;
2132 for (const auto &Candidate : Bundle) {
2133 if (Candidate.IndexResult) {
2134 Quality.merge(*Candidate.IndexResult);
2135 Relevance.merge(*Candidate.IndexResult);
2136 Origin |= Candidate.IndexResult->Origin;
2137 FromIndex = true;
2138 if (!Candidate.IndexResult->Type.empty())
2139 Relevance.HadSymbolType |= true;
2140 if (PreferredType &&
2141 PreferredType->raw() == Candidate.IndexResult->Type) {
2142 Relevance.TypeMatchesPreferred = true;
2143 }
2144 }
2145 if (Candidate.SemaResult) {
2146 Quality.merge(*Candidate.SemaResult);
2147 Relevance.merge(*Candidate.SemaResult);
2148 if (PreferredType) {
2149 if (auto CompletionType = OpaqueType::fromCompletionResult(
2150 Recorder->CCSema->getASTContext(), *Candidate.SemaResult)) {
2151 Relevance.HadSymbolType |= true;
2152 if (PreferredType == CompletionType)
2153 Relevance.TypeMatchesPreferred = true;
2154 }
2155 }
2156 Origin |= SymbolOrigin::AST;
2157 }
2158 if (Candidate.IdentifierResult) {
2159 Quality.References = Candidate.IdentifierResult->References;
2160 Relevance.Scope = SymbolRelevanceSignals::FileScope;
2161 Origin |= SymbolOrigin::Identifier;
2162 }
2163 }
2164
2165 CodeCompletion::Scores Scores = evaluateCompletion(Quality, Relevance);
2166 if (Opts.RecordCCResult)
2167 Opts.RecordCCResult(toCodeCompletion(Bundle), Quality, Relevance,
2168 Scores.Total);
2169
2170 dlog("CodeComplete: {0} ({1}) = {2}\n{3}{4}\n", First.Name,
2171 llvm::to_string(Origin), Scores.Total, llvm::to_string(Quality),
2172 llvm::to_string(Relevance));
2173
2174 NSema += bool(Origin & SymbolOrigin::AST);
2175 NIndex += FromIndex;
2176 NSemaAndIndex += bool(Origin & SymbolOrigin::AST) && FromIndex;
2177 NIdent += bool(Origin & SymbolOrigin::Identifier);
2178 if (Candidates.push({std::move(Bundle), Scores}))
2179 Incomplete = true;
2180 }
2181
2182 CodeCompletion toCodeCompletion(const CompletionCandidate::Bundle &Bundle) {
2183 std::optional<CodeCompletionBuilder> Builder;
2184 for (const auto &Item : Bundle) {
2185 CodeCompletionString *SemaCCS =
2186 Item.SemaResult ? Recorder->codeCompletionString(*Item.SemaResult)
2187 : nullptr;
2188 if (!Builder)
2189 Builder.emplace(Recorder ? &Recorder->CCSema->getASTContext() : nullptr,
2190 Item, SemaCCS, AccessibleScopes, *Inserter, FileName,
2191 CCContextKind, Opts, IsUsingDeclaration, NextTokenKind);
2192 else
2193 Builder->add(Item, SemaCCS, CCContextKind);
2194 }
2195 return Builder->build();
2196 }
2197};
2198
2199} // namespace
2200
2201clang::CodeCompleteOptions CodeCompleteOptions::getClangCompleteOpts() const {
2202 clang::CodeCompleteOptions Result;
2203 Result.IncludeCodePatterns =
2204 EnableSnippets && (CodePatterns != Config::CodePatternsPolicy::None);
2205 Result.IncludeMacros = true;
2206 Result.IncludeGlobals = true;
2207 // We choose to include full comments and not do doxygen parsing in
2208 // completion.
2209 // FIXME: ideally, we should support doxygen in some form, e.g. do markdown
2210 // formatting of the comments.
2211 Result.IncludeBriefComments = false;
2212
2213 // When an is used, Sema is responsible for completing the main file,
2214 // the index can provide results from the preamble.
2215 // Tell Sema not to deserialize the preamble to look for results.
2216 Result.LoadExternal = ForceLoadPreamble || !Index;
2217 Result.IncludeFixIts = IncludeFixIts;
2218
2219 return Result;
2220}
2221
2223 unsigned Offset) {
2224 assert(Offset <= Content.size());
2225 StringRef Rest = Content.take_front(Offset);
2226 CompletionPrefix Result;
2227
2228 // Consume the unqualified name. We only handle ASCII characters.
2229 // isAsciiIdentifierContinue will let us match "0invalid", but we don't mind.
2230 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2231 Rest = Rest.drop_back();
2232 Result.Name = Content.slice(Rest.size(), Offset);
2233
2234 // Consume qualifiers.
2235 while (Rest.consume_back("::") && !Rest.ends_with(":")) // reject ::::
2236 while (!Rest.empty() && isAsciiIdentifierContinue(Rest.back()))
2237 Rest = Rest.drop_back();
2238 Result.Qualifier =
2239 Content.slice(Rest.size(), Result.Name.begin() - Content.begin());
2240
2241 return Result;
2242}
2243
2244// If Offset is inside what looks like argument comment (e.g.
2245// "/*^*/" or "/* foo = ^*/"), returns the offset pointing past the closing
2246// "*/".
2247static std::optional<unsigned>
2248maybeFunctionArgumentCommentEnd(const PathRef FileName, const unsigned Offset,
2249 const llvm::StringRef Content,
2250 const LangOptions &LangOpts) {
2251 if (Offset > Content.size())
2252 return std::nullopt;
2253
2254 SourceManagerForFile FileSM(FileName, Content);
2255 const SourceManager &SM = FileSM.get();
2256 const SourceLocation Cursor = SM.getComposedLoc(SM.getMainFileID(), Offset);
2257 const SourceLocation EndOfSuffix =
2258 Lexer::findEndOfIdentifierContinuation(Cursor, SM, LangOpts);
2259 const unsigned EndOfSuffixOffset = SM.getFileOffset(EndOfSuffix);
2260
2261 const llvm::StringRef Rest = Content.drop_front(EndOfSuffixOffset);
2262 llvm::StringRef RestTrimmed = Rest.ltrim();
2263 // Comment argument pattern: `/* name = */` — skip past optional `=`.
2264 if (RestTrimmed.starts_with("="))
2265 RestTrimmed = RestTrimmed.drop_front(1).ltrim();
2266 if (RestTrimmed.starts_with("*/"))
2267 return EndOfSuffixOffset + (Rest.size() - RestTrimmed.size()) + 2;
2268 return std::nullopt;
2269}
2270
2271// Code complete the argument name on "/*" inside function call.
2272// OutsideStartOffset should be pointing before the comment, i.e.:
2273// foo(^/*, rather than foo(/*^) where the cursor probably is.
2274CodeCompleteResult
2275codeCompleteComment(PathRef FileName, const unsigned CursorOffset,
2276 unsigned OutsideStartOffset, llvm::StringRef Prefix,
2277 const PreambleData *Preamble, const ParseInputs &ParseInput,
2278 const CodeCompleteOptions &Opts) {
2279 if (Preamble == nullptr) // Can't run without Sema.
2280 return CodeCompleteResult();
2281
2282 IgnoreDiagnostics IgnoreDiags;
2283 auto CI = buildCompilerInvocation(ParseInput, IgnoreDiags);
2284 if (!CI)
2285 return CodeCompleteResult();
2286
2287 std::optional<unsigned> OutsideEndOffset;
2288 if (Opts.EnableInsertReplace)
2289 OutsideEndOffset = maybeFunctionArgumentCommentEnd(
2290 FileName, CursorOffset, ParseInput.Contents, CI->getLangOpts());
2291
2292 clang::CodeCompleteOptions Options;
2293 Options.IncludeGlobals = false;
2294 Options.IncludeMacros = false;
2295 Options.IncludeCodePatterns = false;
2296 Options.IncludeBriefComments = false;
2297 std::set<std::string> ParamNames;
2298 // We want to see signatures coming from newly introduced includes, hence a
2299 // full patch.
2300 semaCodeComplete(
2301 std::make_unique<ParamNameCollector>(Options, ParamNames), Options,
2302 {FileName, OutsideStartOffset, *Preamble,
2303 PreamblePatch::createFullPatch(FileName, ParseInput, *Preamble),
2304 ParseInput},
2305 /*Includes=*/nullptr, std::move(CI));
2306 if (ParamNames.empty())
2307 return CodeCompleteResult();
2308
2309 CodeCompleteResult Result;
2310 Range InsertRange;
2311 // Skip /*
2312 const unsigned InsideStartOffset = OutsideStartOffset + 2;
2313 InsertRange.start = offsetToPosition(ParseInput.Contents, InsideStartOffset);
2314 InsertRange.end =
2315 offsetToPosition(ParseInput.Contents, InsideStartOffset + Prefix.size());
2316 Result.InsertRange = InsertRange;
2317
2318 if (Opts.EnableInsertReplace) {
2319 Range ReplaceRange;
2320 ReplaceRange.start = InsertRange.start;
2321 ReplaceRange.end = OutsideEndOffset ? offsetToPosition(ParseInput.Contents,
2322 *OutsideEndOffset)
2323 : InsertRange.end;
2324 Result.ReplaceRange = ReplaceRange;
2325 }
2326
2327 Result.Context = CodeCompletionContext::CCC_NaturalLanguage;
2328 for (llvm::StringRef Name : ParamNames) {
2329 if (!Name.starts_with(Prefix))
2330 continue;
2331 CodeCompletion Item;
2332 Item.Name = Name.str() + "=*/";
2333 Item.FilterText = Item.Name;
2334 Item.Kind = CompletionItemKind::Text;
2335 Item.CompletionInsertRange = InsertRange;
2336 Item.CompletionReplaceRange = Result.ReplaceRange;
2337 Item.Origin = SymbolOrigin::AST;
2338 Result.Completions.push_back(Item);
2339 }
2340
2341 return Result;
2342}
2343
2344// If Offset is inside what looks like argument comment (e.g.
2345// "/*^" or "/* foo^"), returns new offset pointing to the start of the /*
2346// (place where semaCodeComplete should run).
2347std::optional<unsigned>
2348maybeFunctionArgumentCommentStart(llvm::StringRef Content) {
2349 while (!Content.empty() && isAsciiIdentifierContinue(Content.back()))
2350 Content = Content.drop_back();
2351 Content = Content.rtrim();
2352 if (Content.ends_with("/*"))
2353 return Content.size() - 2;
2354 return std::nullopt;
2355}
2356
2357CodeCompleteResult codeComplete(PathRef FileName, Position Pos,
2358 const PreambleData *Preamble,
2359 const ParseInputs &ParseInput,
2361 SpeculativeFuzzyFind *SpecFuzzyFind) {
2362 auto Offset = positionToOffset(ParseInput.Contents, Pos);
2363 if (!Offset) {
2364 elog("Code completion position was invalid {0}", Offset.takeError());
2365 return CodeCompleteResult();
2366 }
2367
2368 auto Content = llvm::StringRef(ParseInput.Contents).take_front(*Offset);
2369 if (auto OffsetBeforeComment = maybeFunctionArgumentCommentStart(Content)) {
2370 // We are doing code completion of a comment, where we currently only
2371 // support completing param names in function calls. To do this, we
2372 // require information from Sema, but Sema's comment completion stops at
2373 // parsing, so we must move back the position before running it, extract
2374 // information we need and construct completion items ourselves.
2375 auto CommentPrefix = Content.substr(*OffsetBeforeComment + 2).trim();
2376 return codeCompleteComment(FileName, *Offset, *OffsetBeforeComment,
2377 CommentPrefix, Preamble, ParseInput, Opts);
2378 }
2379
2380 auto Flow = CodeCompleteFlow(
2381 FileName, Preamble ? Preamble->Includes : IncludeStructure(),
2382 SpecFuzzyFind, Opts);
2383 return (!Preamble || Opts.RunParser == CodeCompleteOptions::NeverParse)
2384 ? std::move(Flow).runWithoutSema(ParseInput.Contents, *Offset,
2385 *ParseInput.TFS)
2386 : std::move(Flow).run({FileName, *Offset, *Preamble,
2387 /*PreamblePatch=*/
2389 FileName, ParseInput, *Preamble),
2390 ParseInput});
2391}
2392
2394 const PreambleData &Preamble,
2395 const ParseInputs &ParseInput,
2396 MarkupKind DocumentationFormat) {
2397 auto Offset = positionToOffset(ParseInput.Contents, Pos);
2398 if (!Offset) {
2399 elog("Signature help position was invalid {0}", Offset.takeError());
2400 return SignatureHelp();
2401 }
2402 SignatureHelp Result;
2403 clang::CodeCompleteOptions Options;
2404 Options.IncludeGlobals = false;
2405 Options.IncludeMacros = false;
2406 Options.IncludeCodePatterns = false;
2407 Options.IncludeBriefComments = false;
2408 semaCodeComplete(
2409 std::make_unique<SignatureHelpCollector>(Options, DocumentationFormat,
2410 ParseInput.Index, Result),
2411 Options,
2412 {FileName, *Offset, Preamble,
2413 PreamblePatch::createFullPatch(FileName, ParseInput, Preamble),
2414 ParseInput});
2415 return Result;
2416}
2417
2418bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx) {
2419 auto InTopLevelScope = [](const NamedDecl &ND) {
2420 switch (ND.getDeclContext()->getDeclKind()) {
2421 case Decl::TranslationUnit:
2422 case Decl::Namespace:
2423 case Decl::LinkageSpec:
2424 return true;
2425 default:
2426 break;
2427 };
2428 return false;
2429 };
2430 auto InClassScope = [](const NamedDecl &ND) {
2431 return ND.getDeclContext()->getDeclKind() == Decl::CXXRecord;
2432 };
2433 // We only complete symbol's name, which is the same as the name of the
2434 // *primary* template in case of template specializations.
2436 return false;
2437
2438 // Category decls are not useful on their own outside the interface or
2439 // implementation blocks. Moreover, sema already provides completion for
2440 // these, even if it requires preamble deserialization. So by excluding them
2441 // from the index, we reduce the noise in all the other completion scopes.
2442 if (llvm::isa<ObjCCategoryDecl>(&ND) || llvm::isa<ObjCCategoryImplDecl>(&ND))
2443 return false;
2444
2445 if (InTopLevelScope(ND))
2446 return true;
2447
2448 // Always index enum constants, even if they're not in the top level scope:
2449 // when
2450 // --all-scopes-completion is set, we'll want to complete those as well.
2451 if (const auto *EnumDecl = dyn_cast<clang::EnumDecl>(ND.getDeclContext()))
2452 return (InTopLevelScope(*EnumDecl) || InClassScope(*EnumDecl));
2453
2454 return false;
2455}
2456
2457CompletionItem CodeCompletion::render(const CodeCompleteOptions &Opts) const {
2458 CompletionItem LSP;
2459 const auto *InsertInclude = Includes.empty() ? nullptr : &Includes[0];
2460 // We could move our indicators from label into labelDetails->description.
2461 // In VSCode there are rendering issues that prevent these being aligned.
2462 LSP.label = ((InsertInclude && InsertInclude->Insertion)
2463 ? Opts.IncludeIndicator.Insert
2464 : Opts.IncludeIndicator.NoInsert) +
2465 (Opts.ShowOrigins ? "[" + llvm::to_string(Origin) + "]" : "") +
2466 RequiredQualifier + Name;
2467 LSP.labelDetails.emplace();
2468 LSP.labelDetails->detail = Signature;
2469
2470 LSP.kind = Kind;
2471 LSP.detail = BundleSize > 1
2472 ? std::string(llvm::formatv("[{0} overloads]", BundleSize))
2473 : ReturnType;
2474 LSP.deprecated = Deprecated;
2475 // Combine header information and documentation in LSP `documentation` field.
2476 // This is not quite right semantically, but tends to display well in editors.
2477 if (InsertInclude || Documentation) {
2478 markup::Document Doc;
2479 if (InsertInclude)
2480 Doc.addParagraph().appendText("From ").appendCode(InsertInclude->Header);
2481 if (Documentation)
2482 Doc.append(*Documentation);
2483 LSP.documentation = renderDoc(Doc, Opts.DocumentationFormat);
2484 }
2485 LSP.sortText = sortText(Score.Total, FilterText);
2486 LSP.filterText = FilterText;
2487 TextEdit Edit;
2488 Edit.range = CompletionInsertRange;
2489 Edit.newText = RequiredQualifier + Name;
2490 // Merge continuous additionalTextEdits into main edit. The main motivation
2491 // behind this is to help LSP clients, it seems most of them are confused when
2492 // they are provided with additionalTextEdits that are consecutive to main
2493 // edit.
2494 // Note that we store additional text edits from back to front in a line. That
2495 // is mainly to help LSP clients again, so that changes do not effect each
2496 // other.
2497 for (const auto &FixIt : FixIts) {
2498 if (FixIt.range.end == Edit.range.start) {
2499 Edit.newText = FixIt.newText + Edit.newText;
2500 Edit.range.start = FixIt.range.start;
2501 } else {
2502 LSP.additionalTextEdits.push_back(FixIt);
2503 }
2504 }
2505 if (Opts.EnableSnippets)
2506 Edit.newText += SnippetSuffix;
2507
2508 // FIXME(kadircet): Do not even fill insertText after making sure textEdit is
2509 // compatible with most of the editors.
2510 LSP.insertText = Edit.newText;
2511 if (Opts.EnableInsertReplace) {
2512 assert(CompletionReplaceRange &&
2513 "CompletionReplaceRange must be already set before render() "
2514 "when EnableInsertReplace is on");
2516 IRE.newText = std::move(Edit.newText);
2517 IRE.insert = Edit.range;
2518 IRE.replace = *CompletionReplaceRange;
2519 // FixIt merging may have extended the insert range start; keep replace
2520 // range as a superset per LSP spec.
2521 IRE.replace.start = IRE.insert.start;
2522 LSP.textEdit = std::move(IRE);
2523 } else {
2524 LSP.textEdit = std::move(Edit);
2525 }
2526 // Some clients support snippets but work better with plaintext.
2527 // So if the snippet is trivial, let the client know.
2528 // https://github.com/clangd/clangd/issues/922
2529 LSP.insertTextFormat = (Opts.EnableSnippets && !SnippetSuffix.empty())
2532 if (InsertInclude && InsertInclude->Insertion)
2533 LSP.additionalTextEdits.push_back(*InsertInclude->Insertion);
2534
2535 LSP.score = Score.ExcludingName;
2536
2537 return LSP;
2538}
2539
2540llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const CodeCompletion &C) {
2541 OS << "Signature: " << "\"" << C.Signature << "\", "
2542 << "SnippetSuffix: " << "\"" << C.SnippetSuffix << "\""
2543 << ", Rendered:";
2544 // For now just lean on CompletionItem.
2545 return OS << C.render(CodeCompleteOptions());
2546}
2547
2548llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
2549 const CodeCompleteResult &R) {
2550 OS << "CodeCompleteResult: " << R.Completions.size() << (R.HasMore ? "+" : "")
2551 << " (" << getCompletionKindString(R.Context) << ")"
2552 << " items:\n";
2553 for (const auto &C : R.Completions)
2554 OS << C << "\n";
2555 return OS;
2556}
2557
2558// Heuristically detect whether the `Line` is an unterminated include filename.
2559bool isIncludeFile(llvm::StringRef Line) {
2560 Line = Line.ltrim();
2561 if (!Line.consume_front("#"))
2562 return false;
2563 Line = Line.ltrim();
2564 if (!(Line.consume_front("include_next") || Line.consume_front("include") ||
2565 Line.consume_front("import")))
2566 return false;
2567 Line = Line.ltrim();
2568 if (Line.consume_front("<"))
2569 return Line.count('>') == 0;
2570 if (Line.consume_front("\""))
2571 return Line.count('"') == 0;
2572 return false;
2573}
2574
2575bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset) {
2576 // Look at last line before completion point only.
2577 Content = Content.take_front(Offset);
2578 auto Pos = Content.rfind('\n');
2579 if (Pos != llvm::StringRef::npos)
2580 Content = Content.substr(Pos + 1);
2581
2582 // Complete after scope operators.
2583 if (Content.ends_with(".") || Content.ends_with("->") ||
2584 Content.ends_with("::") || Content.ends_with("/*"))
2585 return true;
2586 // Complete after `#include <` and #include `<foo/`.
2587 if ((Content.ends_with("<") || Content.ends_with("\"") ||
2588 Content.ends_with("/")) &&
2589 isIncludeFile(Content))
2590 return true;
2591
2592 // Complete words. Give non-ascii characters the benefit of the doubt.
2593 return !Content.empty() && (isAsciiIdentifierContinue(Content.back()) ||
2594 !llvm::isASCII(Content.back()));
2595}
2596
2597} // namespace clangd
2598} // namespace clang
static clang::FrontendPluginRegistry::Add< clang::tidy::ClangTidyPluginAction > X("clang-tidy", "clang-tidy")
#define dlog(...)
Definition Logger.h:101
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
Definition Trace.h:164
static std::optional< OpaqueType > fromCompletionResult(ASTContext &Ctx, const CodeCompletionResult &R)
Create a type from a code completion result.
static std::optional< OpaqueType > fromType(ASTContext &Ctx, QualType Type)
Construct an instance from a clang::QualType.
static PreamblePatch createMacroPatch(llvm::StringRef FileName, const ParseInputs &Modified, const PreambleData &Baseline)
Definition Preamble.cpp:906
static PreamblePatch createFullPatch(llvm::StringRef FileName, const ParseInputs &Modified, const PreambleData &Baseline)
Builds a patch that contains new PP directives introduced to the preamble section of Modified compare...
Definition Preamble.cpp:900
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
Definition URI.cpp:244
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
@ Info
An information message.
Definition Protocol.h:755
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
Definition AST.cpp:354
std::string formatDocumentation(const CodeCompletionString &CCS, llvm::StringRef DocComment)
Assembles formatted documentation for a completion result.
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
std::string sortText(float Score, llvm::StringRef Name)
Returns a string that sorts in the same order as (-Score, Tiebreak), for LSP.
Definition Quality.cpp:552
std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl)
Similar to getDocComment, but returns the comment for a NamedDecl.
bool isIncludeFile(llvm::StringRef Line)
TextEdit toTextEdit(const FixItHint &FixIt, const SourceManager &M, const LangOptions &L)
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
size_t lspLength(llvm::StringRef Code)
CompletionPrefix guessCompletionPrefix(llvm::StringRef Content, unsigned Offset)
std::unique_ptr< CompilerInvocation > buildCompilerInvocation(const ParseInputs &Inputs, clang::DiagnosticConsumer &D, std::vector< std::string > *CC1Args)
Builds compiler invocation that could be used to build AST or preamble.
Definition Compiler.cpp:96
bool isExplicitTemplateSpecialization(const NamedDecl *D)
Indicates if D is an explicit template specialization, e.g.
Definition AST.cpp:187
bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset)
void vlog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:72
static const char * toString(OffsetEncoding OE)
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
Definition Logger.h:79
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
std::string getReturnType(const CodeCompletionString &CCS)
Gets detail to be used as the detail field in an LSP completion item.
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
llvm::StringMap< unsigned > collectIdentifiers(llvm::StringRef Content, const format::FormatStyle &Style)
Collects identifiers with counts in the source code.
bool hasUnstableLinkage(const Decl *D)
Whether we must avoid computing linkage for D during code completion.
Definition AST.cpp:735
llvm::json::Value toJSON(const FuzzyFindRequest &Request)
Definition Index.cpp:45
std::vector< std::string > visibleNamespaces(llvm::StringRef Code, const LangOptions &LangOpts)
Heuristically determine namespaces visible at a point, without parsing Code.
llvm::Expected< HeaderFile > toHeaderFile(llvm::StringRef Header, llvm::StringRef HintPath)
Creates a HeaderFile from Header which can be either a URI or a literal include.
Definition Headers.cpp:143
std::unique_ptr< CompilerInstance > prepareCompilerInstance(std::unique_ptr< clang::CompilerInvocation > CI, const PrecompiledPreamble *Preamble, std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, DiagnosticConsumer &DiagsClient)
Definition Compiler.cpp:131
std::future< T > runAsync(llvm::unique_function< T()> Action)
Runs Action asynchronously with a new std::thread.
Definition Threading.h:127
void log(const char *Fmt, Ts &&... Vals)
Definition Logger.h:67
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
std::optional< unsigned > maybeFunctionArgumentCommentStart(llvm::StringRef Content)
llvm::StringSet collectWords(llvm::StringRef Content)
Collects words from the source code.
void getSignature(const CodeCompletionString &CCS, std::string *Signature, std::string *Snippet, CodeCompletionResult::ResultKind ResultKind, CXCursorKind CursorKind, bool IncludeFunctionArguments, std::string *RequiredQualifiers)
Formats the signature for an item, as a display string and snippet.
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition Path.h:29
CodeCompleteResult codeCompleteComment(PathRef FileName, const unsigned CursorOffset, unsigned OutsideStartOffset, llvm::StringRef Prefix, const PreambleData *Preamble, const ParseInputs &ParseInput, const CodeCompleteOptions &Opts)
llvm::SmallVector< SymbolInclude, 1 > getRankedIncludes(const Symbol &Sym)
Definition Headers.cpp:163
std::pair< size_t, size_t > offsetToClangLineColumn(llvm::StringRef Code, size_t Offset)
@ Deprecated
Deprecated or obsolete code.
Definition Protocol.h:936
@ Full
Documents are synced by always sending the full content of the document.
Definition Protocol.h:343
void parseDocumentation(llvm::StringRef Input, markup::Document &Output)
Definition Hover.cpp:1834
float evaluateSymbolAndRelevance(float SymbolQuality, float SymbolRelevance)
Combine symbol quality and relevance into a single score.
Definition Quality.cpp:534
CodeCompleteResult codeComplete(PathRef FileName, Position Pos, const PreambleData *Preamble, const ParseInputs &ParseInput, CodeCompleteOptions Opts, SpeculativeFuzzyFind *SpecFuzzyFind)
Gets code completions at a specified Pos in FileName.
@ PlainText
The primary text to be inserted is treated as a plain string.
Definition Protocol.h:1327
@ Snippet
The primary text to be inserted is treated as a snippet.
Definition Protocol.h:1337
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
Definition AST.cpp:206
SignatureHelp signatureHelp(PathRef FileName, Position Pos, const PreambleData &Preamble, const ParseInputs &ParseInput, MarkupKind DocumentationFormat)
Get signature help at a specified Pos in FileName.
void elog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:61
std::string getDocComment(const ASTContext &Ctx, const CodeCompletionResult &Result, bool CommentsFromHeaders)
Gets a minimally formatted documentation comment of Result, with comment markers stripped.
static std::optional< unsigned > maybeFunctionArgumentCommentEnd(const PathRef FileName, const unsigned Offset, const llvm::StringRef Content, const LangOptions &LangOpts)
std::string printNamespaceScope(const DeclContext &DC)
Returns the first enclosing namespace scope starting from DC.
Definition AST.cpp:303
bool isIndexedForCodeCompletion(const NamedDecl &ND, ASTContext &ASTCtx)
PreambleBounds computePreambleBounds(const LangOptions &LangOpts, const llvm::MemoryBufferRef &Buffer, bool SkipPreambleBuild)
Definition Preamble.cpp:967
format::FormatStyle getFormatStyleForFile(llvm::StringRef File, llvm::StringRef Content, const ThreadsafeFS &TFS, bool FormatFile)
Choose the clang-format style we should apply to a certain file.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
-clang-tidy
clang::CodeCompleteOptions getClangCompleteOpts() const
Returns options that can be passed to clang's completion engine.
struct clang::clangd::Config::@314053012031341203055315320366267371313202370174 Style
Style of the codebase.
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition Config.cpp:17
ArgumentListsPolicy
controls the completion options for argument lists.
Definition Config.h:140
@ None
nothing, no argument list and also NO Delimiters "()" or "<>".
Definition Config.h:142
@ Delimiters
empty pair of delimiters "()" or "<>".
Definition Config.h:146
@ OpenDelimiter
open, only opening delimiter "(" or "<".
Definition Config.h:144
@ FullPlaceholders
full name of both type and variable.
Definition Config.h:148
@ PlainText
Treat comments as plain text.
Definition Config.h:214
std::vector< std::function< bool(llvm::StringRef)> > QuotedHeaders
Definition Config.h:135
CodePatternsPolicy CodePatterns
Enables code patterns & snippets suggestions.
Definition Config.h:177
CommentFormatPolicy CommentFormat
Definition Config.h:222
std::vector< std::function< bool(llvm::StringRef)> > AngledHeaders
Definition Config.h:136
A set of edits generated for a single file.
Definition SourceCode.h:189
std::string newText
The string to be inserted.
Definition Protocol.h:267
Information required to run clang, e.g. to parse AST or do code completion.
Definition Compiler.h:51
const ThreadsafeFS * TFS
Definition Compiler.h:53
const SymbolIndex * Index
Definition Compiler.h:61
The parsed preamble and associated data.
Definition Preamble.h:97
Position start
The range's start position.
Definition Protocol.h:188
Position end
The range's end position.
Definition Protocol.h:191
Represents the signature of a callable.
Definition Protocol.h:1477
@ Deprecated
Indicates if the symbol is deprecated.
Definition Symbol.h:143
@ Include
#include "header.h"
Definition Symbol.h:93
@ Import
#import "header.h"
Definition Symbol.h:95