clang-tools  7.0.0
ClangTidyMain.cpp
Go to the documentation of this file.
1 //===--- 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"
19 #include "clang/Tooling/CommonOptionsParser.h"
20 #include "llvm/Support/Process.h"
21 #include "llvm/Support/TargetSelect.h"
22 
23 using namespace clang::ast_matchers;
24 using namespace clang::driver;
25 using namespace clang::tooling;
26 using namespace llvm;
27 
28 static cl::OptionCategory ClangTidyCategory("clang-tidy options");
29 
30 static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
31 static cl::extrahelp ClangTidyHelp(R"(
32 Configuration files:
33  clang-tidy attempts to read configuration for each source file from a
34  .clang-tidy file located in the closest parent directory of the source
35  file. If any configuration options have a corresponding command-line
36  option, command-line option takes precedence. The effective
37  configuration can be inspected using -dump-config:
38 
39  $ clang-tidy -dump-config
40  ---
41  Checks: '-*,some-check'
42  WarningsAsErrors: ''
43  HeaderFilterRegex: ''
44  FormatStyle: none
45  User: user
46  CheckOptions:
47  - key: some-check.SomeOption
48  value: 'some value'
49  ...
50 
51 )");
52 
53 const char DefaultChecks[] = // Enable these checks by default:
54  "clang-diagnostic-*," // * compiler diagnostics
55  "clang-analyzer-*"; // * Static Analyzer checks
56 
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 
70 static cl::opt<std::string> WarningsAsErrors("warnings-as-errors", cl::desc(R"(
71 Upgrades warnings to errors. Same format as
72 '-checks'.
73 This option's value is appended to the value of
74 the 'WarningsAsErrors' option in .clang-tidy
75 file, if any.
76 )"),
77  cl::init(""),
78  cl::cat(ClangTidyCategory));
79 
80 static cl::opt<std::string> HeaderFilter("header-filter", cl::desc(R"(
81 Regular expression matching the names of the
82 headers to output diagnostics from. Diagnostics
83 from the main file of each translation unit are
84 always displayed.
85 Can be used together with -line-filter.
86 This option overrides the 'HeaderFilter' option
87 in .clang-tidy file, if any.
88 )"),
89  cl::init(""),
90  cl::cat(ClangTidyCategory));
91 
92 static cl::opt<bool>
93  SystemHeaders("system-headers",
94  cl::desc("Display the errors from system headers."),
95  cl::init(false), cl::cat(ClangTidyCategory));
96 static cl::opt<std::string> LineFilter("line-filter", cl::desc(R"(
97 List of files with line ranges to filter the
98 warnings. Can be used together with
99 -header-filter. The format of the list is a
100 JSON array of objects:
101  [
102  {"name":"file1.cpp","lines":[[1,3],[5,7]]},
103  {"name":"file2.h"}
104  ]
105 )"),
106  cl::init(""),
107  cl::cat(ClangTidyCategory));
108 
109 static cl::opt<bool> Fix("fix", cl::desc(R"(
110 Apply suggested fixes. Without -fix-errors
111 clang-tidy will bail out if any compilation
112 errors were found.
113 )"),
114  cl::init(false), cl::cat(ClangTidyCategory));
115 
116 static cl::opt<bool> FixErrors("fix-errors", cl::desc(R"(
117 Apply suggested fixes even if compilation
118 errors were found. If compiler errors have
119 attached fix-its, clang-tidy will apply them as
120 well.
121 )"),
122  cl::init(false), cl::cat(ClangTidyCategory));
123 
124 static cl::opt<std::string> FormatStyle("format-style", cl::desc(R"(
125 Style for formatting code around applied fixes:
126  - 'none' (default) turns off formatting
127  - 'file' (literally 'file', not a placeholder)
128  uses .clang-format file in the closest parent
129  directory
130  - '{ <json> }' specifies options inline, e.g.
131  -format-style='{BasedOnStyle: llvm, IndentWidth: 8}'
132  - 'llvm', 'google', 'webkit', 'mozilla'
133 See clang-format documentation for the up-to-date
134 information about formatting styles and options.
135 This option overrides the 'FormatStyle` option in
136 .clang-tidy file, if any.
137 )"),
138  cl::init("none"),
139  cl::cat(ClangTidyCategory));
140 
141 static cl::opt<bool> ListChecks("list-checks", cl::desc(R"(
142 List all enabled checks and exit. Use with
143 -checks=* to list all available checks.
144 )"),
145  cl::init(false), cl::cat(ClangTidyCategory));
146 
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 
154 static cl::opt<std::string> Config("config", cl::desc(R"(
155 Specifies a configuration in YAML/JSON format:
156  -config="{Checks: '*',
157  CheckOptions: [{key: x,
158  value: y}]}"
159 When the value is empty, clang-tidy will
160 attempt to find a file named .clang-tidy for
161 each source file in its parent directories.
162 )"),
163  cl::init(""), cl::cat(ClangTidyCategory));
164 
165 static cl::opt<bool> DumpConfig("dump-config", cl::desc(R"(
166 Dumps configuration in the YAML format to
167 stdout. This option can be used along with a
168 file name (and '--' if the file is outside of a
169 project with configured compilation database).
170 The configuration used for this file will be
171 printed.
172 Use along with -checks=* to include
173 configuration of all checks.
174 )"),
175  cl::init(false), cl::cat(ClangTidyCategory));
176 
177 static cl::opt<bool> EnableCheckProfile("enable-check-profile", cl::desc(R"(
178 Enable per-check timing profiles, and print a
179 report to stderr.
180 )"),
181  cl::init(false),
182  cl::cat(ClangTidyCategory));
183 
184 static cl::opt<std::string> StoreCheckProfile("store-check-profile",
185  cl::desc(R"(
186 By default reports are printed in tabulated
187 format to stderr. When this option is passed,
188 these per-TU profiles are instead stored as JSON.
189 )"),
190  cl::value_desc("prefix"),
191  cl::cat(ClangTidyCategory));
192 
193 /// This option allows enabling the experimental alpha checkers from the static
194 /// analyzer. This option is set to false and not visible in help, because it is
195 /// highly not recommended for users.
196 static cl::opt<bool>
197  AllowEnablingAnalyzerAlphaCheckers("allow-enabling-analyzer-alpha-checkers",
198  cl::init(false), cl::Hidden,
199  cl::cat(ClangTidyCategory));
200 
201 static cl::opt<std::string> ExportFixes("export-fixes", cl::desc(R"(
202 YAML file to store suggested fixes in. The
203 stored fixes can be applied to the input source
204 code with clang-apply-replacements.
205 )"),
206  cl::value_desc("filename"),
207  cl::cat(ClangTidyCategory));
208 
209 static cl::opt<bool> Quiet("quiet", cl::desc(R"(
210 Run clang-tidy in quiet mode. This suppresses
211 printing statistics about ignored warnings and
212 warnings treated as errors if the respective
213 options are specified.
214 )"),
215  cl::init(false),
216  cl::cat(ClangTidyCategory));
217 
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 
225 namespace clang {
226 namespace tidy {
227 
228 static void printStats(const ClangTidyStats &Stats) {
229  if (Stats.errorsIgnored()) {
230  llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
231  StringRef Separator = "";
232  if (Stats.ErrorsIgnoredNonUserCode) {
233  llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
234  Separator = ", ";
235  }
236  if (Stats.ErrorsIgnoredLineFilter) {
237  llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
238  << " due to line filter";
239  Separator = ", ";
240  }
241  if (Stats.ErrorsIgnoredNOLINT) {
242  llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
243  Separator = ", ";
244  }
245  if (Stats.ErrorsIgnoredCheckFilter)
246  llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
247  << " with check filters";
248  llvm::errs() << ").\n";
249  if (Stats.ErrorsIgnoredNonUserCode)
250  llvm::errs() << "Use -header-filter=.* to display errors from all "
251  "non-system headers. Use -system-headers to display "
252  "errors from system headers as well.\n";
253  }
254 }
255 
256 static std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider(
257  llvm::IntrusiveRefCntPtr<vfs::FileSystem> FS) {
258  ClangTidyGlobalOptions GlobalOptions;
259  if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
260  llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
261  llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
262  return nullptr;
263  }
264 
265  ClangTidyOptions DefaultOptions;
266  DefaultOptions.Checks = DefaultChecks;
267  DefaultOptions.WarningsAsErrors = "";
268  DefaultOptions.HeaderFilterRegex = HeaderFilter;
269  DefaultOptions.SystemHeaders = SystemHeaders;
270  DefaultOptions.FormatStyle = FormatStyle;
271  DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
272  // USERNAME is used on Windows.
273  if (!DefaultOptions.User)
274  DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
275 
276  ClangTidyOptions OverrideOptions;
277  if (Checks.getNumOccurrences() > 0)
278  OverrideOptions.Checks = Checks;
279  if (WarningsAsErrors.getNumOccurrences() > 0)
280  OverrideOptions.WarningsAsErrors = WarningsAsErrors;
281  if (HeaderFilter.getNumOccurrences() > 0)
282  OverrideOptions.HeaderFilterRegex = HeaderFilter;
283  if (SystemHeaders.getNumOccurrences() > 0)
284  OverrideOptions.SystemHeaders = SystemHeaders;
285  if (FormatStyle.getNumOccurrences() > 0)
286  OverrideOptions.FormatStyle = FormatStyle;
287 
288  if (!Config.empty()) {
289  if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
291  return llvm::make_unique<ConfigOptionsProvider>(
292  GlobalOptions,
293  ClangTidyOptions::getDefaults().mergeWith(DefaultOptions),
294  *ParsedConfig, OverrideOptions);
295  } else {
296  llvm::errs() << "Error: invalid configuration specified.\n"
297  << ParsedConfig.getError().message() << "\n";
298  return nullptr;
299  }
300  }
301  return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
302  OverrideOptions, std::move(FS));
303 }
304 
305 llvm::IntrusiveRefCntPtr<vfs::FileSystem>
306 getVfsOverlayFromFile(const std::string &OverlayFile) {
307  llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFS(
308  new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
309  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
310  OverlayFS->getBufferForFile(OverlayFile);
311  if (!Buffer) {
312  llvm::errs() << "Can't load virtual filesystem overlay file '"
313  << OverlayFile << "': " << Buffer.getError().message()
314  << ".\n";
315  return nullptr;
316  }
317 
318  IntrusiveRefCntPtr<vfs::FileSystem> FS = vfs::getVFSFromYAML(
319  std::move(Buffer.get()), /*DiagHandler*/ nullptr, OverlayFile);
320  if (!FS) {
321  llvm::errs() << "Error: invalid virtual filesystem overlay file '"
322  << OverlayFile << "'.\n";
323  return nullptr;
324  }
325  OverlayFS->pushOverlay(FS);
326  return OverlayFS;
327 }
328 
329 static int clangTidyMain(int argc, const char **argv) {
330  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory,
331  cl::ZeroOrMore);
332  llvm::IntrusiveRefCntPtr<vfs::FileSystem> BaseFS(
333  VfsOverlay.empty() ? vfs::getRealFileSystem()
335  if (!BaseFS)
336  return 1;
337 
338  auto OwningOptionsProvider = createOptionsProvider(BaseFS);
339  auto *OptionsProvider = OwningOptionsProvider.get();
340  if (!OptionsProvider)
341  return 1;
342 
343  auto MakeAbsolute = [](const std::string &Input) -> SmallString<256> {
344  if (Input.empty())
345  return {};
346  SmallString<256> AbsolutePath(Input);
347  if (std::error_code EC = llvm::sys::fs::make_absolute(AbsolutePath)) {
348  llvm::errs() << "Can't make absolute path from " << Input << ": "
349  << EC.message() << "\n";
350  }
351  return AbsolutePath;
352  };
353 
354  SmallString<256> ProfilePrefix = MakeAbsolute(StoreCheckProfile);
355 
356  StringRef FileName("dummy");
357  auto PathList = OptionsParser.getSourcePathList();
358  if (!PathList.empty()) {
359  FileName = PathList.front();
360  }
361 
362  SmallString<256> FilePath = MakeAbsolute(FileName);
363 
364  ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FilePath);
365  std::vector<std::string> EnabledChecks =
367 
368  if (ExplainConfig) {
369  // FIXME: Show other ClangTidyOptions' fields, like ExtraArg.
370  std::vector<clang::tidy::ClangTidyOptionsProvider::OptionsSource>
371  RawOptions = OptionsProvider->getRawOptions(FilePath);
372  for (const std::string &Check : EnabledChecks) {
373  for (auto It = RawOptions.rbegin(); It != RawOptions.rend(); ++It) {
374  if (It->first.Checks && GlobList(*It->first.Checks).contains(Check)) {
375  llvm::outs() << "'" << Check << "' is enabled in the " << It->second
376  << ".\n";
377  break;
378  }
379  }
380  }
381  return 0;
382  }
383 
384  if (ListChecks) {
385  if (EnabledChecks.empty()) {
386  llvm::errs() << "No checks enabled.\n";
387  return 1;
388  }
389  llvm::outs() << "Enabled checks:";
390  for (const auto &CheckName : EnabledChecks)
391  llvm::outs() << "\n " << CheckName;
392  llvm::outs() << "\n\n";
393  return 0;
394  }
395 
396  if (DumpConfig) {
397  EffectiveOptions.CheckOptions =
399  llvm::outs() << configurationAsText(
400  ClangTidyOptions::getDefaults().mergeWith(
401  EffectiveOptions))
402  << "\n";
403  return 0;
404  }
405 
406  if (EnabledChecks.empty()) {
407  llvm::errs() << "Error: no checks enabled.\n";
408  llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
409  return 1;
410  }
412  if (PathList.empty()) {
413  llvm::errs() << "Error: no input files specified.\n";
414  llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
415  return 1;
416  }
417 
418  llvm::InitializeAllTargetInfos();
419  llvm::InitializeAllTargetMCs();
420  llvm::InitializeAllAsmParsers();
422  ClangTidyContext Context(std::move(OwningOptionsProvider),
424  runClangTidy(Context, OptionsParser.getCompilations(), PathList, BaseFS,
425  EnableCheckProfile, ProfilePrefix);
426  ArrayRef<ClangTidyError> Errors = Context.getErrors();
427  bool FoundErrors = llvm::find_if(Errors, [](const ClangTidyError &E) {
428  return E.DiagLevel == ClangTidyError::Error;
429  }) != Errors.end();
430 
431  const bool DisableFixes = Fix && FoundErrors && !FixErrors;
432 
433  unsigned WErrorCount = 0;
434 
435  // -fix-errors implies -fix.
436  handleErrors(Context, (FixErrors || Fix) && !DisableFixes, WErrorCount,
437  BaseFS);
438 
439  if (!ExportFixes.empty() && !Errors.empty()) {
440  std::error_code EC;
441  llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
442  if (EC) {
443  llvm::errs() << "Error opening output file: " << EC.message() << '\n';
444  return 1;
445  }
446  exportReplacements(FilePath.str(), Errors, OS);
447  }
448 
449  if (!Quiet) {
450  printStats(Context.getStats());
451  if (DisableFixes)
452  llvm::errs()
453  << "Found compiler errors, but -fix-errors was not specified.\n"
454  "Fixes have NOT been applied.\n\n";
455  }
456 
457  if (WErrorCount) {
458  if (!Quiet) {
459  StringRef Plural = WErrorCount == 1 ? "" : "s";
460  llvm::errs() << WErrorCount << " warning" << Plural << " treated as error"
461  << Plural << "\n";
462  }
463  return WErrorCount;
464  }
465 
466  if (FoundErrors) {
467  // TODO: Figure out when zero exit code should be used with -fix-errors:
468  // a. when a fix has been applied for an error
469  // b. when a fix has been applied for all errors
470  // c. some other condition.
471  // For now always returning zero when -fix-errors is used.
472  if (FixErrors)
473  return 0;
474  if (!Quiet)
475  llvm::errs() << "Found compiler error(s).\n";
476  return 1;
477  }
478 
479  return 0;
480 }
481 
482 // This anchor is used to force the linker to link the CERTModule.
483 extern volatile int CERTModuleAnchorSource;
484 static int LLVM_ATTRIBUTE_UNUSED CERTModuleAnchorDestination =
486 
487 // This anchor is used to force the linker to link the AbseilModule.
488 extern volatile int AbseilModuleAnchorSource;
489 static int LLVM_ATTRIBUTE_UNUSED AbseilModuleAnchorDestination =
491 
492 // This anchor is used to force the linker to link the BoostModule.
493 extern volatile int BoostModuleAnchorSource;
494 static int LLVM_ATTRIBUTE_UNUSED BoostModuleAnchorDestination =
496 
497 // This anchor is used to force the linker to link the BugproneModule.
498 extern volatile int BugproneModuleAnchorSource;
499 static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination =
501 
502 // This anchor is used to force the linker to link the LLVMModule.
503 extern volatile int LLVMModuleAnchorSource;
504 static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination =
506 
507 // This anchor is used to force the linker to link the CppCoreGuidelinesModule.
508 extern volatile int CppCoreGuidelinesModuleAnchorSource;
509 static int LLVM_ATTRIBUTE_UNUSED CppCoreGuidelinesModuleAnchorDestination =
511 
512 // This anchor is used to force the linker to link the FuchsiaModule.
513 extern volatile int FuchsiaModuleAnchorSource;
514 static int LLVM_ATTRIBUTE_UNUSED FuchsiaModuleAnchorDestination =
516 
517 // This anchor is used to force the linker to link the GoogleModule.
518 extern volatile int GoogleModuleAnchorSource;
519 static int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination =
521 
522 // This anchor is used to force the linker to link the AndroidModule.
523 extern volatile int AndroidModuleAnchorSource;
524 static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination =
526 
527 // This anchor is used to force the linker to link the MiscModule.
528 extern volatile int MiscModuleAnchorSource;
529 static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination =
531 
532 // This anchor is used to force the linker to link the ModernizeModule.
533 extern volatile int ModernizeModuleAnchorSource;
534 static int LLVM_ATTRIBUTE_UNUSED ModernizeModuleAnchorDestination =
536 
537 // This anchor is used to force the linker to link the MPIModule.
538 extern volatile int MPIModuleAnchorSource;
539 static int LLVM_ATTRIBUTE_UNUSED MPIModuleAnchorDestination =
541 
542 // This anchor is used to force the linker to link the PerformanceModule.
543 extern volatile int PerformanceModuleAnchorSource;
544 static int LLVM_ATTRIBUTE_UNUSED PerformanceModuleAnchorDestination =
546 
547 // This anchor is used to force the linker to link the PortabilityModule.
548 extern volatile int PortabilityModuleAnchorSource;
549 static int LLVM_ATTRIBUTE_UNUSED PortabilityModuleAnchorDestination =
551 
552 // This anchor is used to force the linker to link the ReadabilityModule.
553 extern volatile int ReadabilityModuleAnchorSource;
554 static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination =
556 
557 // This anchor is used to force the linker to link the ObjCModule.
558 extern volatile int ObjCModuleAnchorSource;
559 static int LLVM_ATTRIBUTE_UNUSED ObjCModuleAnchorDestination =
561 
562 // This anchor is used to force the linker to link the HICPPModule.
563 extern volatile int HICPPModuleAnchorSource;
564 static int LLVM_ATTRIBUTE_UNUSED HICPPModuleAnchorDestination =
566 
567 // This anchor is used to force the linker to link the ZirconModule.
568 extern volatile int ZirconModuleAnchorSource;
569 static int LLVM_ATTRIBUTE_UNUSED ZirconModuleAnchorDestination =
571 
572 } // namespace tidy
573 } // namespace clang
574 
575 int main(int argc, const char **argv) {
576  return clang::tidy::clangTidyMain(argc, argv);
577 }
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. If any configuration options have a corresponding command-line option, command-line option takes precedence. The effective configuration can be inspected using -dump-config: $ clang-tidy -dump-config --- Checks: '-*,some-check' WarningsAsErrors: '' HeaderFilterRegex: '' FormatStyle: none User: user CheckOptions: - key: some-check.SomeOption value: 'some value' ... )")
llvm::Optional< std::string > Checks
Checks filter.
volatile int GoogleModuleAnchorSource
static void printStats(const ClangTidyStats &Stats)
Some operations such as code completion produce a set of candidates.
llvm::Optional< std::string > User
Specifies the name or e-mail of the user running clang-tidy.
static cl::opt< bool > SystemHeaders("system-headers", cl::desc("Display the errors from system headers."), cl::init(false), cl::cat(ClangTidyCategory))
Read-only set of strings represented as a list of positive and negative globs.
volatile int ReadabilityModuleAnchorSource
static cl::opt< bool > FixErrors("fix-errors", cl::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::opt< std::string > HeaderFilter("header-filter", cl::desc(R"( Regular expression matching the names of the headers to output diagnostics from. Diagnostics from the main file of each translation unit are always displayed. Can be used together with -line-filter. This option overrides the 'HeaderFilter' option in .clang-tidy file, if any. )"), cl::init(""), cl::cat(ClangTidyCategory))
bool contains(StringRef S)
Returns true if the pattern matches S.
static cl::opt< bool > DumpConfig("dump-config", cl::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< std::string > Config("config", cl::desc(R"( Specifies a configuration in YAML/JSON format: -config="{Checks:' *', CheckOptions:[{key:x, value: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::opt< bool > ExplainConfig("explain-config", cl::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< std::string > StoreCheckProfile("store-check-profile", cl::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))
llvm::Optional< std::string > HeaderFilterRegex
Output warnings from headers matching this filter.
def make_absolute(f, directory)
static int LLVM_ATTRIBUTE_UNUSED LLVMModuleAnchorDestination
Contains options for clang-tidy.
volatile int AndroidModuleAnchorSource
ClangTidyOptions::OptionMap getCheckOptions(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers)
Returns the effective check-specific options.
Definition: ClangTidy.cpp:482
std::error_code parseLineFilter(StringRef LineFilter, clang::tidy::ClangTidyGlobalOptions &Options)
Parses -line-filter option and stores it to the Options.
llvm::ErrorOr< ClangTidyOptions > parseConfiguration(StringRef Config)
static cl::opt< bool > ListChecks("list-checks", cl::desc(R"( List all enabled checks and exit. Use with -checks=* to list all available checks. )"), cl::init(false), cl::cat(ClangTidyCategory))
OptionMap CheckOptions
Key-value mapping used to store check-specific options.
llvm::Optional< bool > SystemHeaders
Output warnings from system headers matching HeaderFilterRegex.
volatile int LLVMModuleAnchorSource
volatile int PerformanceModuleAnchorSource
llvm::IntrusiveRefCntPtr< vfs::FileSystem > getVfsOverlayFromFile(const std::string &OverlayFile)
llvm::Optional< std::string > FormatStyle
Format code around applied fixes with clang-format using this style.
void handleErrors(ClangTidyContext &Context, bool Fix, unsigned &WarningsAsErrorsCount, llvm::IntrusiveRefCntPtr< vfs::FileSystem > BaseFS)
Displays the found Errors to the users.
Definition: ClangTidy.cpp:580
volatile int CppCoreGuidelinesModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED ObjCModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED ReadabilityModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED BugproneModuleAnchorDestination
static cl::opt< std::string > LineFilter("line-filter", cl::desc(R"( List of files with line ranges to filter the warnings. Can be used together with -header-filter. The format of the list is a JSON array of objects: [ {"name":"file1.cpp","lines":[[1,3],[5,7]]}, {"name":"file2.h"} ] )"), 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.
volatile int MPIModuleAnchorSource
volatile int HICPPModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED ZirconModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED AndroidModuleAnchorDestination
volatile int PortabilityModuleAnchorSource
std::string configurationAsText(const ClangTidyOptions &Options)
Serializes configuration to a YAML-encoded string.
volatile int ZirconModuleAnchorSource
volatile int CERTModuleAnchorSource
static cl::OptionCategory ClangTidyCategory("clang-tidy options")
static cl::opt< std::string > WarningsAsErrors("warnings-as-errors", cl::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 int LLVM_ATTRIBUTE_UNUSED GoogleModuleAnchorDestination
void runClangTidy(clang::tidy::ClangTidyContext &Context, const CompilationDatabase &Compilations, ArrayRef< std::string > InputFiles, llvm::IntrusiveRefCntPtr< vfs::FileSystem > BaseFS, bool EnableCheckProfile, llvm::StringRef StoreCheckProfile)
Definition: ClangTidy.cpp:492
static cl::opt< bool > EnableCheckProfile("enable-check-profile", cl::desc(R"( Enable per-check timing profiles, and print a report to stderr. )"), cl::init(false), cl::cat(ClangTidyCategory))
PathRef FileName
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage)
llvm::Optional< std::string > WarningsAsErrors
WarningsAsErrors filter.
static int LLVM_ATTRIBUTE_UNUSED HICPPModuleAnchorDestination
static cl::opt< std::string > VfsOverlay("vfsoverlay", cl::desc(R"( Overlay the virtual filesystem described by file over the real file system. )"), cl::value_desc("filename"), cl::cat(ClangTidyCategory))
volatile int BoostModuleAnchorSource
static cl::opt< std::string > ExportFixes("export-fixes", cl::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))
volatile int ObjCModuleAnchorSource
volatile int MiscModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED PerformanceModuleAnchorDestination
volatile int BugproneModuleAnchorSource
static int clangTidyMain(int argc, const char **argv)
static int LLVM_ATTRIBUTE_UNUSED FuchsiaModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED MiscModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED CppCoreGuidelinesModuleAnchorDestination
static std::unique_ptr< ClangTidyOptionsProvider > createOptionsProvider(llvm::IntrusiveRefCntPtr< vfs::FileSystem > FS)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static int LLVM_ATTRIBUTE_UNUSED ModernizeModuleAnchorDestination
void exportReplacements(const llvm::StringRef MainFilePath, const std::vector< ClangTidyError > &Errors, raw_ostream &OS)
Definition: ClangTidy.cpp:606
std::vector< std::string > getCheckNames(const ClangTidyOptions &Options, bool AllowEnablingAnalyzerAlphaCheckers)
Fills the list of check names that are enabled when the provided filters are applied.
Definition: ClangTidy.cpp:471
const char DefaultChecks[]
int main(int argc, const char **argv)
A detected error complete with information to display diagnostic and automatic fix.
Contains displayed and ignored diagnostic counters for a ClangTidy run.
static cl::opt< std::string > Checks("checks", cl::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))
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
volatile int AbseilModuleAnchorSource
volatile int ModernizeModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED MPIModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED PortabilityModuleAnchorDestination
static int LLVM_ATTRIBUTE_UNUSED CERTModuleAnchorDestination
static cl::opt< bool > Fix("fix", cl::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 int LLVM_ATTRIBUTE_UNUSED BoostModuleAnchorDestination
static cl::opt< bool > Quiet("quiet", cl::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))
volatile int FuchsiaModuleAnchorSource
static int LLVM_ATTRIBUTE_UNUSED AbseilModuleAnchorDestination
static cl::opt< std::string > FormatStyle("format-style", cl::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))