blob: 44843b48b7e7dce5184c9fe30048dab7560e8acf [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"
36 " configuration can be inspected using -dump-config.\n\n");
Daniel Jasperd07c8402013-07-29 08:19:24 +000037
Alexander Kornienko50ab1562014-10-29 18:25:09 +000038const char DefaultChecks[] = // Enable these checks:
39 "clang-diagnostic-*," // * compiler diagnostics
40 "clang-analyzer-*," // * Static Analyzer checks
41 "-clang-analyzer-alpha*"; // * but not alpha checks: many false positives
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000042
Alexander Kornienko23fe9592014-05-15 14:27:36 +000043static cl::opt<std::string>
Alexander Kornienko3ab34672014-05-16 13:07:18 +000044Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n"
45 "prefix. Globs are processed in order of appearance\n"
46 "in the list. Globs without '-' prefix add checks\n"
47 "with matching names to the set, globs with the '-'\n"
48 "prefix remove checks with matching names from the\n"
Alexander Kornienkod53d2682014-09-04 14:23:36 +000049 "set of enabled checks.\n"
50 "This option's value is appended to the value read\n"
51 "from a .clang-tidy file, if any."),
Alexander Kornienko23fe9592014-05-15 14:27:36 +000052 cl::init(""), cl::cat(ClangTidyCategory));
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000053
Alexander Kornienko3ab34672014-05-16 13:07:18 +000054static cl::opt<std::string>
55HeaderFilter("header-filter",
56 cl::desc("Regular expression matching the names of the\n"
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000057 "headers to output diagnostics from. Diagnostics\n"
58 "from the main file of each translation unit are\n"
59 "always displayed.\n"
Alexander Kornienkod53d2682014-09-04 14:23:36 +000060 "Can be used together with -line-filter.\n"
61 "This option overrides the value read from a\n"
62 ".clang-tidy file."),
Alexander Kornienko3ab34672014-05-16 13:07:18 +000063 cl::init(""), cl::cat(ClangTidyCategory));
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000064
Alexander Kornienko37f7abe2014-10-28 22:16:13 +000065static cl::opt<bool>
66 SystemHeaders("system-headers",
Alexander Kornienko5eac3c62014-11-03 14:06:31 +000067 cl::desc("Display the errors from system headers."),
Alexander Kornienko37f7abe2014-10-28 22:16:13 +000068 cl::init(false), cl::cat(ClangTidyCategory));
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000069static cl::opt<std::string>
70LineFilter("line-filter",
71 cl::desc("List of files with line ranges to filter the\n"
72 "warnings. Can be used together with\n"
73 "-header-filter. The format of the list is a JSON\n"
74 "array of objects:\n"
75 " [\n"
76 " {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n"
77 " {\"name\":\"file2.h\"}\n"
78 " ]"),
79 cl::init(""), cl::cat(ClangTidyCategory));
80
Alexander Kornienko5eac3c62014-11-03 14:06:31 +000081static cl::opt<bool>
82 Fix("fix", cl::desc("Apply suggested fixes. Without -fix-errors\n"
83 "clang-tidy will bail out if any compilation\n"
84 "errors were found."),
85 cl::init(false), cl::cat(ClangTidyCategory));
86
87static cl::opt<bool>
88 FixErrors("fix-errors",
89 cl::desc("Apply suggested fixes even if compilation errors\n"
90 "were found. If compiler errors have attached\n"
91 "fix-its, clang-tidy will apply them as well."),
92 cl::init(false), cl::cat(ClangTidyCategory));
Daniel Jasperd07c8402013-07-29 08:19:24 +000093
Alexander Kornienko3ab34672014-05-16 13:07:18 +000094static cl::opt<bool>
95ListChecks("list-checks",
96 cl::desc("List all enabled checks and exit. Use with\n"
97 "-checks='*' to list all available checks."),
98 cl::init(false), cl::cat(ClangTidyCategory));
Daniel Jasperd07c8402013-07-29 08:19:24 +000099
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000100static cl::opt<std::string> Config(
101 "config",
102 cl::desc("Specifies a configuration in YAML/JSON format:\n"
103 " -config=\"{Checks: '*', CheckOptions: {key: x, value: y}}\"\n"
104 "When the value is empty, clang-tidy will attempt to find\n"
Alexander Kornienko7165e892014-09-26 11:48:53 +0000105 "a file named .clang-tidy for each source file in its parent\n"
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000106 "directories."),
107 cl::init(""), cl::cat(ClangTidyCategory));
108
Alexander Kornienko3ab34672014-05-16 13:07:18 +0000109static cl::opt<bool>
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000110DumpConfig("dump-config",
111 cl::desc("Dumps configuration in the YAML format to stdout."),
112 cl::init(false), cl::cat(ClangTidyCategory));
113
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000114static cl::opt<bool> EnableCheckProfile(
115 "enable-check-profile",
116 cl::desc("Enable per-check timing profiles, and print a report to stderr."),
117 cl::init(false), cl::cat(ClangTidyCategory));
118
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000119static cl::opt<bool> AnalyzeTemporaryDtors(
120 "analyze-temporary-dtors",
121 cl::desc("Enable temporary destructor-aware analysis in\n"
122 "clang-analyzer- checks.\n"
123 "This option overrides the value read from a\n"
124 ".clang-tidy file."),
125 cl::init(false), cl::cat(ClangTidyCategory));
Alex McCarthyfec08c72014-04-30 14:09:24 +0000126
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000127static cl::opt<std::string> ExportFixes(
128 "export-fixes",
129 cl::desc("YAML file to store suggested fixes in. The\n"
130 "stored fixes can be applied to the input source\n"
131 "code with clang-apply-replacements."),
132 cl::value_desc("filename"), cl::cat(ClangTidyCategory));
133
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000134namespace clang {
135namespace tidy {
136
137static void printStats(const ClangTidyStats &Stats) {
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000138 if (Stats.errorsIgnored()) {
139 llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
Alexander Kornienko5d174542014-05-07 09:06:53 +0000140 StringRef Separator = "";
141 if (Stats.ErrorsIgnoredNonUserCode) {
142 llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
143 Separator = ", ";
144 }
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000145 if (Stats.ErrorsIgnoredLineFilter) {
146 llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
147 << " due to line filter";
148 Separator = ", ";
149 }
Alexander Kornienko5d174542014-05-07 09:06:53 +0000150 if (Stats.ErrorsIgnoredNOLINT) {
151 llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
152 Separator = ", ";
153 }
154 if (Stats.ErrorsIgnoredCheckFilter)
155 llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
156 << " with check filters";
157 llvm::errs() << ").\n";
158 if (Stats.ErrorsIgnoredNonUserCode)
159 llvm::errs() << "Use -header-filter='.*' to display errors from all "
160 "non-system headers.\n";
161 }
162}
163
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000164static void printProfileData(const ProfileData &Profile,
165 llvm::raw_ostream &OS) {
166 // Time is first to allow for sorting by it.
167 std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
168 TimeRecord Total;
169
170 for (const auto& P : Profile.Records) {
171 Timers.emplace_back(P.getValue(), P.getKey());
172 Total += P.getValue();
173 }
174
175 std::sort(Timers.begin(), Timers.end());
176
177 std::string Line = "===" + std::string(73, '-') + "===\n";
178 OS << Line;
179
180 if (Total.getUserTime())
181 OS << " ---User Time---";
182 if (Total.getSystemTime())
183 OS << " --System Time--";
184 if (Total.getProcessTime())
185 OS << " --User+System--";
186 OS << " ---Wall Time---";
187 if (Total.getMemUsed())
188 OS << " ---Mem---";
189 OS << " --- Name ---\n";
190
191 // Loop through all of the timing data, printing it out.
192 for (auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
193 I->first.print(Total, OS);
194 OS << I->second << '\n';
195 }
196
197 Total.print(Total, OS);
198 OS << "Total\n";
199 OS << Line << "\n";
200 OS.flush();
201}
202
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000203std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider() {
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000204 ClangTidyGlobalOptions GlobalOptions;
205 if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000206 llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
207 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000208 return nullptr;
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000209 }
Alexander Kornienko33a9bcc2014-04-29 15:20:10 +0000210
Alexander Kornienkoe9951542014-09-24 18:36:03 +0000211 ClangTidyOptions DefaultOptions;
212 DefaultOptions.Checks = DefaultChecks;
213 DefaultOptions.HeaderFilterRegex = HeaderFilter;
Alexander Kornienko37f7abe2014-10-28 22:16:13 +0000214 DefaultOptions.SystemHeaders = SystemHeaders;
Alexander Kornienkoe9951542014-09-24 18:36:03 +0000215 DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
216 DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
217 // USERNAME is used on Windows.
218 if (!DefaultOptions.User)
219 DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
Alexander Kornienkoa4695222014-06-05 13:31:45 +0000220
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000221 ClangTidyOptions OverrideOptions;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000222 if (Checks.getNumOccurrences() > 0)
223 OverrideOptions.Checks = Checks;
224 if (HeaderFilter.getNumOccurrences() > 0)
225 OverrideOptions.HeaderFilterRegex = HeaderFilter;
Alexander Kornienko37f7abe2014-10-28 22:16:13 +0000226 if (SystemHeaders.getNumOccurrences() > 0)
227 OverrideOptions.SystemHeaders = SystemHeaders;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000228 if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
229 OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
230
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000231 if (!Config.empty()) {
232 if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
233 parseConfiguration(Config)) {
234 return llvm::make_unique<DefaultOptionsProvider>(
235 GlobalOptions, ClangTidyOptions::getDefaults()
236 .mergeWith(DefaultOptions)
237 .mergeWith(*ParsedConfig)
238 .mergeWith(OverrideOptions));
239 } else {
240 llvm::errs() << "Error: invalid configuration specified.\n"
241 << ParsedConfig.getError().message() << "\n";
242 return nullptr;
243 }
244 }
245 return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
246 OverrideOptions);
247}
248
249int clangTidyMain(int argc, const char **argv) {
250 CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory);
251
252 auto OptionsProvider = createOptionsProvider();
253 if (!OptionsProvider)
254 return 1;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000255
256 std::string FileName = OptionsParser.getSourcePathList().front();
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000257 ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
258 std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000259
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000260 // FIXME: Allow using --list-checks without positional arguments.
261 if (ListChecks) {
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000262 llvm::outs() << "Enabled checks:";
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000263 for (auto CheckName : EnabledChecks)
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000264 llvm::outs() << "\n " << CheckName;
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000265 llvm::outs() << "\n\n";
266 return 0;
267 }
268
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000269 if (DumpConfig) {
Alexander Kornienko6e0cbc82014-09-12 08:53:36 +0000270 EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000271 llvm::outs() << configurationAsText(ClangTidyOptions::getDefaults()
272 .mergeWith(EffectiveOptions))
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000273 << "\n";
274 return 0;
275 }
276
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000277 if (EnabledChecks.empty()) {
278 llvm::errs() << "Error: no checks enabled.\n";
279 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
280 return 1;
281 }
282
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000283 ProfileData Profile;
284
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000285 std::vector<ClangTidyError> Errors;
286 ClangTidyStats Stats =
287 runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000288 OptionsParser.getSourcePathList(), &Errors,
289 EnableCheckProfile ? &Profile : nullptr);
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000290 bool FoundErrors =
291 std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
292 return E.DiagLevel == ClangTidyError::Error;
293 }) != Errors.end();
294
295 const bool DisableFixes = Fix && FoundErrors && !FixErrors;
296
297 // -fix-errors implies -fix.
298 handleErrors(Errors, (FixErrors || Fix) && !DisableFixes);
Daniel Jasperd07c8402013-07-29 08:19:24 +0000299
Alexander Kornienko4153da22014-09-04 15:19:49 +0000300 if (!ExportFixes.empty() && !Errors.empty()) {
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000301 std::error_code EC;
302 llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
303 if (EC) {
304 llvm::errs() << "Error opening output file: " << EC.message() << '\n';
305 return 1;
306 }
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000307 exportReplacements(Errors, OS);
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000308 }
309
Alexander Kornienko5d174542014-05-07 09:06:53 +0000310 printStats(Stats);
Alexander Kornienko5eac3c62014-11-03 14:06:31 +0000311 if (DisableFixes)
312 llvm::errs() << "Found compiler errors, but -fix-error was not specified.\n"
313 "Fixes have NOT been applied.\n\n";
314
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000315 if (EnableCheckProfile)
316 printProfileData(Profile, llvm::errs());
317
Daniel Jasperd07c8402013-07-29 08:19:24 +0000318 return 0;
319}
Daniel Jasper89bbab02013-08-04 15:56:30 +0000320
Daniel Jasper89bbab02013-08-04 15:56:30 +0000321// This anchor is used to force the linker to link the LLVMModule.
322extern volatile int LLVMModuleAnchorSource;
323static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource;
324
325// This anchor is used to force the linker to link the GoogleModule.
326extern volatile int GoogleModuleAnchorSource;
327static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource;
328
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000329// This anchor is used to force the linker to link the MiscModule.
330extern volatile int MiscModuleAnchorSource;
331static int MiscModuleAnchorDestination = MiscModuleAnchorSource;
332
Alexander Kornienko2192a8e2014-10-26 01:41:14 +0000333// This anchor is used to force the linker to link the ReadabilityModule.
334extern volatile int ReadabilityModuleAnchorSource;
335static int ReadabilityModuleAnchorDestination = ReadabilityModuleAnchorSource;
336
Daniel Jasper89bbab02013-08-04 15:56:30 +0000337} // namespace tidy
338} // namespace clang
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000339
340int main(int argc, const char **argv) {
341 return clang::tidy::clangTidyMain(argc, argv);
342}