18 #include "../ClangTidy.h"
19 #include "clang/Tooling/CommonOptionsParser.h"
20 #include "llvm/Support/Process.h"
22 using namespace clang::ast_matchers;
23 using namespace clang::driver;
24 using namespace clang::tooling;
29 static cl::extrahelp
CommonHelp(CommonOptionsParser::HelpMessage);
32 clang-tidy attempts to read configuration for each source file from a
33 .clang-tidy file located in the closest parent directory of the source
34 file. If any configuration options have a corresponding command-line
35 option, command-line option takes precedence. The effective
36 configuration can be inspected using -dump-config:
38 $ clang-tidy -dump-config
40 Checks: '-*,some-check'
43 AnalyzeTemporaryDtors: false
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 Enable temporary destructor-aware analysis in
187 clang-analyzer- checks.
188 This option overrides the value read from a
194 static cl::opt<std::string>
ExportFixes(
"export-fixes", cl::desc(R
"(
195 YAML file to store suggested fixes in. The
196 stored fixes can be applied to the input source
197 code with clang-apply-replacements.
199 cl::value_desc("filename"),
202 static cl::opt<bool>
Quiet(
"quiet", cl::desc(R
"(
203 Run clang-tidy in quiet mode. This suppresses
204 printing statistics about ignored warnings and
205 warnings treated as errors if the respective
206 options are specified.
216 llvm::errs() <<
"Suppressed " << Stats.
errorsIgnored() <<
" warnings (";
217 StringRef Separator =
"";
224 <<
" due to line filter";
233 <<
" with check filters";
234 llvm::errs() <<
").\n";
236 llvm::errs() <<
"Use -header-filter=.* to display errors from all "
237 "non-system headers. Use -system-headers to display "
238 "errors from system headers as well.\n";
243 llvm::raw_ostream &OS) {
245 std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
248 for (
const auto &P : Profile.Records) {
249 Timers.emplace_back(P.getValue(), P.getKey());
250 Total += P.getValue();
253 std::sort(Timers.begin(), Timers.end());
255 std::string
Line =
"===" + std::string(73,
'-') +
"===\n";
258 if (Total.getUserTime())
259 OS <<
" ---User Time---";
260 if (Total.getSystemTime())
261 OS <<
" --System Time--";
262 if (Total.getProcessTime())
263 OS <<
" --User+System--";
264 OS <<
" ---Wall Time---";
265 if (Total.getMemUsed())
267 OS <<
" --- Name ---\n";
270 for (
auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
271 I->first.print(Total, OS);
272 OS << I->second <<
'\n';
275 Total.print(Total, OS);
282 ClangTidyGlobalOptions GlobalOptions;
284 llvm::errs() <<
"Invalid LineFilter: " << Err.message() <<
"\n\nUsage:\n";
285 llvm::cl::PrintHelpMessage(
false,
true);
289 ClangTidyOptions DefaultOptions;
291 DefaultOptions.WarningsAsErrors =
"";
296 DefaultOptions.User = llvm::sys::Process::GetEnv(
"USER");
298 if (!DefaultOptions.User)
299 DefaultOptions.User = llvm::sys::Process::GetEnv(
"USERNAME");
301 ClangTidyOptions OverrideOptions;
302 if (
Checks.getNumOccurrences() > 0)
303 OverrideOptions.Checks =
Checks;
316 if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
318 return llvm::make_unique<ConfigOptionsProvider>(
320 ClangTidyOptions::getDefaults().mergeWith(DefaultOptions),
321 *ParsedConfig, OverrideOptions);
323 llvm::errs() <<
"Error: invalid configuration specified.\n"
324 << ParsedConfig.getError().message() <<
"\n";
328 return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
337 auto *OptionsProvider = OwningOptionsProvider.get();
338 if (!OptionsProvider)
341 StringRef FileName(
"dummy");
342 auto PathList = OptionsParser.getSourcePathList();
343 if (!PathList.empty()) {
344 FileName = PathList.front();
347 SmallString<256> FilePath(FileName);
348 if (std::error_code EC = llvm::sys::fs::make_absolute(FilePath)) {
349 llvm::errs() <<
"Can't make absolute path from " << FileName <<
": "
350 << EC.message() <<
"\n";
352 ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FilePath);
353 std::vector<std::string> EnabledChecks =
getCheckNames(EffectiveOptions);
357 std::vector<clang::tidy::ClangTidyOptionsProvider::OptionsSource>
358 RawOptions = OptionsProvider->getRawOptions(FilePath);
359 for (
const std::string &
Check : EnabledChecks) {
360 for (
auto It = RawOptions.rbegin(); It != RawOptions.rend(); ++It) {
362 llvm::outs() <<
"'" <<
Check <<
"' is enabled in the " << It->second
372 if (EnabledChecks.empty()) {
373 llvm::errs() <<
"No checks enabled.\n";
376 llvm::outs() <<
"Enabled checks:";
377 for (
const auto &CheckName : EnabledChecks)
378 llvm::outs() <<
"\n " << CheckName;
379 llvm::outs() <<
"\n\n";
386 ClangTidyOptions::getDefaults().mergeWith(
392 if (EnabledChecks.empty()) {
393 llvm::errs() <<
"Error: no checks enabled.\n";
394 llvm::cl::PrintHelpMessage(
false,
true);
398 if (PathList.empty()) {
399 llvm::errs() <<
"Error: no input files specified.\n";
400 llvm::cl::PrintHelpMessage(
false,
true);
406 ClangTidyContext
Context(std::move(OwningOptionsProvider));
409 ArrayRef<ClangTidyError> Errors =
Context.getErrors();
411 std::find_if(Errors.begin(), Errors.end(), [](
const ClangTidyError &E) {
412 return E.DiagLevel == ClangTidyError::Error;
415 const bool DisableFixes =
Fix && FoundErrors && !
FixErrors;
417 unsigned WErrorCount = 0;
424 llvm::raw_fd_ostream OS(
ExportFixes, EC, llvm::sys::fs::F_None);
426 llvm::errs() <<
"Error opening output file: " << EC.message() <<
'\n';
436 <<
"Found compiler errors, but -fix-errors was not specified.\n"
437 "Fixes have NOT been applied.\n\n";
445 StringRef Plural = WErrorCount == 1 ?
"" :
"s";
446 llvm::errs() << WErrorCount <<
" warning" << Plural <<
" treated as error"
523 int main(
int argc,
const char **argv) {
volatile int GoogleModuleAnchorSource
static void printStats(const ClangTidyStats &Stats)
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< 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))
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options)
Returns the effective check-specific options.
static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination
unsigned ErrorsIgnoredCheckFilter
volatile int AndroidModuleAnchorSource
void runClangTidy(clang::tidy::ClangTidyContext &Context, const CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, ProfileData *Profile)
std::error_code parseLineFilter(StringRef LineFilter, clang::tidy::ClangTidyGlobalOptions &Options)
Parses -line-filter option and stores it to the Options.
static cl::opt< bool > AnalyzeTemporaryDtors("analyze-temporary-dtors", cl::desc(R"(
Enable temporary destructor-aware analysis in
clang-analyzer- checks.
This option overrides the value read from a
.clang-tidy file.
)"), cl::init(false), cl::cat(ClangTidyCategory))
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))
volatile int LLVMModuleAnchorSource
volatile int PerformanceModuleAnchorSource
volatile int CppCoreGuidelinesModuleAnchorSource
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))
unsigned ErrorsIgnoredNonUserCode
volatile int MPIModuleAnchorSource
volatile int HICPPModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination
std::string configurationAsText(const ClangTidyOptions &Options)
Serializes configuration to a YAML-encoded string.
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
std::vector< std::string > getCheckNames(const ClangTidyOptions &Options)
Fills the list of check names that are enabled when the provided filters are applied.
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))
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)
void handleErrors(ClangTidyContext &Context, bool Fix, unsigned &WarningsAsErrorsCount)
Displays the found Errors to the users.
static int LLVM_ATTRIBUTE_UNUSED HICPPModuleAnchorDestination
static void printProfileData(const ProfileData &Profile, llvm::raw_ostream &OS)
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 MiscModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED PerformanceModuleAnchorDestination
volatile int BugproneModuleAnchorSource
static int clangTidyMain(int argc, const char **argv)
static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED CppCoreGuidelinesModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED ModernizeModuleAnchorDestination
void exportReplacements(const llvm::StringRef MainFilePath, const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
unsigned errorsIgnored() const
const char DefaultChecks[]
static std::unique_ptr< ClangTidyOptionsProvider > createOptionsProvider()
int main(int argc, const char **argv)
Contains displayed and ignored diagnostic counters for a ClangTidy run.
ClangTidyContext & Context
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))
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: ''
AnalyzeTemporaryDtors: false
FormatStyle: none
User: user
CheckOptions:
- key: some-check.SomeOption
value: 'some value'
...
)")
volatile int ModernizeModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED MPIModuleAnchorDestination
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))
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))