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' 44 AnalyzeTemporaryDtors: false 48 - key: some-check.SomeOption 58 static cl::opt<std::string>
Checks(
"checks", cl::desc(R
"( 59 Comma-separated list of globs with optional '-' 60 prefix. Globs are processed in order of 61 appearance in the list. Globs without '-' 62 prefix add checks with matching names to the 63 set, globs with the '-' prefix remove checks 64 with matching names from the set of enabled 65 checks. This option's value is appended to the 66 value of the 'Checks' option in .clang-tidy 71 static cl::opt<std::string>
WarningsAsErrors(
"warnings-as-errors", cl::desc(R
"( 72 Upgrades warnings to errors. Same format as 74 This option's value is appended to the value of 75 the 'WarningsAsErrors' option in .clang-tidy 81 static cl::opt<std::string>
HeaderFilter(
"header-filter", cl::desc(R
"( 82 Regular expression matching the names of the 83 headers to output diagnostics from. Diagnostics 84 from the main file of each translation unit are 86 Can be used together with -line-filter. 87 This option overrides the 'HeaderFilter' option 88 in .clang-tidy file, if any. 95 cl::desc(
"Display the errors from system headers."),
97 static cl::opt<std::string>
LineFilter(
"line-filter", cl::desc(R
"( 98 List of files with line ranges to filter the 99 warnings. Can be used together with 100 -header-filter. The format of the list is a 101 JSON array of objects: 103 {"name":"file1.cpp","lines":[[1,3],[5,7]]}, 110 static cl::opt<bool>
Fix(
"fix", cl::desc(R
"( 111 Apply suggested fixes. Without -fix-errors 112 clang-tidy will bail out if any compilation 117 static cl::opt<bool>
FixErrors(
"fix-errors", cl::desc(R
"( 118 Apply suggested fixes even if compilation 119 errors were found. If compiler errors have 120 attached fix-its, clang-tidy will apply them as 125 static cl::opt<std::string>
FormatStyle(
"format-style", cl::desc(R
"( 126 Style for formatting code around applied fixes: 127 - 'none' (default) turns off formatting 128 - 'file' (literally 'file', not a placeholder) 129 uses .clang-format file in the closest parent 131 - '{ <json> }' specifies options inline, e.g. 132 -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' 133 - 'llvm', 'google', 'webkit', 'mozilla' 134 See clang-format documentation for the up-to-date 135 information about formatting styles and options. 136 This option overrides the 'FormatStyle` option in 137 .clang-tidy file, if any. 142 static cl::opt<bool>
ListChecks(
"list-checks", cl::desc(R
"( 143 List all enabled checks and exit. Use with 144 -checks=* to list all available checks. 148 static cl::opt<bool>
ExplainConfig(
"explain-config", cl::desc(R
"( 149 For each enabled check explains, where it is 150 enabled, i.e. in clang-tidy binary, command 151 line or a specific configuration file. 155 static cl::opt<std::string>
Config(
"config", cl::desc(R
"( 156 Specifies a configuration in YAML/JSON format: 157 -config="{Checks: '*', 158 CheckOptions: [{key: x, 160 When the value is empty, clang-tidy will 161 attempt to find a file named .clang-tidy for 162 each source file in its parent directories. 166 static cl::opt<bool>
DumpConfig(
"dump-config", cl::desc(R
"( 167 Dumps configuration in the YAML format to 168 stdout. This option can be used along with a 169 file name (and '--' if the file is outside of a 170 project with configured compilation database). 171 The configuration used for this file will be 173 Use along with -checks=* to include 174 configuration of all checks. 179 Enable per-check timing profiles, and print a 187 Enable temporary destructor-aware analysis in 188 clang-analyzer- checks. 189 This option overrides the value read from a 195 static cl::opt<std::string>
ExportFixes(
"export-fixes", cl::desc(R
"( 196 YAML file to store suggested fixes in. The 197 stored fixes can be applied to the input source 198 code with clang-apply-replacements. 200 cl::value_desc("filename"),
203 static cl::opt<bool>
Quiet(
"quiet", cl::desc(R
"( 204 Run clang-tidy in quiet mode. This suppresses 205 printing statistics about ignored warnings and 206 warnings treated as errors if the respective 207 options are specified. 217 llvm::errs() <<
"Suppressed " << Stats.
errorsIgnored() <<
" warnings (";
218 StringRef Separator =
"";
225 <<
" due to line filter";
234 <<
" with check filters";
235 llvm::errs() <<
").\n";
237 llvm::errs() <<
"Use -header-filter=.* to display errors from all " 238 "non-system headers. Use -system-headers to display " 239 "errors from system headers as well.\n";
244 llvm::raw_ostream &OS) {
246 std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
249 for (
const auto &P : Profile.
Records) {
250 Timers.emplace_back(P.getValue(), P.getKey());
251 Total += P.getValue();
254 std::sort(Timers.begin(), Timers.end());
256 std::string
Line =
"===" + std::string(73,
'-') +
"===\n";
259 if (Total.getUserTime())
260 OS <<
" ---User Time---";
261 if (Total.getSystemTime())
262 OS <<
" --System Time--";
263 if (Total.getProcessTime())
264 OS <<
" --User+System--";
265 OS <<
" ---Wall Time---";
266 if (Total.getMemUsed())
268 OS <<
" --- Name ---\n";
271 for (
auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
272 I->first.print(Total, OS);
273 OS << I->second <<
'\n';
276 Total.print(Total, OS);
285 llvm::errs() <<
"Invalid LineFilter: " << Err.message() <<
"\n\nUsage:\n";
286 llvm::cl::PrintHelpMessage(
false,
true);
297 DefaultOptions.
User = llvm::sys::Process::GetEnv(
"USER");
299 if (!DefaultOptions.
User)
300 DefaultOptions.
User = llvm::sys::Process::GetEnv(
"USERNAME");
303 if (
Checks.getNumOccurrences() > 0)
317 if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
319 return llvm::make_unique<ConfigOptionsProvider>(
321 ClangTidyOptions::getDefaults().mergeWith(DefaultOptions),
322 *ParsedConfig, OverrideOptions);
324 llvm::errs() <<
"Error: invalid configuration specified.\n" 325 << ParsedConfig.getError().message() <<
"\n";
329 return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
338 auto *OptionsProvider = OwningOptionsProvider.get();
339 if (!OptionsProvider)
342 StringRef FileName(
"dummy");
343 auto PathList = OptionsParser.getSourcePathList();
344 if (!PathList.empty()) {
345 FileName = PathList.front();
348 SmallString<256> FilePath(FileName);
350 llvm::errs() <<
"Can't make absolute path from " << FileName <<
": " 351 << EC.message() <<
"\n";
354 std::vector<std::string> EnabledChecks =
getCheckNames(EffectiveOptions);
358 std::vector<clang::tidy::ClangTidyOptionsProvider::OptionsSource>
359 RawOptions = OptionsProvider->getRawOptions(FilePath);
360 for (
const std::string &Check : EnabledChecks) {
361 for (
auto It = RawOptions.rbegin(); It != RawOptions.rend(); ++It) {
363 llvm::outs() <<
"'" << Check <<
"' is enabled in the " << It->second
373 if (EnabledChecks.empty()) {
374 llvm::errs() <<
"No checks enabled.\n";
377 llvm::outs() <<
"Enabled checks:";
378 for (
const auto &CheckName : EnabledChecks)
379 llvm::outs() <<
"\n " << CheckName;
380 llvm::outs() <<
"\n\n";
387 ClangTidyOptions::getDefaults().mergeWith(
393 if (EnabledChecks.empty()) {
394 llvm::errs() <<
"Error: no checks enabled.\n";
395 llvm::cl::PrintHelpMessage(
false,
true);
399 if (PathList.empty()) {
400 llvm::errs() <<
"Error: no input files specified.\n";
401 llvm::cl::PrintHelpMessage(
false,
true);
407 llvm::InitializeAllTargetInfos();
408 llvm::InitializeAllTargetMCs();
409 llvm::InitializeAllAsmParsers();
412 runClangTidy(Context, OptionsParser.getCompilations(), PathList,
414 ArrayRef<ClangTidyError> Errors = Context.getErrors();
416 std::find_if(Errors.begin(), Errors.end(), [](
const ClangTidyError &E) {
417 return E.DiagLevel == ClangTidyError::Error;
420 const bool DisableFixes =
Fix && FoundErrors && !
FixErrors;
422 unsigned WErrorCount = 0;
429 llvm::raw_fd_ostream OS(
ExportFixes, EC, llvm::sys::fs::F_None);
431 llvm::errs() <<
"Error opening output file: " << EC.message() <<
'\n';
441 <<
"Found compiler errors, but -fix-errors was not specified.\n" 442 "Fixes have NOT been applied.\n\n";
450 StringRef Plural = WErrorCount == 1 ?
"" :
"s";
451 llvm::errs() << WErrorCount <<
" warning" << Plural <<
" treated as error" 538 int main(
int argc,
const char **argv) {
llvm::Optional< std::string > Checks
Checks filter.
volatile int GoogleModuleAnchorSource
static void printStats(const ClangTidyStats &Stats)
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))
llvm::Optional< std::string > HeaderFilterRegex
Output warnings from headers matching this filter.
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options)
Returns the effective check-specific options.
def make_absolute(f, directory)
static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination
Contains options for clang-tidy.
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.
llvm::StringMap< llvm::TimeRecord > Records
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))
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::Optional< std::string > FormatStyle
Format code around applied fixes with clang-format using this style.
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))
unsigned errorsIgnored() const
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.
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.
llvm::Optional< std::string > WarningsAsErrors
WarningsAsErrors filter.
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 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
llvm::Optional< bool > AnalyzeTemporaryDtors
Turns on temporary destructor-based analysis.
static int LLVM_ATTRIBUTE_UNUSED ModernizeModuleAnchorDestination
void exportReplacements(const llvm::StringRef MainFilePath, const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
const char DefaultChecks[]
static std::unique_ptr< ClangTidyOptionsProvider > createOptionsProvider()
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.
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
Container for clang-tidy profiling data.
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 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))