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