27#include "../clang-tidy/ClangTidyModule.h"
28#include "../clang-tidy/ClangTidyOptions.h"
29#include "../clang-tidy/GlobList.h"
52#include "clang-include-cleaner/Record.h"
59#include "clang/AST/ASTContext.h"
60#include "clang/Basic/Diagnostic.h"
61#include "clang/Basic/LLVM.h"
62#include "clang/Format/Format.h"
63#include "clang/Frontend/CompilerInvocation.h"
64#include "clang/Tooling/CompilationDatabase.h"
65#include "llvm/ADT/ArrayRef.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/ScopeExit.h"
68#include "llvm/ADT/SmallString.h"
69#include "llvm/Support/Chrono.h"
70#include "llvm/Support/CommandLine.h"
71#include "llvm/Support/Path.h"
72#include "llvm/Support/Process.h"
87llvm::cl::opt<std::string> CheckTidyTime{
89 llvm::cl::desc(
"Print the overhead of checks matching this glob"),
91llvm::cl::opt<std::string> CheckFileLines{
94 "Limits the range of tokens in -check file on which "
95 "various features are tested. Example --check-lines=3-7 restricts "
96 "testing to lines 3 to 7 (inclusive) or --check-lines=5 to restrict "
97 "to one line. Default is testing entire file."),
99llvm::cl::opt<bool> CheckLocations{
102 "Runs certain features (e.g. hover) at each point in the file. "
104 llvm::cl::init(
true)};
105llvm::cl::opt<bool> CheckCompletion{
107 llvm::cl::desc(
"Run code-completion at each point (slow)"),
108 llvm::cl::init(
false)};
109llvm::cl::opt<bool> CheckWarnings{
111 llvm::cl::desc(
"Print warnings as well as errors"),
112 llvm::cl::init(
false)};
115unsigned showErrors(llvm::ArrayRef<Diag> Diags) {
116 unsigned ErrCount = 0;
117 for (
const auto &D : Diags) {
118 if (
D.Severity >= DiagnosticsEngine::Error || CheckWarnings)
119 elog(
"[{0}] Line {1}: {2}",
D.Name,
D.Range.start.line + 1,
D.Message);
120 if (
D.Severity >= DiagnosticsEngine::Error)
126std::vector<std::string> listTidyChecks(llvm::StringRef Glob) {
127 tidy::GlobList G(Glob);
128 tidy::ClangTidyCheckFactories CTFactories;
129 for (
const auto &E : tidy::ClangTidyModuleRegistry::entries())
130 E.instantiate()->addCheckFactories(CTFactories);
131 std::vector<std::string> Result;
132 for (
const auto &E : CTFactories)
133 if (G.contains(E.getKey()))
134 Result.push_back(E.getKey().str());
147 const ClangdLSPServer::Options &Opts;
149 tooling::CompileCommand Cmd;
150 std::unique_ptr<GlobalCompilationDatabase> BaseCDB;
151 std::unique_ptr<GlobalCompilationDatabase> CDB;
154 std::unique_ptr<CompilerInvocation> Invocation;
155 format::FormatStyle Style;
156 std::optional<ModulesBuilder> ModulesManager;
158 std::shared_ptr<const PreambleData> Preamble;
159 std::optional<ParsedAST> AST;
164 unsigned ErrCount = 0;
166 Checker(llvm::StringRef File,
const ClangdLSPServer::Options &Opts)
167 : File(File), Opts(Opts), Index(true) {}
170 bool buildCommand(
const ThreadsafeFS &TFS) {
171 log(
"Loading compilation database...");
172 DirectoryBasedGlobalCompilationDatabase::Options CDBOpts(TFS);
173 if (Opts.StrongWorkspaceMode)
174 CDBOpts.applyFallbackWorkingDirectory(Opts.WorkspaceRoot);
175 CDBOpts.CompileCommandsDir =
178 std::make_unique<DirectoryBasedGlobalCompilationDatabase>(CDBOpts);
180 Mangler.SystemIncludeExtractor =
182 if (Opts.ResourceDir)
183 Mangler.ResourceDir = *Opts.ResourceDir;
185 CDB = std::make_unique<OverlayCDB>(
186 BaseCDB.get(), std::vector<std::string>{}, std::move(Mangler),
187 CDBOpts.FallbackWorkingDirectory);
189 if (
auto TrueCmd = CDB->getCompileCommand(File)) {
190 Cmd = std::move(*TrueCmd);
191 log(
"Compile command {0} is: [{1}] {2}",
192 Cmd.Heuristic.empty() ?
"from CDB" : Cmd.Heuristic, Cmd.Directory,
195 Cmd = CDB->getFallbackCommand(File);
196 log(
"Generic fallback command is: [{0}] {1}", Cmd.Directory,
204 bool buildInvocation(
const ThreadsafeFS &TFS,
205 std::optional<std::string> Contents) {
206 StoreDiags CaptureInvocationDiags;
207 std::vector<std::string> CC1Args;
208 Inputs.CompileCommand = Cmd;
210 Inputs.FeatureModules = Opts.FeatureModules;
211 Inputs.Opts.PreambleParseForwardingFunctions =
212 Opts.PreambleParseForwardingFunctions;
214 Inputs.Contents = *Contents;
215 log(
"Imaginary source file contents:\n{0}", Inputs.Contents);
217 if (
auto Contents = TFS.view(std::nullopt)->getBufferForFile(File)) {
218 Inputs.Contents = Contents->get()->getBuffer().str();
220 elog(
"Couldn't read {0}: {1}", File, Contents.getError().message());
224 if (Opts.EnableExperimentalModulesSupport) {
226 ModulesManager.emplace(*CDB);
227 Inputs.ModulesManager = &*ModulesManager;
229 log(
"Parsing command...");
232 auto InvocationDiags = CaptureInvocationDiags.take();
233 ErrCount += showErrors(InvocationDiags);
234 log(
"internal (cc1) args are: {0}",
printArgv(CC1Args));
236 elog(
"Failed to parse command line");
249 log(
"Building preamble...");
251 File, *Invocation, Inputs,
true,
252 [&](CapturedASTCtx Ctx,
253 std::shared_ptr<const include_cleaner::PragmaIncludes> PI) {
254 if (!Opts.BuildDynamicSymbolIndex)
256 log(
"Indexing headers...");
257 Index.updatePreamble(File,
"null", Ctx.getASTContext(),
258 Ctx.getPreprocessor(), *PI);
261 elog(
"Failed to build preamble");
264 ErrCount += showErrors(Preamble->Diags);
266 log(
"Building AST...");
268 std::vector<Diag>{}, Preamble);
270 elog(
"Failed to build AST");
274 showErrors(AST->getDiagnostics().drop_front(Preamble->Diags.size()));
276 if (Opts.BuildDynamicSymbolIndex) {
277 log(
"Indexing AST...");
278 Index.updateMain(File, *AST);
281 if (!CheckTidyTime.empty()) {
282 if (!CLANGD_TIDY_CHECKS) {
283 elog(
"-{0} requires -DCLANGD_TIDY_CHECKS!", CheckTidyTime.ArgStr);
287 elog(
"Timing clang-tidy checks in asserts-mode is not representative!");
289 if (!checkTidyTimes())
303 bool checkTidyTimes() {
306 Inputs.FeatureModules
307 ? Inputs.FeatureModules->get<ClangTidyFeatureModule>()
310 elog(
"Cannot time clang-tidy checks without a clang-tidy feature module");
313 double Stability = 0.03;
314 log(
"Timing AST build with individual clang-tidy checks (target accuracy "
318 using Duration = std::chrono::nanoseconds;
320 auto Time = [&](
auto &&Run) -> Duration {
321 llvm::sys::TimePoint<> Elapsed;
322 std::chrono::nanoseconds UserBegin, UserEnd, System;
323 llvm::sys::Process::GetTimeUsage(Elapsed, UserBegin, System);
325 llvm::sys::Process::GetTimeUsage(Elapsed, UserEnd, System);
326 return UserEnd - UserBegin;
328 auto Change = [&](Duration Exp, Duration Base) ->
double {
329 return (
double)(Exp.count() - Base.count()) / Base.count();
332 auto Build = [&](llvm::StringRef
Checks) -> Duration {
333 TidyProvider CTProvider = [&](tidy::ClangTidyOptions &Opts,
335 Opts.Checks =
Checks.str();
338 std::make_shared<const TidyProvider>(std::move(CTProvider));
339 TidyModule->swapProvider(Provider);
341 llvm::scope_exit RestoreProvider(
342 [&] { TidyModule->swapProvider(Provider); });
344 IgnoringDiagConsumer IgnoreDiags;
346 Duration Val = Time([&] {
353 auto MedianTime = [&](llvm::StringRef
Checks) -> Duration {
354 std::array<Duration, 5> Measurements;
355 for (
auto &M : Measurements)
357 llvm::sort(Measurements);
358 return Measurements[Measurements.size() / 2];
360 Duration Baseline = MedianTime(
"-*");
361 log(
" Baseline = {0}", Baseline);
363 auto Measure = [&](llvm::StringRef Check) ->
double {
365 Duration Median = MedianTime((
"-*," + Check).str());
366 Duration NewBase = MedianTime(
"-*");
369 double DeltaFraction = Change(NewBase, Baseline);
371 vlog(
" Baseline = {0}", Baseline);
372 if (DeltaFraction < -Stability || DeltaFraction > Stability) {
373 elog(
" Speed unstable, discarding measurement.");
376 return Change(Median, Baseline);
380 for (
const auto& Check : listTidyChecks(CheckTidyTime)) {
382 vlog(
" Timing {0}", Check);
383 double Fraction = Measure(Check);
384 log(
" {0} = {1:P0}", Check, Fraction);
386 log(
"Finished individual clang-tidy checks");
391 void buildInlayHints(std::optional<Range> LineRange) {
392 log(
"Building inlay hints");
395 for (
const auto &Hint : Hints) {
396 vlog(
" {0} {1} [{2}]", Hint.kind, Hint.position, [&] {
397 return llvm::join(llvm::map_range(Hint.label,
399 return llvm::formatv(
"{{{0}}", L);
406 void buildSemanticHighlighting(std::optional<Range> LineRange) {
407 log(
"Building semantic highlighting");
410 for (
const auto HL : Highlights)
411 if (!LineRange || LineRange->contains(HL.R))
412 vlog(
" {0} {1} {2}", HL.R, HL.Kind, HL.Modifiers);
416 void testLocationFeatures(std::optional<Range> LineRange) {
418 log(
"Testing features at each token (may be slow in large files)");
419 auto &SM =
AST->getSourceManager();
420 auto SpelledTokens =
AST->getTokens().spelledTokens(SM.getMainFileID());
423 CCOpts.Index = &Index;
425 for (
const auto &Tok : SpelledTokens) {
426 unsigned Start =
AST->getSourceManager().getFileOffset(Tok.location());
427 unsigned End = Start + Tok.length();
430 if (LineRange && !LineRange->contains(Pos))
439 vlog(
" {0} {1}", Pos, Tok.text(
AST->getSourceManager()));
441 AST->getTokens(), Start, End);
447 prepareTweaks(Selection, Opts.TweakFilter, Opts.FeatureModules);
449 &
AST->getSourceManager().getFileManager().getVirtualFileSystem();
450 for (
const auto &T : Tweaks) {
451 auto Result =
T->apply(Selection);
453 elog(
" tweak: {0} ==> FAIL: {1}",
T->id(), Result.takeError());
456 vlog(
" tweak: {0}",
T->id());
460 vlog(
" definition: {0}", Definitions);
466 vlog(
" documentHighlight: {0}", DocHighlights);
468 if (CheckCompletion) {
471 vlog(
" code completion: {0}",
472 CC.Completions.empty() ?
"<empty>" : CC.Completions[0].Name);
482 std::optional<Range> LineRange;
483 if (!CheckFileLines.empty()) {
484 uint32_t Begin = 0, End = std::numeric_limits<uint32_t>::max();
485 StringRef RangeStr(CheckFileLines);
486 bool ParseError = RangeStr.consumeInteger(0, Begin);
487 if (RangeStr.empty()) {
491 ParseError |= RangeStr.consumeInteger(0, End);
493 if (
ParseError || !RangeStr.empty() || Begin <= 0 || End < Begin) {
494 elog(
"Invalid --check-lines specified. Use Begin-End format, e.g. 3-17");
498 Position{
static_cast<int>(End), 0}};
501 llvm::SmallString<0> FakeFile;
502 std::optional<std::string> Contents;
504 llvm::sys::path::system_temp_directory(
false, FakeFile);
505 llvm::sys::path::append(FakeFile,
"test.cc");
512 auto xxx = std::string(N, 'x');
515 log("Testing on source file {0}",
File);
518 std::vector<config::CompiledFragment>
524 if (CheckTidyTime.getNumOccurrences())
526 return {std::move(F).compile(
Diag)};
529 std::vector<std::unique_ptr<config::Provider>> ConfigProviders;
530 ConfigProviders.push_back(std::move(Opts.ConfigProvider));
531 ConfigProviders.push_back(std::make_unique<OverrideConfigProvider>());
535 ConfigProvider.get(),
nullptr);
540 Checker C(
File, Opts);
541 if (!C.buildCommand(TFS) || !C.buildInvocation(TFS, Contents) ||
544 C.buildInlayHints(LineRange);
545 C.buildSemanticHighlighting(LineRange);
547 C.testLocationFeatures(LineRange);
549 log(
"All checks completed, {0} errors", C.ErrCount);
550 return C.ErrCount == 0;
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)
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
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.
A source of configuration fragments.
static std::unique_ptr< Provider > combine(std::vector< std::unique_ptr< Provider > >)
A provider that includes fragments from all the supplied providers.
Records an event whose duration is the lifetime of the Span object.
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.
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)
bool check(llvm::StringRef File, const ThreadsafeFS &TFS, ClangdLSPServer::Options &&Opts)
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.
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.
void vlog(const char *Fmt, Ts &&... Vals)
std::optional< HoverInfo > getHover(ParsedAST &AST, Position Pos, const format::FormatStyle &Style, const SymbolIndex *Index)
Get the hover information when hovering at Pos.
std::vector< LocatedSymbol > locateSymbolAt(ParsedAST &AST, Position Pos, const SymbolIndex *Index)
Get definition of symbol at a specified Pos.
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.
void log(const char *Fmt, Ts &&... Vals)
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.
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.
void elog(const char *Fmt, Ts &&... Vals)
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++ -*-===//
static CommandMangler detect()
std::optional< std::string > FixedCDBPath
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.
CDBSearchSpec CDBSearch
Where to search for compilation databases for this file's flags.
A top-level diagnostic that may have Notes and Fixes.
Input to prepare and apply tweaks.
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.
DiagnosticsBlock Diagnostics
Describes the context used to evaluate configuration fragments.