ClangTidyMain.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. //===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file This file implements a clang-tidy tool.
  10. ///
  11. /// This tool uses the Clang Tooling infrastructure, see
  12. /// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
  13. /// for details on setting it up with LLVM source tree.
  14. ///
  15. //===----------------------------------------------------------------------===//
  16. #include "ClangTidyMain.h"
  17. #include "../ClangTidy.h"
  18. #include "../ClangTidyForceLinker.h"
  19. #include "../GlobList.h"
  20. #include "clang/Tooling/CommonOptionsParser.h"
  21. #include "llvm/ADT/StringSet.h"
  22. #include "llvm/Support/InitLLVM.h"
  23. #include "llvm/Support/PluginLoader.h"
  24. #include "llvm/Support/Process.h"
  25. #include "llvm/Support/Signals.h"
  26. #include "llvm/Support/TargetSelect.h"
  27. #include "llvm/Support/WithColor.h"
  28. #include <optional>
  29. using namespace clang::tooling;
  30. using namespace llvm;
  31. static cl::OptionCategory ClangTidyCategory("clang-tidy options");
  32. static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
  33. static cl::extrahelp ClangTidyHelp(R"(
  34. Configuration files:
  35. clang-tidy attempts to read configuration for each source file from a
  36. .clang-tidy file located in the closest parent directory of the source
  37. file. If InheritParentConfig is true in a config file, the configuration file
  38. in the parent directory (if any exists) will be taken and current config file
  39. will be applied on top of the parent one. If any configuration options have
  40. a corresponding command-line option, command-line option takes precedence.
  41. The effective configuration can be inspected using -dump-config:
  42. $ clang-tidy -dump-config
  43. ---
  44. Checks: '-*,some-check'
  45. WarningsAsErrors: ''
  46. HeaderFilterRegex: ''
  47. FormatStyle: none
  48. InheritParentConfig: true
  49. User: user
  50. CheckOptions:
  51. some-check.SomeOption: 'some value'
  52. ...
  53. )");
  54. const char DefaultChecks[] = // Enable these checks by default:
  55. "clang-diagnostic-*," // * compiler diagnostics
  56. "clang-analyzer-*"; // * Static Analyzer checks
  57. static cl::opt<std::string> Checks("checks", cl::desc(R"(
  58. Comma-separated list of globs with optional '-'
  59. prefix. Globs are processed in order of
  60. appearance in the list. Globs without '-'
  61. prefix add checks with matching names to the
  62. set, globs with the '-' prefix remove checks
  63. with matching names from the set of enabled
  64. checks. This option's value is appended to the
  65. value of the 'Checks' option in .clang-tidy
  66. file, if any.
  67. )"),
  68. cl::init(""), cl::cat(ClangTidyCategory));
  69. static cl::opt<std::string> WarningsAsErrors("warnings-as-errors", cl::desc(R"(
  70. Upgrades warnings to errors. Same format as
  71. '-checks'.
  72. This option's value is appended to the value of
  73. the 'WarningsAsErrors' option in .clang-tidy
  74. file, if any.
  75. )"),
  76. cl::init(""),
  77. cl::cat(ClangTidyCategory));
  78. static cl::opt<std::string> HeaderFilter("header-filter", cl::desc(R"(
  79. Regular expression matching the names of the
  80. headers to output diagnostics from. Diagnostics
  81. from the main file of each translation unit are
  82. always displayed.
  83. Can be used together with -line-filter.
  84. This option overrides the 'HeaderFilterRegex'
  85. option in .clang-tidy file, if any.
  86. )"),
  87. cl::init(""),
  88. cl::cat(ClangTidyCategory));
  89. static cl::opt<bool>
  90. SystemHeaders("system-headers",
  91. cl::desc("Display the errors from system headers."),
  92. cl::init(false), cl::cat(ClangTidyCategory));
  93. static cl::opt<std::string> LineFilter("line-filter", cl::desc(R"(
  94. List of files with line ranges to filter the
  95. warnings. Can be used together with
  96. -header-filter. The format of the list is a
  97. JSON array of objects:
  98. [
  99. {"name":"file1.cpp","lines":[[1,3],[5,7]]},
  100. {"name":"file2.h"}
  101. ]
  102. )"),
  103. cl::init(""),
  104. cl::cat(ClangTidyCategory));
  105. static cl::opt<bool> Fix("fix", cl::desc(R"(
  106. Apply suggested fixes. Without -fix-errors
  107. clang-tidy will bail out if any compilation
  108. errors were found.
  109. )"),
  110. cl::init(false), cl::cat(ClangTidyCategory));
  111. static cl::opt<bool> FixErrors("fix-errors", cl::desc(R"(
  112. Apply suggested fixes even if compilation
  113. errors were found. If compiler errors have
  114. attached fix-its, clang-tidy will apply them as
  115. well.
  116. )"),
  117. cl::init(false), cl::cat(ClangTidyCategory));
  118. static cl::opt<bool> FixNotes("fix-notes", cl::desc(R"(
  119. If a warning has no fix, but a single fix can
  120. be found through an associated diagnostic note,
  121. apply the fix.
  122. Specifying this flag will implicitly enable the
  123. '--fix' flag.
  124. )"),
  125. cl::init(false), cl::cat(ClangTidyCategory));
  126. static cl::opt<std::string> FormatStyle("format-style", cl::desc(R"(
  127. Style for formatting code around applied fixes:
  128. - 'none' (default) turns off formatting
  129. - 'file' (literally 'file', not a placeholder)
  130. uses .clang-format file in the closest parent
  131. directory
  132. - '{ <json> }' specifies options inline, e.g.
  133. -format-style='{BasedOnStyle: llvm, IndentWidth: 8}'
  134. - 'llvm', 'google', 'webkit', 'mozilla'
  135. See clang-format documentation for the up-to-date
  136. information about formatting styles and options.
  137. This option overrides the 'FormatStyle` option in
  138. .clang-tidy file, if any.
  139. )"),
  140. cl::init("none"),
  141. cl::cat(ClangTidyCategory));
  142. static cl::opt<bool> ListChecks("list-checks", cl::desc(R"(
  143. List all enabled checks and exit. Use with
  144. -checks=* to list all available checks.
  145. )"),
  146. cl::init(false), cl::cat(ClangTidyCategory));
  147. static cl::opt<bool> ExplainConfig("explain-config", cl::desc(R"(
  148. For each enabled check explains, where it is
  149. enabled, i.e. in clang-tidy binary, command
  150. line or a specific configuration file.
  151. )"),
  152. cl::init(false), cl::cat(ClangTidyCategory));
  153. static cl::opt<std::string> Config("config", cl::desc(R"(
  154. Specifies a configuration in YAML/JSON format:
  155. -config="{Checks: '*',
  156. CheckOptions: {x: y}}"
  157. When the value is empty, clang-tidy will
  158. attempt to find a file named .clang-tidy for
  159. each source file in its parent directories.
  160. )"),
  161. cl::init(""), cl::cat(ClangTidyCategory));
  162. static cl::opt<std::string> ConfigFile("config-file", cl::desc(R"(
  163. Specify the path of .clang-tidy or custom config file:
  164. e.g. --config-file=/some/path/myTidyConfigFile
  165. This option internally works exactly the same way as
  166. --config option after reading specified config file.
  167. Use either --config-file or --config, not both.
  168. )"),
  169. cl::init(""),
  170. cl::cat(ClangTidyCategory));
  171. static cl::opt<bool> DumpConfig("dump-config", cl::desc(R"(
  172. Dumps configuration in the YAML format to
  173. stdout. This option can be used along with a
  174. file name (and '--' if the file is outside of a
  175. project with configured compilation database).
  176. The configuration used for this file will be
  177. printed.
  178. Use along with -checks=* to include
  179. configuration of all checks.
  180. )"),
  181. cl::init(false), cl::cat(ClangTidyCategory));
  182. static cl::opt<bool> EnableCheckProfile("enable-check-profile", cl::desc(R"(
  183. Enable per-check timing profiles, and print a
  184. report to stderr.
  185. )"),
  186. cl::init(false),
  187. cl::cat(ClangTidyCategory));
  188. static cl::opt<std::string> StoreCheckProfile("store-check-profile",
  189. cl::desc(R"(
  190. By default reports are printed in tabulated
  191. format to stderr. When this option is passed,
  192. these per-TU profiles are instead stored as JSON.
  193. )"),
  194. cl::value_desc("prefix"),
  195. cl::cat(ClangTidyCategory));
  196. /// This option allows enabling the experimental alpha checkers from the static
  197. /// analyzer. This option is set to false and not visible in help, because it is
  198. /// highly not recommended for users.
  199. static cl::opt<bool>
  200. AllowEnablingAnalyzerAlphaCheckers("allow-enabling-analyzer-alpha-checkers",
  201. cl::init(false), cl::Hidden,
  202. cl::cat(ClangTidyCategory));
  203. static cl::opt<std::string> ExportFixes("export-fixes", cl::desc(R"(
  204. YAML file to store suggested fixes in. The
  205. stored fixes can be applied to the input source
  206. code with clang-apply-replacements.
  207. )"),
  208. cl::value_desc("filename"),
  209. cl::cat(ClangTidyCategory));
  210. static cl::opt<bool> Quiet("quiet", cl::desc(R"(
  211. Run clang-tidy in quiet mode. This suppresses
  212. printing statistics about ignored warnings and
  213. warnings treated as errors if the respective
  214. options are specified.
  215. )"),
  216. cl::init(false),
  217. cl::cat(ClangTidyCategory));
  218. static cl::opt<std::string> VfsOverlay("vfsoverlay", cl::desc(R"(
  219. Overlay the virtual filesystem described by file
  220. over the real file system.
  221. )"),
  222. cl::value_desc("filename"),
  223. cl::cat(ClangTidyCategory));
  224. static cl::opt<bool> UseColor("use-color", cl::desc(R"(
  225. Use colors in diagnostics. If not set, colors
  226. will be used if the terminal connected to
  227. standard output supports colors.
  228. This option overrides the 'UseColor' option in
  229. .clang-tidy file, if any.
  230. )"),
  231. cl::init(false), cl::cat(ClangTidyCategory));
  232. static cl::opt<bool> VerifyConfig("verify-config", cl::desc(R"(
  233. Check the config files to ensure each check and
  234. option is recognized.
  235. )"),
  236. cl::init(false), cl::cat(ClangTidyCategory));
  237. namespace clang::tidy {
  238. static void printStats(const ClangTidyStats &Stats) {
  239. if (Stats.errorsIgnored()) {
  240. llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
  241. StringRef Separator = "";
  242. if (Stats.ErrorsIgnoredNonUserCode) {
  243. llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
  244. Separator = ", ";
  245. }
  246. if (Stats.ErrorsIgnoredLineFilter) {
  247. llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
  248. << " due to line filter";
  249. Separator = ", ";
  250. }
  251. if (Stats.ErrorsIgnoredNOLINT) {
  252. llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
  253. Separator = ", ";
  254. }
  255. if (Stats.ErrorsIgnoredCheckFilter)
  256. llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
  257. << " with check filters";
  258. llvm::errs() << ").\n";
  259. if (Stats.ErrorsIgnoredNonUserCode)
  260. llvm::errs() << "Use -header-filter=.* to display errors from all "
  261. "non-system headers. Use -system-headers to display "
  262. "errors from system headers as well.\n";
  263. }
  264. }
  265. static std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider(
  266. llvm::IntrusiveRefCntPtr<vfs::FileSystem> FS) {
  267. ClangTidyGlobalOptions GlobalOptions;
  268. if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
  269. llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
  270. llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
  271. return nullptr;
  272. }
  273. ClangTidyOptions DefaultOptions;
  274. DefaultOptions.Checks = DefaultChecks;
  275. DefaultOptions.WarningsAsErrors = "";
  276. DefaultOptions.HeaderFilterRegex = HeaderFilter;
  277. DefaultOptions.SystemHeaders = SystemHeaders;
  278. DefaultOptions.FormatStyle = FormatStyle;
  279. DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
  280. // USERNAME is used on Windows.
  281. if (!DefaultOptions.User)
  282. DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
  283. ClangTidyOptions OverrideOptions;
  284. if (Checks.getNumOccurrences() > 0)
  285. OverrideOptions.Checks = Checks;
  286. if (WarningsAsErrors.getNumOccurrences() > 0)
  287. OverrideOptions.WarningsAsErrors = WarningsAsErrors;
  288. if (HeaderFilter.getNumOccurrences() > 0)
  289. OverrideOptions.HeaderFilterRegex = HeaderFilter;
  290. if (SystemHeaders.getNumOccurrences() > 0)
  291. OverrideOptions.SystemHeaders = SystemHeaders;
  292. if (FormatStyle.getNumOccurrences() > 0)
  293. OverrideOptions.FormatStyle = FormatStyle;
  294. if (UseColor.getNumOccurrences() > 0)
  295. OverrideOptions.UseColor = UseColor;
  296. auto LoadConfig =
  297. [&](StringRef Configuration,
  298. StringRef Source) -> std::unique_ptr<ClangTidyOptionsProvider> {
  299. llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
  300. parseConfiguration(MemoryBufferRef(Configuration, Source));
  301. if (ParsedConfig)
  302. return std::make_unique<ConfigOptionsProvider>(
  303. std::move(GlobalOptions),
  304. ClangTidyOptions::getDefaults().merge(DefaultOptions, 0),
  305. std::move(*ParsedConfig), std::move(OverrideOptions), std::move(FS));
  306. llvm::errs() << "Error: invalid configuration specified.\n"
  307. << ParsedConfig.getError().message() << "\n";
  308. return nullptr;
  309. };
  310. if (ConfigFile.getNumOccurrences() > 0) {
  311. if (Config.getNumOccurrences() > 0) {
  312. llvm::errs() << "Error: --config-file and --config are "
  313. "mutually exclusive. Specify only one.\n";
  314. return nullptr;
  315. }
  316. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
  317. llvm::MemoryBuffer::getFile(ConfigFile);
  318. if (std::error_code EC = Text.getError()) {
  319. llvm::errs() << "Error: can't read config-file '" << ConfigFile
  320. << "': " << EC.message() << "\n";
  321. return nullptr;
  322. }
  323. return LoadConfig((*Text)->getBuffer(), ConfigFile);
  324. }
  325. if (Config.getNumOccurrences() > 0)
  326. return LoadConfig(Config, "<command-line-config>");
  327. return std::make_unique<FileOptionsProvider>(
  328. std::move(GlobalOptions), std::move(DefaultOptions),
  329. std::move(OverrideOptions), std::move(FS));
  330. }
  331. llvm::IntrusiveRefCntPtr<vfs::FileSystem>
  332. getVfsFromFile(const std::string &OverlayFile,
  333. llvm::IntrusiveRefCntPtr<vfs::FileSystem> BaseFS) {
  334. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
  335. BaseFS->getBufferForFile(OverlayFile);
  336. if (!Buffer) {
  337. llvm::errs() << "Can't load virtual filesystem overlay file '"
  338. << OverlayFile << "': " << Buffer.getError().message()
  339. << ".\n";
  340. return nullptr;
  341. }
  342. IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getVFSFromYAML(
  343. std::move(Buffer.get()), /*DiagHandler*/ nullptr, OverlayFile);
  344. if (!FS) {
  345. llvm::errs() << "Error: invalid virtual filesystem overlay file '"
  346. << OverlayFile << "'.\n";
  347. return nullptr;
  348. }
  349. return FS;
  350. }
  351. static StringRef closest(StringRef Value, const StringSet<> &Allowed) {
  352. unsigned MaxEdit = 5U;
  353. StringRef Closest;
  354. for (auto Item : Allowed.keys()) {
  355. unsigned Cur = Value.edit_distance_insensitive(Item, true, MaxEdit);
  356. if (Cur < MaxEdit) {
  357. Closest = Item;
  358. MaxEdit = Cur;
  359. }
  360. }
  361. return Closest;
  362. }
  363. static constexpr StringLiteral VerifyConfigWarningEnd = " [-verify-config]\n";
  364. static bool verifyChecks(const StringSet<> &AllChecks, StringRef CheckGlob,
  365. StringRef Source) {
  366. llvm::StringRef Cur, Rest;
  367. bool AnyInvalid = false;
  368. for (std::tie(Cur, Rest) = CheckGlob.split(',');
  369. !(Cur.empty() && Rest.empty()); std::tie(Cur, Rest) = Rest.split(',')) {
  370. Cur = Cur.trim();
  371. if (Cur.empty())
  372. continue;
  373. Cur.consume_front("-");
  374. if (Cur.startswith("clang-diagnostic"))
  375. continue;
  376. if (Cur.contains('*')) {
  377. SmallString<128> RegexText("^");
  378. StringRef MetaChars("()^$|*+?.[]\\{}");
  379. for (char C : Cur) {
  380. if (C == '*')
  381. RegexText.push_back('.');
  382. else if (MetaChars.contains(C))
  383. RegexText.push_back('\\');
  384. RegexText.push_back(C);
  385. }
  386. RegexText.push_back('$');
  387. llvm::Regex Glob(RegexText);
  388. std::string Error;
  389. if (!Glob.isValid(Error)) {
  390. AnyInvalid = true;
  391. llvm::WithColor::error(llvm::errs(), Source)
  392. << "building check glob '" << Cur << "' " << Error << "'\n";
  393. continue;
  394. }
  395. if (llvm::none_of(AllChecks.keys(),
  396. [&Glob](StringRef S) { return Glob.match(S); })) {
  397. AnyInvalid = true;
  398. llvm::WithColor::warning(llvm::errs(), Source)
  399. << "check glob '" << Cur << "' doesn't match any known check"
  400. << VerifyConfigWarningEnd;
  401. }
  402. } else {
  403. if (AllChecks.contains(Cur))
  404. continue;
  405. AnyInvalid = true;
  406. llvm::raw_ostream &Output = llvm::WithColor::warning(llvm::errs(), Source)
  407. << "unknown check '" << Cur << '\'';
  408. llvm::StringRef Closest = closest(Cur, AllChecks);
  409. if (!Closest.empty())
  410. Output << "; did you mean '" << Closest << '\'';
  411. Output << VerifyConfigWarningEnd;
  412. }
  413. }
  414. return AnyInvalid;
  415. }
  416. int clangTidyMain(int argc, const char **argv) {
  417. llvm::InitLLVM X(argc, argv);
  418. // Enable help for -load option, if plugins are enabled.
  419. if (cl::Option *LoadOpt = cl::getRegisteredOptions().lookup("load"))
  420. LoadOpt->addCategory(ClangTidyCategory);
  421. llvm::Expected<CommonOptionsParser> OptionsParser =
  422. CommonOptionsParser::create(argc, argv, ClangTidyCategory,
  423. cl::ZeroOrMore);
  424. if (!OptionsParser) {
  425. llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
  426. return 1;
  427. }
  428. llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> BaseFS(
  429. new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
  430. if (!VfsOverlay.empty()) {
  431. IntrusiveRefCntPtr<vfs::FileSystem> VfsFromFile =
  432. getVfsFromFile(VfsOverlay, BaseFS);
  433. if (!VfsFromFile)
  434. return 1;
  435. BaseFS->pushOverlay(std::move(VfsFromFile));
  436. }
  437. auto OwningOptionsProvider = createOptionsProvider(BaseFS);
  438. auto *OptionsProvider = OwningOptionsProvider.get();
  439. if (!OptionsProvider)
  440. return 1;
  441. auto MakeAbsolute = [](const std::string &Input) -> SmallString<256> {
  442. if (Input.empty())
  443. return {};
  444. SmallString<256> AbsolutePath(Input);
  445. if (std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath)) {
  446. llvm::errs() << "Can't make absolute path from " << Input << ": "
  447. << EC.message() << "\n";
  448. }
  449. return AbsolutePath;
  450. };
  451. SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
  452. StringRef FileName("dummy");
  453. auto PathList = OptionsParser->getSourcePathList();
  454. if (!PathList.empty()) {
  455. FileName = PathList.front();
  456. }
  457. SmallString<256> FilePath = MakeAbsolute(std::string(FileName));
  458. ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FilePath);
  459. std::vector<std::string> EnabledChecks =
  460. getCheckNames(EffectiveOptions, AllowEnablingAnalyzerAlphaCheckers);
  461. if (ExplainConfig) {
  462. // FIXME: Show other ClangTidyOptions' fields, like ExtraArg.
  463. std::vector<clang::tidy::ClangTidyOptionsProvider::OptionsSource>
  464. RawOptions = OptionsProvider->getRawOptions(FilePath);
  465. for (const std::string &Check : EnabledChecks) {
  466. for (const auto &[Opts, Source] : llvm::reverse(RawOptions)) {
  467. if (Opts.Checks && GlobList(*Opts.Checks).contains(Check)) {
  468. llvm::outs() << "'" << Check << "' is enabled in the " << Source
  469. << ".\n";
  470. break;
  471. }
  472. }
  473. }
  474. return 0;
  475. }
  476. if (ListChecks) {
  477. if (EnabledChecks.empty()) {
  478. llvm::errs() << "No checks enabled.\n";
  479. return 1;
  480. }
  481. llvm::outs() << "Enabled checks:";
  482. for (const auto &CheckName : EnabledChecks)
  483. llvm::outs() << "\n " << CheckName;
  484. llvm::outs() << "\n\n";
  485. return 0;
  486. }
  487. if (DumpConfig) {
  488. EffectiveOptions.CheckOptions =
  489. getCheckOptions(EffectiveOptions, AllowEnablingAnalyzerAlphaCheckers);
  490. llvm::outs() << configurationAsText(ClangTidyOptions::getDefaults().merge(
  491. EffectiveOptions, 0))
  492. << "\n";
  493. return 0;
  494. }
  495. if (VerifyConfig) {
  496. std::vector<ClangTidyOptionsProvider::OptionsSource> RawOptions =
  497. OptionsProvider->getRawOptions(FileName);
  498. NamesAndOptions Valid =
  499. getAllChecksAndOptions(AllowEnablingAnalyzerAlphaCheckers);
  500. bool AnyInvalid = false;
  501. for (const auto &[Opts, Source] : RawOptions) {
  502. if (Opts.Checks)
  503. AnyInvalid |= verifyChecks(Valid.Names, *Opts.Checks, Source);
  504. for (auto Key : Opts.CheckOptions.keys()) {
  505. if (Valid.Options.contains(Key))
  506. continue;
  507. AnyInvalid = true;
  508. auto &Output = llvm::WithColor::warning(llvm::errs(), Source)
  509. << "unknown check option '" << Key << '\'';
  510. llvm::StringRef Closest = closest(Key, Valid.Options);
  511. if (!Closest.empty())
  512. Output << "; did you mean '" << Closest << '\'';
  513. Output << VerifyConfigWarningEnd;
  514. }
  515. }
  516. if (AnyInvalid)
  517. return 1;
  518. llvm::outs() << "No config errors detected.\n";
  519. return 0;
  520. }
  521. if (EnabledChecks.empty()) {
  522. llvm::errs() << "Error: no checks enabled.\n";
  523. llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
  524. return 1;
  525. }
  526. if (PathList.empty()) {
  527. llvm::errs() << "Error: no input files specified.\n";
  528. llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
  529. return 1;
  530. }
  531. llvm::InitializeAllTargetInfos();
  532. llvm::InitializeAllTargetMCs();
  533. llvm::InitializeAllAsmParsers();
  534. ClangTidyContext Context(std::move(OwningOptionsProvider),
  535. AllowEnablingAnalyzerAlphaCheckers);
  536. std::vector<ClangTidyError> Errors =
  537. runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
  538. FixNotes, EnableCheckProfile, ProfilePrefix);
  539. bool FoundErrors = llvm::any_of(Errors, [](const ClangTidyError &E) {
  540. return E.DiagLevel == ClangTidyError::Error;
  541. });
  542. // --fix-errors and --fix-notes imply --fix.
  543. FixBehaviour Behaviour = FixNotes ? FB_FixNotes
  544. : (Fix || FixErrors) ? FB_Fix
  545. : FB_NoFix;
  546. const bool DisableFixes = FoundErrors && !FixErrors;
  547. unsigned WErrorCount = 0;
  548. handleErrors(Errors, Context, DisableFixes ? FB_NoFix : Behaviour,
  549. WErrorCount, BaseFS);
  550. if (!ExportFixes.empty() && !Errors.empty()) {
  551. std::error_code EC;
  552. llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::OF_None);
  553. if (EC) {
  554. llvm::errs() << "Error opening output file: " << EC.message() << '\n';
  555. return 1;
  556. }
  557. exportReplacements(FilePath.str(), Errors, OS);
  558. }
  559. if (!Quiet) {
  560. printStats(Context.getStats());
  561. if (DisableFixes && Behaviour != FB_NoFix)
  562. llvm::errs()
  563. << "Found compiler errors, but -fix-errors was not specified.\n"
  564. "Fixes have NOT been applied.\n\n";
  565. }
  566. if (WErrorCount) {
  567. if (!Quiet) {
  568. StringRef Plural = WErrorCount == 1 ? "" : "s";
  569. llvm::errs() << WErrorCount << " warning" << Plural << " treated as error"
  570. << Plural << "\n";
  571. }
  572. return 1;
  573. }
  574. if (FoundErrors) {
  575. // TODO: Figure out when zero exit code should be used with -fix-errors:
  576. // a. when a fix has been applied for an error
  577. // b. when a fix has been applied for all errors
  578. // c. some other condition.
  579. // For now always returning zero when -fix-errors is used.
  580. if (FixErrors)
  581. return 0;
  582. if (!Quiet)
  583. llvm::errs() << "Found compiler error(s).\n";
  584. return 1;
  585. }
  586. return 0;
  587. }
  588. } // namespace clang::tidy