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"
23#define DEBUG_TYPE "clang-tidy-options"
35template <>
struct SequenceTraits<
FileFilter::LineRange> {
36 static size_t size(IO &IO, FileFilter::LineRange &
Range) {
37 return Range.first == 0 ? 0 :
Range.second == 0 ? 1 : 2;
39 static unsigned &
element(IO &IO, FileFilter::LineRange &
Range,
size_t Index) {
41 IO.setError(
"Too many elements in line range.");
42 return Index == 0 ?
Range.first :
Range.second;
48 IO.mapRequired(
"name", File.Name);
49 IO.mapOptional(
"lines", File.LineRanges);
52 if (File.Name.empty())
53 return "No file name specified";
54 for (
const FileFilter::LineRange &
Range : File.LineRanges) {
56 return "Invalid line range";
63 static void mapping(IO &IO, ClangTidyOptions::StringPair &KeyValue) {
64 IO.mapRequired(
"key", KeyValue.first);
65 IO.mapRequired(
"value", KeyValue.second);
71 NOptionMap(IO &,
const ClangTidyOptions::OptionMap &OptionMap) {
72 Options.reserve(OptionMap.size());
73 for (
const auto &KeyValue : OptionMap)
74 Options.emplace_back(std::string(KeyValue.getKey()), KeyValue.getValue().Value);
77 ClangTidyOptions::OptionMap Map;
78 for (
const auto &KeyValue :
Options)
79 Map[KeyValue.first] = ClangTidyOptions::ClangTidyValue(KeyValue.second);
82 std::vector<ClangTidyOptions::StringPair>
Options;
86void yamlize(IO &IO, ClangTidyOptions::OptionMap &Val,
bool,
88 if (IO.outputting()) {
90 std::vector<std::pair<StringRef, StringRef>> SortedOptions;
91 SortedOptions.reserve(Val.size());
92 for (
auto &Key : Val) {
93 SortedOptions.emplace_back(Key.getKey(), Key.getValue().Value);
95 std::sort(SortedOptions.begin(), SortedOptions.end());
99 for (
auto &Option : SortedOptions) {
100 bool UseDefault =
false;
101 void *SaveInfo =
nullptr;
102 IO.preflightKey(Option.first.data(),
true,
false, UseDefault, SaveInfo);
103 IO.scalarString(Option.second, needsQuotes(Option.second));
104 IO.postflightKey(SaveInfo);
110 auto &I =
reinterpret_cast<Input &
>(IO);
111 if (isa<SequenceNode>(I.getCurrentNode())) {
112 MappingNormalization<NOptionMap, ClangTidyOptions::OptionMap> NOpts(IO,
115 yamlize(IO, NOpts->Options,
true, Ctx);
116 }
else if (isa<MappingNode>(I.getCurrentNode())) {
118 for (StringRef Key : IO.keys()) {
119 IO.mapRequired(Key.data(), Val[Key].Value);
123 IO.setError(
"expected a sequence or map");
134 if (!IO.outputting()) {
137 auto &I =
reinterpret_cast<Input &
>(IO);
138 if (isa<ScalarNode, BlockScalarNode>(I.getCurrentNode())) {
141 }
else if (isa<SequenceNode>(I.getCurrentNode())) {
142 Val.
AsVector = std::vector<std::string>();
145 IO.setError(
"expected string or sequence");
150static void mapChecks(IO &IO, std::optional<std::string> &Checks) {
151 if (IO.outputting()) {
153 IO.mapOptional(
"Checks", Checks);
157 IO.mapOptional(
"Checks", ChecksAsVariant);
161 Checks = llvm::join(*ChecksAsVariant.
AsVector,
",");
170 IO.mapOptional(
"ImplementationFileExtensions",
173 IO.mapOptional(
"FormatStyle", Options.
FormatStyle);
174 IO.mapOptional(
"User", Options.
User);
176 IO.mapOptional(
"ExtraArgs", Options.
ExtraArgs);
179 IO.mapOptional(
"UseColor", Options.
UseColor);
197 Options.
User = std::nullopt;
198 for (
const ClangTidyModuleRegistry::entry &Module :
199 ClangTidyModuleRegistry::entries())
200 Options.
mergeWith(Module.instantiate()->getModuleOptions(), 0);
208 Dest->insert(Dest->end(),
Src->begin(),
Src->end());
215 const std::optional<std::string> &
Src) {
217 Dest = (Dest && !Dest->empty() ? *Dest +
"," :
"") + *
Src;
245 KeyValue.getValue().Priority + Order));
251 unsigned Order)
const {
253 Result.mergeWith(Other, Order);
260 "command-line option '-checks'";
263 "command-line option '-config'";
268 unsigned Priority = 0;
270 Result.mergeWith(Source.first, ++Priority);
274std::vector<OptionsSource>
276 std::vector<OptionsSource> Result;
284 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS)
286 std::move(DefaultOptions),
287 std::move(OverrideOptions), std::move(FS)),
288 ConfigOptions(std::move(ConfigOptions)) {}
290std::vector<OptionsSource>
292 std::vector<OptionsSource> RawOptions =
295 LLVM_DEBUG(llvm::dbgs()
296 <<
"Getting options for file " <<
FileName <<
"...\n");
297 assert(
FS &&
"FS must be set.");
299 llvm::SmallString<128> AbsoluteFilePath(
FileName);
301 if (!
FS->makeAbsolute(AbsoluteFilePath)) {
305 RawOptions.emplace_back(ConfigOptions,
315 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
317 std::move(DefaultOptions)),
318 OverrideOptions(std::move(OverrideOptions)), FS(std::move(VFS)) {
320 FS = llvm::vfs::getRealFileSystem();
329 std::move(DefaultOptions)),
330 OverrideOptions(std::move(OverrideOptions)),
331 ConfigHandlers(std::move(ConfigHandlers)) {}
334 llvm::StringRef AbsolutePath, std::vector<OptionsSource> &CurOptions) {
335 auto CurSize = CurOptions.size();
339 StringRef
Path = llvm::sys::path::parent_path(AbsolutePath);
340 for (StringRef CurrentPath =
Path; !CurrentPath.empty();
341 CurrentPath = llvm::sys::path::parent_path(CurrentPath)) {
342 std::optional<OptionsSource> Result;
346 Result = Iter->second;
353 while (
Path != CurrentPath) {
354 LLVM_DEBUG(llvm::dbgs()
355 <<
"Caching configuration for path " <<
Path <<
".\n");
358 Path = llvm::sys::path::parent_path(
Path);
362 CurOptions.push_back(*Result);
363 if (!Result->first.InheritParentConfig.value_or(
false))
369 std::reverse(CurOptions.begin() + CurSize, CurOptions.end());
375 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS)
377 std::move(DefaultOptions),
378 std::move(OverrideOptions), std::move(VFS)) {}
385 std::move(GlobalOptions), std::move(DefaultOptions),
386 std::move(OverrideOptions), std::move(ConfigHandlers)) {}
391std::vector<OptionsSource>
393 LLVM_DEBUG(llvm::dbgs() <<
"Getting options for file " <<
FileName
395 assert(
FS &&
"FS must be set.");
397 llvm::SmallString<128> AbsoluteFilePath(
FileName);
399 if (
FS->makeAbsolute(AbsoluteFilePath))
402 std::vector<OptionsSource> RawOptions =
408 RawOptions.push_back(CommandLineOptions);
412std::optional<OptionsSource>
416 llvm::ErrorOr<llvm::vfs::Status> DirectoryStatus =
FS->status(
Directory);
418 if (!DirectoryStatus || !DirectoryStatus->isDirectory()) {
419 llvm::errs() <<
"Error reading configuration from " <<
Directory
420 <<
": directory doesn't exist.\n";
426 llvm::sys::path::append(
ConfigFile, ConfigHandler.first);
427 LLVM_DEBUG(llvm::dbgs() <<
"Trying " <<
ConfigFile <<
"...\n");
429 llvm::ErrorOr<llvm::vfs::Status> FileStatus =
FS->status(
ConfigFile);
431 if (!FileStatus || !FileStatus->isRegularFile())
434 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
Text =
436 if (std::error_code EC =
Text.getError()) {
437 llvm::errs() <<
"Can't read " <<
ConfigFile <<
": " << EC.message()
444 if ((*Text)->getBuffer().empty())
446 llvm::ErrorOr<ClangTidyOptions> ParsedOptions =
447 ConfigHandler.second({(*Text)->getBuffer(),
ConfigFile});
448 if (!ParsedOptions) {
449 if (ParsedOptions.getError())
450 llvm::errs() <<
"Error parsing " <<
ConfigFile <<
": "
451 << ParsedOptions.getError().message() <<
"\n";
464 return Input.error();
467llvm::ErrorOr<ClangTidyOptions>
469 llvm::yaml::Input Input(
Config);
473 return Input.error();
481llvm::ErrorOr<ClangTidyOptions>
489 return Input.error();
495 llvm::raw_string_ostream Stream(
Text);
496 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.
ClangTidyOptions OverrideOptions
std::optional< OptionsSource > tryReadConfigFile(llvm::StringRef Directory)
Try to read configuration files from Directory using registered ConfigHandlers.
llvm::StringMap< OptionsSource > CachedOptions
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< 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).
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)