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/ErrorOr.h"
16#include "llvm/Support/FileSystem.h"
17#include "llvm/Support/MemoryBufferRef.h"
18#include "llvm/Support/Path.h"
19#include "llvm/Support/YAMLTraits.h"
24#define DEBUG_TYPE "clang-tidy-options"
36template <>
struct SequenceTraits<
FileFilter::LineRange> {
37 static size_t size(IO &IO, FileFilter::LineRange &
Range) {
38 return Range.first == 0 ? 0 :
Range.second == 0 ? 1 : 2;
40 static unsigned &
element(IO &IO, FileFilter::LineRange &
Range,
size_t Index) {
42 IO.setError(
"Too many elements in line range.");
43 return Index == 0 ?
Range.first :
Range.second;
49 IO.mapRequired(
"name", File.Name);
50 IO.mapOptional(
"lines", File.LineRanges);
53 if (File.Name.empty())
54 return "No file name specified";
55 for (
const FileFilter::LineRange &
Range : File.LineRanges) {
57 return "Invalid line range";
64 static void mapping(IO &IO, ClangTidyOptions::StringPair &KeyValue) {
65 IO.mapRequired(
"key", KeyValue.first);
66 IO.mapRequired(
"value", KeyValue.second);
72 NOptionMap(IO &,
const ClangTidyOptions::OptionMap &OptionMap) {
73 Options.reserve(OptionMap.size());
74 for (
const auto &KeyValue : OptionMap)
75 Options.emplace_back(std::string(KeyValue.getKey()), KeyValue.getValue().Value);
78 ClangTidyOptions::OptionMap Map;
79 for (
const auto &KeyValue :
Options)
80 Map[KeyValue.first] = ClangTidyOptions::ClangTidyValue(KeyValue.second);
83 std::vector<ClangTidyOptions::StringPair>
Options;
87void yamlize(IO &IO, ClangTidyOptions::OptionMap &Val,
bool,
89 if (IO.outputting()) {
91 std::vector<std::pair<StringRef, StringRef>> SortedOptions;
92 SortedOptions.reserve(Val.size());
93 for (
auto &Key : Val) {
94 SortedOptions.emplace_back(Key.getKey(), Key.getValue().Value);
96 std::sort(SortedOptions.begin(), SortedOptions.end());
100 for (
auto &Option : SortedOptions) {
101 bool UseDefault =
false;
102 void *SaveInfo =
nullptr;
103 IO.preflightKey(Option.first.data(),
true,
false, UseDefault, SaveInfo);
104 IO.scalarString(Option.second, needsQuotes(Option.second));
105 IO.postflightKey(SaveInfo);
111 auto &I =
reinterpret_cast<Input &
>(IO);
112 if (isa<SequenceNode>(I.getCurrentNode())) {
113 MappingNormalization<NOptionMap, ClangTidyOptions::OptionMap> NOpts(IO,
116 yamlize(IO, NOpts->Options,
true, Ctx);
117 }
else if (isa<MappingNode>(I.getCurrentNode())) {
119 for (StringRef Key : IO.keys()) {
120 IO.mapRequired(Key.data(), Val[Key].Value);
124 IO.setError(
"expected a sequence or map");
135 if (!IO.outputting()) {
138 auto &I =
reinterpret_cast<Input &
>(IO);
139 if (isa<ScalarNode, BlockScalarNode>(I.getCurrentNode())) {
142 }
else if (isa<SequenceNode>(I.getCurrentNode())) {
143 Val.
AsVector = std::vector<std::string>();
146 IO.setError(
"expected string or sequence");
151static void mapChecks(IO &IO, std::optional<std::string> &Checks) {
152 if (IO.outputting()) {
154 IO.mapOptional(
"Checks", Checks);
158 IO.mapOptional(
"Checks", ChecksAsVariant);
162 Checks = llvm::join(*ChecksAsVariant.
AsVector,
",");
171 IO.mapOptional(
"ImplementationFileExtensions",
174 IO.mapOptional(
"ExcludeHeaderFilterRegex",
176 IO.mapOptional(
"FormatStyle", Options.
FormatStyle);
177 IO.mapOptional(
"User", Options.
User);
179 IO.mapOptional(
"ExtraArgs", Options.
ExtraArgs);
182 IO.mapOptional(
"UseColor", Options.
UseColor);
201 Options.
User = std::nullopt;
202 for (
const ClangTidyModuleRegistry::entry &Module :
203 ClangTidyModuleRegistry::entries())
204 Options.
mergeWith(Module.instantiate()->getModuleOptions(), 0);
212 Dest->insert(Dest->end(),
Src->begin(),
Src->end());
219 const std::optional<std::string> &
Src) {
221 Dest = (Dest && !Dest->empty() ? *Dest +
"," :
"") + *
Src;
250 KeyValue.getValue().Priority + Order));
256 unsigned Order)
const {
258 Result.mergeWith(Other, Order);
265 "command-line option '-checks'";
268 "command-line option '-config'";
273 unsigned Priority = 0;
275 Result.mergeWith(Source.first, ++Priority);
279std::vector<OptionsSource>
281 std::vector<OptionsSource> Result;
289 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
291 std::move(DefaultOptions),
292 std::move(OverrideOptions), std::move(FS)),
293 ConfigOptions(std::move(ConfigOptions)) {}
295std::vector<OptionsSource>
297 std::vector<OptionsSource> RawOptions =
300 LLVM_DEBUG(llvm::dbgs()
301 <<
"Getting options for file " <<
FileName <<
"...\n");
303 llvm::ErrorOr<llvm::SmallString<128>> AbsoluteFilePath =
305 if (AbsoluteFilePath) {
309 RawOptions.emplace_back(ConfigOptions,
319 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
321 std::move(DefaultOptions)),
322 OverrideOptions(std::move(OverrideOptions)), FS(std::move(VFS)) {
324 FS = llvm::vfs::getRealFileSystem();
333 std::move(DefaultOptions)),
334 OverrideOptions(std::move(OverrideOptions)),
335 ConfigHandlers(std::move(ConfigHandlers)) {}
337llvm::ErrorOr<llvm::SmallString<128>>
339 assert(
FS &&
"FS must be set.");
340 llvm::SmallString<128> NormalizedAbsolutePath = {
Path};
341 std::error_code Err =
FS->makeAbsolute(NormalizedAbsolutePath);
344 llvm::sys::path::remove_dots(NormalizedAbsolutePath,
true);
345 return NormalizedAbsolutePath;
349 llvm::StringRef AbsolutePath, std::vector<OptionsSource> &CurOptions) {
350 auto CurSize = CurOptions.size();
353 StringRef RootPath = llvm::sys::path::parent_path(AbsolutePath);
354 auto MemorizedConfigFile =
355 [
this, &RootPath](StringRef CurrentPath) -> std::optional<OptionsSource> {
363 while (RootPath != CurrentPath) {
364 LLVM_DEBUG(llvm::dbgs()
365 <<
"Caching configuration for path " << RootPath <<
".\n");
367 RootPath = llvm::sys::path::parent_path(RootPath);
370 RootPath = llvm::sys::path::parent_path(CurrentPath);
374 for (StringRef CurrentPath = RootPath; !CurrentPath.empty();
375 CurrentPath = llvm::sys::path::parent_path(CurrentPath)) {
376 if (std::optional<OptionsSource> Result =
377 MemorizedConfigFile(CurrentPath)) {
378 CurOptions.emplace_back(Result.value());
379 if (!Result->first.InheritParentConfig.value_or(
false))
385 std::reverse(CurOptions.begin() + CurSize, CurOptions.end());
391 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
393 std::move(DefaultOptions),
394 std::move(OverrideOptions), std::move(VFS)) {}
401 std::move(GlobalOptions), std::move(DefaultOptions),
402 std::move(OverrideOptions), std::move(ConfigHandlers)) {}
407std::vector<OptionsSource>
409 LLVM_DEBUG(llvm::dbgs() <<
"Getting options for file " <<
FileName
412 llvm::ErrorOr<llvm::SmallString<128>> AbsoluteFilePath =
414 if (!AbsoluteFilePath)
417 std::vector<OptionsSource> RawOptions =
423 RawOptions.push_back(CommandLineOptions);
427std::optional<OptionsSource>
431 llvm::ErrorOr<llvm::vfs::Status> DirectoryStatus =
FS->status(
Directory);
433 if (!DirectoryStatus || !DirectoryStatus->isDirectory()) {
434 llvm::errs() <<
"Error reading configuration from " <<
Directory
435 <<
": directory doesn't exist.\n";
441 llvm::sys::path::append(
ConfigFile, ConfigHandler.first);
442 LLVM_DEBUG(llvm::dbgs() <<
"Trying " <<
ConfigFile <<
"...\n");
444 llvm::ErrorOr<llvm::vfs::Status> FileStatus =
FS->status(
ConfigFile);
446 if (!FileStatus || !FileStatus->isRegularFile())
449 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
451 if (std::error_code EC =
Text.getError()) {
452 llvm::errs() <<
"Can't read " <<
ConfigFile <<
": " << EC.message()
459 if ((*Text)->getBuffer().empty())
461 llvm::ErrorOr<ClangTidyOptions> ParsedOptions =
462 ConfigHandler.second({(*Text)->getBuffer(),
ConfigFile});
463 if (!ParsedOptions) {
464 if (ParsedOptions.getError())
465 llvm::errs() <<
"Error parsing " <<
ConfigFile <<
": "
466 << ParsedOptions.getError().message() <<
"\n";
479 return Input.error();
482llvm::ErrorOr<ClangTidyOptions>
484 llvm::yaml::Input Input(
Config);
488 return Input.error();
496llvm::ErrorOr<ClangTidyOptions>
504 return Input.error();
510 llvm::raw_string_ostream Stream(
Text);
511 llvm::yaml::Output
Output(Stream);
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< 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::opt< std::string > LineFilter("line-filter", 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))
clang::tidy::ClangTidyOptionsProvider::OptionsSource OptionsSource
CharSourceRange Range
SourceRange for the file name.
std::vector< HeaderHandle > Path
llvm::StringRef Directory
ClangTidyOptions getOptions(llvm::StringRef FileName)
Returns options applying to a specific translation unit with the specified FileName.
static const char OptionsSourceTypeCheckCommandLineOption[]
virtual std::vector< OptionsSource > getRawOptions(llvm::StringRef FileName)=0
Returns an ordered vector of OptionsSources, in order of increasing priority.
std::pair< ClangTidyOptions, std::string > OptionsSource
ClangTidyOptions and its source.
static const char OptionsSourceTypeConfigCommandLineOption[]
static const char OptionsSourceTypeDefaultBinary[]
ConfigOptionsProvider(ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions, ClangTidyOptions ConfigOptions, ClangTidyOptions OverrideOptions, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS=nullptr)
std::vector< OptionsSource > getRawOptions(llvm::StringRef FileName) override
Returns an ordered vector of OptionsSources, in order of increasing priority.
Implementation of the ClangTidyOptionsProvider interface, which returns the same options for all file...
std::vector< OptionsSource > getRawOptions(llvm::StringRef FileName) override
Returns an ordered vector of OptionsSources, in order of increasing priority.
struct clang::tidy::FileOptionsBaseProvider::OptionsCache CachedOptions
ClangTidyOptions OverrideOptions
llvm::ErrorOr< llvm::SmallString< 128 > > getNormalizedAbsolutePath(llvm::StringRef AbsolutePath)
std::optional< OptionsSource > tryReadConfigFile(llvm::StringRef Directory)
Try to read configuration files from Directory using registered ConfigHandlers.
ConfigFileHandlers ConfigHandlers
llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS
FileOptionsBaseProvider(ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions, ClangTidyOptions OverrideOptions, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS)
std::vector< ConfigFileHandler > ConfigFileHandlers
Configuration file handlers listed in the order of priority.
void addRawFileOptions(llvm::StringRef AbsolutePath, std::vector< OptionsSource > &CurOptions)
std::pair< std::string, std::function< llvm::ErrorOr< ClangTidyOptions >(llvm::MemoryBufferRef)> > ConfigFileHandler
std::vector< OptionsSource > getRawOptions(llvm::StringRef FileName) override
Returns an ordered vector of OptionsSources, in order of increasing priority.
FileOptionsProvider(ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions, ClangTidyOptions OverrideOptions, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > FS=nullptr)
Initializes the FileOptionsProvider instance.
std::error_code parseLineFilter(StringRef LineFilter, clang::tidy::ClangTidyGlobalOptions &Options)
Parses -line-filter option and stores it to the Options.
static void diagHandlerImpl(const llvm::SMDiagnostic &Diag, void *Ctx)
static void mergeVectors(std::optional< T > &Dest, const std::optional< T > &Src)
llvm::function_ref< void(const llvm::SMDiagnostic &)> DiagCallback
llvm::ErrorOr< ClangTidyOptions > parseConfigurationWithDiags(llvm::MemoryBufferRef Config, DiagCallback Handler)
static void mergeCommaSeparatedLists(std::optional< std::string > &Dest, const std::optional< std::string > &Src)
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 void overrideValue(std::optional< T > &Dest, const std::optional< T > &Src)
static void mapChecks(IO &IO, std::optional< std::string > &Checks)
void yamlize(IO &IO, ClangTidyOptions::OptionMap &Val, bool, EmptyContext &Ctx)
std::vector< FileFilter > LineFilter
Output warnings from certain line ranges of certain files only.
Helper structure for storing option value with priority of the value.
Contains options for clang-tidy.
OptionMap CheckOptions
Key-value mapping used to store check-specific options.
ClangTidyOptions merge(const ClangTidyOptions &Other, unsigned Order) const
Creates a new ClangTidyOptions instance combined from all fields of this instance overridden by the f...
std::optional< bool > InheritParentConfig
Only used in the FileOptionsProvider and ConfigOptionsProvider.
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< std::vector< std::string > > ImplementationFileExtensions
File extensions to consider to determine if a given diagnostic is located is located in an implementa...
ClangTidyOptions & mergeWith(const ClangTidyOptions &Other, unsigned Order)
Overwrites all fields in here by the fields of Other that have a value.
std::optional< std::string > User
Specifies the name or e-mail of the user running clang-tidy.
std::optional< std::vector< std::string > > HeaderFileExtensions
File extensions to consider to determine if a given diagnostic is located in a header file.
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.
static ClangTidyOptions getDefaults()
These options are used for all settings that haven't been overridden by the OptionsProvider.
std::optional< std::string > ExcludeHeaderFilterRegex
Exclude warnings from headers matching this filter, even if they match HeaderFilterRegex.
std::optional< ArgList > ExtraArgsBefore
Add extra compilation arguments to the start of the list.
std::optional< std::string > FormatStyle
Format code around applied fixes with clang-format using this style.
std::optional< ArgList > ExtraArgs
Add extra compilation arguments to the end of the list.
Contains a list of line ranges in a single file.
std::pair< unsigned int, unsigned int > LineRange
LineRange is a pair<start, end> (inclusive).
llvm::StringMap< size_t > Memorized
llvm::SmallVector< OptionsSource, 4U > Storage
std::optional< std::string > AsString
std::optional< std::vector< std::string > > AsVector
static void mapping(IO &IO, ClangTidyOptions &Options)
static void mapping(IO &IO, ClangTidyOptions::StringPair &KeyValue)
static std::string validate(IO &Io, FileFilter &File)
static void mapping(IO &IO, FileFilter &File)
ClangTidyOptions::OptionMap denormalize(IO &)
NOptionMap(IO &, const ClangTidyOptions::OptionMap &OptionMap)
std::vector< ClangTidyOptions::StringPair > Options
static unsigned & element(IO &IO, FileFilter::LineRange &Range, size_t Index)
static size_t size(IO &IO, FileFilter::LineRange &Range)