18 #include "../ClangTidy.h" 19 #include "clang/Tooling/CommonOptionsParser.h" 20 #include "llvm/Support/Process.h" 21 #include "llvm/Support/TargetSelect.h" 30 static cl::extrahelp
CommonHelp(CommonOptionsParser::HelpMessage);
33 clang-tidy attempts to read configuration for each source file from a 34 .clang-tidy file located in the closest parent directory of the source 35 file. If any configuration options have a corresponding command-line 36 option, command-line option takes precedence. The effective 37 configuration can be inspected using -dump-config: 39 $ clang-tidy -dump-config 41 Checks: '-*,some-check' 47 - key: some-check.SomeOption 57 static cl::opt<std::string>
Checks(
"checks", cl::desc(R
"( 58 Comma-separated list of globs with optional '-' 59 prefix. Globs are processed in order of 60 appearance in the list. Globs without '-' 61 prefix add checks with matching names to the 62 set, globs with the '-' prefix remove checks 63 with matching names from the set of enabled 64 checks. This option's value is appended to the 65 value of the 'Checks' option in .clang-tidy 70 static cl::opt<std::string>
WarningsAsErrors(
"warnings-as-errors", cl::desc(R
"( 71 Upgrades warnings to errors. Same format as 73 This option's value is appended to the value of 74 the 'WarningsAsErrors' option in .clang-tidy 80 static cl::opt<std::string>
HeaderFilter(
"header-filter", cl::desc(R
"( 81 Regular expression matching the names of the 82 headers to output diagnostics from. Diagnostics 83 from the main file of each translation unit are 85 Can be used together with -line-filter. 86 This option overrides the 'HeaderFilter' option 87 in .clang-tidy file, if any. 94 cl::desc(
"Display the errors from system headers."),
96 static cl::opt<std::string>
LineFilter(
"line-filter", cl::desc(R
"( 97 List of files with line ranges to filter the 98 warnings. Can be used together with 99 -header-filter. The format of the list is a 100 JSON array of objects: 102 {"name":"file1.cpp","lines":[[1,3],[5,7]]}, 109 static cl::opt<bool>
Fix(
"fix", cl::desc(R
"( 110 Apply suggested fixes. Without -fix-errors 111 clang-tidy will bail out if any compilation 116 static cl::opt<bool>
FixErrors(
"fix-errors", cl::desc(R
"( 117 Apply suggested fixes even if compilation 118 errors were found. If compiler errors have 119 attached fix-its, clang-tidy will apply them as 124 static cl::opt<std::string>
FormatStyle(
"format-style", cl::desc(R
"( 125 Style for formatting code around applied fixes: 126 - 'none' (default) turns off formatting 127 - 'file' (literally 'file', not a placeholder) 128 uses .clang-format file in the closest parent 130 - '{ <json> }' specifies options inline, e.g. 131 -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' 132 - 'llvm', 'google', 'webkit', 'mozilla' 133 See clang-format documentation for the up-to-date 134 information about formatting styles and options. 135 This option overrides the 'FormatStyle` option in 136 .clang-tidy file, if any. 141 static cl::opt<bool>
ListChecks(
"list-checks", cl::desc(R
"( 142 List all enabled checks and exit. Use with 143 -checks=* to list all available checks. 147 static cl::opt<bool>
ExplainConfig(
"explain-config", cl::desc(R
"( 148 For each enabled check explains, where it is 149 enabled, i.e. in clang-tidy binary, command 150 line or a specific configuration file. 154 static cl::opt<std::string>
Config(
"config", cl::desc(R
"( 155 Specifies a configuration in YAML/JSON format: 156 -config="{Checks: '*', 157 CheckOptions: [{key: x, 159 When the value is empty, clang-tidy will 160 attempt to find a file named .clang-tidy for 161 each source file in its parent directories. 165 static cl::opt<bool>
DumpConfig(
"dump-config", cl::desc(R
"( 166 Dumps configuration in the YAML format to 167 stdout. This option can be used along with a 168 file name (and '--' if the file is outside of a 169 project with configured compilation database). 170 The configuration used for this file will be 172 Use along with -checks=* to include 173 configuration of all checks. 178 Enable per-check timing profiles, and print a 186 By default reports are printed in tabulated 187 format to stderr. When this option is passed, 188 these per-TU profiles are instead stored as JSON. 190 cl::value_desc("prefix"),
198 cl::init(
false), cl::Hidden,
201 static cl::opt<std::string>
ExportFixes(
"export-fixes", cl::desc(R
"( 202 YAML file to store suggested fixes in. The 203 stored fixes can be applied to the input source 204 code with clang-apply-replacements. 206 cl::value_desc("filename"),
209 static cl::opt<bool>
Quiet(
"quiet", cl::desc(R
"( 210 Run clang-tidy in quiet mode. This suppresses 211 printing statistics about ignored warnings and 212 warnings treated as errors if the respective 213 options are specified. 218 static cl::opt<std::string>
VfsOverlay(
"vfsoverlay", cl::desc(R
"( 219 Overlay the virtual filesystem described by file 220 over the real file system. 222 cl::value_desc("filename"),
230 llvm::errs() <<
"Suppressed " << Stats.
errorsIgnored() <<
" warnings (";
238 <<
" due to line filter";
247 <<
" with check filters";
248 llvm::errs() <<
").\n";
250 llvm::errs() <<
"Use -header-filter=.* to display errors from all " 251 "non-system headers. Use -system-headers to display " 252 "errors from system headers as well.\n";
257 llvm::IntrusiveRefCntPtr<vfs::FileSystem> FS) {
260 llvm::errs() <<
"Invalid LineFilter: " << Err.message() <<
"\n\nUsage:\n";
261 llvm::cl::PrintHelpMessage(
false,
true);
271 DefaultOptions.
User = llvm::sys::Process::GetEnv(
"USER");
273 if (!DefaultOptions.
User)
274 DefaultOptions.
User = llvm::sys::Process::GetEnv(
"USERNAME");
277 if (
Checks.getNumOccurrences() > 0)
289 if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
291 return llvm::make_unique<ConfigOptionsProvider>(
293 ClangTidyOptions::getDefaults().mergeWith(DefaultOptions),
294 *ParsedConfig, OverrideOptions);
296 llvm::errs() <<
"Error: invalid configuration specified.\n" 297 << ParsedConfig.getError().message() <<
"\n";
301 return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
302 OverrideOptions, std::move(FS));
305 llvm::IntrusiveRefCntPtr<vfs::FileSystem>
307 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFS(
308 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
309 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
310 OverlayFS->getBufferForFile(OverlayFile);
312 llvm::errs() <<
"Can't load virtual filesystem overlay file '" 313 << OverlayFile <<
"': " << Buffer.getError().message()
318 IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getVFSFromYAML(
319 std::move(Buffer.get()),
nullptr, OverlayFile);
321 llvm::errs() <<
"Error: invalid virtual filesystem overlay file '" 322 << OverlayFile <<
"'.\n";
325 OverlayFS->pushOverlay(FS);
332 llvm::IntrusiveRefCntPtr<vfs::FileSystem> BaseFS(
339 auto *OptionsProvider = OwningOptionsProvider.get();
340 if (!OptionsProvider)
343 auto MakeAbsolute = [](
const std::string &Input) -> SmallString<256> {
346 SmallString<256> AbsolutePath(Input);
348 llvm::errs() <<
"Can't make absolute path from " << Input <<
": " 349 << EC.message() <<
"\n";
357 auto PathList = OptionsParser.getSourcePathList();
358 if (!PathList.empty()) {
362 SmallString<256> FilePath = MakeAbsolute(
FileName);
365 std::vector<std::string> EnabledChecks =
370 std::vector<clang::tidy::ClangTidyOptionsProvider::OptionsSource>
371 RawOptions = OptionsProvider->getRawOptions(FilePath);
372 for (
const std::string &Check : EnabledChecks) {
373 for (
auto It = RawOptions.rbegin(); It != RawOptions.rend(); ++It) {
375 llvm::outs() <<
"'" << Check <<
"' is enabled in the " << It->second
385 if (EnabledChecks.empty()) {
386 llvm::errs() <<
"No checks enabled.\n";
389 llvm::outs() <<
"Enabled checks:";
390 for (
const auto &CheckName : EnabledChecks)
391 llvm::outs() <<
"\n " << CheckName;
392 llvm::outs() <<
"\n\n";
400 ClangTidyOptions::getDefaults().mergeWith(
406 if (EnabledChecks.empty()) {
407 llvm::errs() <<
"Error: no checks enabled.\n";
408 llvm::cl::PrintHelpMessage(
false,
true);
412 if (PathList.empty()) {
413 llvm::errs() <<
"Error: no input files specified.\n";
414 llvm::cl::PrintHelpMessage(
false,
true);
418 llvm::InitializeAllTargetInfos();
419 llvm::InitializeAllTargetMCs();
420 llvm::InitializeAllAsmParsers();
424 runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
426 ArrayRef<ClangTidyError> Errors = Context.getErrors();
427 bool FoundErrors = llvm::find_if(Errors, [](
const ClangTidyError &E) {
428 return E.DiagLevel == ClangTidyError::Error;
433 unsigned WErrorCount = 0;
443 llvm::errs() <<
"Error opening output file: " << EC.message() <<
'\n';
453 <<
"Found compiler errors, but -fix-errors was not specified.\n" 454 "Fixes have NOT been applied.\n\n";
459 StringRef Plural = WErrorCount == 1 ?
"" :
"s";
460 llvm::errs() << WErrorCount <<
" warning" << Plural <<
" treated as error" 475 llvm::errs() <<
"Found compiler error(s).\n";
575 int main(
int argc,
const char **argv) {
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. If any configuration options have a corresponding command-line
option, command-line option takes precedence. The effective
configuration can be inspected using -dump-config:
$ clang-tidy -dump-config
---
Checks: '-*,some-check'
WarningsAsErrors: ''
HeaderFilterRegex: ''
FormatStyle: none
User: user
CheckOptions:
- key: some-check.SomeOption
value: 'some value'
...
)")
llvm::Optional< std::string > Checks
Checks filter.
volatile int GoogleModuleAnchorSource
static void printStats(const ClangTidyStats &Stats)
Some operations such as code completion produce a set of candidates.
llvm::Optional< std::string > User
Specifies the name or e-mail of the user running clang-tidy.
static cl::opt< bool > SystemHeaders("system-headers", cl::desc("Display the errors from system headers."), cl::init(false), cl::cat(ClangTidyCategory))
Read-only set of strings represented as a list of positive and negative globs.
volatile int ReadabilityModuleAnchorSource
static cl::opt< bool > FixErrors("fix-errors", cl::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::opt< std::string > HeaderFilter("header-filter", cl::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 'HeaderFilter' option
in .clang-tidy file, if any.
)"), cl::init(""), cl::cat(ClangTidyCategory))
bool contains(StringRef S)
Returns true if the pattern matches S.
static cl::opt< bool > DumpConfig("dump-config", cl::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< std::string > Config("config", cl::desc(R"(
Specifies a configuration in YAML/JSON format:
-config="{Checks:' *', CheckOptions:[{key:x, value: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::opt< bool > ExplainConfig("explain-config", cl::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< std::string > StoreCheckProfile("store-check-profile", cl::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))
llvm::Optional< std::string > HeaderFilterRegex
Output warnings from headers matching this filter.
def make_absolute(f, directory)
static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination
Contains options for clang-tidy.
unsigned ErrorsIgnoredCheckFilter
volatile int AndroidModuleAnchorSource
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers)
Returns the effective check-specific options.
std::error_code parseLineFilter(StringRef LineFilter, clang::tidy::ClangTidyGlobalOptions &Options)
Parses -line-filter option and stores it to the Options.
llvm::ErrorOr< ClangTidyOptions > parseConfiguration(StringRef Config)
unsigned ErrorsIgnoredNOLINT
static cl::opt< bool > ListChecks("list-checks", cl::desc(R"(
List all enabled checks and exit. Use with
-checks=* to list all available checks.
)"), cl::init(false), cl::cat(ClangTidyCategory))
OptionMap CheckOptions
Key-value mapping used to store check-specific options.
llvm::Optional< bool > SystemHeaders
Output warnings from system headers matching HeaderFilterRegex.
volatile int LLVMModuleAnchorSource
volatile int PerformanceModuleAnchorSource
llvm::IntrusiveRefCntPtr< vfs::FileSystem > getVfsOverlayFromFile(const std::string &OverlayFile)
llvm::Optional< std::string > FormatStyle
Format code around applied fixes with clang-format using this style.
void handleErrors(ClangTidyContext &Context, bool Fix, unsigned &WarningsAsErrorsCount, llvm::IntrusiveRefCntPtr< vfs::FileSystem > BaseFS)
Displays the found Errors to the users.
volatile int CppCoreGuidelinesModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED ObjCModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination
static cl::opt< std::string > LineFilter("line-filter", cl::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 > 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.
unsigned errorsIgnored() const
unsigned ErrorsIgnoredNonUserCode
volatile int MPIModuleAnchorSource
volatile int HICPPModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED ZirconModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination
volatile int PortabilityModuleAnchorSource
std::string configurationAsText(const ClangTidyOptions &Options)
Serializes configuration to a YAML-encoded string.
volatile int ZirconModuleAnchorSource
volatile int CERTModuleAnchorSource
static cl::OptionCategory ClangTidyCategory("clang-tidy options")
static cl::opt< std::string > WarningsAsErrors("warnings-as-errors", cl::desc(R"(
Upgrades warnings to errors. Same format as
'-checks'.
This option's value is appended to the value of
the 'WarningsAsErrors' option in .clang-tidy
file, if any.
)"), cl::init(""), cl::cat(ClangTidyCategory))
static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination
void runClangTidy(clang::tidy::ClangTidyContext &Context, const CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, llvm::IntrusiveRefCntPtr< vfs::FileSystem > BaseFS, bool EnableCheckProfile, llvm::StringRef StoreCheckProfile)
unsigned ErrorsIgnoredLineFilter
static cl::opt< bool > EnableCheckProfile("enable-check-profile", cl::desc(R"(
Enable per-check timing profiles, and print a
report to stderr.
)"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage)
llvm::Optional< std::string > WarningsAsErrors
WarningsAsErrors filter.
static int LLVM_ATTRIBUTE_UNUSED HICPPModuleAnchorDestination
static cl::opt< std::string > VfsOverlay("vfsoverlay", cl::desc(R"(
Overlay the virtual filesystem described by file
over the real file system.
)"), cl::value_desc("filename"), cl::cat(ClangTidyCategory))
volatile int BoostModuleAnchorSource
static cl::opt< std::string > ExportFixes("export-fixes", cl::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))
volatile int ObjCModuleAnchorSource
volatile int MiscModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED PerformanceModuleAnchorDestination
volatile int BugproneModuleAnchorSource
static int clangTidyMain(int argc, const char **argv)
static int LLVM_ATTRIBUTE_UNUSED FuchsiaModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED CppCoreGuidelinesModuleAnchorDestination
static std::unique_ptr< ClangTidyOptionsProvider > createOptionsProvider(llvm::IntrusiveRefCntPtr< vfs::FileSystem > FS)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static int LLVM_ATTRIBUTE_UNUSED ModernizeModuleAnchorDestination
void exportReplacements(const llvm::StringRef MainFilePath, const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
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.
const char DefaultChecks[]
int main(int argc, const char **argv)
A detected error complete with information to display diagnostic and automatic fix.
Contains displayed and ignored diagnostic counters for a ClangTidy run.
static cl::opt< std::string > Checks("checks", cl::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))
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
volatile int AbseilModuleAnchorSource
volatile int ModernizeModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED MPIModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED PortabilityModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED CERTModuleAnchorDestination
static cl::opt< bool > Fix("fix", cl::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 int LLVM_ATTRIBUTE_UNUSED BoostModuleAnchorDestination
static cl::opt< bool > Quiet("quiet", cl::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))
volatile int FuchsiaModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED AbseilModuleAnchorDestination
static cl::opt< std::string > FormatStyle("format-style", cl::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))