blob: 5ef39bfa3c7f5d1c1628504643239095cdf25d78 [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",
67 cl::desc("Display the errors from system headers"),
68 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
Daniel Jasperd07c8402013-07-29 08:19:24 +000081static cl::opt<bool> Fix("fix", cl::desc("Fix detected errors if possible."),
82 cl::init(false), cl::cat(ClangTidyCategory));
83
Alexander Kornienko3ab34672014-05-16 13:07:18 +000084static cl::opt<bool>
85ListChecks("list-checks",
86 cl::desc("List all enabled checks and exit. Use with\n"
87 "-checks='*' to list all available checks."),
88 cl::init(false), cl::cat(ClangTidyCategory));
Daniel Jasperd07c8402013-07-29 08:19:24 +000089
Alexander Kornienkoeff4e922014-09-26 11:42:29 +000090static cl::opt<std::string> Config(
91 "config",
92 cl::desc("Specifies a configuration in YAML/JSON format:\n"
93 " -config=\"{Checks: '*', CheckOptions: {key: x, value: y}}\"\n"
94 "When the value is empty, clang-tidy will attempt to find\n"
Alexander Kornienko7165e892014-09-26 11:48:53 +000095 "a file named .clang-tidy for each source file in its parent\n"
Alexander Kornienkoeff4e922014-09-26 11:42:29 +000096 "directories."),
97 cl::init(""), cl::cat(ClangTidyCategory));
98
Alexander Kornienko3ab34672014-05-16 13:07:18 +000099static cl::opt<bool>
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000100DumpConfig("dump-config",
101 cl::desc("Dumps configuration in the YAML format to stdout."),
102 cl::init(false), cl::cat(ClangTidyCategory));
103
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000104static cl::opt<bool> EnableCheckProfile(
105 "enable-check-profile",
106 cl::desc("Enable per-check timing profiles, and print a report to stderr."),
107 cl::init(false), cl::cat(ClangTidyCategory));
108
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000109static cl::opt<bool> AnalyzeTemporaryDtors(
110 "analyze-temporary-dtors",
111 cl::desc("Enable temporary destructor-aware analysis in\n"
112 "clang-analyzer- checks.\n"
113 "This option overrides the value read from a\n"
114 ".clang-tidy file."),
115 cl::init(false), cl::cat(ClangTidyCategory));
Alex McCarthyfec08c72014-04-30 14:09:24 +0000116
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000117static cl::opt<std::string> ExportFixes(
118 "export-fixes",
119 cl::desc("YAML file to store suggested fixes in. The\n"
120 "stored fixes can be applied to the input source\n"
121 "code with clang-apply-replacements."),
122 cl::value_desc("filename"), cl::cat(ClangTidyCategory));
123
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000124namespace clang {
125namespace tidy {
126
127static void printStats(const ClangTidyStats &Stats) {
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000128 if (Stats.errorsIgnored()) {
129 llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
Alexander Kornienko5d174542014-05-07 09:06:53 +0000130 StringRef Separator = "";
131 if (Stats.ErrorsIgnoredNonUserCode) {
132 llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
133 Separator = ", ";
134 }
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000135 if (Stats.ErrorsIgnoredLineFilter) {
136 llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
137 << " due to line filter";
138 Separator = ", ";
139 }
Alexander Kornienko5d174542014-05-07 09:06:53 +0000140 if (Stats.ErrorsIgnoredNOLINT) {
141 llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
142 Separator = ", ";
143 }
144 if (Stats.ErrorsIgnoredCheckFilter)
145 llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
146 << " with check filters";
147 llvm::errs() << ").\n";
148 if (Stats.ErrorsIgnoredNonUserCode)
149 llvm::errs() << "Use -header-filter='.*' to display errors from all "
150 "non-system headers.\n";
151 }
152}
153
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000154static void printProfileData(const ProfileData &Profile,
155 llvm::raw_ostream &OS) {
156 // Time is first to allow for sorting by it.
157 std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
158 TimeRecord Total;
159
160 for (const auto& P : Profile.Records) {
161 Timers.emplace_back(P.getValue(), P.getKey());
162 Total += P.getValue();
163 }
164
165 std::sort(Timers.begin(), Timers.end());
166
167 std::string Line = "===" + std::string(73, '-') + "===\n";
168 OS << Line;
169
170 if (Total.getUserTime())
171 OS << " ---User Time---";
172 if (Total.getSystemTime())
173 OS << " --System Time--";
174 if (Total.getProcessTime())
175 OS << " --User+System--";
176 OS << " ---Wall Time---";
177 if (Total.getMemUsed())
178 OS << " ---Mem---";
179 OS << " --- Name ---\n";
180
181 // Loop through all of the timing data, printing it out.
182 for (auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
183 I->first.print(Total, OS);
184 OS << I->second << '\n';
185 }
186
187 Total.print(Total, OS);
188 OS << "Total\n";
189 OS << Line << "\n";
190 OS.flush();
191}
192
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000193std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider() {
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000194 ClangTidyGlobalOptions GlobalOptions;
195 if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000196 llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
197 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000198 return nullptr;
Alexander Kornienkodad4acb2014-05-22 16:07:11 +0000199 }
Alexander Kornienko33a9bcc2014-04-29 15:20:10 +0000200
Alexander Kornienkoe9951542014-09-24 18:36:03 +0000201 ClangTidyOptions DefaultOptions;
202 DefaultOptions.Checks = DefaultChecks;
203 DefaultOptions.HeaderFilterRegex = HeaderFilter;
Alexander Kornienko37f7abe2014-10-28 22:16:13 +0000204 DefaultOptions.SystemHeaders = SystemHeaders;
Alexander Kornienkoe9951542014-09-24 18:36:03 +0000205 DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
206 DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
207 // USERNAME is used on Windows.
208 if (!DefaultOptions.User)
209 DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
Alexander Kornienkoa4695222014-06-05 13:31:45 +0000210
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000211 ClangTidyOptions OverrideOptions;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000212 if (Checks.getNumOccurrences() > 0)
213 OverrideOptions.Checks = Checks;
214 if (HeaderFilter.getNumOccurrences() > 0)
215 OverrideOptions.HeaderFilterRegex = HeaderFilter;
Alexander Kornienko37f7abe2014-10-28 22:16:13 +0000216 if (SystemHeaders.getNumOccurrences() > 0)
217 OverrideOptions.SystemHeaders = SystemHeaders;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000218 if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
219 OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
220
Alexander Kornienkoeff4e922014-09-26 11:42:29 +0000221 if (!Config.empty()) {
222 if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
223 parseConfiguration(Config)) {
224 return llvm::make_unique<DefaultOptionsProvider>(
225 GlobalOptions, ClangTidyOptions::getDefaults()
226 .mergeWith(DefaultOptions)
227 .mergeWith(*ParsedConfig)
228 .mergeWith(OverrideOptions));
229 } else {
230 llvm::errs() << "Error: invalid configuration specified.\n"
231 << ParsedConfig.getError().message() << "\n";
232 return nullptr;
233 }
234 }
235 return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
236 OverrideOptions);
237}
238
239int clangTidyMain(int argc, const char **argv) {
240 CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory);
241
242 auto OptionsProvider = createOptionsProvider();
243 if (!OptionsProvider)
244 return 1;
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000245
246 std::string FileName = OptionsParser.getSourcePathList().front();
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000247 ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
248 std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000249
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000250 // FIXME: Allow using --list-checks without positional arguments.
251 if (ListChecks) {
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000252 llvm::outs() << "Enabled checks:";
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000253 for (auto CheckName : EnabledChecks)
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000254 llvm::outs() << "\n " << CheckName;
Alexander Kornienkofb9e92b2013-12-19 19:57:05 +0000255 llvm::outs() << "\n\n";
256 return 0;
257 }
258
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000259 if (DumpConfig) {
Alexander Kornienko6e0cbc82014-09-12 08:53:36 +0000260 EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000261 llvm::outs() << configurationAsText(ClangTidyOptions::getDefaults()
262 .mergeWith(EffectiveOptions))
Alexander Kornienkod53d2682014-09-04 14:23:36 +0000263 << "\n";
264 return 0;
265 }
266
Alexander Kornienkofbf92582014-06-02 20:32:06 +0000267 if (EnabledChecks.empty()) {
268 llvm::errs() << "Error: no checks enabled.\n";
269 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
270 return 1;
271 }
272
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000273 ProfileData Profile;
274
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000275 std::vector<ClangTidyError> Errors;
276 ClangTidyStats Stats =
277 runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000278 OptionsParser.getSourcePathList(), &Errors,
279 EnableCheckProfile ? &Profile : nullptr);
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000280 handleErrors(Errors, Fix);
Daniel Jasperd07c8402013-07-29 08:19:24 +0000281
Alexander Kornienko4153da22014-09-04 15:19:49 +0000282 if (!ExportFixes.empty() && !Errors.empty()) {
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000283 std::error_code EC;
284 llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
285 if (EC) {
286 llvm::errs() << "Error opening output file: " << EC.message() << '\n';
287 return 1;
288 }
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000289 exportReplacements(Errors, OS);
Benjamin Kramerfb98b742014-09-04 10:31:23 +0000290 }
291
Alexander Kornienko5d174542014-05-07 09:06:53 +0000292 printStats(Stats);
Samuel Benzaquenaedd9942014-10-23 17:23:20 +0000293 if (EnableCheckProfile)
294 printProfileData(Profile, llvm::errs());
295
Daniel Jasperd07c8402013-07-29 08:19:24 +0000296 return 0;
297}
Daniel Jasper89bbab02013-08-04 15:56:30 +0000298
Daniel Jasper89bbab02013-08-04 15:56:30 +0000299// This anchor is used to force the linker to link the LLVMModule.
300extern volatile int LLVMModuleAnchorSource;
301static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource;
302
303// This anchor is used to force the linker to link the GoogleModule.
304extern volatile int GoogleModuleAnchorSource;
305static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource;
306
Alexander Kornienko16ac6ce2014-03-05 13:14:32 +0000307// This anchor is used to force the linker to link the MiscModule.
308extern volatile int MiscModuleAnchorSource;
309static int MiscModuleAnchorDestination = MiscModuleAnchorSource;
310
Alexander Kornienko2192a8e2014-10-26 01:41:14 +0000311// This anchor is used to force the linker to link the ReadabilityModule.
312extern volatile int ReadabilityModuleAnchorSource;
313static int ReadabilityModuleAnchorDestination = ReadabilityModuleAnchorSource;
314
Daniel Jasper89bbab02013-08-04 15:56:30 +0000315} // namespace tidy
316} // namespace clang
Alexander Kornienkoc28c32d2014-09-10 11:43:09 +0000317
318int main(int argc, const char **argv) {
319 return clang::tidy::clangTidyMain(argc, argv);
320}