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