blob: b6e6445c6207597abe50e970461df7e76fd4ce25 [file] [log] [blame]
Daniel Jasperd07c8402013-07-29 08:19:24 +00001//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file This file implements a clang-tidy tool.
11///
12/// This tool uses the Clang Tooling infrastructure, see
13/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
14/// for details on setting it up with LLVM source tree.
15///
16//===----------------------------------------------------------------------===//
17
18#include "../ClangTidy.h"
Manuel Klimek814f9bd2013-11-14 15:49:44 +000019#include "clang/Tooling/CommonOptionsParser.h"
Alexander Kornienkoe9951542014-09-24 18:36:03 +000020#include "llvm/Support/Process.h"
Daniel Jasperd07c8402013-07-29 08:19:24 +000021
22using namespace clang::ast_matchers;
23using namespace clang::driver;
24using namespace clang::tooling;
25using namespace llvm;
26
Alexander Kornienko99c9d6a2014-02-05 13:43:27 +000027static cl::OptionCategory ClangTidyCategory("clang-tidy options");
Daniel Jasperd07c8402013-07-29 08:19:24 +000028
Manuel Klimek814f9bd2013-11-14 15:49:44 +000029static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
Alexander Kornienkod53d2682014-09-04 14:23:36 +000030static cl::extrahelp ClangTidyHelp(
31 "Configuration files:\n"
32 " clang-tidy attempts to read configuration for each source file from a\n"
33 " .clang-tidy file located in the closest parent directory of the source\n"
34 " file. If any configuration options have a corresponding command-line\n"
35 " option, command-line option takes precedence. The effective\n"
Alexander Kornienko5c423312014-12-03 14:03:03 +000036 " configuration can be inspected using -dump-config:\n"
37 "\n"
38 " $ clang-tidy -dump-config - --\n"
39 " ---\n"
40 " Checks: '-*,some-check'\n"
41 " HeaderFilterRegex: ''\n"
42 " AnalyzeTemporaryDtors: false\n"
43 " User: user\n"
44 " CheckOptions: \n"
45 " - key: some-check.SomeOption\n"
46 " value: 'some value'\n"
47 " ...\n"
48 "\n\n");
Daniel Jasperd07c8402013-07-29 08:19:24 +000049
Alexander Kornienko50ab1562014-10-29 18:25:09 +000050const char DefaultChecks[] = // Enable these checks:
51 "clang-diagnostic-*," // * compiler diagnostics
52 "clang-analyzer-*," // * Static Analyzer checks
53 "-clang-analyzer-alpha*"; // * but not alpha checks: many false positives
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000054
Alexander Kornienko23fe9592014-05-15 14:27:36 +000055static cl::opt<std::string>
Alexander Kornienko3ab34672014-05-16 13:07:18 +000056Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n"
57 "prefix. Globs are processed in order of appearance\n"
58 "in the list. Globs without '-' prefix add checks\n"
59 "with matching names to the set, globs with the '-'\n"
60 "prefix remove checks with matching names from the\n"
Alexander Kornienkod53d2682014-09-04 14:23:36 +000061 "set of enabled checks.\n"
62 "This option's value is appended to the value read\n"
63 "from a .clang-tidy file, if any."),
Alexander Kornienko23fe9592014-05-15 14:27:36 +000064 cl::init(""), cl::cat(ClangTidyCategory));
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000065
Alexander Kornienko3ab34672014-05-16 13:07:18 +000066static cl::opt<std::string>
67HeaderFilter("header-filter",
68 cl::desc("Regular expression matching the names of the\n"
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000069 "headers to output diagnostics from. Diagnostics\n"
70 "from the main file of each translation unit are\n"
71 "always displayed.\n"
Alexander Kornienkod53d2682014-09-04 14:23:36 +000072 "Can be used together with -line-filter.\n"
73 "This option overrides the value read from a\n"
74 ".clang-tidy file."),
Alexander Kornienko3ab34672014-05-16 13:07:18 +000075 cl::init(""), cl::cat(ClangTidyCategory));
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000076
Alexander Kornienko37f7abe2014-10-28 22:16:13 +000077static cl::opt<bool>
78 SystemHeaders("system-headers",
Alexander Kornienko5eac3c62014-11-03 14:06:31 +000079 cl::desc("Display the errors from system headers."),
Alexander Kornienko37f7abe2014-10-28 22:16:13 +000080 cl::init(false), cl::cat(ClangTidyCategory));
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000081static cl::opt<std::string>
82LineFilter("line-filter",
83 cl::desc("List of files with line ranges to filter the\n"
84 "warnings. Can be used together with\n"
85 "-header-filter. The format of the list is a JSON\n"
86 "array of objects:\n"
87 " [\n"
88 " {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n"
89 " {\"name\":\"file2.h\"}\n"
90 " ]"),
91 cl::init(""), cl::cat(ClangTidyCategory));
92
Alexander Kornienko5eac3c62014-11-03 14:06:31 +000093static cl::opt<bool>
94 Fix("fix", cl::desc("Apply suggested fixes. Without -fix-errors\n"
95 "clang-tidy will bail out if any compilation\n"
96 "errors were found."),
97 cl::init(false), cl::cat(ClangTidyCategory));
98
99static cl::opt<bool>
100 FixErrors("fix-errors",
101 cl::desc("Apply suggested fixes even if compilation errors\n"
102 "were found. If compiler errors have attached\n"
103 "fix-its, clang-tidy will apply them as well."),
104 cl::init(false), cl::cat(ClangTidyCategory));
Daniel Jasperd07c8402013-07-29 08:19:24 +0000105
Alexander Kornienko3ab34672014-05-16 13:07:18 +0000106static cl::opt<bool>
107ListChecks("list-checks",
108 cl::desc("List all enabled checks and exit. Use with\n"
Aaron Ballman5a4892b2015-07-27 13:41:30 +0000109 "-checks=* to list all available checks."),
Alexander Kornienko3ab34672014-05-16 13:07:18 +0000110 cl::init(false), cl::cat(ClangTidyCategory));
Daniel Jasperd07c8402013-07-29 08:19:24 +0000111
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000112static cl::opt<std::string> Config(
113 "config",
114 cl::desc("Specifies a configuration in YAML/JSON format:\n"
Alexander Kornienko5c423312014-12-03 14:03:03 +0000115 " -config=\"{Checks: '*', CheckOptions: [{key: x, value: y}]}\"\n"
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000116 "When the value is empty, clang-tidy will attempt to find\n"
Alexander Kornienko7165e892014-09-26 11:48:53 +0000117 "a file named .clang-tidy for each source file in its parent\n"
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000118 "directories."),
119 cl::init(""), cl::cat(ClangTidyCategory));
120
Alexander Kornienko5c423312014-12-03 14:03:03 +0000121static cl::opt<bool> DumpConfig(
122 "dump-config",
123 cl::desc("Dumps configuration in the YAML format to stdout. This option\n"
Alexander Kornienkobe506982015-09-16 13:21:57 +0000124 "can be used along with a file name (and '--' if the file is\n"
Alexander Kornienko5c423312014-12-03 14:03:03 +0000125 "outside of a project with configured compilation database). The\n"
Alexander Kornienkobe506982015-09-16 13:21:57 +0000126 "configuration used for this file will be printed.\n"
127 "Use along with -checks=* to include configuration of all\n"
128 "checks.\n"),
Alexander Kornienko5c423312014-12-03 14:03:03 +0000129 cl::init(false), cl::cat(ClangTidyCategory));
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000130
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000131static cl::opt<bool> EnableCheckProfile(
132 "enable-check-profile",
133 cl::desc("Enable per-check timing profiles, and print a report to stderr."),
134 cl::init(false), cl::cat(ClangTidyCategory));
135
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000136static cl::opt<bool> AnalyzeTemporaryDtors(
137 "analyze-temporary-dtors",
138 cl::desc("Enable temporary destructor-aware analysis in\n"
139 "clang-analyzer- checks.\n"
140 "This option overrides the value read from a\n"
141 ".clang-tidy file."),
142 cl::init(false), cl::cat(ClangTidyCategory));
Alex McCarthyfec08c72014-04-30 14:09:24 +0000143
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000144static cl::opt<std::string> ExportFixes(
145 "export-fixes",
146 cl::desc("YAML file to store suggested fixes in. The\n"
147 "stored fixes can be applied to the input source\n"
148 "code with clang-apply-replacements."),
149 cl::value_desc("filename"), cl::cat(ClangTidyCategory));
150
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000151namespace clang {
152namespace tidy {
153
154static void printStats(const ClangTidyStats &Stats) {
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000155 if (Stats.errorsIgnored()) {
156 llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
Alexander Kornienko5d174542014-05-07 09:06:53 +0000157 StringRef Separator = "";
158 if (Stats.ErrorsIgnoredNonUserCode) {
159 llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
160 Separator = ", ";
161 }
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000162 if (Stats.ErrorsIgnoredLineFilter) {
163 llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
164 << " due to line filter";
165 Separator = ", ";
166 }
Alexander Kornienko5d174542014-05-07 09:06:53 +0000167 if (Stats.ErrorsIgnoredNOLINT) {
168 llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
169 Separator = ", ";
170 }
171 if (Stats.ErrorsIgnoredCheckFilter)
172 llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
173 << " with check filters";
174 llvm::errs() << ").\n";
175 if (Stats.ErrorsIgnoredNonUserCode)
Aaron Ballman5a4892b2015-07-27 13:41:30 +0000176 llvm::errs() << "Use -header-filter=.* to display errors from all "
Alexander Kornienko5d174542014-05-07 09:06:53 +0000177 "non-system headers.\n";
178 }
179}
180
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000181static void printProfileData(const ProfileData &Profile,
182 llvm::raw_ostream &OS) {
183 // Time is first to allow for sorting by it.
184 std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
185 TimeRecord Total;
186
187 for (const auto& P : Profile.Records) {
188 Timers.emplace_back(P.getValue(), P.getKey());
189 Total += P.getValue();
190 }
191
192 std::sort(Timers.begin(), Timers.end());
193
194 std::string Line = "===" + std::string(73, '-') + "===\n";
195 OS << Line;
196
197 if (Total.getUserTime())
198 OS << " ---User Time---";
199 if (Total.getSystemTime())
200 OS << " --System Time--";
201 if (Total.getProcessTime())
202 OS << " --User+System--";
203 OS << " ---Wall Time---";
204 if (Total.getMemUsed())
205 OS << " ---Mem---";
206 OS << " --- Name ---\n";
207
208 // Loop through all of the timing data, printing it out.
209 for (auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
210 I->first.print(Total, OS);
211 OS << I->second << '\n';
212 }
213
214 Total.print(Total, OS);
215 OS << "Total\n";
216 OS << Line << "\n";
217 OS.flush();
218}
219
Benjamin Kramere7103712015-03-23 12:49:15 +0000220static std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider() {
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000221 ClangTidyGlobalOptions GlobalOptions;
222 if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000223 llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
224 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000225 return nullptr;
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000226 }
Alexander Kornienko33a9bcc2014-04-29 15:20:10 +0000227
Alexander Kornienkoe9951542014-09-24 18:36:03 +0000228 ClangTidyOptions DefaultOptions;
229 DefaultOptions.Checks = DefaultChecks;
230 DefaultOptions.HeaderFilterRegex = HeaderFilter;
Alexander Kornienko37f7abe2014-10-28 22:16:13 +0000231 DefaultOptions.SystemHeaders = SystemHeaders;
Alexander Kornienkoe9951542014-09-24 18:36:03 +0000232 DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
233 DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
234 // USERNAME is used on Windows.
235 if (!DefaultOptions.User)
236 DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
Alexander Kornienkoa4695222014-06-05 13:31:45 +0000237
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000238 ClangTidyOptions OverrideOptions;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000239 if (Checks.getNumOccurrences() > 0)
240 OverrideOptions.Checks = Checks;
241 if (HeaderFilter.getNumOccurrences() > 0)
242 OverrideOptions.HeaderFilterRegex = HeaderFilter;
Alexander Kornienko37f7abe2014-10-28 22:16:13 +0000243 if (SystemHeaders.getNumOccurrences() > 0)
244 OverrideOptions.SystemHeaders = SystemHeaders;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000245 if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
246 OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
247
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000248 if (!Config.empty()) {
249 if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
250 parseConfiguration(Config)) {
251 return llvm::make_unique<DefaultOptionsProvider>(
252 GlobalOptions, ClangTidyOptions::getDefaults()
253 .mergeWith(DefaultOptions)
254 .mergeWith(*ParsedConfig)
255 .mergeWith(OverrideOptions));
256 } else {
257 llvm::errs() << "Error: invalid configuration specified.\n"
258 << ParsedConfig.getError().message() << "\n";
259 return nullptr;
260 }
261 }
262 return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
263 OverrideOptions);
264}
265
Benjamin Kramere7103712015-03-23 12:49:15 +0000266static int clangTidyMain(int argc, const char **argv) {
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000267 CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
268 cl::ZeroOrMore);
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000269
270 auto OptionsProvider = createOptionsProvider();
271 if (!OptionsProvider)
272 return 1;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000273
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000274 StringRef FileName("dummy");
275 auto PathList = OptionsParser.getSourcePathList();
276 if (!PathList.empty()) {
Alexander Kornienkoe0c900e2015-08-17 11:27:11 +0000277 FileName = PathList.front();
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000278 }
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000279 ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
280 std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000281
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000282 if (ListChecks) {
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000283 llvm::outs() << "Enabled checks:";
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000284 for (auto CheckName : EnabledChecks)
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000285 llvm::outs() << "\n " << CheckName;
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000286 llvm::outs() << "\n\n";
287 return 0;
288 }
289
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000290 if (DumpConfig) {
Alexander Kornienko6e0cbc82014-09-12 08:53:36 +0000291 EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000292 llvm::outs() << configurationAsText(
293 ClangTidyOptions::getDefaults().mergeWith(
294 EffectiveOptions))
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000295 << "\n";
296 return 0;
297 }
298
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000299 if (EnabledChecks.empty()) {
300 llvm::errs() << "Error: no checks enabled.\n";
301 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
302 return 1;
303 }
304
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000305 if (PathList.empty()) {
306 llvm::errs() << "Error: no input files specified.\n";
307 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
308 return 1;
309 }
310
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000311 ProfileData Profile;
312
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000313 std::vector<ClangTidyError> Errors;
314 ClangTidyStats Stats =
315 runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000316 PathList, &Errors,
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000317 EnableCheckProfile ? &Profile : nullptr);
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000318 bool FoundErrors =
319 std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
320 return E.DiagLevel == ClangTidyError::Error;
321 }) != Errors.end();
322
323 const bool DisableFixes = Fix && FoundErrors && !FixErrors;
324
325 // -fix-errors implies -fix.
326 handleErrors(Errors, (FixErrors || Fix) && !DisableFixes);
Daniel Jasperd07c8402013-07-29 08:19:24 +0000327
Alexander Kornienko4153da22014-09-04 15:19:49 +0000328 if (!ExportFixes.empty() && !Errors.empty()) {
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000329 std::error_code EC;
330 llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
331 if (EC) {
332 llvm::errs() << "Error opening output file: " << EC.message() << '\n';
333 return 1;
334 }
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000335 exportReplacements(Errors, OS);
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000336 }
337
Alexander Kornienko5d174542014-05-07 09:06:53 +0000338 printStats(Stats);
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000339 if (DisableFixes)
Alexander Kornienkob0a9b702014-12-09 15:02:17 +0000340 llvm::errs()
341 << "Found compiler errors, but -fix-errors was not specified.\n"
342 "Fixes have NOT been applied.\n\n";
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000343
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000344 if (EnableCheckProfile)
345 printProfileData(Profile, llvm::errs());
346
Daniel Jasperd07c8402013-07-29 08:19:24 +0000347 return 0;
348}
Daniel Jasper89bbab02013-08-04 15:56:30 +0000349
Daniel Jasper89bbab02013-08-04 15:56:30 +0000350// This anchor is used to force the linker to link the LLVMModule.
351extern volatile int LLVMModuleAnchorSource;
Alexander Kornienkoe1292f82015-08-19 16:54:51 +0000352static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination =
353 LLVMModuleAnchorSource;
Daniel Jasper89bbab02013-08-04 15:56:30 +0000354
355// This anchor is used to force the linker to link the GoogleModule.
356extern volatile int GoogleModuleAnchorSource;
Alexander Kornienkoe1292f82015-08-19 16:54:51 +0000357static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination =
358 GoogleModuleAnchorSource;
Daniel Jasper89bbab02013-08-04 15:56:30 +0000359
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000360// This anchor is used to force the linker to link the MiscModule.
361extern volatile int MiscModuleAnchorSource;
Alexander Kornienkoe1292f82015-08-19 16:54:51 +0000362static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination =
363 MiscModuleAnchorSource;
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000364
Alexander Kornienkofc650862015-08-14 13:17:11 +0000365// This anchor is used to force the linker to link the ModernizeModule.
366extern volatile int ModernizeModuleAnchorSource;
Alexander Kornienkoe1292f82015-08-19 16:54:51 +0000367static int LLVM_ATTRIBUTE_UNUSED ModernizeModuleAnchorDestination =
368 ModernizeModuleAnchorSource;
Alexander Kornienkofc650862015-08-14 13:17:11 +0000369
Alexander Kornienko2192a8e2014-10-26 01:41:14 +0000370// This anchor is used to force the linker to link the ReadabilityModule.
371extern volatile int ReadabilityModuleAnchorSource;
Alexander Kornienkoe1292f82015-08-19 16:54:51 +0000372static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination =
373 ReadabilityModuleAnchorSource;
Alexander Kornienko2192a8e2014-10-26 01:41:14 +0000374
Daniel Jasper89bbab02013-08-04 15:56:30 +0000375} // namespace tidy
376} // namespace clang
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000377
378int main(int argc, const char **argv) {
379 return clang::tidy::clangTidyMain(argc, argv);
380}