clang-tools 22.0.0git
Check.cpp
Go to the documentation of this file.
1//===--- Check.cpp - clangd self-diagnostics ------------------------------===//
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// Many basic problems can occur processing a file in clangd, e.g.:
10// - system includes are not found
11// - crash when indexing its AST
12// clangd --check provides a simplified, isolated way to reproduce these,
13// with no editor, LSP, threads, background indexing etc to contend with.
14//
15// One important use case is gathering information for bug reports.
16// Another is reproducing crashes, and checking which setting prevent them.
17//
18// It simulates opening a file (determining compile command, parsing, indexing)
19// and then running features at many locations.
20//
21// Currently it adds some basic logging of progress and results.
22// We should consider extending it to also recognize common symptoms and
23// recommend solutions (e.g. standard library installation issues).
24//
25//===----------------------------------------------------------------------===//
26
27#include "../clang-tidy/ClangTidyModule.h"
28#include "../clang-tidy/ClangTidyOptions.h"
29#include "../clang-tidy/GlobList.h"
30#include "ClangdLSPServer.h"
31#include "ClangdServer.h"
32#include "CodeComplete.h"
33#include "CompileCommands.h"
34#include "Compiler.h"
35#include "Config.h"
36#include "ConfigFragment.h"
37#include "ConfigProvider.h"
38#include "Diagnostics.h"
39#include "Feature.h"
41#include "Hover.h"
42#include "InlayHints.h"
43#include "ParsedAST.h"
44#include "Preamble.h"
45#include "Protocol.h"
46#include "Selection.h"
48#include "SourceCode.h"
49#include "TidyProvider.h"
50#include "XRefs.h"
51#include "clang-include-cleaner/Record.h"
52#include "index/FileIndex.h"
53#include "refactor/Tweak.h"
54#include "support/Context.h"
55#include "support/Logger.h"
57#include "support/Trace.h"
58#include "clang/AST/ASTContext.h"
59#include "clang/Basic/Diagnostic.h"
60#include "clang/Basic/LLVM.h"
61#include "clang/Format/Format.h"
62#include "clang/Frontend/CompilerInvocation.h"
63#include "clang/Tooling/CompilationDatabase.h"
64#include "llvm/ADT/ArrayRef.h"
65#include "llvm/ADT/STLExtras.h"
66#include "llvm/ADT/SmallString.h"
67#include "llvm/Support/Chrono.h"
68#include "llvm/Support/CommandLine.h"
69#include "llvm/Support/Path.h"
70#include "llvm/Support/Process.h"
71#include <array>
72#include <chrono>
73#include <cstdint>
74#include <limits>
75#include <memory>
76#include <optional>
77#include <utility>
78#include <vector>
79
80namespace clang {
81namespace clangd {
82namespace {
83
84// These will never be shown in --help, ClangdMain doesn't list the category.
85llvm::cl::opt<std::string> CheckTidyTime{
86 "check-tidy-time",
87 llvm::cl::desc("Print the overhead of checks matching this glob"),
88 llvm::cl::init("")};
89llvm::cl::opt<std::string> CheckFileLines{
90 "check-lines",
91 llvm::cl::desc(
92 "Limits the range of tokens in -check file on which "
93 "various features are tested. Example --check-lines=3-7 restricts "
94 "testing to lines 3 to 7 (inclusive) or --check-lines=5 to restrict "
95 "to one line. Default is testing entire file."),
96 llvm::cl::init("")};
97llvm::cl::opt<bool> CheckLocations{
98 "check-locations",
99 llvm::cl::desc(
100 "Runs certain features (e.g. hover) at each point in the file. "
101 "Somewhat slow."),
102 llvm::cl::init(true)};
103llvm::cl::opt<bool> CheckCompletion{
104 "check-completion",
105 llvm::cl::desc("Run code-completion at each point (slow)"),
106 llvm::cl::init(false)};
107llvm::cl::opt<bool> CheckWarnings{
108 "check-warnings",
109 llvm::cl::desc("Print warnings as well as errors"),
110 llvm::cl::init(false)};
111
112// Print the diagnostics meeting severity threshold, and return count of errors.
113unsigned showErrors(llvm::ArrayRef<Diag> Diags) {
114 unsigned ErrCount = 0;
115 for (const auto &D : Diags) {
116 if (D.Severity >= DiagnosticsEngine::Error || CheckWarnings)
117 elog("[{0}] Line {1}: {2}", D.Name, D.Range.start.line + 1, D.Message);
118 if (D.Severity >= DiagnosticsEngine::Error)
119 ++ErrCount;
120 }
121 return ErrCount;
122}
123
124std::vector<std::string> listTidyChecks(llvm::StringRef Glob) {
125 tidy::GlobList G(Glob);
126 tidy::ClangTidyCheckFactories CTFactories;
127 for (const auto &E : tidy::ClangTidyModuleRegistry::entries())
128 E.instantiate()->addCheckFactories(CTFactories);
129 std::vector<std::string> Result;
130 for (const auto &E : CTFactories)
131 if (G.contains(E.getKey()))
132 Result.push_back(E.getKey().str());
133 llvm::sort(Result);
134 return Result;
135}
136
137// This class is just a linear pipeline whose functions get called in sequence.
138// Each exercises part of clangd's logic on our test file and logs results.
139// Later steps depend on state built in earlier ones (such as the AST).
140// Many steps can fatally fail (return false), then subsequent ones cannot run.
141// Nonfatal failures are logged and tracked in ErrCount.
142class Checker {
143 // from constructor
144 std::string File;
145 ClangdLSPServer::Options Opts;
146 // from buildCommand
147 tooling::CompileCommand Cmd;
148 std::unique_ptr<GlobalCompilationDatabase> BaseCDB;
149 std::unique_ptr<GlobalCompilationDatabase> CDB;
150 // from buildInvocation
151 ParseInputs Inputs;
152 std::unique_ptr<CompilerInvocation> Invocation;
153 format::FormatStyle Style;
154 std::optional<ModulesBuilder> ModulesManager;
155 // from buildAST
156 std::shared_ptr<const PreambleData> Preamble;
157 std::optional<ParsedAST> AST;
158 FileIndex Index;
159
160public:
161 // Number of non-fatal errors seen.
162 unsigned ErrCount = 0;
163
164 Checker(llvm::StringRef File, const ClangdLSPServer::Options &Opts)
165 : File(File), Opts(Opts), Index(/*SupportContainedRefs=*/true) {}
166
167 // Read compilation database and choose a compile command for the file.
168 bool buildCommand(const ThreadsafeFS &TFS) {
169 log("Loading compilation database...");
170 DirectoryBasedGlobalCompilationDatabase::Options CDBOpts(TFS);
171 if (Opts.StrongWorkspaceMode)
172 CDBOpts.applyFallbackWorkingDirectory(Opts.WorkspaceRoot);
173 CDBOpts.CompileCommandsDir =
175 BaseCDB =
176 std::make_unique<DirectoryBasedGlobalCompilationDatabase>(CDBOpts);
177 auto Mangler = CommandMangler::detect();
178 Mangler.SystemIncludeExtractor =
179 getSystemIncludeExtractor(llvm::ArrayRef(Opts.QueryDriverGlobs));
180 if (Opts.ResourceDir)
181 Mangler.ResourceDir = *Opts.ResourceDir;
182
183 CDB = std::make_unique<OverlayCDB>(
184 BaseCDB.get(), std::vector<std::string>{}, std::move(Mangler),
185 CDBOpts.FallbackWorkingDirectory);
186
187 if (auto TrueCmd = CDB->getCompileCommand(File)) {
188 Cmd = std::move(*TrueCmd);
189 log("Compile command {0} is: [{1}] {2}",
190 Cmd.Heuristic.empty() ? "from CDB" : Cmd.Heuristic, Cmd.Directory,
191 printArgv(Cmd.CommandLine));
192 } else {
193 Cmd = CDB->getFallbackCommand(File);
194 log("Generic fallback command is: [{0}] {1}", Cmd.Directory,
195 printArgv(Cmd.CommandLine));
196 }
197
198 return true;
199 }
200
201 // Prepare inputs and build CompilerInvocation (parsed compile command).
202 bool buildInvocation(const ThreadsafeFS &TFS,
203 std::optional<std::string> Contents) {
204 StoreDiags CaptureInvocationDiags;
205 std::vector<std::string> CC1Args;
206 Inputs.CompileCommand = Cmd;
207 Inputs.TFS = &TFS;
208 Inputs.ClangTidyProvider = Opts.ClangTidyProvider;
209 Inputs.Opts.PreambleParseForwardingFunctions =
210 Opts.PreambleParseForwardingFunctions;
211 if (Contents) {
212 Inputs.Contents = *Contents;
213 log("Imaginary source file contents:\n{0}", Inputs.Contents);
214 } else {
215 if (auto Contents = TFS.view(std::nullopt)->getBufferForFile(File)) {
216 Inputs.Contents = Contents->get()->getBuffer().str();
217 } else {
218 elog("Couldn't read {0}: {1}", File, Contents.getError().message());
219 return false;
220 }
221 }
222 if (Opts.EnableExperimentalModulesSupport) {
223 if (!ModulesManager)
224 ModulesManager.emplace(*CDB);
225 Inputs.ModulesManager = &*ModulesManager;
226 }
227 log("Parsing command...");
228 Invocation =
229 buildCompilerInvocation(Inputs, CaptureInvocationDiags, &CC1Args);
230 auto InvocationDiags = CaptureInvocationDiags.take();
231 ErrCount += showErrors(InvocationDiags);
232 log("internal (cc1) args are: {0}", printArgv(CC1Args));
233 if (!Invocation) {
234 elog("Failed to parse command line");
235 return false;
236 }
237
238 // FIXME: Check that resource-dir/built-in-headers exist?
239
240 Style = getFormatStyleForFile(File, Inputs.Contents, TFS, false);
241
242 return true;
243 }
244
245 // Build preamble and AST, and index them.
246 bool buildAST() {
247 log("Building preamble...");
248 Preamble = buildPreamble(
249 File, *Invocation, Inputs, /*StoreInMemory=*/true,
250 [&](CapturedASTCtx Ctx,
251 std::shared_ptr<const include_cleaner::PragmaIncludes> PI) {
252 if (!Opts.BuildDynamicSymbolIndex)
253 return;
254 log("Indexing headers...");
255 Index.updatePreamble(File, /*Version=*/"null", Ctx.getASTContext(),
256 Ctx.getPreprocessor(), *PI);
257 });
258 if (!Preamble) {
259 elog("Failed to build preamble");
260 return false;
261 }
262 ErrCount += showErrors(Preamble->Diags);
263
264 log("Building AST...");
265 AST = ParsedAST::build(File, Inputs, std::move(Invocation),
266 /*InvocationDiags=*/std::vector<Diag>{}, Preamble);
267 if (!AST) {
268 elog("Failed to build AST");
269 return false;
270 }
271 ErrCount +=
272 showErrors(AST->getDiagnostics().drop_front(Preamble->Diags.size()));
273
274 if (Opts.BuildDynamicSymbolIndex) {
275 log("Indexing AST...");
276 Index.updateMain(File, *AST);
277 }
278
279 if (!CheckTidyTime.empty()) {
280 if (!CLANGD_TIDY_CHECKS) {
281 elog("-{0} requires -DCLANGD_TIDY_CHECKS!", CheckTidyTime.ArgStr);
282 return false;
283 }
284 #ifndef NDEBUG
285 elog("Timing clang-tidy checks in asserts-mode is not representative!");
286 #endif
287 checkTidyTimes();
288 }
289
290 return true;
291 }
292
293 // For each check foo, we want to build with checks=-* and checks=-*,foo.
294 // (We do a full build rather than just AST matchers to meausre PPCallbacks).
295 //
296 // However, performance has both random noise and systematic changes, such as
297 // step-function slowdowns due to CPU scaling.
298 // We take the median of 5 measurements, and after every check discard the
299 // measurement if the baseline changed by >3%.
300 void checkTidyTimes() {
301 double Stability = 0.03;
302 log("Timing AST build with individual clang-tidy checks (target accuracy "
303 "{0:P0})",
304 Stability);
305
306 using Duration = std::chrono::nanoseconds;
307 // Measure time elapsed by a block of code. Currently: user CPU time.
308 auto Time = [&](auto &&Run) -> Duration {
309 llvm::sys::TimePoint<> Elapsed;
310 std::chrono::nanoseconds UserBegin, UserEnd, System;
311 llvm::sys::Process::GetTimeUsage(Elapsed, UserBegin, System);
312 Run();
313 llvm::sys::Process::GetTimeUsage(Elapsed, UserEnd, System);
314 return UserEnd - UserBegin;
315 };
316 auto Change = [&](Duration Exp, Duration Base) -> double {
317 return (double)(Exp.count() - Base.count()) / Base.count();
318 };
319 // Build ParsedAST with a fixed check glob, and return the time taken.
320 auto Build = [&](llvm::StringRef Checks) -> Duration {
321 TidyProvider CTProvider = [&](tidy::ClangTidyOptions &Opts,
322 llvm::StringRef) {
323 Opts.Checks = Checks.str();
324 };
325 Inputs.ClangTidyProvider = CTProvider;
326 // Sigh, can't reuse the CompilerInvocation.
327 IgnoringDiagConsumer IgnoreDiags;
328 auto Invocation = buildCompilerInvocation(Inputs, IgnoreDiags);
329 Duration Val = Time([&] {
330 ParsedAST::build(File, Inputs, std::move(Invocation), {}, Preamble);
331 });
332 vlog(" Measured {0} ==> {1}", Checks, Val);
333 return Val;
334 };
335 // Measure several times, return the median.
336 auto MedianTime = [&](llvm::StringRef Checks) -> Duration {
337 std::array<Duration, 5> Measurements;
338 for (auto &M : Measurements)
339 M = Build(Checks);
340 llvm::sort(Measurements);
341 return Measurements[Measurements.size() / 2];
342 };
343 Duration Baseline = MedianTime("-*");
344 log(" Baseline = {0}", Baseline);
345 // Attempt to time a check, may update Baseline if it is unstable.
346 auto Measure = [&](llvm::StringRef Check) -> double {
347 for (;;) {
348 Duration Median = MedianTime(("-*," + Check).str());
349 Duration NewBase = MedianTime("-*");
350
351 // Value only usable if baseline is fairly consistent before/after.
352 double DeltaFraction = Change(NewBase, Baseline);
353 Baseline = NewBase;
354 vlog(" Baseline = {0}", Baseline);
355 if (DeltaFraction < -Stability || DeltaFraction > Stability) {
356 elog(" Speed unstable, discarding measurement.");
357 continue;
358 }
359 return Change(Median, Baseline);
360 }
361 };
362
363 for (const auto& Check : listTidyChecks(CheckTidyTime)) {
364 // vlog the check name in case we crash!
365 vlog(" Timing {0}", Check);
366 double Fraction = Measure(Check);
367 log(" {0} = {1:P0}", Check, Fraction);
368 }
369 log("Finished individual clang-tidy checks");
370
371 // Restore old options.
372 Inputs.ClangTidyProvider = Opts.ClangTidyProvider;
373 }
374
375 // Build Inlay Hints for the entire AST or the specified range
376 void buildInlayHints(std::optional<Range> LineRange) {
377 log("Building inlay hints");
378 auto Hints = inlayHints(*AST, LineRange);
379
380 for (const auto &Hint : Hints) {
381 vlog(" {0} {1} [{2}]", Hint.kind, Hint.position, [&] {
382 return llvm::join(llvm::map_range(Hint.label,
383 [&](auto &L) {
384 return llvm::formatv("{{{0}}", L);
385 }),
386 ", ");
387 }());
388 }
389 }
390
391 void buildSemanticHighlighting(std::optional<Range> LineRange) {
392 log("Building semantic highlighting");
393 auto Highlights =
394 getSemanticHighlightings(*AST, /*IncludeInactiveRegionTokens=*/true);
395 for (const auto HL : Highlights)
396 if (!LineRange || LineRange->contains(HL.R))
397 vlog(" {0} {1} {2}", HL.R, HL.Kind, HL.Modifiers);
398 }
399
400 // Run AST-based features at each token in the file.
401 void testLocationFeatures(std::optional<Range> LineRange) {
402 trace::Span Trace("testLocationFeatures");
403 log("Testing features at each token (may be slow in large files)");
404 auto &SM = AST->getSourceManager();
405 auto SpelledTokens = AST->getTokens().spelledTokens(SM.getMainFileID());
406
407 CodeCompleteOptions CCOpts = Opts.CodeComplete;
408 CCOpts.Index = &Index;
409
410 for (const auto &Tok : SpelledTokens) {
411 unsigned Start = AST->getSourceManager().getFileOffset(Tok.location());
412 unsigned End = Start + Tok.length();
413 Position Pos = offsetToPosition(Inputs.Contents, Start);
414
415 if (LineRange && !LineRange->contains(Pos))
416 continue;
417
418 trace::Span Trace("Token");
419 SPAN_ATTACH(Trace, "pos", Pos);
420 SPAN_ATTACH(Trace, "text", Tok.text(AST->getSourceManager()));
421
422 // FIXME: dumping the tokens may leak sensitive code into bug reports.
423 // Add an option to turn this off, once we decide how options work.
424 vlog(" {0} {1}", Pos, Tok.text(AST->getSourceManager()));
425 auto Tree = SelectionTree::createRight(AST->getASTContext(),
426 AST->getTokens(), Start, End);
427 Tweak::Selection Selection(&Index, *AST, Start, End, std::move(Tree),
428 nullptr);
429 // FS is only populated when applying a tweak, not during prepare as
430 // prepare should not do any I/O to be fast.
431 auto Tweaks =
432 prepareTweaks(Selection, Opts.TweakFilter, Opts.FeatureModules);
433 Selection.FS =
434 &AST->getSourceManager().getFileManager().getVirtualFileSystem();
435 for (const auto &T : Tweaks) {
436 auto Result = T->apply(Selection);
437 if (!Result) {
438 elog(" tweak: {0} ==> FAIL: {1}", T->id(), Result.takeError());
439 ++ErrCount;
440 } else {
441 vlog(" tweak: {0}", T->id());
442 }
443 }
444 unsigned Definitions = locateSymbolAt(*AST, Pos, &Index).size();
445 vlog(" definition: {0}", Definitions);
446
447 auto Hover = getHover(*AST, Pos, Style, &Index);
448 vlog(" hover: {0}", Hover.has_value());
449
450 unsigned DocHighlights = findDocumentHighlights(*AST, Pos).size();
451 vlog(" documentHighlight: {0}", DocHighlights);
452
453 if (CheckCompletion) {
454 Position EndPos = offsetToPosition(Inputs.Contents, End);
455 auto CC = codeComplete(File, EndPos, Preamble.get(), Inputs, CCOpts);
456 vlog(" code completion: {0}",
457 CC.Completions.empty() ? "<empty>" : CC.Completions[0].Name);
458 }
459 }
460 }
461};
462
463} // namespace
464
465bool check(llvm::StringRef File, const ThreadsafeFS &TFS,
466 const ClangdLSPServer::Options &Opts) {
467 std::optional<Range> LineRange;
468 if (!CheckFileLines.empty()) {
469 uint32_t Begin = 0, End = std::numeric_limits<uint32_t>::max();
470 StringRef RangeStr(CheckFileLines);
471 bool ParseError = RangeStr.consumeInteger(0, Begin);
472 if (RangeStr.empty()) {
473 End = Begin;
474 } else {
475 ParseError |= !RangeStr.consume_front("-");
476 ParseError |= RangeStr.consumeInteger(0, End);
477 }
478 if (ParseError || !RangeStr.empty() || Begin <= 0 || End < Begin) {
479 elog("Invalid --check-lines specified. Use Begin-End format, e.g. 3-17");
480 return false;
481 }
482 LineRange = Range{Position{static_cast<int>(Begin - 1), 0},
483 Position{static_cast<int>(End), 0}};
484 }
485
486 llvm::SmallString<0> FakeFile;
487 std::optional<std::string> Contents;
488 if (File.empty()) {
489 llvm::sys::path::system_temp_directory(false, FakeFile);
490 llvm::sys::path::append(FakeFile, "test.cc");
491 File = FakeFile;
492 Contents = R"cpp(
493 #include <stddef.h>
494 #include <string>
495
496 size_t N = 50;
497 auto xxx = std::string(N, 'x');
498 )cpp";
499 }
500 log("Testing on source file {0}", File);
501
502 class OverrideConfigProvider : public config::Provider {
503 std::vector<config::CompiledFragment>
504 getFragments(const config::Params &,
505 config::DiagnosticCallback Diag) const override {
507 // If we're timing clang-tidy checks, implicitly disabling the slow ones
508 // is counterproductive!
509 if (CheckTidyTime.getNumOccurrences())
510 F.Diagnostics.ClangTidy.FastCheckFilter.emplace("None");
511 return {std::move(F).compile(Diag)};
512 }
513 } OverrideConfig;
514 auto ConfigProvider =
515 config::Provider::combine({Opts.ConfigProvider, &OverrideConfig});
516
518 ConfigProvider.get(), nullptr);
519 WithContext Ctx(ContextProvider(
520 FakeFile.empty()
521 ? File
522 : /*Don't turn on local configs for an arbitrary temp path.*/ ""));
523 Checker C(File, Opts);
524 if (!C.buildCommand(TFS) || !C.buildInvocation(TFS, Contents) ||
525 !C.buildAST())
526 return false;
527 C.buildInlayHints(LineRange);
528 C.buildSemanticHighlighting(LineRange);
529 if (CheckLocations)
530 C.testLocationFeatures(LineRange);
531
532 log("All checks completed, {0} errors", C.ErrCount);
533 return C.ErrCount == 0;
534}
535
536} // namespace clangd
537} // namespace clang
static cl::opt< std::string > Checks("checks", desc(R"( Comma-separated list of globs with optional '-' prefix. Globs are processed in order of appearance in the list. Globs without '-' prefix add checks with matching names to the set, globs with the '-' prefix remove checks with matching names from the set of enabled checks. This option's value is appended to the value of the 'Checks' option in .clang-tidy file, if any. )"), cl::init(""), cl::cat(ClangTidyCategory))
void elog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:61
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
Definition Trace.h:164
static std::function< Context(PathRef)> createConfiguredContextProvider(const config::Provider *Provider, ClangdServer::Callbacks *)
Creates a context provider that loads and installs config.
static std::optional< ParsedAST > build(llvm::StringRef Filename, const ParseInputs &Inputs, std::unique_ptr< clang::CompilerInvocation > CI, llvm::ArrayRef< Diag > CompilerInvocationDiags, std::shared_ptr< const PreambleData > Preamble)
Attempts to run Clang and store the parsed AST.
static SelectionTree createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End)
Wrapper for vfs::FileSystem for use in multithreaded programs like clangd.
WithContext replaces Context::current() with a provided scope.
Definition Context.h:185
A source of configuration fragments.
static std::unique_ptr< Provider > combine(std::vector< const Provider * >)
A provider that includes fragments from all the supplied providers.
Records an event whose duration is the lifetime of the Span object.
Definition Trace.h:143
llvm::function_ref< void(const llvm::SMDiagnostic &)> DiagnosticCallback
Used to report problems in parsing or interpreting a config.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:44
llvm::unique_function< void(tidy::ClangTidyOptions &, llvm::StringRef) const > TidyProvider
A factory to modify a tidy::ClangTidyOptions.
std::vector< HighlightingToken > getSemanticHighlightings(ParsedAST &AST, bool IncludeInactiveRegionTokens)
SystemIncludeExtractorFn getSystemIncludeExtractor(llvm::ArrayRef< std::string > QueryDriverGlobs)
Position offsetToPosition(llvm::StringRef Code, size_t Offset)
Turn an offset in Code into a [line, column] pair.
std::vector< DocumentHighlight > findDocumentHighlights(ParsedAST &AST, Position Pos)
Returns highlights for all usages of a symbol at Pos.
Definition XRefs.cpp:1313
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
void vlog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:72
std::optional< HoverInfo > getHover(ParsedAST &AST, Position Pos, const format::FormatStyle &Style, const SymbolIndex *Index)
Get the hover information when hovering at Pos.
Definition Hover.cpp:1255
std::vector< LocatedSymbol > locateSymbolAt(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Get definition of symbol at a specified Pos.
Definition XRefs.cpp:776
std::shared_ptr< const PreambleData > buildPreamble(PathRef FileName, CompilerInvocation CI, const ParseInputs &Inputs, bool StoreInMemory, PreambleParsedCallback PreambleCallback, PreambleBuildStats *Stats)
Build a preamble for the new inputs unless an old one can be reused.
Definition Preamble.cpp:571
void log(const char *Fmt, Ts &&... Vals)
Definition Logger.h:67
std::string printArgv(llvm::ArrayRef< llvm::StringRef > Args)
std::vector< std::unique_ptr< Tweak > > prepareTweaks(const Tweak::Selection &S, llvm::function_ref< bool(const Tweak &)> Filter, const FeatureModuleSet *Modules)
Calls prepare() on all tweaks that satisfy the filter, returning those that can run on the selection.
Definition Tweak.cpp:72
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.
bool check(llvm::StringRef File, const ThreadsafeFS &TFS, const ClangdLSPServer::Options &Opts)
Definition Check.cpp:465
void elog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:61
std::vector< InlayHint > inlayHints(ParsedAST &AST, std::optional< Range > RestrictRange, InlayHintOptions HintOptions)
Compute and return inlay hints for a file.
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++ -*-===//
config::Provider * ConfigProvider
Supplies configuration (overrides ClangdServer::ContextProvider).
static CommandMangler detect()
std::optional< std::string > FixedCDBPath
Definition Config.h:59
struct clang::clangd::Config::@347104204155140144054042115114221214347344026246 CompileFlags
Controls how the compile command for the current file is determined.
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition Config.cpp:17
CDBSearchSpec CDBSearch
Where to search for compilation databases for this file's flags.
Definition Config.h:69
A top-level diagnostic that may have Notes and Fixes.
Definition Diagnostics.h:98
Input to prepare and apply tweaks.
Definition Tweak.h:49
std::optional< Located< std::string > > FastCheckFilter
Whether to run checks that may slow down clangd.
A chunk of configuration obtained from a config file, LSP, or elsewhere.
Describes the context used to evaluate configuration fragments.