clang-tools 24.0.0git
ClangTidyMain.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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/// https://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
13/// for details on setting it up with LLVM source tree.
14///
15//===----------------------------------------------------------------------===//
16
17#include "ClangTidyMain.h"
18#include "../ClangTidy.h"
19#include "../ClangTidyForceLinker.h" // IWYU pragma: keep
20#include "../GlobList.h"
21#include "clang/Tooling/CommonOptionsParser.h"
22#include "llvm/ADT/StringSet.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/FileSystem.h"
25#include "llvm/Support/InitLLVM.h"
26#include "llvm/Support/PluginLoader.h" // IWYU pragma: keep
27#include "llvm/Support/Process.h"
28#include "llvm/Support/Signals.h"
29#include "llvm/Support/TargetSelect.h"
30#include "llvm/Support/WithColor.h"
31#include "llvm/TargetParser/Host.h"
32#include <optional>
33
34using namespace clang::tooling;
35using namespace llvm;
36
37static cl::desc desc(StringRef Description) { return {Description.ltrim()}; }
38
39static cl::OptionCategory ClangTidyCategory("clang-tidy options");
40
41static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
42static cl::extrahelp ClangTidyParameterFileHelp(R"(
43Parameters files:
44 A large number of options or source files can be passed as parameter files
45 by use '@parameter-file' in the command line.
46)");
47static cl::extrahelp ClangTidyHelp(R"(
48Configuration files:
49 clang-tidy attempts to read configuration for each source file from a
50 .clang-tidy file located in the closest parent directory of the source
51 file. The .clang-tidy file is specified in YAML format. If any configuration
52 options have a corresponding command-line option, command-line option takes
53 precedence.
54
55 The following configuration options may be used in a .clang-tidy file:
56
57 CheckOptions - List of key-value pairs defining check-specific
58 options. Example:
59 CheckOptions:
60 some-check.SomeOption: 'some value'
61 Checks - Same as '--checks'. Additionally, the list of
62 globs can be specified as a list instead of a
63 string.
64 CustomChecks - Array of user defined checks based on
65 Clang-Query syntax.
66 ExcludeHeaderFilterRegex - Same as '--exclude-header-filter'.
67 ExtraArgs - Same as '--extra-arg'.
68 ExtraArgsBefore - Same as '--extra-arg-before'.
69 FormatStyle - Same as '--format-style'.
70 HeaderFileExtensions - File extensions to consider to determine if a
71 given diagnostic is located in a header file.
72 HeaderFilterRegex - Same as '--header-filter'.
73 ImplementationFileExtensions - File extensions to consider to determine if a
74 given diagnostic is located in an
75 implementation file.
76 InheritParentConfig - If this option is true in a config file, the
77 configuration file in the parent directory
78 (if any exists) will be taken and the current
79 config file will be applied on top of the
80 parent one.
81 RemovedArgs - Same as '--removed-arg'.
82 SystemHeaders - Same as '--system-headers'.
83 UseColor - Same as '--use-color'.
84 User - Specifies the name or e-mail of the user
85 running clang-tidy. This option is used, for
86 example, to place the correct user name in
87 TODO() comments in the relevant check.
88 WarningsAsErrors - Same as '--warnings-as-errors'.
89
90 The effective configuration can be inspected using --dump-config:
91
92 $ clang-tidy --dump-config
93 ---
94 Checks: '-*,some-check'
95 WarningsAsErrors: ''
96 HeaderFileExtensions: ['', 'h','hh','hpp','hxx']
97 ImplementationFileExtensions: ['c','cc','cpp','cxx']
98 HeaderFilterRegex: '.*'
99 FormatStyle: none
100 InheritParentConfig: true
101 User: user
102 CheckOptions:
103 some-check.SomeOption: 'some value'
104 ...
105
106)");
107
108const char DefaultChecks[] = // Enable these checks by default:
109 "clang-diagnostic-*"; // * compiler diagnostics
110
111static cl::opt<std::string> Checks("checks", desc(R"(
112Comma-separated list of globs with optional '-'
113prefix. Globs are processed in order of
114appearance in the list. Globs without '-'
115prefix add checks with matching names to the
116set, globs with the '-' prefix remove checks
117with matching names from the set of enabled
118checks. This option's value is appended to the
119value of the 'Checks' option in .clang-tidy
120file, if any.
121)"),
122 cl::init(""), cl::cat(ClangTidyCategory));
123
124static cl::opt<std::string> WarningsAsErrors("warnings-as-errors", desc(R"(
125Upgrades warnings to errors. Same format as
126'-checks'.
127This option's value is appended to the value of
128the 'WarningsAsErrors' option in .clang-tidy
129file, if any.
130)"),
131 cl::init(""),
133
134static cl::opt<std::string> HeaderFilter("header-filter", desc(R"(
135Regular expression matching the names of the
136headers to output diagnostics from. The default
137value is '.*', i.e. diagnostics from all non-system
138headers are displayed by default. Diagnostics
139from the main file of each translation unit are
140always displayed.
141Can be used together with -line-filter.
142This option overrides the 'HeaderFilterRegex'
143option in .clang-tidy file, if any.
144)"),
145 cl::init(".*"),
146 cl::cat(ClangTidyCategory));
147
148static cl::opt<std::string> ExcludeHeaderFilter("exclude-header-filter",
149 desc(R"(
150Regular expression matching the names of the
151headers to exclude diagnostics from. Diagnostics
152from the main file of each translation unit are
153always displayed.
154Must be used together with --header-filter.
155Can be used together with -line-filter.
156This option overrides the 'ExcludeHeaderFilterRegex'
157option in .clang-tidy file, if any.
158)"),
159 cl::init(""),
160 cl::cat(ClangTidyCategory));
161
162static cl::opt<bool> SystemHeaders("system-headers", desc(R"(
163Display the errors from system headers.
164This option overrides the 'SystemHeaders' option
165in .clang-tidy file, if any.
166)"),
167 cl::init(false), cl::cat(ClangTidyCategory));
168
169static cl::opt<std::string> LineFilter("line-filter", desc(R"(
170List of files and line ranges to output diagnostics from.
171The range is inclusive on both ends. Can be used together
172with -header-filter. The format of the list is a JSON
173array of objects. For example:
174
175 [
176 {"name":"file1.cpp","lines":[[1,3],[5,7]]},
177 {"name":"file2.h"}
178 ]
179
180This will output diagnostics from 'file1.cpp' only for
181the line ranges [1,3] and [5,7], as well as all from the
182entire 'file2.h'.
183)"),
184 cl::init(""),
185 cl::cat(ClangTidyCategory));
186
187static cl::opt<bool> Fix("fix", desc(R"(
188Apply suggested fixes. Without -fix-errors
189clang-tidy will bail out if any compilation
190errors were found.
191)"),
192 cl::init(false), cl::cat(ClangTidyCategory));
193
194static cl::opt<bool> FixErrors("fix-errors", desc(R"(
195Apply suggested fixes even if compilation
196errors were found. If compiler errors have
197attached fix-its, clang-tidy will apply them as
198well.
199)"),
200 cl::init(false), cl::cat(ClangTidyCategory));
201
202static cl::opt<bool> FixNotes("fix-notes", desc(R"(
203If a warning has no fix, but a single fix can
204be found through an associated diagnostic note,
205apply the fix.
206Specifying this flag will implicitly enable the
207'--fix' flag.
208)"),
209 cl::init(false), cl::cat(ClangTidyCategory));
210
211static cl::opt<std::string> FormatStyle("format-style", desc(R"(
212Style for formatting code around applied fixes:
213 - 'none' (default) turns off formatting
214 - 'file' (literally 'file', not a placeholder)
215 uses .clang-format file in the closest parent
216 directory
217 - '{ <json> }' specifies options inline, e.g.
218 -format-style='{BasedOnStyle: llvm, IndentWidth: 8}'
219 - 'llvm', 'google', 'webkit', 'mozilla'
220See clang-format documentation for the up-to-date
221information about formatting styles and options.
222This option overrides the 'FormatStyle` option in
223.clang-tidy file, if any.
224)"),
225 cl::init("none"),
226 cl::cat(ClangTidyCategory));
227
228static cl::opt<bool> ListChecks("list-checks", desc(R"(
229List all enabled checks and exit. Use with
230-checks=* to list all available checks.
231)"),
232 cl::init(false), cl::cat(ClangTidyCategory));
233
234static cl::opt<bool> ExplainConfig("explain-config", desc(R"(
235For each enabled check explains, where it is
236enabled, i.e. in clang-tidy binary, command
237line or a specific configuration file.
238)"),
239 cl::init(false), cl::cat(ClangTidyCategory));
240
241static cl::opt<std::string> Config("config", desc(R"(
242Specifies a configuration in YAML/JSON format:
243 -config="{Checks: '*',
244 CheckOptions: {x: y}}"
245When the value is empty, clang-tidy will
246attempt to find a file named .clang-tidy for
247each source file in its parent directories.
248)"),
249 cl::init(""), cl::cat(ClangTidyCategory));
250
251static cl::opt<std::string> ConfigFile("config-file", desc(R"(
252Specify the path of .clang-tidy or custom config file:
253 e.g. --config-file=/some/path/myTidyConfigFile
254This option internally works exactly the same way as
255 --config option after reading specified config file.
256Use either --config-file or --config, not both.
257)"),
258 cl::init(""),
259 cl::cat(ClangTidyCategory));
260
261static cl::opt<bool> DumpConfig("dump-config", desc(R"(
262Dumps configuration in the YAML format to
263stdout. This option can be used along with a
264file name (and '--' if the file is outside of a
265project with configured compilation database).
266The configuration used for this file will be
267printed.
268Use along with -checks=* to include
269configuration of all checks.
270)"),
271 cl::init(false), cl::cat(ClangTidyCategory));
272
273static cl::opt<bool> EnableCheckProfile("enable-check-profile", desc(R"(
274Enable per-check timing profiles, and print a
275report to stderr.
276)"),
277 cl::init(false),
278 cl::cat(ClangTidyCategory));
279
280static cl::opt<std::string> StoreCheckProfile("store-check-profile", desc(R"(
281By default reports are printed in tabulated
282format to stderr. When this option is passed,
283these per-TU profiles are instead stored as JSON.
284)"),
285 cl::value_desc("prefix"),
286 cl::cat(ClangTidyCategory));
287
288/// This option allows enabling the experimental alpha checkers from the static
289/// analyzer. This option is set to false and not visible in help, because it is
290/// highly not recommended for users.
291static cl::opt<bool>
292 AllowEnablingAnalyzerAlphaCheckers("allow-enabling-analyzer-alpha-checkers",
293 cl::init(false), cl::Hidden,
294 cl::cat(ClangTidyCategory));
295
296static cl::opt<bool> EnableModuleHeadersParsing("enable-module-headers-parsing",
298Enables preprocessor-level module header parsing
299for C++20 and above, empowering specific checks
300to detect macro definitions within modules. This
301feature may cause performance and parsing issues
302and is therefore considered experimental.
303)"),
304 cl::init(false),
305 cl::cat(ClangTidyCategory));
306
307static cl::opt<std::string> ExportFixes("export-fixes", desc(R"(
308YAML file to store suggested fixes in. The
309stored fixes can be applied to the input source
310code with clang-apply-replacements.
311)"),
312 cl::value_desc("filename"),
313 cl::cat(ClangTidyCategory));
314
315static cl::opt<std::string> SarifExport("experimental-sarif-export", desc(R"(
316File in which to store diagnostics in SARIF format.
317Use '-' to write to stdout instead of the
318usual diagnostic output.
319)"),
320 cl::value_desc("filename"),
321 cl::cat(ClangTidyCategory));
322
323static cl::opt<bool> Quiet("quiet", desc(R"(
324Run clang-tidy in quiet mode. This suppresses
325printing statistics about ignored warnings and
326warnings treated as errors if the respective
327options are specified.
328)"),
329 cl::init(false), cl::cat(ClangTidyCategory));
330
331static cl::opt<std::string> VfsOverlay("vfsoverlay", desc(R"(
332Overlay the virtual filesystem described by file
333over the real file system.
334)"),
335 cl::value_desc("filename"),
336 cl::cat(ClangTidyCategory));
337
338static cl::opt<bool> UseColor("use-color", desc(R"(
339Use colors in diagnostics. If not set, colors
340will be used if the terminal connected to
341standard output supports colors.
342This option overrides the 'UseColor' option in
343.clang-tidy file, if any.
344)"),
345 cl::init(false), cl::cat(ClangTidyCategory));
346
347static cl::opt<bool> VerifyConfig("verify-config", desc(R"(
348Check the config files to ensure each check and
349option is recognized without running any checks.
350)"),
351 cl::init(false), cl::cat(ClangTidyCategory));
352
353static cl::opt<bool> AllowNoChecks("allow-no-checks", desc(R"(
354Allow empty enabled checks. This suppresses
355the "no checks enabled" error when disabling
356all of the checks.
357)"),
358 cl::init(false), cl::cat(ClangTidyCategory));
359
360static cl::opt<bool> ExperimentalCustomChecks("experimental-custom-checks",
361 desc(R"(
362Enable experimental clang-query based
363custom checks.
364see https://clang.llvm.org/extra/clang-tidy/QueryBasedCustomChecks.html.
365)"),
366 cl::init(false),
367 cl::cat(ClangTidyCategory));
368
369static cl::list<std::string> RemovedArgs("removed-arg", desc(R"(
370List of arguments to remove from the command
371line sent to the compiler. Please note that
372removing arguments might change the semantic
373of the analyzed code, possibly leading to
374compiler errors, false positives or
375false negatives. This option is applied
376before --extra-arg and --extra-arg-before)"),
377 cl::cat(ClangTidyCategory));
378
379namespace clang::tidy {
380
381static void printStats(const ClangTidyStats &Stats) {
382 if (Stats.errorsIgnored()) {
383 llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
384 StringRef Separator = "";
385 if (Stats.ErrorsIgnoredNonUserCode) {
386 llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
387 Separator = ", ";
388 }
389 if (Stats.ErrorsIgnoredLineFilter) {
390 llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
391 << " due to line filter";
392 Separator = ", ";
393 }
394 if (Stats.ErrorsIgnoredNOLINT) {
395 llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
396 Separator = ", ";
397 }
398 if (Stats.ErrorsIgnoredCheckFilter)
399 llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
400 << " with check filters";
401 llvm::errs() << ").\n";
402 if (Stats.ErrorsIgnoredNonUserCode)
403 llvm::errs() << "Use -header-filter=.* or leave it as default to display "
404 "errors from all non-system headers. Use -system-headers "
405 "to display errors from system headers as well.\n";
406 }
407}
408
409static std::unique_ptr<ClangTidyOptionsProvider>
410createOptionsProvider(llvm::IntrusiveRefCntPtr<vfs::FileSystem> FS) {
411 ClangTidyGlobalOptions GlobalOptions;
412 if (const std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
413 llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
414 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
415 return nullptr;
416 }
417
418 ClangTidyOptions DefaultOptions;
419 DefaultOptions.Checks = DefaultChecks;
420 DefaultOptions.WarningsAsErrors = "";
421 DefaultOptions.HeaderFilterRegex = HeaderFilter;
423 DefaultOptions.SystemHeaders = SystemHeaders;
424 DefaultOptions.FormatStyle = FormatStyle;
425 DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
426 // USERNAME is used on Windows.
427 if (!DefaultOptions.User)
428 DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
429
430 ClangTidyOptions OverrideOptions;
431 if (Checks.getNumOccurrences() > 0)
432 OverrideOptions.Checks = Checks;
433 if (WarningsAsErrors.getNumOccurrences() > 0)
434 OverrideOptions.WarningsAsErrors = WarningsAsErrors;
435 if (HeaderFilter.getNumOccurrences() > 0)
436 OverrideOptions.HeaderFilterRegex = HeaderFilter;
437 if (ExcludeHeaderFilter.getNumOccurrences() > 0)
439 if (SystemHeaders.getNumOccurrences() > 0)
440 OverrideOptions.SystemHeaders = SystemHeaders;
441 if (FormatStyle.getNumOccurrences() > 0)
442 OverrideOptions.FormatStyle = FormatStyle;
443 if (UseColor.getNumOccurrences() > 0)
444 OverrideOptions.UseColor = UseColor;
445 if (RemovedArgs.getNumOccurrences() > 0)
446 OverrideOptions.RemovedArgs = RemovedArgs;
447
448 const auto LoadConfig =
449 [&](StringRef Configuration,
450 StringRef Source) -> std::unique_ptr<ClangTidyOptionsProvider> {
451 llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
452 parseConfiguration(MemoryBufferRef(Configuration, Source));
453 if (ParsedConfig)
454 return std::make_unique<ConfigOptionsProvider>(
455 std::move(GlobalOptions),
456 ClangTidyOptions::getDefaults().merge(DefaultOptions, 0),
457 std::move(*ParsedConfig), std::move(OverrideOptions), std::move(FS));
458 llvm::errs() << "Error: invalid configuration specified.\n"
459 << ParsedConfig.getError().message() << "\n";
460 return nullptr;
461 };
462
463 if (ConfigFile.getNumOccurrences() > 0) {
464 if (Config.getNumOccurrences() > 0) {
465 llvm::errs() << "Error: --config-file and --config are "
466 "mutually exclusive. Specify only one.\n";
467 return nullptr;
468 }
469
470 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
471 llvm::MemoryBuffer::getFile(ConfigFile);
472 if (const std::error_code EC = Text.getError()) {
473 llvm::errs() << "Error: can't read config-file '" << ConfigFile
474 << "': " << EC.message() << "\n";
475 return nullptr;
476 }
477
478 return LoadConfig((*Text)->getBuffer(), ConfigFile);
479 }
480
481 if (Config.getNumOccurrences() > 0)
482 return LoadConfig(Config, "<command-line-config>");
483
484 return std::make_unique<FileOptionsProvider>(
485 std::move(GlobalOptions), std::move(DefaultOptions),
486 std::move(OverrideOptions), std::move(FS));
487}
488
489static llvm::IntrusiveRefCntPtr<vfs::FileSystem>
490getVfsFromFile(const std::string &OverlayFile, vfs::FileSystem &BaseFS) {
491 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
492 BaseFS.getBufferForFile(OverlayFile);
493 if (!Buffer) {
494 llvm::errs() << "Can't load virtual filesystem overlay file '"
495 << OverlayFile << "': " << Buffer.getError().message()
496 << ".\n";
497 return nullptr;
498 }
499
500 IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getVFSFromYAML(
501 std::move(Buffer.get()), /*DiagHandler*/ nullptr, OverlayFile);
502 if (!FS) {
503 llvm::errs() << "Error: invalid virtual filesystem overlay file '"
504 << OverlayFile << "'.\n";
505 return nullptr;
506 }
507 return FS;
508}
509
510static StringRef closest(StringRef Value, const StringSet<> &Allowed) {
511 unsigned MaxEdit = 5U;
512 StringRef Closest;
513 for (const auto Item : Allowed.keys()) {
514 const unsigned Cur = Value.edit_distance_insensitive(Item, true, MaxEdit);
515 if (Cur < MaxEdit) {
516 Closest = Item;
517 MaxEdit = Cur;
518 }
519 }
520 return Closest;
521}
522
523static constexpr StringLiteral VerifyConfigWarningEnd = " [-verify-config]\n";
524
525static bool verifyChecks(const StringSet<> &AllChecks, StringRef CheckGlob,
526 StringRef Source) {
527 const GlobList Globs(CheckGlob);
528 bool AnyInvalid = false;
529 for (const auto &Item : Globs.getItems()) {
530 if (Item.Text.starts_with("clang-diagnostic"))
531 continue;
532 if (llvm::none_of(AllChecks.keys(),
533 [&Item](StringRef S) { return Item.Regex.match(S); })) {
534 AnyInvalid = true;
535 if (Item.Text.contains('*')) {
536 llvm::WithColor::warning(llvm::errs(), Source)
537 << "check glob '" << Item.Text << "' doesn't match any known check"
539 } else {
540 llvm::raw_ostream &Output =
541 llvm::WithColor::warning(llvm::errs(), Source)
542 << "unknown check '" << Item.Text << '\'';
543 const StringRef Closest = closest(Item.Text, AllChecks);
544 if (!Closest.empty())
545 Output << "; did you mean '" << Closest << '\'';
546 Output << VerifyConfigWarningEnd;
547 }
548 }
549 }
550 return AnyInvalid;
551}
552
553static bool verifyFileExtensions(
554 const std::vector<std::string> &HeaderFileExtensions,
555 const std::vector<std::string> &ImplementationFileExtensions,
556 StringRef Source) {
557 bool AnyInvalid = false;
558 for (const auto &HeaderExtension : HeaderFileExtensions) {
559 for (const auto &ImplementationExtension : ImplementationFileExtensions) {
560 if (HeaderExtension == ImplementationExtension) {
561 AnyInvalid = true;
562 auto &Output = llvm::WithColor::warning(llvm::errs(), Source)
563 << "HeaderFileExtension '" << HeaderExtension << '\''
564 << " is the same as ImplementationFileExtension '"
565 << ImplementationExtension << '\'';
566 Output << VerifyConfigWarningEnd;
567 }
568 }
569 }
570 return AnyInvalid;
571}
572
573static bool verifyOptions(const llvm::StringSet<> &ValidOptions,
574 const ClangTidyOptions::OptionMap &OptionMap,
575 StringRef Source) {
576 bool AnyInvalid = false;
577 for (const auto Key : OptionMap.keys()) {
578 if (ValidOptions.contains(Key))
579 continue;
580 AnyInvalid = true;
581 auto &Output = llvm::WithColor::warning(llvm::errs(), Source)
582 << "unknown check option '" << Key << '\'';
583 const StringRef Closest = closest(Key, ValidOptions);
584 if (!Closest.empty())
585 Output << "; did you mean '" << Closest << '\'';
586 Output << VerifyConfigWarningEnd;
587 }
588 return AnyInvalid;
589}
590
591static SmallString<256> makeAbsolute(StringRef Input) {
592 if (Input.empty())
593 return {};
594 SmallString<256> AbsolutePath(Input);
595 if (const std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath)) {
596 llvm::errs() << "Can't make absolute path from " << Input << ": "
597 << EC.message() << "\n";
598 }
599 return AbsolutePath;
600}
601
602static llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> createBaseFS() {
603 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> BaseFS(
604 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
605
606 if (!VfsOverlay.empty()) {
607 IntrusiveRefCntPtr<vfs::FileSystem> VfsFromFile =
608 getVfsFromFile(VfsOverlay, *BaseFS);
609 if (!VfsFromFile)
610 return nullptr;
611 BaseFS->pushOverlay(std::move(VfsFromFile));
612 }
613 return BaseFS;
614}
615
616int clangTidyMain(int argc, const char **argv) {
617 const llvm::InitLLVM X(argc, argv);
618 SmallVector<const char *> Args{argv, argv + argc};
619
620 // expand parameters file to argc and argv.
621 llvm::BumpPtrAllocator Alloc;
622 llvm::cl::TokenizerCallback Tokenizer =
623 llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows()
624 ? llvm::cl::TokenizeWindowsCommandLine
625 : llvm::cl::TokenizeGNUCommandLine;
626 llvm::cl::ExpansionContext ECtx(Alloc, Tokenizer);
627 if (llvm::Error Err = ECtx.expandResponseFiles(Args)) {
628 llvm::WithColor::error() << llvm::toString(std::move(Err)) << "\n";
629 return 1;
630 }
631 argc = static_cast<int>(Args.size());
632 argv = Args.data();
633
634 // Enable help for -load option, if plugins are enabled.
635 if (cl::Option *LoadOpt = cl::getRegisteredOptions().lookup("load"))
636 LoadOpt->addCategory(ClangTidyCategory);
637
638 llvm::Expected<CommonOptionsParser> OptionsParser =
639 CommonOptionsParser::create(argc, argv, ClangTidyCategory,
640 cl::ZeroOrMore);
641 if (!OptionsParser) {
642 llvm::WithColor::error() << llvm::toString(OptionsParser.takeError());
643 return 1;
644 }
645
646 if (!SarifExport.empty() && SarifExport == ExportFixes &&
647 !llvm::sys::fs::equivalent(SarifExport, ExportFixes)) {
648 llvm::errs() << "Error: --experimental-sarif-export and --export-fixes "
649 "cannot write to "
650 "the same output '"
651 << SarifExport << "'.\n";
652 return 1;
653 }
654
655 const llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> BaseFS =
656 createBaseFS();
657 if (!BaseFS)
658 return 1;
659
660 auto OwningOptionsProvider = createOptionsProvider(BaseFS);
661 auto *OptionsProvider = OwningOptionsProvider.get();
662 if (!OptionsProvider)
663 return 1;
664
665 const SmallString<256> ProfilePrefix = makeAbsolute(StoreCheckProfile);
666
667 StringRef FileName("dummy");
668 auto PathList = OptionsParser->getSourcePathList();
669 if (!PathList.empty())
670 FileName = PathList.front();
671
672 const SmallString<256> FilePath = makeAbsolute(FileName);
673 ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FilePath);
674
675 const std::vector<std::string> EnabledChecks =
678
679 if (ExplainConfig) {
680 // FIXME: Show other ClangTidyOptions' fields, like ExtraArg.
681 std::vector<ClangTidyOptionsProvider::OptionsSource> RawOptions =
682 OptionsProvider->getRawOptions(FilePath);
683 for (const std::string &Check : EnabledChecks) {
684 for (const auto &[Opts, Source] : llvm::reverse(RawOptions)) {
685 if (Opts.Checks && GlobList(*Opts.Checks).contains(Check)) {
686 llvm::outs() << "'" << Check << "' is enabled in the " << Source
687 << ".\n";
688 break;
689 }
690 }
691 }
692 return 0;
693 }
694
695 if (ListChecks) {
696 if (EnabledChecks.empty() && !AllowNoChecks) {
697 llvm::errs() << "No checks enabled.\n";
698 return 1;
699 }
700 llvm::outs() << "Enabled checks:";
701 for (const auto &CheckName : EnabledChecks)
702 llvm::outs() << "\n " << CheckName;
703 llvm::outs() << "\n\n";
704 return 0;
705 }
706
707 if (DumpConfig) {
708 EffectiveOptions.CheckOptions =
711 ClangTidyOptions OptionsToDump =
712 ClangTidyOptions::getDefaults().merge(EffectiveOptions, 0);
713 filterCheckOptions(OptionsToDump, EnabledChecks);
714 llvm::outs() << configurationAsText(OptionsToDump) << "\n";
715 return 0;
716 }
717
718 if (VerifyConfig) {
719 const std::vector<ClangTidyOptionsProvider::OptionsSource> RawOptions =
720 OptionsProvider->getRawOptions(FileName);
723 bool AnyInvalid = false;
724 for (const auto &[Opts, Source] : RawOptions) {
725 if (Opts.Checks)
726 AnyInvalid |= verifyChecks(Valid.Checks, *Opts.Checks, Source);
727 if (Opts.HeaderFileExtensions && Opts.ImplementationFileExtensions)
728 AnyInvalid |=
729 verifyFileExtensions(*Opts.HeaderFileExtensions,
730 *Opts.ImplementationFileExtensions, Source);
731 AnyInvalid |= verifyOptions(Valid.Options, Opts.CheckOptions, Source);
732 }
733 if (AnyInvalid)
734 return 1;
735 llvm::outs() << "No config errors detected.\n";
736 return 0;
737 }
738
739 if (EnabledChecks.empty() && !AllowNoChecks) {
740 llvm::errs() << "Error: no checks enabled.\n";
741 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
742 return 1;
743 }
744
745 if (PathList.empty()) {
746 llvm::errs() << "Error: no input files specified.\n";
747 llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
748 return 1;
749 }
750
751 // Checked after the informational modes so they never truncate the file.
752 if (!SarifExport.empty() && SarifExport != "-") {
753 std::error_code EC;
754 {
755 const llvm::raw_fd_ostream OS(SarifExport, EC, llvm::sys::fs::OF_Text);
756 }
757 if (EC) {
758 llvm::errs() << "Error opening SARIF export file '" << SarifExport
759 << "': " << EC.message() << '\n';
760 return 1;
761 }
762 }
763
764 llvm::InitializeAllTargetInfos();
765 llvm::InitializeAllTargetMCs();
766 llvm::InitializeAllAsmParsers();
767
768 ClangTidyContext Context(
769 std::move(OwningOptionsProvider), AllowEnablingAnalyzerAlphaCheckers,
771 std::vector<ClangTidyError> Errors =
772 runClangTidy(Context, OptionsParser->getCompilations(), PathList, BaseFS,
773 FixNotes, EnableCheckProfile, ProfilePrefix, Quiet);
774 const bool FoundErrors = llvm::any_of(Errors, [](const ClangTidyError &E) {
775 return E.DiagLevel == ClangTidyError::Error;
776 });
777
778 // --fix-errors and --fix-notes imply --fix.
779 const FixBehaviour Behaviour = FixNotes ? FB_FixNotes
780 : (Fix || FixErrors) ? FB_Fix
781 : FB_NoFix;
782
783 const bool DisableFixes = FoundErrors && !FixErrors;
784
785 unsigned WErrorCount = 0;
786
787 handleErrors(Errors, Context, DisableFixes ? FB_NoFix : Behaviour,
788 WErrorCount, BaseFS, SarifExport);
789
790 if (!ExportFixes.empty() && !Errors.empty()) {
791 std::error_code EC;
792 llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::OF_None);
793 if (EC) {
794 llvm::errs() << "Error opening output file: " << EC.message() << '\n';
795 return 1;
796 }
797 exportReplacements(FilePath.str(), Errors, OS);
798 }
799
800 if (!Quiet) {
801 printStats(Context.getStats());
802 if (DisableFixes && Behaviour != FB_NoFix)
803 llvm::errs()
804 << "Found compiler errors, but -fix-errors was not specified.\n"
805 "Fixes have NOT been applied.\n\n";
806 }
807
808 if (WErrorCount) {
809 if (!Quiet) {
810 const StringRef Plural = WErrorCount == 1 ? "" : "s";
811 llvm::errs() << WErrorCount << " warning" << Plural << " treated as error"
812 << Plural << "\n";
813 }
814 return 1;
815 }
816
817 if (FoundErrors) {
818 // TODO: Figure out when zero exit code should be used with -fix-errors:
819 // a. when a fix has been applied for an error
820 // b. when a fix has been applied for all errors
821 // c. some other condition.
822 // For now always returning zero when -fix-errors is used.
823 if (FixErrors)
824 return 0;
825 if (!Quiet)
826 llvm::errs() << "Found compiler error(s).\n";
827 return 1;
828 }
829
830 return 0;
831}
832
833} // namespace clang::tidy
static cl::opt< bool > UseColor("use-color", cl::desc(R"(Use colors in detailed AST output. If not set, colors will be used if the terminal connected to standard output supports colors.)"), cl::init(false), cl::cat(ClangQueryCategory))
static cl::opt< bool > EnableCheckProfile("enable-check-profile", desc(R"( Enable per-check timing profiles, and print a report to stderr. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > VfsOverlay("vfsoverlay", desc(R"( Overlay the virtual filesystem described by file over the real file system. )"), cl::value_desc("filename"), cl::cat(ClangTidyCategory))
static cl::opt< bool > FixNotes("fix-notes", desc(R"( If a warning has no fix, but a single fix can be found through an associated diagnostic note, apply the fix. Specifying this flag will implicitly enable the '--fix' flag. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< bool > Fix("fix", desc(R"( Apply suggested fixes. Without -fix-errors clang-tidy will bail out if any compilation errors were found. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::list< std::string > RemovedArgs("removed-arg", desc(R"( List of arguments to remove from the command line sent to the compiler. Please note that removing arguments might change the semantic of the analyzed code, possibly leading to compiler errors, false positives or false negatives. This option is applied before --extra-arg and --extra-arg-before)"), cl::cat(ClangTidyCategory))
static cl::opt< bool > ExplainConfig("explain-config", desc(R"( For each enabled check explains, where it is enabled, i.e. in clang-tidy binary, command line or a specific configuration file. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< bool > UseColor("use-color", desc(R"( Use colors in diagnostics. If not set, colors will be used if the terminal connected to standard output supports colors. This option overrides the 'UseColor' option in .clang-tidy file, if any. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > WarningsAsErrors("warnings-as-errors", desc(R"( Upgrades warnings to errors. Same format as '-checks'. This option's value is appended to the value of the 'WarningsAsErrors' option in .clang-tidy file, if any. )"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::opt< bool > ExperimentalCustomChecks("experimental-custom-checks", desc(R"( Enable experimental clang-query based custom checks. see https://clang.llvm.org/extra/clang-tidy/QueryBasedCustomChecks.html. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > ExcludeHeaderFilter("exclude-header-filter", desc(R"( Regular expression matching the names of the headers to exclude diagnostics from. Diagnostics from the main file of each translation unit are always displayed. Must be used together with --header-filter. Can be used together with -line-filter. This option overrides the 'ExcludeHeaderFilterRegex' option in .clang-tidy file, if any. )"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::opt< bool > AllowEnablingAnalyzerAlphaCheckers("allow-enabling-analyzer-alpha-checkers", cl::init(false), cl::Hidden, cl::cat(ClangTidyCategory))
This option allows enabling the experimental alpha checkers from the static analyzer.
static cl::opt< std::string > ConfigFile("config-file", desc(R"( Specify the path of .clang-tidy or custom config file: e.g. --config-file=/some/path/myTidyConfigFile This option internally works exactly the same way as --config option after reading specified config file. Use either --config-file or --config, not both. )"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::opt< bool > EnableModuleHeadersParsing("enable-module-headers-parsing", desc(R"( Enables preprocessor-level module header parsing for C++20 and above, empowering specific checks to detect macro definitions within modules. This feature may cause performance and parsing issues and is therefore considered experimental. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > Config("config", desc(R"( Specifies a configuration in YAML/JSON format: -config="{Checks:' *', CheckOptions:{x:y}}" When the value is empty, clang-tidy will attempt to find a file named .clang-tidy for each source file in its parent directories. )"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::OptionCategory ClangTidyCategory("clang-tidy options")
static cl::opt< bool > FixErrors("fix-errors", desc(R"( Apply suggested fixes even if compilation errors were found. If compiler errors have attached fix-its, clang-tidy will apply them as well. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::extrahelp ClangTidyParameterFileHelp(R"( Parameters files: A large number of options or source files can be passed as parameter files by use '@parameter-file' in the command line. )")
static cl::opt< bool > ListChecks("list-checks", desc(R"( List all enabled checks and exit. Use with -checks=* to list all available checks. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > HeaderFilter("header-filter", desc(R"( Regular expression matching the names of the headers to output diagnostics from. The default value is '.*', i.e. diagnostics from all non-system headers are displayed by default. Diagnostics from the main file of each translation unit are always displayed. Can be used together with -line-filter. This option overrides the 'HeaderFilterRegex' option in .clang-tidy file, if any. )"), cl::init(".*"), cl::cat(ClangTidyCategory))
static cl::opt< bool > DumpConfig("dump-config", desc(R"( Dumps configuration in the YAML format to stdout. This option can be used along with a file name (and '--' if the file is outside of a project with configured compilation database). The configuration used for this file will be printed. Use along with -checks=* to include configuration of all checks. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< bool > SystemHeaders("system-headers", desc(R"( Display the errors from system headers. This option overrides the 'SystemHeaders' option in .clang-tidy file, if any. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > LineFilter("line-filter", desc(R"( List of files and line ranges to output diagnostics from. The range is inclusive on both ends. Can be used together with -header-filter. The format of the list is a JSON array of objects. For example: [ {"name":"file1.cpp","lines":[[1,3],[5,7]]}, {"name":"file2.h"} ] This will output diagnostics from 'file1.cpp' only for the line ranges [1,3] and [5,7], as well as all from the entire 'file2.h'. )"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage)
static cl::opt< bool > VerifyConfig("verify-config", desc(R"( Check the config files to ensure each check and option is recognized without running any checks. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > Checks("checks", desc(R"( Comma-separated list of globs with optional '-' prefix. Globs are processed in order of appearance in the list. Globs without '-' prefix add checks with matching names to the set, globs with the '-' prefix remove checks with matching names from the set of enabled checks. This option's value is appended to the value of the 'Checks' option in .clang-tidy file, if any. )"), cl::init(""), cl::cat(ClangTidyCategory))
static cl::opt< bool > AllowNoChecks("allow-no-checks", desc(R"( Allow empty enabled checks. This suppresses the "no checks enabled" error when disabling all of the checks. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::extrahelp ClangTidyHelp(R"( Configuration files: clang-tidy attempts to read configuration for each source file from a .clang-tidy file located in the closest parent directory of the source file. The .clang-tidy file is specified in YAML format. If any configuration options have a corresponding command-line option, command-line option takes precedence. The following configuration options may be used in a .clang-tidy file: CheckOptions - List of key-value pairs defining check-specific options. Example: CheckOptions: some-check.SomeOption: 'some value' Checks - Same as '--checks'. Additionally, the list of globs can be specified as a list instead of a string. CustomChecks - Array of user defined checks based on Clang-Query syntax. ExcludeHeaderFilterRegex - Same as '--exclude-header-filter'. ExtraArgs - Same as '--extra-arg'. ExtraArgsBefore - Same as '--extra-arg-before'. FormatStyle - Same as '--format-style'. HeaderFileExtensions - File extensions to consider to determine if a given diagnostic is located in a header file. HeaderFilterRegex - Same as '--header-filter'. ImplementationFileExtensions - File extensions to consider to determine if a given diagnostic is located in an implementation file. InheritParentConfig - If this option is true in a config file, the configuration file in the parent directory (if any exists) will be taken and the current config file will be applied on top of the parent one. RemovedArgs - Same as '--removed-arg'. SystemHeaders - Same as '--system-headers'. UseColor - Same as '--use-color'. User - Specifies the name or e-mail of the user running clang-tidy. This option is used, for example, to place the correct user name in TODO() comments in the relevant check. WarningsAsErrors - Same as '--warnings-as-errors'. The effective configuration can be inspected using --dump-config: $ clang-tidy --dump-config --- Checks: '-*,some-check' WarningsAsErrors: '' HeaderFileExtensions: ['', 'h','hh','hpp','hxx'] ImplementationFileExtensions: ['c','cc','cpp','cxx'] HeaderFilterRegex: '.*' FormatStyle: none InheritParentConfig: true User: user CheckOptions: some-check.SomeOption: 'some value' ... )")
const char DefaultChecks[]
static cl::opt< std::string > SarifExport("experimental-sarif-export", desc(R"( File in which to store diagnostics in SARIF format. Use '-' to write to stdout instead of the usual diagnostic output. )"), cl::value_desc("filename"), cl::cat(ClangTidyCategory))
static cl::opt< bool > Quiet("quiet", desc(R"( Run clang-tidy in quiet mode. This suppresses printing statistics about ignored warnings and warnings treated as errors if the respective options are specified. )"), cl::init(false), cl::cat(ClangTidyCategory))
static cl::opt< std::string > ExportFixes("export-fixes", desc(R"( YAML file to store suggested fixes in. The stored fixes can be applied to the input source code with clang-apply-replacements. )"), cl::value_desc("filename"), cl::cat(ClangTidyCategory))
static cl::desc desc(StringRef Description)
static cl::opt< std::string > FormatStyle("format-style", desc(R"( Style for formatting code around applied fixes: - 'none' (default) turns off formatting - 'file' (literally 'file', not a placeholder) uses .clang-format file in the closest parent directory - '{ <json> }' specifies options inline, e.g. -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' - 'llvm', 'google', 'webkit', 'mozilla' See clang-format documentation for the up-to-date information about formatting styles and options. This option overrides the 'FormatStyle` option in .clang-tidy file, if any. )"), cl::init("none"), cl::cat(ClangTidyCategory))
static cl::opt< std::string > StoreCheckProfile("store-check-profile", desc(R"( By default reports are printed in tabulated format to stderr. When this option is passed, these per-TU profiles are instead stored as JSON. )"), cl::value_desc("prefix"), cl::cat(ClangTidyCategory))
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Read-only set of strings represented as a list of positive and negative globs.
Definition GlobList.h:25
virtual bool contains(StringRef S) const
Returns true if the pattern matches S.
Definition GlobList.cpp:59
std::vector< std::string > lookup(const SymbolIndex &I, llvm::ArrayRef< SymbolID > IDs)
static llvm::IntrusiveRefCntPtr< vfs::FileSystem > getVfsFromFile(const std::string &OverlayFile, vfs::FileSystem &BaseFS)
ChecksAndOptions getAllChecksAndOptions(bool AllowEnablingAnalyzerAlphaCheckers, bool ExperimentalCustomChecks)
std::error_code parseLineFilter(StringRef LineFilter, clang::tidy::ClangTidyGlobalOptions &Options)
Parses -line-filter option and stores it to the Options.
FixBehaviour
Controls what kind of fixes clang-tidy is allowed to apply.
Definition ClangTidy.h:102
@ FB_NoFix
Don't try to apply any fix.
Definition ClangTidy.h:104
@ FB_FixNotes
Apply fixes found in notes.
Definition ClangTidy.h:108
@ FB_Fix
Only apply fixes added to warnings.
Definition ClangTidy.h:106
static SmallString< 256 > makeAbsolute(StringRef Input)
std::vector< std::string > getCheckNames(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers, bool ExperimentalCustomChecks)
Fills the list of check names that are enabled when the provided filters are applied.
int clangTidyMain(int argc, const char **argv)
static ClangTidyModuleRegistry::Add< altera::AlteraModule > X("altera-module", "Adds Altera FPGA OpenCL lint checks.")
static void printStats(const ClangTidyStats &Stats)
static llvm::IntrusiveRefCntPtr< vfs::OverlayFileSystem > createBaseFS()
void handleErrors(llvm::ArrayRef< ClangTidyError > Errors, ClangTidyContext &Context, FixBehaviour Fix, unsigned &WarningsAsErrorsCount, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS, StringRef SarifExportPath)
Displays the found Errors to the users.
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers, bool ExperimentalCustomChecks)
Returns the effective check-specific options.
void exportReplacements(const StringRef MainFilePath, const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
Serializes replacements into YAML and writes them to the specified output stream.
void filterCheckOptions(ClangTidyOptions &Options, const std::vector< std::string > &EnabledChecks)
Filters CheckOptions in Options to only include options specified in the EnabledChecks which is a sor...
static constexpr StringLiteral VerifyConfigWarningEnd
std::vector< ClangTidyError > runClangTidy(ClangTidyContext &Context, const CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, llvm::IntrusiveRefCntPtr< llvm::vfs::OverlayFileSystem > BaseFS, bool ApplyAnyFix, bool EnableCheckProfile, StringRef StoreCheckProfile, bool Quiet)
static bool verifyOptions(const llvm::StringSet<> &ValidOptions, const ClangTidyOptions::OptionMap &OptionMap, StringRef Source)
static std::unique_ptr< ClangTidyOptionsProvider > createOptionsProvider(llvm::IntrusiveRefCntPtr< vfs::FileSystem > FS)
static bool verifyFileExtensions(const std::vector< std::string > &HeaderFileExtensions, const std::vector< std::string > &ImplementationFileExtensions, StringRef Source)
std::string configurationAsText(const ClangTidyOptions &Options)
Serializes configuration to a YAML-encoded string.
llvm::ErrorOr< ClangTidyOptions > parseConfiguration(llvm::MemoryBufferRef Config)
Parses configuration from JSON and returns ClangTidyOptions or an error.
static bool verifyChecks(const StringSet<> &AllChecks, StringRef CheckGlob, StringRef Source)
static StringRef closest(StringRef Value, const StringSet<> &Allowed)
Some operations such as code completion produce a set of candidates.
Definition Generators.h:150
OptionMap CheckOptions
Key-value mapping used to store check-specific options.
std::optional< std::string > HeaderFilterRegex
Output warnings from headers matching this filter.
std::optional< std::string > Checks
Checks filter.
std::optional< std::string > WarningsAsErrors
WarningsAsErrors filter.
std::optional< ArgList > RemovedArgs
Remove command line arguments sent to the compiler matching this.
std::optional< std::string > User
Specifies the name or e-mail of the user running clang-tidy.
std::optional< bool > UseColor
Use colors in diagnostics. If missing, it will be auto detected.
std::optional< bool > SystemHeaders
Output warnings from system headers matching HeaderFilterRegex.
std::optional< std::string > ExcludeHeaderFilterRegex
Exclude warnings from headers matching this filter, even if they match HeaderFilterRegex.
std::optional< std::string > FormatStyle
Format code around applied fixes with clang-format using this style.
A detected error complete with information to display diagnostic and automatic fix.
Contains options for clang-tidy.
ClangTidyOptions merge(const ClangTidyOptions &Other, unsigned Order) const
Creates a new ClangTidyOptions instance combined from all fields of this instance overridden by the f...
llvm::StringMap< ClangTidyValue > OptionMap
static ClangTidyOptions getDefaults()
These options are used for all settings that haven't been overridden by the OptionsProvider.
Contains displayed and ignored diagnostic counters for a ClangTidy run.