18#include "../ClangTidy.h"
19#include "../ClangTidyForceLinker.h"
20#include "../GlobList.h"
21#include "clang/Tooling/CommonOptionsParser.h"
22#include "llvm/ADT/StringSet.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/InitLLVM.h"
25#include "llvm/Support/PluginLoader.h"
26#include "llvm/Support/Process.h"
27#include "llvm/Support/Signals.h"
28#include "llvm/Support/TargetSelect.h"
29#include "llvm/Support/WithColor.h"
30#include "llvm/TargetParser/Host.h"
36static cl::desc
desc(StringRef description) {
return {description.ltrim()}; }
40static cl::extrahelp
CommonHelp(CommonOptionsParser::HelpMessage);
43 A large number of options or source files can be passed as parameter files
44 by use '@parameter-file' in the command line.
48 clang-tidy attempts to read configuration for each source file from a
49 .clang-tidy file located in the closest parent directory of the source
50 file. The .clang-tidy file is specified in YAML format. If any configuration
51 options have a corresponding command-line option, command-line option takes
54 The following configuration options may be used in a .clang-tidy file:
56 CheckOptions - List of key-value pairs defining check-specific
59 some-check.SomeOption: 'some value'
60 Checks - Same as '--checks'. Additionally, the list of
61 globs can be specified as a list instead of a
63 ExcludeHeaderFilterRegex - Same as '--exclude-header-filter'.
64 ExtraArgs - Same as '--extra-arg'.
65 ExtraArgsBefore - Same as '--extra-arg-before'.
66 FormatStyle - Same as '--format-style'.
67 HeaderFileExtensions - File extensions to consider to determine if a
68 given diagnostic is located in a header file.
69 HeaderFilterRegex - Same as '--header-filter'.
70 ImplementationFileExtensions - File extensions to consider to determine if a
71 given diagnostic is located in an
73 InheritParentConfig - If this option is true in a config file, the
74 configuration file in the parent directory
75 (if any exists) will be taken and the current
76 config file will be applied on top of the
78 SystemHeaders - Same as '--system-headers'.
79 UseColor - Same as '--use-color'.
80 User - Specifies the name or e-mail of the user
81 running clang-tidy. This option is used, for
82 example, to place the correct user name in
83 TODO() comments in the relevant check.
84 WarningsAsErrors - Same as '--warnings-as-errors'.
86 The effective configuration can be inspected using --dump-config:
88 $ clang-tidy --dump-config
90 Checks: '-*,some-check'
92 HeaderFileExtensions: ['', 'h','hh','hpp','hxx']
93 ImplementationFileExtensions: ['c','cc','cpp','cxx']
96 InheritParentConfig: true
99 some-check.SomeOption: 'some value'
105 "clang-diagnostic-*,"
108static cl::opt<std::string> Checks(
"checks",
desc(R
"(
109Comma-separated list of globs with optional '-'
110prefix. Globs are processed in order of
111appearance in the list. Globs without '-'
112prefix add checks with matching names to the
113set, globs with the '-' prefix remove checks
114with matching names from the set of enabled
115checks. This option's value is appended to the
116value of the 'Checks' option in .clang-tidy
121static cl::opt<std::string> WarningsAsErrors(
"warnings-as-errors",
desc(R
"(
122Upgrades warnings to errors. Same format as
124This option's value is appended to the value of
125the 'WarningsAsErrors' option in .clang-tidy
132Regular expression matching the names of the
133headers to output diagnostics from. Diagnostics
134from the main file of each translation unit are
136Can be used together with -line-filter.
137This option overrides the 'HeaderFilterRegex'
138option in .clang-tidy file, if any.
145Regular expression matching the names of the
146headers to exclude diagnostics from. Diagnostics
147from the main file of each translation unit are
149Must be used together with --header-filter.
150Can be used together with -line-filter.
151This option overrides the 'ExcludeHeaderFilterRegex'
152option in .clang-tidy file, if any.
158Display the errors from system headers.
159This option overrides the 'SystemHeaders' option
160in .clang-tidy file, if any.
165List of files with line ranges to filter the
166warnings. Can be used together with
167-header-filter. The format of the list is a
168JSON array of objects:
170 {"name":"file1.cpp","lines":[[1,3],[5,7]]},
177static cl::opt<bool>
Fix(
"fix",
desc(R
"(
178Apply suggested fixes. Without -fix-errors
179clang-tidy will bail out if any compilation
185Apply suggested fixes even if compilation
186errors were found. If compiler errors have
187attached fix-its, clang-tidy will apply them as
193If a warning has no fix, but a single fix can
194be found through an associated diagnostic note,
196Specifying this flag will implicitly enable the
202Style for formatting code around applied fixes:
203 - 'none' (default) turns off formatting
204 - 'file' (literally 'file', not a placeholder)
205 uses .clang-format file in the closest parent
207 - '{ <json> }' specifies options inline, e.g.
208 -format-style='{BasedOnStyle: llvm, IndentWidth: 8}'
209 - 'llvm', 'google', 'webkit', 'mozilla'
210See clang-format documentation for the up-to-date
211information about formatting styles and options.
212This option overrides the 'FormatStyle` option in
213.clang-tidy file, if any.
219List all enabled checks and exit. Use with
220-checks=* to list all available checks.
225For each enabled check explains, where it is
226enabled, i.e. in clang-tidy binary, command
227line or a specific configuration file.
231static cl::opt<std::string>
Config(
"config",
desc(R
"(
232Specifies a configuration in YAML/JSON format:
233 -config="{Checks: '*',
234 CheckOptions: {x: y}}"
235When the value is empty, clang-tidy will
236attempt to find a file named .clang-tidy for
237each source file in its parent directories.
242Specify the path of .clang-tidy or custom config file:
243 e.g. --config-file=/some/path/myTidyConfigFile
244This option internally works exactly the same way as
245 --config option after reading specified config file.
246Use either --config-file or --config, not both.
252Dumps configuration in the YAML format to
253stdout. This option can be used along with a
254file name (and '--' if the file is outside of a
255project with configured compilation database).
256The configuration used for this file will be
258Use along with -checks=* to include
259configuration of all checks.
264Enable per-check timing profiles, and print a
271By default reports are printed in tabulated
272format to stderr. When this option is passed,
273these per-TU profiles are instead stored as JSON.
275 cl::value_desc("prefix"),
283 cl::init(
false), cl::Hidden,
288Enables preprocessor-level module header parsing
289for C++20 and above, empowering specific checks
290to detect macro definitions within modules. This
291feature may cause performance and parsing issues
292and is therefore considered experimental.
298YAML file to store suggested fixes in. The
299stored fixes can be applied to the input source
300code with clang-apply-replacements.
302 cl::value_desc("filename"),
305static cl::opt<bool>
Quiet(
"quiet",
desc(R
"(
306Run clang-tidy in quiet mode. This suppresses
307printing statistics about ignored warnings and
308warnings treated as errors if the respective
309options are specified.
314Overlay the virtual filesystem described by file
315over the real file system.
317 cl::value_desc("filename"),
321Use colors in diagnostics. If not set, colors
322will be used if the terminal connected to
323standard output supports colors.
324This option overrides the 'UseColor' option in
325.clang-tidy file, if any.
330Check the config files to ensure each check and
336Allow empty enabled checks. This suppresses
337the "no checks enabled" error when disabling
346 if (Stats.errorsIgnored()) {
347 llvm::errs() <<
"Suppressed " << Stats.errorsIgnored() <<
" warnings (";
348 StringRef Separator =
"";
349 if (Stats.ErrorsIgnoredNonUserCode) {
350 llvm::errs() << Stats.ErrorsIgnoredNonUserCode <<
" in non-user code";
353 if (Stats.ErrorsIgnoredLineFilter) {
354 llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
355 <<
" due to line filter";
358 if (Stats.ErrorsIgnoredNOLINT) {
359 llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT <<
" NOLINT";
362 if (Stats.ErrorsIgnoredCheckFilter)
363 llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
364 <<
" with check filters";
365 llvm::errs() <<
").\n";
366 if (Stats.ErrorsIgnoredNonUserCode)
367 llvm::errs() <<
"Use -header-filter=.* to display errors from all "
368 "non-system headers. Use -system-headers to display "
369 "errors from system headers as well.\n";
374 llvm::IntrusiveRefCntPtr<vfs::FileSystem> FS) {
375 ClangTidyGlobalOptions GlobalOptions;
377 llvm::errs() <<
"Invalid LineFilter: " << Err.message() <<
"\n\nUsage:\n";
378 llvm::cl::PrintHelpMessage(
false,
true);
382 ClangTidyOptions DefaultOptions;
384 DefaultOptions.WarningsAsErrors =
"";
389 DefaultOptions.User = llvm::sys::Process::GetEnv(
"USER");
391 if (!DefaultOptions.User)
392 DefaultOptions.User = llvm::sys::Process::GetEnv(
"USERNAME");
394 ClangTidyOptions OverrideOptions;
395 if (Checks.getNumOccurrences() > 0)
396 OverrideOptions.Checks = Checks;
397 if (WarningsAsErrors.getNumOccurrences() > 0)
398 OverrideOptions.WarningsAsErrors = WarningsAsErrors;
407 if (
UseColor.getNumOccurrences() > 0)
408 OverrideOptions.UseColor =
UseColor;
411 [&](StringRef Configuration,
412 StringRef Source) -> std::unique_ptr<ClangTidyOptionsProvider> {
413 llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
416 return std::make_unique<ConfigOptionsProvider>(
417 std::move(GlobalOptions),
419 std::move(*ParsedConfig), std::move(OverrideOptions), std::move(FS));
420 llvm::errs() <<
"Error: invalid configuration specified.\n"
421 << ParsedConfig.getError().message() <<
"\n";
426 if (
Config.getNumOccurrences() > 0) {
427 llvm::errs() <<
"Error: --config-file and --config are "
428 "mutually exclusive. Specify only one.\n";
432 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
434 if (std::error_code EC =
Text.getError()) {
435 llvm::errs() <<
"Error: can't read config-file '" <<
ConfigFile
436 <<
"': " << EC.message() <<
"\n";
440 return LoadConfig((*Text)->getBuffer(),
ConfigFile);
443 if (
Config.getNumOccurrences() > 0)
444 return LoadConfig(
Config,
"<command-line-config>");
446 return std::make_unique<FileOptionsProvider>(
447 std::move(GlobalOptions), std::move(DefaultOptions),
448 std::move(OverrideOptions), std::move(FS));
451llvm::IntrusiveRefCntPtr<vfs::FileSystem>
453 llvm::IntrusiveRefCntPtr<vfs::FileSystem> BaseFS) {
454 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
455 BaseFS->getBufferForFile(OverlayFile);
457 llvm::errs() <<
"Can't load virtual filesystem overlay file '"
458 << OverlayFile <<
"': " << Buffer.getError().message()
463 IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getVFSFromYAML(
464 std::move(Buffer.get()),
nullptr, OverlayFile);
466 llvm::errs() <<
"Error: invalid virtual filesystem overlay file '"
467 << OverlayFile <<
"'.\n";
473static StringRef
closest(StringRef Value,
const StringSet<> &Allowed) {
474 unsigned MaxEdit = 5U;
476 for (
auto Item : Allowed.keys()) {
477 unsigned Cur = Value.edit_distance_insensitive(Item,
true, MaxEdit);
488static bool verifyChecks(
const StringSet<> &AllChecks, StringRef CheckGlob,
490 GlobList Globs(CheckGlob);
491 bool AnyInvalid =
false;
492 for (
const auto &Item : Globs.getItems()) {
493 if (Item.Text.starts_with(
"clang-diagnostic"))
495 if (llvm::none_of(AllChecks.keys(),
496 [&Item](StringRef S) { return Item.Regex.match(S); })) {
498 if (Item.Text.contains(
'*'))
499 llvm::WithColor::warning(llvm::errs(), Source)
500 <<
"check glob '" << Item.Text <<
"' doesn't match any known check"
503 llvm::raw_ostream &
Output =
504 llvm::WithColor::warning(llvm::errs(), Source)
505 <<
"unknown check '" << Item.Text <<
'\'';
506 llvm::StringRef Closest =
closest(Item.Text, AllChecks);
507 if (!Closest.empty())
508 Output <<
"; did you mean '" << Closest <<
'\'';
517 const std::vector<std::string> &HeaderFileExtensions,
518 const std::vector<std::string> &ImplementationFileExtensions,
520 bool AnyInvalid =
false;
521 for (
const auto &HeaderExtension : HeaderFileExtensions) {
522 for (
const auto &ImplementationExtension : ImplementationFileExtensions) {
523 if (HeaderExtension == ImplementationExtension) {
525 auto &
Output = llvm::WithColor::warning(llvm::errs(), Source)
526 <<
"HeaderFileExtension '" << HeaderExtension <<
'\''
527 <<
" is the same as ImplementationFileExtension '"
528 << ImplementationExtension <<
'\'';
536static bool verifyOptions(
const llvm::StringSet<> &ValidOptions,
539 bool AnyInvalid =
false;
540 for (
auto Key : OptionMap.keys()) {
541 if (ValidOptions.contains(Key))
544 auto &
Output = llvm::WithColor::warning(llvm::errs(), Source)
545 <<
"unknown check option '" <<
Key <<
'\'';
546 llvm::StringRef Closest =
closest(Key, ValidOptions);
547 if (!Closest.empty())
548 Output <<
"; did you mean '" << Closest <<
'\'';
554static SmallString<256>
makeAbsolute(llvm::StringRef Input) {
557 SmallString<256> AbsolutePath(Input);
558 if (std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath)) {
559 llvm::errs() <<
"Can't make absolute path from " << Input <<
": "
560 << EC.message() <<
"\n";
565static llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem>
createBaseFS() {
566 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> BaseFS(
567 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
570 IntrusiveRefCntPtr<vfs::FileSystem> VfsFromFile =
574 BaseFS->pushOverlay(std::move(VfsFromFile));
580 llvm::InitLLVM
X(argc, argv);
581 SmallVector<const char *>
Args{argv, argv + argc};
584 llvm::BumpPtrAllocator Alloc;
585 llvm::cl::TokenizerCallback Tokenizer =
586 llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows()
587 ? llvm::cl::TokenizeWindowsCommandLine
588 : llvm::cl::TokenizeGNUCommandLine;
589 llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
590 if (llvm::Error Err = ECtx.expandResponseFiles(
Args)) {
591 llvm::WithColor::error() << llvm::toString(std::move(Err)) <<
"\n";
594 argc =
static_cast<int>(
Args.size());
598 if (cl::Option *LoadOpt = cl::getRegisteredOptions().lookup(
"load"))
601 llvm::Expected<CommonOptionsParser> OptionsParser =
604 if (!OptionsParser) {
605 llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
609 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> BaseFS =
createBaseFS();
614 auto *OptionsProvider = OwningOptionsProvider.get();
615 if (!OptionsProvider)
621 auto PathList = OptionsParser->getSourcePathList();
622 if (!PathList.empty()) {
627 ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FilePath);
629 std::vector<std::string> EnabledChecks =
634 std::vector<clang::tidy::ClangTidyOptionsProvider::OptionsSource>
635 RawOptions = OptionsProvider->getRawOptions(FilePath);
636 for (
const std::string &Check : EnabledChecks) {
637 for (
const auto &[Opts, Source] : llvm::reverse(RawOptions)) {
638 if (Opts.Checks && GlobList(*Opts.Checks).contains(Check)) {
639 llvm::outs() <<
"'" << Check <<
"' is enabled in the " << Source
650 llvm::errs() <<
"No checks enabled.\n";
653 llvm::outs() <<
"Enabled checks:";
654 for (
const auto &CheckName : EnabledChecks)
655 llvm::outs() <<
"\n " << CheckName;
656 llvm::outs() <<
"\n\n";
661 EffectiveOptions.CheckOptions =
664 EffectiveOptions, 0))
670 std::vector<ClangTidyOptionsProvider::OptionsSource> RawOptions =
671 OptionsProvider->getRawOptions(
FileName);
672 ChecksAndOptions Valid =
674 bool AnyInvalid =
false;
675 for (
const auto &[Opts, Source] : RawOptions) {
677 AnyInvalid |=
verifyChecks(Valid.Checks, *Opts.Checks, Source);
678 if (Opts.HeaderFileExtensions && Opts.ImplementationFileExtensions)
681 *Opts.ImplementationFileExtensions, Source);
682 AnyInvalid |=
verifyOptions(Valid.Options, Opts.CheckOptions, Source);
686 llvm::outs() <<
"No config errors detected.\n";
690 if (EnabledChecks.empty()) {
692 llvm::outs() <<
"No checks enabled.\n";
695 llvm::errs() <<
"Error: no checks enabled.\n";
696 llvm::cl::PrintHelpMessage(
false,
true);
700 if (PathList.empty()) {
701 llvm::errs() <<
"Error: no input files specified.\n";
702 llvm::cl::PrintHelpMessage(
false,
true);
706 llvm::InitializeAllTargetInfos();
707 llvm::InitializeAllTargetMCs();
708 llvm::InitializeAllAsmParsers();
710 ClangTidyContext Context(std::move(OwningOptionsProvider),
713 std::vector<ClangTidyError>
Errors =
714 runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
716 bool FoundErrors = llvm::any_of(
Errors, [](
const ClangTidyError &
E) {
717 return E.DiagLevel == ClangTidyError::Error;
725 const bool DisableFixes = FoundErrors && !
FixErrors;
727 unsigned WErrorCount = 0;
730 WErrorCount, BaseFS);
734 llvm::raw_fd_ostream
OS(
ExportFixes, EC, llvm::sys::fs::OF_None);
736 llvm::errs() <<
"Error opening output file: " << EC.message() <<
'\n';
744 if (DisableFixes && Behaviour !=
FB_NoFix)
746 <<
"Found compiler errors, but -fix-errors was not specified.\n"
747 "Fixes have NOT been applied.\n\n";
752 StringRef Plural = WErrorCount == 1 ?
"" :
"s";
753 llvm::errs() << WErrorCount <<
" warning" << Plural <<
" treated as error"
768 llvm::errs() <<
"Found compiler error(s).\n";
static cl::opt< bool > UseColor("use-color", cl::desc(R"(Use colors in detailed AST output. If not set, colors
will be used if the terminal connected to
standard output supports colors.)"), cl::init(false), cl::cat(ClangQueryCategory))
static cl::opt< bool > EnableCheckProfile("enable-check-profile", desc(R"(
Enable per-check timing profiles, and print a
report to stderr.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > VfsOverlay("vfsoverlay", desc(R"(
Overlay the virtual filesystem described by file
over the real file system.
)"), cl::value_desc("filename"), cl::cat(ClangTidyCategory))
static cl::opt< bool > FixNotes("fix-notes", desc(R"(
If a warning has no fix, but a single fix can
be found through an associated diagnostic note,
apply the fix.
Specifying this flag will implicitly enable the
'--fix' flag.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< bool > Fix("fix", desc(R"(
Apply suggested fixes. Without -fix-errors
clang-tidy will bail out if any compilation
errors were found.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< bool > ExplainConfig("explain-config", desc(R"(
For each enabled check explains, where it is
enabled, i.e. in clang-tidy binary, command
line or a specific configuration file.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< bool > UseColor("use-color", desc(R"(
Use colors in diagnostics. If not set, colors
will be used if the terminal connected to
standard output supports colors.
This option overrides the 'UseColor' option in
.clang-tidy file, if any.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< bool > VerifyConfig("verify-config", desc(R"(
Check the config files to ensure each check and
option is recognized.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > ExcludeHeaderFilter("exclude-header-filter", desc(R"(
Regular expression matching the names of the
headers to exclude diagnostics from. Diagnostics
from the main file of each translation unit are
always displayed.
Must be used together with --header-filter.
Can be used together with -line-filter.
This option overrides the 'ExcludeHeaderFilterRegex'
option in .clang-tidy file, if any.
)"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::opt< bool > AllowEnablingAnalyzerAlphaCheckers("allow-enabling-analyzer-alpha-checkers", cl::init(false), cl::Hidden, cl::cat(ClangTidyCategory))
This option allows enabling the experimental alpha checkers from the static analyzer.
static cl::opt< std::string > ConfigFile("config-file", desc(R"(
Specify the path of .clang-tidy or custom config file:
e.g. --config-file=/some/path/myTidyConfigFile
This option internally works exactly the same way as
--config option after reading specified config file.
Use either --config-file or --config, not both.
)"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::opt< bool > EnableModuleHeadersParsing("enable-module-headers-parsing", desc(R"(
Enables preprocessor-level module header parsing
for C++20 and above, empowering specific checks
to detect macro definitions within modules. This
feature may cause performance and parsing issues
and is therefore considered experimental.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > Config("config", desc(R"(
Specifies a configuration in YAML/JSON format:
-config="{Checks:' *', CheckOptions:{x:y}}"
When the value is empty, clang-tidy will
attempt to find a file named .clang-tidy for
each source file in its parent directories.
)"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::OptionCategory ClangTidyCategory("clang-tidy options")
static cl::opt< std::string > LineFilter("line-filter", desc(R"(
List of files with line ranges to filter the
warnings. Can be used together with
-header-filter. The format of the list is a
JSON array of objects:
[
{"name":"file1.cpp","lines":[[1,3],[5,7]]},
{"name":"file2.h"}
]
)"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::opt< bool > FixErrors("fix-errors", desc(R"(
Apply suggested fixes even if compilation
errors were found. If compiler errors have
attached fix-its, clang-tidy will apply them as
well.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::extrahelp ClangTidyParameterFileHelp(R"(
Parameters files:
A large number of options or source files can be passed as parameter files
by use '@parameter-file' in the command line.
)")
static cl::opt< std::string > HeaderFilter("header-filter", desc(R"(
Regular expression matching the names of the
headers to output diagnostics from. Diagnostics
from the main file of each translation unit are
always displayed.
Can be used together with -line-filter.
This option overrides the 'HeaderFilterRegex'
option in .clang-tidy file, if any.
)"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::opt< bool > ListChecks("list-checks", desc(R"(
List all enabled checks and exit. Use with
-checks=* to list all available checks.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< bool > DumpConfig("dump-config", desc(R"(
Dumps configuration in the YAML format to
stdout. This option can be used along with a
file name (and '--' if the file is outside of a
project with configured compilation database).
The configuration used for this file will be
printed.
Use along with -checks=* to include
configuration of all checks.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< bool > SystemHeaders("system-headers", desc(R"(
Display the errors from system headers.
This option overrides the 'SystemHeaders' option
in .clang-tidy file, if any.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::desc desc(StringRef description)
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage)
static cl::opt< bool > AllowNoChecks("allow-no-checks", desc(R"(
Allow empty enabled checks. This suppresses
the "no checks enabled" error when disabling
all of the checks.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::extrahelp ClangTidyHelp(R"(
Configuration files:
clang-tidy attempts to read configuration for each source file from a
.clang-tidy file located in the closest parent directory of the source
file. The .clang-tidy file is specified in YAML format. If any configuration
options have a corresponding command-line option, command-line option takes
precedence.
The following configuration options may be used in a .clang-tidy file:
CheckOptions - List of key-value pairs defining check-specific
options. Example:
CheckOptions:
some-check.SomeOption: 'some value'
Checks - Same as '--checks'. Additionally, the list of
globs can be specified as a list instead of a
string.
ExcludeHeaderFilterRegex - Same as '--exclude-header-filter'.
ExtraArgs - Same as '--extra-arg'.
ExtraArgsBefore - Same as '--extra-arg-before'.
FormatStyle - Same as '--format-style'.
HeaderFileExtensions - File extensions to consider to determine if a
given diagnostic is located in a header file.
HeaderFilterRegex - Same as '--header-filter'.
ImplementationFileExtensions - File extensions to consider to determine if a
given diagnostic is located in an
implementation file.
InheritParentConfig - If this option is true in a config file, the
configuration file in the parent directory
(if any exists) will be taken and the current
config file will be applied on top of the
parent one.
SystemHeaders - Same as '--system-headers'.
UseColor - Same as '--use-color'.
User - Specifies the name or e-mail of the user
running clang-tidy. This option is used, for
example, to place the correct user name in
TODO() comments in the relevant check.
WarningsAsErrors - Same as '--warnings-as-errors'.
The effective configuration can be inspected using --dump-config:
$ clang-tidy --dump-config
---
Checks: '-*,some-check'
WarningsAsErrors: ''
HeaderFileExtensions: ['', 'h','hh','hpp','hxx']
ImplementationFileExtensions: ['c','cc','cpp','cxx']
HeaderFilterRegex: ''
FormatStyle: none
InheritParentConfig: true
User: user
CheckOptions:
some-check.SomeOption: 'some value'
...
)")
const char DefaultChecks[]
static cl::opt< bool > Quiet("quiet", desc(R"(
Run clang-tidy in quiet mode. This suppresses
printing statistics about ignored warnings and
warnings treated as errors if the respective
options are specified.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > ExportFixes("export-fixes", desc(R"(
YAML file to store suggested fixes in. The
stored fixes can be applied to the input source
code with clang-apply-replacements.
)"), cl::value_desc("filename"), cl::cat(ClangTidyCategory))
static cl::opt< std::string > FormatStyle("format-style", desc(R"(
Style for formatting code around applied fixes:
- 'none' (default) turns off formatting
- 'file' (literally 'file', not a placeholder)
uses .clang-format file in the closest parent
directory
- '{ <json> }' specifies options inline, e.g.
-format-style='{BasedOnStyle: llvm, IndentWidth: 8}'
- 'llvm', 'google', 'webkit', 'mozilla'
See clang-format documentation for the up-to-date
information about formatting styles and options.
This option overrides the 'FormatStyle` option in
.clang-tidy file, if any.
)"), cl::init("none"), cl::cat(ClangTidyCategory))
static cl::opt< std::string > StoreCheckProfile("store-check-profile", desc(R"(
By default reports are printed in tabulated
format to stderr. When this option is passed,
these per-TU profiles are instead stored as JSON.
)"), cl::value_desc("prefix"), cl::cat(ClangTidyCategory))
std::error_code parseLineFilter(StringRef LineFilter, clang::tidy::ClangTidyGlobalOptions &Options)
Parses -line-filter option and stores it to the Options.
std::vector< std::string > getCheckNames(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers)
Fills the list of check names that are enabled when the provided filters are applied.
ChecksAndOptions getAllChecksAndOptions(bool AllowEnablingAnalyzerAlphaCheckers)
FixBehaviour
Controls what kind of fixes clang-tidy is allowed to apply.
@ FB_NoFix
Don't try to apply any fix.
@ FB_FixNotes
Apply fixes found in notes.
@ FB_Fix
Only apply fixes added to warnings.
int clangTidyMain(int argc, const char **argv)
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers)
Returns the effective check-specific options.
static void printStats(const ClangTidyStats &Stats)
static llvm::IntrusiveRefCntPtr< vfs::OverlayFileSystem > createBaseFS()
llvm::IntrusiveRefCntPtr< vfs::FileSystem > getVfsFromFile(const std::string &OverlayFile, llvm::IntrusiveRefCntPtr< vfs::FileSystem > BaseFS)
void handleErrors(llvm::ArrayRef< ClangTidyError > Errors, ClangTidyContext &Context, FixBehaviour Fix, unsigned &WarningsAsErrorsCount, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS)
Displays the found Errors to the users.
static constexpr StringLiteral VerifyConfigWarningEnd
static SmallString< 256 > makeAbsolute(llvm::StringRef Input)
static bool verifyOptions(const llvm::StringSet<> &ValidOptions, const ClangTidyOptions::OptionMap &OptionMap, StringRef Source)
static std::unique_ptr< ClangTidyOptionsProvider > createOptionsProvider(llvm::IntrusiveRefCntPtr< vfs::FileSystem > FS)
std::vector< ClangTidyError > runClangTidy(clang::tidy::ClangTidyContext &Context, const CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, llvm::IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem > BaseFS, bool ApplyAnyFix, bool EnableCheckProfile, llvm::StringRef StoreCheckProfile)
static bool verifyFileExtensions(const std::vector< std::string > &HeaderFileExtensions, const std::vector< std::string > &ImplementationFileExtensions, StringRef Source)
std::string configurationAsText(const ClangTidyOptions &Options)
Serializes configuration to a YAML-encoded string.
llvm::ErrorOr< ClangTidyOptions > parseConfiguration(llvm::MemoryBufferRef Config)
Parses configuration from JSON and returns ClangTidyOptions or an error.
void exportReplacements(const llvm::StringRef MainFilePath, const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
static bool verifyChecks(const StringSet<> &AllChecks, StringRef CheckGlob, StringRef Source)
static StringRef closest(StringRef Value, const StringSet<> &Allowed)
Some operations such as code completion produce a set of candidates.
llvm::StringMap< ClangTidyValue > OptionMap
static ClangTidyOptions getDefaults()
These options are used for all settings that haven't been overridden by the OptionsProvider.
Contains displayed and ignored diagnostic counters for a ClangTidy run.