| 1 | //===--- ClangTidyOptions.cpp - clang-tidy ----------------------*- C++ -*-===// |
| 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 | #include "ClangTidyOptions.h" |
| 10 | #include "ClangTidyModuleRegistry.h" |
| 11 | #include "clang/Basic/LLVM.h" |
| 12 | #include "llvm/ADT/SmallString.h" |
| 13 | #include "llvm/Support/Debug.h" |
| 14 | #include "llvm/Support/Errc.h" |
| 15 | #include "llvm/Support/FileSystem.h" |
| 16 | #include "llvm/Support/MemoryBufferRef.h" |
| 17 | #include "llvm/Support/Path.h" |
| 18 | #include "llvm/Support/YAMLTraits.h" |
| 19 | #include <optional> |
| 20 | #include <utility> |
| 21 | |
| 22 | #define DEBUG_TYPE "clang-tidy-options" |
| 23 | |
| 24 | using clang::tidy::ClangTidyOptions; |
| 25 | using clang::tidy::FileFilter; |
| 26 | using OptionsSource = clang::tidy::ClangTidyOptionsProvider::OptionsSource; |
| 27 | |
| 28 | LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(FileFilter) |
| 29 | LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(FileFilter::LineRange) |
| 30 | |
| 31 | namespace llvm::yaml { |
| 32 | |
| 33 | // Map std::pair<int, int> to a JSON array of size 2. |
| 34 | template <> struct SequenceTraits<FileFilter::LineRange> { |
| 35 | static size_t size(IO &IO, FileFilter::LineRange &Range) { |
| 36 | return Range.first == 0 ? 0 : Range.second == 0 ? 1 : 2; |
| 37 | } |
| 38 | static unsigned &element(IO &IO, FileFilter::LineRange &Range, size_t Index) { |
| 39 | if (Index > 1) |
| 40 | IO.setError("Too many elements in line range."); |
| 41 | return Index == 0 ? Range.first : Range.second; |
| 42 | } |
| 43 | }; |
| 44 | |
| 45 | template <> struct MappingTraits<FileFilter> { |
| 46 | static void mapping(IO &IO, FileFilter &File) { |
| 47 | IO.mapRequired("name", File.Name); |
| 48 | IO.mapOptional("lines", File.LineRanges); |
| 49 | } |
| 50 | static std::string validate(IO &Io, FileFilter &File) { |
| 51 | if (File.Name.empty()) |
| 52 | return "No file name specified"; |
| 53 | for (const FileFilter::LineRange &Range : File.LineRanges) { |
| 54 | if (Range.first <= 0 || Range.second <= 0) |
| 55 | return "Invalid line range"; |
| 56 | } |
| 57 | return ""; |
| 58 | } |
| 59 | }; |
| 60 | |
| 61 | template <> struct MappingTraits<ClangTidyOptions::StringPair> { |
| 62 | static void mapping(IO &IO, ClangTidyOptions::StringPair &KeyValue) { |
| 63 | IO.mapRequired("key", KeyValue.first); |
| 64 | IO.mapRequired("value", KeyValue.second); |
| 65 | } |
| 66 | }; |
| 67 | |
| 68 | struct NOptionMap { |
| 69 | NOptionMap(IO &) {} |
| 70 | NOptionMap(IO &, const ClangTidyOptions::OptionMap &OptionMap) { |
| 71 | Options.reserve(OptionMap.size()); |
| 72 | for (const auto &KeyValue : OptionMap) |
| 73 | Options.emplace_back(std::string(KeyValue.getKey()), KeyValue.getValue().Value); |
| 74 | } |
| 75 | ClangTidyOptions::OptionMap denormalize(IO &) { |
| 76 | ClangTidyOptions::OptionMap Map; |
| 77 | for (const auto &KeyValue : Options) |
| 78 | Map[KeyValue.first] = ClangTidyOptions::ClangTidyValue(KeyValue.second); |
| 79 | return Map; |
| 80 | } |
| 81 | std::vector<ClangTidyOptions::StringPair> Options; |
| 82 | }; |
| 83 | |
| 84 | template <> |
| 85 | void yamlize(IO &IO, ClangTidyOptions::OptionMap &Options, bool, |
| 86 | EmptyContext &Ctx) { |
| 87 | if (IO.outputting()) { |
| 88 | IO.beginMapping(); |
| 89 | // Only output as a map |
| 90 | for (auto &Key : Options) { |
| 91 | bool UseDefault; |
| 92 | void *SaveInfo; |
| 93 | IO.preflightKey(Key.getKey().data(), true, false, UseDefault, SaveInfo); |
| 94 | StringRef S = Key.getValue().Value; |
| 95 | IO.scalarString(S, needsQuotes(S)); |
| 96 | IO.postflightKey(SaveInfo); |
| 97 | } |
| 98 | IO.endMapping(); |
| 99 | } else { |
| 100 | // We need custom logic here to support the old method of specifying check |
| 101 | // options using a list of maps containing key and value keys. |
| 102 | Input &I = reinterpret_cast<Input &>(IO); |
| 103 | if (isa<SequenceNode>(I.getCurrentNode())) { |
| 104 | MappingNormalization<NOptionMap, ClangTidyOptions::OptionMap> NOpts( |
| 105 | IO, Options); |
| 106 | EmptyContext Ctx; |
| 107 | yamlize(IO, NOpts->Options, true, Ctx); |
| 108 | } else if (isa<MappingNode>(I.getCurrentNode())) { |
| 109 | IO.beginMapping(); |
| 110 | for (StringRef Key : IO.keys()) { |
| 111 | IO.mapRequired(Key.data(), Options[Key].Value); |
| 112 | } |
| 113 | IO.endMapping(); |
| 114 | } else { |
| 115 | IO.setError("expected a sequence or map"); |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | template <> struct MappingTraits<ClangTidyOptions> { |
| 121 | static void mapping(IO &IO, ClangTidyOptions &Options) { |
| 122 | bool Ignored = false; |
| 123 | IO.mapOptional("Checks", Options.Checks); |
| 124 | IO.mapOptional("WarningsAsErrors", Options.WarningsAsErrors); |
| 125 | IO.mapOptional("HeaderFilterRegex", Options.HeaderFilterRegex); |
| 126 | IO.mapOptional("AnalyzeTemporaryDtors", Ignored); // deprecated |
| 127 | IO.mapOptional("FormatStyle", Options.FormatStyle); |
| 128 | IO.mapOptional("User", Options.User); |
| 129 | IO.mapOptional("CheckOptions", Options.CheckOptions); |
| 130 | IO.mapOptional("ExtraArgs", Options.ExtraArgs); |
| 131 | IO.mapOptional("ExtraArgsBefore", Options.ExtraArgsBefore); |
| 132 | IO.mapOptional("InheritParentConfig", Options.InheritParentConfig); |
| 133 | IO.mapOptional("UseColor", Options.UseColor); |
| 134 | } |
| 135 | }; |
| 136 | |
| 137 | } // namespace llvm::yaml |
| 138 | |
| 139 | namespace clang::tidy { |
| 140 | |
| 141 | ClangTidyOptions ClangTidyOptions::getDefaults() { |
| 142 | ClangTidyOptions Options; |
| 143 | Options.Checks = ""; |
| 144 | Options.WarningsAsErrors = ""; |
| 145 | Options.HeaderFilterRegex = ""; |
| 146 | Options.SystemHeaders = false; |
| 147 | Options.FormatStyle = "none"; |
| 148 | Options.User = std::nullopt; |
| 149 | for (const ClangTidyModuleRegistry::entry &Module : |
| 150 | ClangTidyModuleRegistry::entries()) |
| 151 | Options.mergeWith(Module.instantiate()->getModuleOptions(), 0); |
| 152 | return Options; |
| 153 | } |
| 154 | |
| 155 | template <typename T> |
| 156 | static void mergeVectors(std::optional<T> &Dest, const std::optional<T> &Src) { |
| 157 | if (Src) { |
| 158 | if (Dest) |
| 159 | Dest->insert(Dest->end(), Src->begin(), Src->end()); |
| 160 | else |
| 161 | Dest = Src; |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | static void mergeCommaSeparatedLists(std::optional<std::string> &Dest, |
| 166 | const std::optional<std::string> &Src) { |
| 167 | if (Src) |
| 168 | Dest = (Dest && !Dest->empty() ? *Dest + "," : "") + *Src; |
| 169 | } |
| 170 | |
| 171 | template <typename T> |
| 172 | static void overrideValue(std::optional<T> &Dest, const std::optional<T> &Src) { |
| 173 | if (Src) |
| 174 | Dest = Src; |
| 175 | } |
| 176 | |
| 177 | ClangTidyOptions &ClangTidyOptions::mergeWith(const ClangTidyOptions &Other, |
| 178 | unsigned Order) { |
| 179 | mergeCommaSeparatedLists(Checks, Other.Checks); |
| 180 | mergeCommaSeparatedLists(WarningsAsErrors, Other.WarningsAsErrors); |
| 181 | overrideValue(HeaderFilterRegex, Other.HeaderFilterRegex); |
| 182 | overrideValue(SystemHeaders, Other.SystemHeaders); |
| 183 | overrideValue(FormatStyle, Other.FormatStyle); |
| 184 | overrideValue(User, Other.User); |
| 185 | overrideValue(UseColor, Other.UseColor); |
| 186 | mergeVectors(ExtraArgs, Other.ExtraArgs); |
| 187 | mergeVectors(ExtraArgsBefore, Other.ExtraArgsBefore); |
| 188 | |
| 189 | for (const auto &KeyValue : Other.CheckOptions) { |
| 190 | CheckOptions.insert_or_assign( |
| 191 | KeyValue.getKey(), |
| 192 | ClangTidyValue(KeyValue.getValue().Value, |
| 193 | KeyValue.getValue().Priority + Order)); |
| 194 | } |
| 195 | return *this; |
| 196 | } |
| 197 | |
| 198 | ClangTidyOptions ClangTidyOptions::merge(const ClangTidyOptions &Other, |
| 199 | unsigned Order) const { |
| 200 | ClangTidyOptions Result = *this; |
| 201 | Result.mergeWith(Other, Order); |
| 202 | return Result; |
| 203 | } |
| 204 | |
| 205 | const char ClangTidyOptionsProvider::OptionsSourceTypeDefaultBinary[] = |
| 206 | "clang-tidy binary"; |
| 207 | const char ClangTidyOptionsProvider::OptionsSourceTypeCheckCommandLineOption[] = |
| 208 | "command-line option '-checks'"; |
| 209 | const char |
| 210 | ClangTidyOptionsProvider::OptionsSourceTypeConfigCommandLineOption[] = |
| 211 | "command-line option '-config'"; |
| 212 | |
| 213 | ClangTidyOptions |
| 214 | ClangTidyOptionsProvider::getOptions(llvm::StringRef FileName) { |
| 215 | ClangTidyOptions Result; |
| 216 | unsigned Priority = 0; |
| 217 | for (auto &Source : getRawOptions(FileName)) |
| 218 | Result.mergeWith(Source.first, ++Priority); |
| 219 | return Result; |
| 220 | } |
| 221 | |
| 222 | std::vector<OptionsSource> |
| 223 | DefaultOptionsProvider::getRawOptions(llvm::StringRef FileName) { |
| 224 | std::vector<OptionsSource> Result; |
| 225 | Result.emplace_back(DefaultOptions, OptionsSourceTypeDefaultBinary); |
| 226 | return Result; |
| 227 | } |
| 228 | |
| 229 | ConfigOptionsProvider::ConfigOptionsProvider( |
| 230 | ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions, |
| 231 | ClangTidyOptions ConfigOptions, ClangTidyOptions OverrideOptions, |
| 232 | llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS) |
| 233 | : FileOptionsBaseProvider(std::move(GlobalOptions), |
| 234 | std::move(DefaultOptions), |
| 235 | std::move(OverrideOptions), std::move(FS)), |
| 236 | ConfigOptions(std::move(ConfigOptions)) {} |
| 237 | |
| 238 | std::vector<OptionsSource> |
| 239 | ConfigOptionsProvider::getRawOptions(llvm::StringRef FileName) { |
| 240 | std::vector<OptionsSource> RawOptions = |
| 241 | DefaultOptionsProvider::getRawOptions(FileName); |
| 242 | if (ConfigOptions.InheritParentConfig.value_or(false)) { |
| 243 | LLVM_DEBUG(llvm::dbgs() |
| 244 | << "Getting options for file " << FileName << "...\n"); |
| 245 | assert(FS && "FS must be set."); |
| 246 | |
| 247 | llvm::SmallString<128> AbsoluteFilePath(FileName); |
| 248 | |
| 249 | if (!FS->makeAbsolute(AbsoluteFilePath)) { |
| 250 | addRawFileOptions(AbsoluteFilePath, RawOptions); |
| 251 | } |
| 252 | } |
| 253 | RawOptions.emplace_back(ConfigOptions, |
| 254 | OptionsSourceTypeConfigCommandLineOption); |
| 255 | RawOptions.emplace_back(OverrideOptions, |
| 256 | OptionsSourceTypeCheckCommandLineOption); |
| 257 | return RawOptions; |
| 258 | } |
| 259 | |
| 260 | FileOptionsBaseProvider::FileOptionsBaseProvider( |
| 261 | ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions, |
| 262 | ClangTidyOptions OverrideOptions, |
| 263 | llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) |
| 264 | : DefaultOptionsProvider(std::move(GlobalOptions), |
| 265 | std::move(DefaultOptions)), |
| 266 | OverrideOptions(std::move(OverrideOptions)), FS(std::move(VFS)) { |
| 267 | if (!FS) |
| 268 | FS = llvm::vfs::getRealFileSystem(); |
| 269 | ConfigHandlers.emplace_back(".clang-tidy", parseConfiguration); |
| 270 | } |
| 271 | |
| 272 | FileOptionsBaseProvider::FileOptionsBaseProvider( |
| 273 | ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions, |
| 274 | ClangTidyOptions OverrideOptions, |
| 275 | FileOptionsBaseProvider::ConfigFileHandlers ConfigHandlers) |
| 276 | : DefaultOptionsProvider(std::move(GlobalOptions), |
| 277 | std::move(DefaultOptions)), |
| 278 | OverrideOptions(std::move(OverrideOptions)), |
| 279 | ConfigHandlers(std::move(ConfigHandlers)) {} |
| 280 | |
| 281 | void FileOptionsBaseProvider::addRawFileOptions( |
| 282 | llvm::StringRef AbsolutePath, std::vector<OptionsSource> &CurOptions) { |
| 283 | auto CurSize = CurOptions.size(); |
| 284 | |
| 285 | // Look for a suitable configuration file in all parent directories of the |
| 286 | // file. Start with the immediate parent directory and move up. |
| 287 | StringRef Path = llvm::sys::path::parent_path(AbsolutePath); |
| 288 | for (StringRef CurrentPath = Path; !CurrentPath.empty(); |
| 289 | CurrentPath = llvm::sys::path::parent_path(CurrentPath)) { |
| 290 | std::optional<OptionsSource> Result; |
| 291 | |
| 292 | auto Iter = CachedOptions.find(CurrentPath); |
| 293 | if (Iter != CachedOptions.end()) |
| 294 | Result = Iter->second; |
| 295 | |
| 296 | if (!Result) |
| 297 | Result = tryReadConfigFile(CurrentPath); |
| 298 | |
| 299 | if (Result) { |
| 300 | // Store cached value for all intermediate directories. |
| 301 | while (Path != CurrentPath) { |
| 302 | LLVM_DEBUG(llvm::dbgs() |
| 303 | << "Caching configuration for path " << Path << ".\n"); |
| 304 | if (!CachedOptions.count(Path)) |
| 305 | CachedOptions[Path] = *Result; |
| 306 | Path = llvm::sys::path::parent_path(Path); |
| 307 | } |
| 308 | CachedOptions[Path] = *Result; |
| 309 | |
| 310 | CurOptions.push_back(*Result); |
| 311 | if (!Result->first.InheritParentConfig.value_or(false)) |
| 312 | break; |
| 313 | } |
| 314 | } |
| 315 | // Reverse order of file configs because closer configs should have higher |
| 316 | // priority. |
| 317 | std::reverse(CurOptions.begin() + CurSize, CurOptions.end()); |
| 318 | } |
| 319 | |
| 320 | FileOptionsProvider::FileOptionsProvider( |
| 321 | ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions, |
| 322 | ClangTidyOptions OverrideOptions, |
| 323 | llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) |
| 324 | : FileOptionsBaseProvider(std::move(GlobalOptions), |
| 325 | std::move(DefaultOptions), |
| 326 | std::move(OverrideOptions), std::move(VFS)) {} |
| 327 | |
| 328 | FileOptionsProvider::FileOptionsProvider( |
| 329 | ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions, |
| 330 | ClangTidyOptions OverrideOptions, |
| 331 | FileOptionsBaseProvider::ConfigFileHandlers ConfigHandlers) |
| 332 | : FileOptionsBaseProvider( |
| 333 | std::move(GlobalOptions), std::move(DefaultOptions), |
| 334 | std::move(OverrideOptions), std::move(ConfigHandlers)) {} |
| 335 | |
| 336 | // FIXME: This method has some common logic with clang::format::getStyle(). |
| 337 | // Consider pulling out common bits to a findParentFileWithName function or |
| 338 | // similar. |
| 339 | std::vector<OptionsSource> |
| 340 | FileOptionsProvider::getRawOptions(StringRef FileName) { |
| 341 | LLVM_DEBUG(llvm::dbgs() << "Getting options for file " << FileName |
| 342 | << "...\n"); |
| 343 | assert(FS && "FS must be set."); |
| 344 | |
| 345 | llvm::SmallString<128> AbsoluteFilePath(FileName); |
| 346 | |
| 347 | if (FS->makeAbsolute(AbsoluteFilePath)) |
| 348 | return {}; |
| 349 | |
| 350 | std::vector<OptionsSource> RawOptions = |
| 351 | DefaultOptionsProvider::getRawOptions(AbsoluteFilePath.str()); |
| 352 | addRawFileOptions(AbsoluteFilePath, RawOptions); |
| 353 | OptionsSource CommandLineOptions(OverrideOptions, |
| 354 | OptionsSourceTypeCheckCommandLineOption); |
| 355 | |
| 356 | RawOptions.push_back(CommandLineOptions); |
| 357 | return RawOptions; |
| 358 | } |
| 359 | |
| 360 | std::optional<OptionsSource> |
| 361 | FileOptionsBaseProvider::tryReadConfigFile(StringRef Directory) { |
| 362 | assert(!Directory.empty()); |
| 363 | |
| 364 | llvm::ErrorOr<llvm::vfs::Status> DirectoryStatus = FS->status(Directory); |
| 365 | |
| 366 | if (!DirectoryStatus || !DirectoryStatus->isDirectory()) { |
| 367 | llvm::errs() << "Error reading configuration from " << Directory |
| 368 | << ": directory doesn't exist.\n"; |
| 369 | return std::nullopt; |
| 370 | } |
| 371 | |
| 372 | for (const ConfigFileHandler &ConfigHandler : ConfigHandlers) { |
| 373 | SmallString<128> ConfigFile(Directory); |
| 374 | llvm::sys::path::append(ConfigFile, ConfigHandler.first); |
| 375 | LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n"); |
| 376 | |
| 377 | llvm::ErrorOr<llvm::vfs::Status> FileStatus = FS->status(ConfigFile); |
| 378 | |
| 379 | if (!FileStatus || !FileStatus->isRegularFile()) |
| 380 | continue; |
| 381 | |
| 382 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text = |
| 383 | FS->getBufferForFile(ConfigFile); |
| 384 | if (std::error_code EC = Text.getError()) { |
| 385 | llvm::errs() << "Can't read " << ConfigFile << ": " << EC.message() |
| 386 | << "\n"; |
| 387 | continue; |
| 388 | } |
| 389 | |
| 390 | // Skip empty files, e.g. files opened for writing via shell output |
| 391 | // redirection. |
| 392 | if ((*Text)->getBuffer().empty()) |
| 393 | continue; |
| 394 | llvm::ErrorOr<ClangTidyOptions> ParsedOptions = |
| 395 | ConfigHandler.second({(*Text)->getBuffer(), ConfigFile}); |
| 396 | if (!ParsedOptions) { |
| 397 | if (ParsedOptions.getError()) |
| 398 | llvm::errs() << "Error parsing " << ConfigFile << ": " |
| 399 | << ParsedOptions.getError().message() << "\n"; |
| 400 | continue; |
| 401 | } |
| 402 | return OptionsSource(*ParsedOptions, std::string(ConfigFile)); |
| 403 | } |
| 404 | return std::nullopt; |
| 405 | } |
| 406 | |
| 407 | /// Parses -line-filter option and stores it to the \c Options. |
| 408 | std::error_code parseLineFilter(StringRef LineFilter, |
| 409 | clang::tidy::ClangTidyGlobalOptions &Options) { |
| 410 | llvm::yaml::Input Input(LineFilter); |
| 411 | Input >> Options.LineFilter; |
| 412 | return Input.error(); |
| 413 | } |
| 414 | |
| 415 | llvm::ErrorOr<ClangTidyOptions> |
| 416 | parseConfiguration(llvm::MemoryBufferRef Config) { |
| 417 | llvm::yaml::Input Input(Config); |
| 418 | ClangTidyOptions Options; |
| 419 | Input >> Options; |
| 420 | if (Input.error()) |
| 421 | return Input.error(); |
| 422 | return Options; |
| 423 | } |
| 424 | |
| 425 | static void diagHandlerImpl(const llvm::SMDiagnostic &Diag, void *Ctx) { |
| 426 | (*reinterpret_cast<DiagCallback *>(Ctx))(Diag); |
| 427 | } |
| 428 | |
| 429 | llvm::ErrorOr<ClangTidyOptions> |
| 430 | parseConfigurationWithDiags(llvm::MemoryBufferRef Config, |
| 431 | DiagCallback Handler) { |
| 432 | llvm::yaml::Input Input(Config, nullptr, Handler ? diagHandlerImpl : nullptr, |
| 433 | &Handler); |
| 434 | ClangTidyOptions Options; |
| 435 | Input >> Options; |
| 436 | if (Input.error()) |
| 437 | return Input.error(); |
| 438 | return Options; |
| 439 | } |
| 440 | |
| 441 | std::string configurationAsText(const ClangTidyOptions &Options) { |
| 442 | std::string Text; |
| 443 | llvm::raw_string_ostream Stream(Text); |
| 444 | llvm::yaml::Output Output(Stream); |
| 445 | // We use the same mapping method for input and output, so we need a non-const |
| 446 | // reference here. |
| 447 | ClangTidyOptions NonConstValue = Options; |
| 448 | Output << NonConstValue; |
| 449 | return Stream.str(); |
| 450 | } |
| 451 | |
| 452 | } // namespace clang::tidy |