27#include "../clang-tidy/ClangTidyModule.h"
28#include "../clang-tidy/ClangTidyOptions.h"
29#include "../clang-tidy/GlobList.h"
51#include "clang-include-cleaner/Record.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"
85llvm::cl::opt<std::string> CheckTidyTime{
87 llvm::cl::desc(
"Print the overhead of checks matching this glob"),
89llvm::cl::opt<std::string> CheckFileLines{
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."),
97llvm::cl::opt<bool> CheckLocations{
100 "Runs certain features (e.g. hover) at each point in the file. "
102 llvm::cl::init(
true)};
103llvm::cl::opt<bool> CheckCompletion{
105 llvm::cl::desc(
"Run code-completion at each point (slow)"),
106 llvm::cl::init(
false)};
107llvm::cl::opt<bool> CheckWarnings{
109 llvm::cl::desc(
"Print warnings as well as errors"),
110 llvm::cl::init(
false)};
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)
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());
145 ClangdLSPServer::Options Opts;
147 tooling::CompileCommand Cmd;
148 std::unique_ptr<GlobalCompilationDatabase> BaseCDB;
149 std::unique_ptr<GlobalCompilationDatabase> CDB;
152 std::unique_ptr<CompilerInvocation> Invocation;
153 format::FormatStyle Style;
154 std::optional<ModulesBuilder> ModulesManager;
156 std::shared_ptr<const PreambleData> Preamble;
157 std::optional<ParsedAST> AST;
162 unsigned ErrCount = 0;
164 Checker(llvm::StringRef File,
const ClangdLSPServer::Options &Opts)
165 : File(File), Opts(Opts), Index(true) {}
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 =
176 std::make_unique<DirectoryBasedGlobalCompilationDatabase>(CDBOpts);
178 Mangler.SystemIncludeExtractor =
180 if (Opts.ResourceDir)
181 Mangler.ResourceDir = *Opts.ResourceDir;
183 CDB = std::make_unique<OverlayCDB>(
184 BaseCDB.get(), std::vector<std::string>{}, std::move(Mangler),
185 CDBOpts.FallbackWorkingDirectory);
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,
193 Cmd = CDB->getFallbackCommand(File);
194 log(
"Generic fallback command is: [{0}] {1}", Cmd.Directory,
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;
208 Inputs.ClangTidyProvider = Opts.ClangTidyProvider;
209 Inputs.Opts.PreambleParseForwardingFunctions =
210 Opts.PreambleParseForwardingFunctions;
212 Inputs.Contents = *Contents;
213 log(
"Imaginary source file contents:\n{0}", Inputs.Contents);
215 if (
auto Contents = TFS.view(std::nullopt)->getBufferForFile(File)) {
216 Inputs.Contents = Contents->get()->getBuffer().str();
218 elog(
"Couldn't read {0}: {1}", File, Contents.getError().message());
222 if (Opts.EnableExperimentalModulesSupport) {
224 ModulesManager.emplace(*CDB);
225 Inputs.ModulesManager = &*ModulesManager;
227 log(
"Parsing command...");
230 auto InvocationDiags = CaptureInvocationDiags.take();
231 ErrCount += showErrors(InvocationDiags);
232 log(
"internal (cc1) args are: {0}",
printArgv(CC1Args));
234 elog(
"Failed to parse command line");
247 log(
"Building preamble...");
249 File, *Invocation, Inputs,
true,
250 [&](CapturedASTCtx Ctx,
251 std::shared_ptr<const include_cleaner::PragmaIncludes> PI) {
252 if (!Opts.BuildDynamicSymbolIndex)
254 log(
"Indexing headers...");
255 Index.updatePreamble(File,
"null", Ctx.getASTContext(),
256 Ctx.getPreprocessor(), *PI);
259 elog(
"Failed to build preamble");
262 ErrCount += showErrors(Preamble->Diags);
264 log(
"Building AST...");
266 std::vector<Diag>{}, Preamble);
268 elog(
"Failed to build AST");
272 showErrors(AST->getDiagnostics().drop_front(Preamble->Diags.size()));
274 if (Opts.BuildDynamicSymbolIndex) {
275 log(
"Indexing AST...");
276 Index.updateMain(File, *AST);
279 if (!CheckTidyTime.empty()) {
280 if (!CLANGD_TIDY_CHECKS) {
281 elog(
"-{0} requires -DCLANGD_TIDY_CHECKS!", CheckTidyTime.ArgStr);
285 elog(
"Timing clang-tidy checks in asserts-mode is not representative!");
300 void checkTidyTimes() {
301 double Stability = 0.03;
302 log(
"Timing AST build with individual clang-tidy checks (target accuracy "
306 using Duration = std::chrono::nanoseconds;
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);
313 llvm::sys::Process::GetTimeUsage(Elapsed, UserEnd, System);
314 return UserEnd - UserBegin;
316 auto Change = [&](Duration Exp, Duration Base) ->
double {
317 return (
double)(Exp.count() - Base.count()) / Base.count();
320 auto Build = [&](llvm::StringRef
Checks) -> Duration {
321 TidyProvider CTProvider = [&](tidy::ClangTidyOptions &Opts,
323 Opts.Checks =
Checks.str();
325 Inputs.ClangTidyProvider = CTProvider;
327 IgnoringDiagConsumer IgnoreDiags;
329 Duration Val = Time([&] {
336 auto MedianTime = [&](llvm::StringRef
Checks) -> Duration {
337 std::array<Duration, 5> Measurements;
338 for (
auto &M : Measurements)
340 llvm::sort(Measurements);
341 return Measurements[Measurements.size() / 2];
343 Duration Baseline = MedianTime(
"-*");
344 log(
" Baseline = {0}", Baseline);
346 auto Measure = [&](llvm::StringRef Check) ->
double {
348 Duration Median = MedianTime((
"-*," + Check).str());
349 Duration NewBase = MedianTime(
"-*");
352 double DeltaFraction = Change(NewBase, Baseline);
354 vlog(
" Baseline = {0}", Baseline);
355 if (DeltaFraction < -Stability || DeltaFraction > Stability) {
356 elog(
" Speed unstable, discarding measurement.");
359 return Change(Median, Baseline);
363 for (
const auto& Check : listTidyChecks(CheckTidyTime)) {
365 vlog(
" Timing {0}", Check);
366 double Fraction = Measure(Check);
367 log(
" {0} = {1:P0}", Check, Fraction);
369 log(
"Finished individual clang-tidy checks");
372 Inputs.ClangTidyProvider = Opts.ClangTidyProvider;
376 void buildInlayHints(std::optional<Range> LineRange) {
377 log(
"Building inlay hints");
380 for (
const auto &Hint : Hints) {
381 vlog(
" {0} {1} [{2}]", Hint.kind, Hint.position, [&] {
382 return llvm::join(llvm::map_range(Hint.label,
384 return llvm::formatv(
"{{{0}}", L);
391 void buildSemanticHighlighting(std::optional<Range> LineRange) {
392 log(
"Building semantic highlighting");
395 for (
const auto HL : Highlights)
396 if (!LineRange || LineRange->contains(HL.R))
397 vlog(
" {0} {1} {2}", HL.R, HL.Kind, HL.Modifiers);
401 void testLocationFeatures(std::optional<Range> LineRange) {
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());
408 CCOpts.Index = &Index;
410 for (
const auto &Tok : SpelledTokens) {
411 unsigned Start =
AST->getSourceManager().getFileOffset(Tok.location());
412 unsigned End = Start + Tok.length();
415 if (LineRange && !LineRange->contains(Pos))
424 vlog(
" {0} {1}", Pos, Tok.text(
AST->getSourceManager()));
426 AST->getTokens(), Start, End);
432 prepareTweaks(Selection, Opts.TweakFilter, Opts.FeatureModules);
434 &
AST->getSourceManager().getFileManager().getVirtualFileSystem();
435 for (
const auto &T : Tweaks) {
436 auto Result =
T->apply(Selection);
438 elog(
" tweak: {0} ==> FAIL: {1}",
T->id(), Result.takeError());
441 vlog(
" tweak: {0}",
T->id());
445 vlog(
" definition: {0}", Definitions);
451 vlog(
" documentHighlight: {0}", DocHighlights);
453 if (CheckCompletion) {
456 vlog(
" code completion: {0}",
457 CC.Completions.empty() ?
"<empty>" : CC.Completions[0].Name);
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()) {
476 ParseError |= RangeStr.consumeInteger(0, End);
478 if (
ParseError || !RangeStr.empty() || Begin <= 0 || End < Begin) {
479 elog(
"Invalid --check-lines specified. Use Begin-End format, e.g. 3-17");
483 Position{
static_cast<int>(End), 0}};
486 llvm::SmallString<0> FakeFile;
487 std::optional<std::string> Contents;
489 llvm::sys::path::system_temp_directory(
false, FakeFile);
490 llvm::sys::path::append(FakeFile,
"test.cc");
497 auto xxx = std::string(N, 'x');
500 log("Testing on source file {0}",
File);
503 std::vector<config::CompiledFragment>
509 if (CheckTidyTime.getNumOccurrences())
511 return {std::move(F).compile(
Diag)};
514 auto ConfigProvider =
518 ConfigProvider.get(),
nullptr);
523 Checker C(
File, Opts);
524 if (!C.buildCommand(TFS) || !C.buildInvocation(TFS, Contents) ||
527 C.buildInlayHints(LineRange);
528 C.buildSemanticHighlighting(LineRange);
530 C.testLocationFeatures(LineRange);
532 log(
"All checks completed, {0} errors", C.ErrCount);
533 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< const 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)
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.
bool check(llvm::StringRef File, const ThreadsafeFS &TFS, const ClangdLSPServer::Options &Opts)
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++ -*-===//
config::Provider * ConfigProvider
Supplies configuration (overrides ClangdServer::ContextProvider).
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.