blob: 231533db4d6fc371897bd9cdc1c7a84e40080499 [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"
124 "should be used along with a file name (and '--' if the file is\n"
125 "outside of a project with configured compilation database). The\n"
126 "configuration used for this file will be printed."),
127 cl::init(false), cl::cat(ClangTidyCategory));
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000128
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000129static cl::opt<bool> EnableCheckProfile(
130 "enable-check-profile",
131 cl::desc("Enable per-check timing profiles, and print a report to stderr."),
132 cl::init(false), cl::cat(ClangTidyCategory));
133
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000134static cl::opt<bool> AnalyzeTemporaryDtors(
135 "analyze-temporary-dtors",
136 cl::desc("Enable temporary destructor-aware analysis in\n"
137 "clang-analyzer- checks.\n"
138 "This option overrides the value read from a\n"
139 ".clang-tidy file."),
140 cl::init(false), cl::cat(ClangTidyCategory));
Alex McCarthyfec08c72014-04-30 14:09:24 +0000141
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000142static cl::opt<std::string> ExportFixes(
143 "export-fixes",
144 cl::desc("YAML file to store suggested fixes in. The\n"
145 "stored fixes can be applied to the input source\n"
146 "code with clang-apply-replacements."),
147 cl::value_desc("filename"), cl::cat(ClangTidyCategory));
148
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000149namespace clang {
150namespace tidy {
151
152static void printStats(const ClangTidyStats &Stats) {
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000153 if (Stats.errorsIgnored()) {
154 llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
Alexander Kornienko5d174542014-05-07 09:06:53 +0000155 StringRef Separator = "";
156 if (Stats.ErrorsIgnoredNonUserCode) {
157 llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
158 Separator = ", ";
159 }
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000160 if (Stats.ErrorsIgnoredLineFilter) {
161 llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
162 << " due to line filter";
163 Separator = ", ";
164 }
Alexander Kornienko5d174542014-05-07 09:06:53 +0000165 if (Stats.ErrorsIgnoredNOLINT) {
166 llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
167 Separator = ", ";
168 }
169 if (Stats.ErrorsIgnoredCheckFilter)
170 llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
171 << " with check filters";
172 llvm::errs() << ").\n";
173 if (Stats.ErrorsIgnoredNonUserCode)
Aaron Ballman5a4892b2015-07-27 13:41:30 +0000174 llvm::errs() << "Use -header-filter=.* to display errors from all "
Alexander Kornienko5d174542014-05-07 09:06:53 +0000175 "non-system headers.\n";
176 }
177}
178
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000179static void printProfileData(const ProfileData &Profile,
180 llvm::raw_ostream &OS) {
181 // Time is first to allow for sorting by it.
182 std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
183 TimeRecord Total;
184
185 for (const auto& P : Profile.Records) {
186 Timers.emplace_back(P.getValue(), P.getKey());
187 Total += P.getValue();
188 }
189
190 std::sort(Timers.begin(), Timers.end());
191
192 std::string Line = "===" + std::string(73, '-') + "===\n";
193 OS << Line;
194
195 if (Total.getUserTime())
196 OS << " ---User Time---";
197 if (Total.getSystemTime())
198 OS << " --System Time--";
199 if (Total.getProcessTime())
200 OS << " --User+System--";
201 OS << " ---Wall Time---";
202 if (Total.getMemUsed())
203 OS << " ---Mem---";
204 OS << " --- Name ---\n";
205
206 // Loop through all of the timing data, printing it out.
207 for (auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
208 I->first.print(Total, OS);
209 OS << I->second << '\n';
210 }
211
212 Total.print(Total, OS);
213 OS << "Total\n";
214 OS << Line << "\n";
215 OS.flush();
216}
217
Benjamin Kramere7103712015-03-23 12:49:15 +0000218static std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider() {
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000219 ClangTidyGlobalOptions GlobalOptions;
220 if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000221 llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
222 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000223 return nullptr;
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000224 }
Alexander Kornienko33a9bcc2014-04-29 15:20:10 +0000225
Alexander Kornienkoe9951542014-09-24 18:36:03 +0000226 ClangTidyOptions DefaultOptions;
227 DefaultOptions.Checks = DefaultChecks;
228 DefaultOptions.HeaderFilterRegex = HeaderFilter;
Alexander Kornienko37f7abe2014-10-28 22:16:13 +0000229 DefaultOptions.SystemHeaders = SystemHeaders;
Alexander Kornienkoe9951542014-09-24 18:36:03 +0000230 DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
231 DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
232 // USERNAME is used on Windows.
233 if (!DefaultOptions.User)
234 DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
Alexander Kornienkoa4695222014-06-05 13:31:45 +0000235
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000236 ClangTidyOptions OverrideOptions;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000237 if (Checks.getNumOccurrences() > 0)
238 OverrideOptions.Checks = Checks;
239 if (HeaderFilter.getNumOccurrences() > 0)
240 OverrideOptions.HeaderFilterRegex = HeaderFilter;
Alexander Kornienko37f7abe2014-10-28 22:16:13 +0000241 if (SystemHeaders.getNumOccurrences() > 0)
242 OverrideOptions.SystemHeaders = SystemHeaders;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000243 if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
244 OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
245
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000246 if (!Config.empty()) {
247 if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
248 parseConfiguration(Config)) {
249 return llvm::make_unique<DefaultOptionsProvider>(
250 GlobalOptions, ClangTidyOptions::getDefaults()
251 .mergeWith(DefaultOptions)
252 .mergeWith(*ParsedConfig)
253 .mergeWith(OverrideOptions));
254 } else {
255 llvm::errs() << "Error: invalid configuration specified.\n"
256 << ParsedConfig.getError().message() << "\n";
257 return nullptr;
258 }
259 }
260 return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
261 OverrideOptions);
262}
263
Benjamin Kramere7103712015-03-23 12:49:15 +0000264static int clangTidyMain(int argc, const char **argv) {
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000265 CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
266 cl::ZeroOrMore);
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000267
268 auto OptionsProvider = createOptionsProvider();
269 if (!OptionsProvider)
270 return 1;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000271
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000272 StringRef FileName("dummy");
273 auto PathList = OptionsParser.getSourcePathList();
274 if (!PathList.empty()) {
Alexander Kornienkoe0c900e2015-08-17 11:27:11 +0000275 FileName = PathList.front();
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000276 }
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000277 ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
278 std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000279
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000280 if (ListChecks) {
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000281 llvm::outs() << "Enabled checks:";
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000282 for (auto CheckName : EnabledChecks)
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000283 llvm::outs() << "\n " << CheckName;
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000284 llvm::outs() << "\n\n";
285 return 0;
286 }
287
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000288 if (DumpConfig) {
Alexander Kornienko6e0cbc82014-09-12 08:53:36 +0000289 EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000290 llvm::outs() << configurationAsText(
291 ClangTidyOptions::getDefaults().mergeWith(
292 EffectiveOptions))
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000293 << "\n";
294 return 0;
295 }
296
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000297 if (EnabledChecks.empty()) {
298 llvm::errs() << "Error: no checks enabled.\n";
299 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
300 return 1;
301 }
302
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000303 if (PathList.empty()) {
304 llvm::errs() << "Error: no input files specified.\n";
305 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
306 return 1;
307 }
308
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000309 ProfileData Profile;
310
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000311 std::vector<ClangTidyError> Errors;
312 ClangTidyStats Stats =
313 runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
Alexander Kornienko65eccb42015-08-17 10:03:27 +0000314 PathList, &Errors,
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000315 EnableCheckProfile ? &Profile : nullptr);
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000316 bool FoundErrors =
317 std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
318 return E.DiagLevel == ClangTidyError::Error;
319 }) != Errors.end();
320
321 const bool DisableFixes = Fix && FoundErrors && !FixErrors;
322
323 // -fix-errors implies -fix.
324 handleErrors(Errors, (FixErrors || Fix) && !DisableFixes);
Daniel Jasperd07c8402013-07-29 08:19:24 +0000325
Alexander Kornienko4153da22014-09-04 15:19:49 +0000326 if (!ExportFixes.empty() && !Errors.empty()) {
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000327 std::error_code EC;
328 llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
329 if (EC) {
330 llvm::errs() << "Error opening output file: " << EC.message() << '\n';
331 return 1;
332 }
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000333 exportReplacements(Errors, OS);
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000334 }
335
Alexander Kornienko5d174542014-05-07 09:06:53 +0000336 printStats(Stats);
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000337 if (DisableFixes)
Alexander Kornienkob0a9b702014-12-09 15:02:17 +0000338 llvm::errs()
339 << "Found compiler errors, but -fix-errors was not specified.\n"
340 "Fixes have NOT been applied.\n\n";
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000341
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000342 if (EnableCheckProfile)
343 printProfileData(Profile, llvm::errs());
344
Daniel Jasperd07c8402013-07-29 08:19:24 +0000345 return 0;
346}
Daniel Jasper89bbab02013-08-04 15:56:30 +0000347
Daniel Jasper89bbab02013-08-04 15:56:30 +0000348// This anchor is used to force the linker to link the LLVMModule.
349extern volatile int LLVMModuleAnchorSource;
Yaron Keren43b7ca72015-08-07 16:37:34 +0000350static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination = LLVMModuleAnchorSource;
Daniel Jasper89bbab02013-08-04 15:56:30 +0000351
352// This anchor is used to force the linker to link the GoogleModule.
353extern volatile int GoogleModuleAnchorSource;
Yaron Keren43b7ca72015-08-07 16:37:34 +0000354static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination = GoogleModuleAnchorSource;
Daniel Jasper89bbab02013-08-04 15:56:30 +0000355
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000356// This anchor is used to force the linker to link the MiscModule.
357extern volatile int MiscModuleAnchorSource;
Yaron Keren43b7ca72015-08-07 16:37:34 +0000358static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination = MiscModuleAnchorSource;
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000359
Alexander Kornienkofc650862015-08-14 13:17:11 +0000360// This anchor is used to force the linker to link the ModernizeModule.
361extern volatile int ModernizeModuleAnchorSource;
362static int ModernizeModuleAnchorDestination = ModernizeModuleAnchorSource;
363
Alexander Kornienko2192a8e2014-10-26 01:41:14 +0000364// This anchor is used to force the linker to link the ReadabilityModule.
365extern volatile int ReadabilityModuleAnchorSource;
Yaron Keren43b7ca72015-08-07 16:37:34 +0000366static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination = ReadabilityModuleAnchorSource;
Alexander Kornienko2192a8e2014-10-26 01:41:14 +0000367
Daniel Jasper89bbab02013-08-04 15:56:30 +0000368} // namespace tidy
369} // namespace clang
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000370
371int main(int argc, const char **argv) {
372 return clang::tidy::clangTidyMain(argc, argv);
373}