blob: a925a74de60aeec6ceb4b44b074be319e2a215e1 [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 Kornienko23fe9592014-05-15 14:27:36 +000038const char DefaultChecks[] =
39 "*," // Enable all checks, except these:
40 "-clang-analyzer-alpha*," // Too many false positives.
41 "-llvm-include-order," // Not implemented yet.
Alexander Kornienko23fe9592014-05-15 14:27:36 +000042 "-google-*,"; // Doesn't apply to LLVM.
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000043
Alexander Kornienko23fe9592014-05-15 14:27:36 +000044static cl::opt<std::string>
Alexander Kornienko3ab34672014-05-16 13:07:18 +000045Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n"
46 "prefix. Globs are processed in order of appearance\n"
47 "in the list. Globs without '-' prefix add checks\n"
48 "with matching names to the set, globs with the '-'\n"
49 "prefix remove checks with matching names from the\n"
Alexander Kornienkod53d2682014-09-04 14:23:36 +000050 "set of enabled checks.\n"
51 "This option's value is appended to the value read\n"
52 "from a .clang-tidy file, if any."),
Alexander Kornienko23fe9592014-05-15 14:27:36 +000053 cl::init(""), cl::cat(ClangTidyCategory));
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000054
Alexander Kornienko3ab34672014-05-16 13:07:18 +000055static cl::opt<std::string>
56HeaderFilter("header-filter",
57 cl::desc("Regular expression matching the names of the\n"
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000058 "headers to output diagnostics from. Diagnostics\n"
59 "from the main file of each translation unit are\n"
60 "always displayed.\n"
Alexander Kornienkod53d2682014-09-04 14:23:36 +000061 "Can be used together with -line-filter.\n"
62 "This option overrides the value read from a\n"
63 ".clang-tidy file."),
Alexander Kornienko3ab34672014-05-16 13:07:18 +000064 cl::init(""), cl::cat(ClangTidyCategory));
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000065
Alexander Kornienko37f7abe2014-10-28 22:16:13 +000066static cl::opt<bool>
67 SystemHeaders("system-headers",
68 cl::desc("Display the errors from system headers"),
69 cl::init(false), cl::cat(ClangTidyCategory));
Alexander Kornienkodad4acb2014-05-22 16:07:11 +000070static cl::opt<std::string>
71LineFilter("line-filter",
72 cl::desc("List of files with line ranges to filter the\n"
73 "warnings. Can be used together with\n"
74 "-header-filter. The format of the list is a JSON\n"
75 "array of objects:\n"
76 " [\n"
77 " {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n"
78 " {\"name\":\"file2.h\"}\n"
79 " ]"),
80 cl::init(""), cl::cat(ClangTidyCategory));
81
Daniel Jasperd07c8402013-07-29 08:19:24 +000082static cl::opt<bool> Fix("fix", cl::desc("Fix detected errors if possible."),
83 cl::init(false), cl::cat(ClangTidyCategory));
84
Alexander Kornienko3ab34672014-05-16 13:07:18 +000085static cl::opt<bool>
86ListChecks("list-checks",
87 cl::desc("List all enabled checks and exit. Use with\n"
88 "-checks='*' to list all available checks."),
89 cl::init(false), cl::cat(ClangTidyCategory));
Daniel Jasperd07c8402013-07-29 08:19:24 +000090
Alexander Kornienkoeff4e922014-09-26 11:42:29 +000091static cl::opt<std::string> Config(
92 "config",
93 cl::desc("Specifies a configuration in YAML/JSON format:\n"
94 " -config=\"{Checks: '*', CheckOptions: {key: x, value: y}}\"\n"
95 "When the value is empty, clang-tidy will attempt to find\n"
Alexander Kornienko7165e892014-09-26 11:48:53 +000096 "a file named .clang-tidy for each source file in its parent\n"
Alexander Kornienkoeff4e922014-09-26 11:42:29 +000097 "directories."),
98 cl::init(""), cl::cat(ClangTidyCategory));
99
Alexander Kornienko3ab34672014-05-16 13:07:18 +0000100static cl::opt<bool>
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000101DumpConfig("dump-config",
102 cl::desc("Dumps configuration in the YAML format to stdout."),
103 cl::init(false), cl::cat(ClangTidyCategory));
104
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000105static cl::opt<bool> EnableCheckProfile(
106 "enable-check-profile",
107 cl::desc("Enable per-check timing profiles, and print a report to stderr."),
108 cl::init(false), cl::cat(ClangTidyCategory));
109
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000110static cl::opt<bool> AnalyzeTemporaryDtors(
111 "analyze-temporary-dtors",
112 cl::desc("Enable temporary destructor-aware analysis in\n"
113 "clang-analyzer- checks.\n"
114 "This option overrides the value read from a\n"
115 ".clang-tidy file."),
116 cl::init(false), cl::cat(ClangTidyCategory));
Alex McCarthyfec08c72014-04-30 14:09:24 +0000117
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000118static cl::opt<std::string> ExportFixes(
119 "export-fixes",
120 cl::desc("YAML file to store suggested fixes in. The\n"
121 "stored fixes can be applied to the input source\n"
122 "code with clang-apply-replacements."),
123 cl::value_desc("filename"), cl::cat(ClangTidyCategory));
124
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000125namespace clang {
126namespace tidy {
127
128static void printStats(const ClangTidyStats &Stats) {
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000129 if (Stats.errorsIgnored()) {
130 llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
Alexander Kornienko5d174542014-05-07 09:06:53 +0000131 StringRef Separator = "";
132 if (Stats.ErrorsIgnoredNonUserCode) {
133 llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
134 Separator = ", ";
135 }
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000136 if (Stats.ErrorsIgnoredLineFilter) {
137 llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
138 << " due to line filter";
139 Separator = ", ";
140 }
Alexander Kornienko5d174542014-05-07 09:06:53 +0000141 if (Stats.ErrorsIgnoredNOLINT) {
142 llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
143 Separator = ", ";
144 }
145 if (Stats.ErrorsIgnoredCheckFilter)
146 llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
147 << " with check filters";
148 llvm::errs() << ").\n";
149 if (Stats.ErrorsIgnoredNonUserCode)
150 llvm::errs() << "Use -header-filter='.*' to display errors from all "
151 "non-system headers.\n";
152 }
153}
154
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000155static void printProfileData(const ProfileData &Profile,
156 llvm::raw_ostream &OS) {
157 // Time is first to allow for sorting by it.
158 std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
159 TimeRecord Total;
160
161 for (const auto& P : Profile.Records) {
162 Timers.emplace_back(P.getValue(), P.getKey());
163 Total += P.getValue();
164 }
165
166 std::sort(Timers.begin(), Timers.end());
167
168 std::string Line = "===" + std::string(73, '-') + "===\n";
169 OS << Line;
170
171 if (Total.getUserTime())
172 OS << " ---User Time---";
173 if (Total.getSystemTime())
174 OS << " --System Time--";
175 if (Total.getProcessTime())
176 OS << " --User+System--";
177 OS << " ---Wall Time---";
178 if (Total.getMemUsed())
179 OS << " ---Mem---";
180 OS << " --- Name ---\n";
181
182 // Loop through all of the timing data, printing it out.
183 for (auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
184 I->first.print(Total, OS);
185 OS << I->second << '\n';
186 }
187
188 Total.print(Total, OS);
189 OS << "Total\n";
190 OS << Line << "\n";
191 OS.flush();
192}
193
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000194std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider() {
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000195 ClangTidyGlobalOptions GlobalOptions;
196 if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000197 llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
198 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000199 return nullptr;
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000200 }
Alexander Kornienko33a9bcc2014-04-29 15:20:10 +0000201
Alexander Kornienkoe9951542014-09-24 18:36:03 +0000202 ClangTidyOptions DefaultOptions;
203 DefaultOptions.Checks = DefaultChecks;
204 DefaultOptions.HeaderFilterRegex = HeaderFilter;
Alexander Kornienko37f7abe2014-10-28 22:16:13 +0000205 DefaultOptions.SystemHeaders = SystemHeaders;
Alexander Kornienkoe9951542014-09-24 18:36:03 +0000206 DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
207 DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
208 // USERNAME is used on Windows.
209 if (!DefaultOptions.User)
210 DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
Alexander Kornienkoa4695222014-06-05 13:31:45 +0000211
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000212 ClangTidyOptions OverrideOptions;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000213 if (Checks.getNumOccurrences() > 0)
214 OverrideOptions.Checks = Checks;
215 if (HeaderFilter.getNumOccurrences() > 0)
216 OverrideOptions.HeaderFilterRegex = HeaderFilter;
Alexander Kornienko37f7abe2014-10-28 22:16:13 +0000217 if (SystemHeaders.getNumOccurrences() > 0)
218 OverrideOptions.SystemHeaders = SystemHeaders;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000219 if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
220 OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
221
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000222 if (!Config.empty()) {
223 if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
224 parseConfiguration(Config)) {
225 return llvm::make_unique<DefaultOptionsProvider>(
226 GlobalOptions, ClangTidyOptions::getDefaults()
227 .mergeWith(DefaultOptions)
228 .mergeWith(*ParsedConfig)
229 .mergeWith(OverrideOptions));
230 } else {
231 llvm::errs() << "Error: invalid configuration specified.\n"
232 << ParsedConfig.getError().message() << "\n";
233 return nullptr;
234 }
235 }
236 return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
237 OverrideOptions);
238}
239
240int clangTidyMain(int argc, const char **argv) {
241 CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory);
242
243 auto OptionsProvider = createOptionsProvider();
244 if (!OptionsProvider)
245 return 1;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000246
247 std::string FileName = OptionsParser.getSourcePathList().front();
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000248 ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
249 std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000250
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000251 // FIXME: Allow using --list-checks without positional arguments.
252 if (ListChecks) {
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000253 llvm::outs() << "Enabled checks:";
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000254 for (auto CheckName : EnabledChecks)
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000255 llvm::outs() << "\n " << CheckName;
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000256 llvm::outs() << "\n\n";
257 return 0;
258 }
259
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000260 if (DumpConfig) {
Alexander Kornienko6e0cbc82014-09-12 08:53:36 +0000261 EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000262 llvm::outs() << configurationAsText(ClangTidyOptions::getDefaults()
263 .mergeWith(EffectiveOptions))
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000264 << "\n";
265 return 0;
266 }
267
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000268 if (EnabledChecks.empty()) {
269 llvm::errs() << "Error: no checks enabled.\n";
270 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
271 return 1;
272 }
273
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000274 ProfileData Profile;
275
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000276 std::vector<ClangTidyError> Errors;
277 ClangTidyStats Stats =
278 runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000279 OptionsParser.getSourcePathList(), &Errors,
280 EnableCheckProfile ? &Profile : nullptr);
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000281 handleErrors(Errors, Fix);
Daniel Jasperd07c8402013-07-29 08:19:24 +0000282
Alexander Kornienko4153da22014-09-04 15:19:49 +0000283 if (!ExportFixes.empty() && !Errors.empty()) {
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000284 std::error_code EC;
285 llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
286 if (EC) {
287 llvm::errs() << "Error opening output file: " << EC.message() << '\n';
288 return 1;
289 }
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000290 exportReplacements(Errors, OS);
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000291 }
292
Alexander Kornienko5d174542014-05-07 09:06:53 +0000293 printStats(Stats);
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000294 if (EnableCheckProfile)
295 printProfileData(Profile, llvm::errs());
296
Daniel Jasperd07c8402013-07-29 08:19:24 +0000297 return 0;
298}
Daniel Jasper89bbab02013-08-04 15:56:30 +0000299
Daniel Jasper89bbab02013-08-04 15:56:30 +0000300// This anchor is used to force the linker to link the LLVMModule.
301extern volatile int LLVMModuleAnchorSource;
302static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource;
303
304// This anchor is used to force the linker to link the GoogleModule.
305extern volatile int GoogleModuleAnchorSource;
306static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource;
307
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000308// This anchor is used to force the linker to link the MiscModule.
309extern volatile int MiscModuleAnchorSource;
310static int MiscModuleAnchorDestination = MiscModuleAnchorSource;
311
Alexander Kornienko2192a8e2014-10-26 01:41:14 +0000312// This anchor is used to force the linker to link the ReadabilityModule.
313extern volatile int ReadabilityModuleAnchorSource;
314static int ReadabilityModuleAnchorDestination = ReadabilityModuleAnchorSource;
315
Daniel Jasper89bbab02013-08-04 15:56:30 +0000316} // namespace tidy
317} // namespace clang
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000318
319int main(int argc, const char **argv) {
320 return clang::tidy::clangTidyMain(argc, argv);
321}