blob: a9437a846d8ae0487fa048024eecd0c3c164eb21 [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"
109 "-checks='*' to list all available checks."),
110 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)
174 llvm::errs() << "Use -header-filter='.*' to display errors from all "
175 "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 Kornienkoeff4e922014-09-26 11:42:29 +0000265 CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory);
266
267 auto OptionsProvider = createOptionsProvider();
268 if (!OptionsProvider)
269 return 1;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000270
271 std::string FileName = OptionsParser.getSourcePathList().front();
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000272 ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
273 std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000274
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000275 // FIXME: Allow using --list-checks without positional arguments.
276 if (ListChecks) {
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000277 llvm::outs() << "Enabled checks:";
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000278 for (auto CheckName : EnabledChecks)
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000279 llvm::outs() << "\n " << CheckName;
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000280 llvm::outs() << "\n\n";
281 return 0;
282 }
283
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000284 if (DumpConfig) {
Alexander Kornienko6e0cbc82014-09-12 08:53:36 +0000285 EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000286 llvm::outs() << configurationAsText(ClangTidyOptions::getDefaults()
287 .mergeWith(EffectiveOptions))
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000288 << "\n";
289 return 0;
290 }
291
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000292 if (EnabledChecks.empty()) {
293 llvm::errs() << "Error: no checks enabled.\n";
294 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
295 return 1;
296 }
297
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000298 ProfileData Profile;
299
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000300 std::vector<ClangTidyError> Errors;
301 ClangTidyStats Stats =
302 runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000303 OptionsParser.getSourcePathList(), &Errors,
304 EnableCheckProfile ? &Profile : nullptr);
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000305 bool FoundErrors =
306 std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
307 return E.DiagLevel == ClangTidyError::Error;
308 }) != Errors.end();
309
310 const bool DisableFixes = Fix && FoundErrors && !FixErrors;
311
312 // -fix-errors implies -fix.
313 handleErrors(Errors, (FixErrors || Fix) && !DisableFixes);
Daniel Jasperd07c8402013-07-29 08:19:24 +0000314
Alexander Kornienko4153da22014-09-04 15:19:49 +0000315 if (!ExportFixes.empty() && !Errors.empty()) {
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000316 std::error_code EC;
317 llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
318 if (EC) {
319 llvm::errs() << "Error opening output file: " << EC.message() << '\n';
320 return 1;
321 }
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000322 exportReplacements(Errors, OS);
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000323 }
324
Alexander Kornienko5d174542014-05-07 09:06:53 +0000325 printStats(Stats);
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000326 if (DisableFixes)
Alexander Kornienkob0a9b702014-12-09 15:02:17 +0000327 llvm::errs()
328 << "Found compiler errors, but -fix-errors was not specified.\n"
329 "Fixes have NOT been applied.\n\n";
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000330
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000331 if (EnableCheckProfile)
332 printProfileData(Profile, llvm::errs());
333
Daniel Jasperd07c8402013-07-29 08:19:24 +0000334 return 0;
335}
Daniel Jasper89bbab02013-08-04 15:56:30 +0000336
Daniel Jasper89bbab02013-08-04 15:56:30 +0000337// This anchor is used to force the linker to link the LLVMModule.
338extern volatile int LLVMModuleAnchorSource;
339static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource;
340
341// This anchor is used to force the linker to link the GoogleModule.
342extern volatile int GoogleModuleAnchorSource;
343static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource;
344
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000345// This anchor is used to force the linker to link the MiscModule.
346extern volatile int MiscModuleAnchorSource;
347static int MiscModuleAnchorDestination = MiscModuleAnchorSource;
348
Alexander Kornienko2192a8e2014-10-26 01:41:14 +0000349// This anchor is used to force the linker to link the ReadabilityModule.
350extern volatile int ReadabilityModuleAnchorSource;
351static int ReadabilityModuleAnchorDestination = ReadabilityModuleAnchorSource;
352
Daniel Jasper89bbab02013-08-04 15:56:30 +0000353} // namespace tidy
354} // namespace clang
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000355
356int main(int argc, const char **argv) {
357 return clang::tidy::clangTidyMain(argc, argv);
358}