clang-tools 22.0.0git
ClangTidyOptions.h
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H
10#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H
11
12#include "clang/Basic/DiagnosticIDs.h"
13#include "llvm/ADT/IntrusiveRefCntPtr.h"
14#include "llvm/ADT/SmallString.h"
15#include "llvm/ADT/StringMap.h"
16#include "llvm/ADT/StringRef.h"
17#include "llvm/Support/ErrorOr.h"
18#include "llvm/Support/MemoryBufferRef.h"
19#include "llvm/Support/VirtualFileSystem.h"
20#include <functional>
21#include <optional>
22#include <string>
23#include <system_error>
24#include <utility>
25#include <vector>
26
27namespace clang::tidy {
28
29/// Contains a list of line ranges in a single file.
30struct FileFilter {
31 /// File name.
32 std::string Name;
33
34 /// LineRange is a pair<start, end> (inclusive).
35 using LineRange = std::pair<unsigned int, unsigned int>;
36
37 /// A list of line ranges in this file, for which we show warnings.
38 std::vector<LineRange> LineRanges;
39};
40
41/// Global options. These options are neither stored nor read from
42/// configuration files.
44 /// Output warnings from certain line ranges of certain files only.
45 /// If empty, no warnings will be filtered.
46 std::vector<FileFilter> LineFilter;
47};
48
49/// Contains options for clang-tidy. These options may be read from
50/// configuration files, and may be different for different translation units.
52 /// These options are used for all settings that haven't been
53 /// overridden by the \c OptionsProvider.
54 ///
55 /// Allow no checks and no headers by default. This method initializes
56 /// check-specific options by calling \c ClangTidyModule::getModuleOptions()
57 /// of each registered \c ClangTidyModule.
59
60 /// Overwrites all fields in here by the fields of \p Other that have a value.
61 /// \p Order specifies precedence of \p Other option.
62 ClangTidyOptions &mergeWith(const ClangTidyOptions &Other, unsigned Order);
63
64 /// Creates a new \c ClangTidyOptions instance combined from all fields
65 /// of this instance overridden by the fields of \p Other that have a value.
66 /// \p Order specifies precedence of \p Other option.
67 [[nodiscard]] ClangTidyOptions merge(const ClangTidyOptions &Other,
68 unsigned Order) const;
69
70 /// Checks filter.
71 std::optional<std::string> Checks;
72
73 /// WarningsAsErrors filter.
74 std::optional<std::string> WarningsAsErrors;
75
76 /// File extensions to consider to determine if a given diagnostic is located
77 /// in a header file.
78 std::optional<std::vector<std::string>> HeaderFileExtensions;
79
80 /// File extensions to consider to determine if a given diagnostic is located
81 /// is located in an implementation file.
82 std::optional<std::vector<std::string>> ImplementationFileExtensions;
83
84 /// Output warnings from headers matching this filter. Warnings from
85 /// main files will always be displayed.
86 std::optional<std::string> HeaderFilterRegex;
87
88 /// Exclude warnings from headers matching this filter, even if they
89 /// match \c HeaderFilterRegex.
90 std::optional<std::string> ExcludeHeaderFilterRegex;
91
92 /// Output warnings from system headers matching \c HeaderFilterRegex.
93 std::optional<bool> SystemHeaders;
94
95 /// Format code around applied fixes with clang-format using this
96 /// style.
97 ///
98 /// Can be one of:
99 /// * 'none' - don't format code around applied fixes;
100 /// * 'llvm', 'google', 'mozilla' or other predefined clang-format style
101 /// names;
102 /// * 'file' - use the .clang-format file in the closest parent directory of
103 /// each source file;
104 /// * '{inline-formatting-style-in-yaml-format}'.
105 ///
106 /// See clang-format documentation for more about configuring format style.
107 std::optional<std::string> FormatStyle;
108
109 /// Specifies the name or e-mail of the user running clang-tidy.
110 ///
111 /// This option is used, for example, to place the correct user name in TODO()
112 /// comments in the relevant check.
113 std::optional<std::string> User;
114
115 /// Helper structure for storing option value with priority of the value.
117 ClangTidyValue() = default;
118 ClangTidyValue(const char *Value) : Value(Value) {}
119 ClangTidyValue(llvm::StringRef Value, unsigned Priority = 0)
121
122 std::string Value;
123 /// Priority stores relative precedence of the value loaded from config
124 /// files to disambiguate local vs global value from different levels.
125 unsigned Priority = 0;
126 };
127 using StringPair = std::pair<std::string, std::string>;
128 using OptionMap = llvm::StringMap<ClangTidyValue>;
129
130 /// Key-value mapping used to store check-specific options.
132
134 std::string BindName;
135 std::string Message;
136 std::optional<DiagnosticIDs::Level> Level;
137 };
139 std::string Name;
140 std::string Query;
141 llvm::SmallVector<CustomCheckDiag> Diags;
142 };
143 using CustomCheckValueList = llvm::SmallVector<CustomCheckValue>;
144 std::optional<CustomCheckValueList> CustomChecks;
145
146 using ArgList = std::vector<std::string>;
147
148 /// Add extra compilation arguments to the end of the list.
149 std::optional<ArgList> ExtraArgs;
150
151 /// Add extra compilation arguments to the start of the list.
152 std::optional<ArgList> ExtraArgsBefore;
153
154 /// Remove command line arguments sent to the compiler matching this.
155 std::optional<ArgList> RemovedArgs;
156
157 /// Only used in the FileOptionsProvider and ConfigOptionsProvider. If true
158 /// and using a FileOptionsProvider, it will take a configuration file in the
159 /// parent directory (if any exists) and apply this config file on top of the
160 /// parent one. IF true and using a ConfigOptionsProvider, it will apply this
161 /// config on top of any configuration file it finds in the directory using
162 /// the same logic as FileOptionsProvider. If false or missing, only this
163 /// configuration file will be used.
164 std::optional<bool> InheritParentConfig;
165
166 /// Use colors in diagnostics. If missing, it will be auto detected.
167 std::optional<bool> UseColor;
168};
169
170/// Abstract interface for retrieving various ClangTidy options.
172public:
176
177 virtual ~ClangTidyOptionsProvider() = default;
178
179 /// Returns global options, which are independent of the file.
181
182 /// ClangTidyOptions and its source.
183 //
184 /// clang-tidy has 3 types of the sources in order of increasing priority:
185 /// * clang-tidy binary.
186 /// * '-config' commandline option or a specific configuration file. If the
187 /// commandline option is specified, clang-tidy will ignore the
188 /// configuration file.
189 /// * '-checks' commandline option.
190 using OptionsSource = std::pair<ClangTidyOptions, std::string>;
191
192 /// Returns an ordered vector of OptionsSources, in order of increasing
193 /// priority.
194 virtual std::vector<OptionsSource>
195 getRawOptions(llvm::StringRef FileName) = 0;
196
197 /// Returns options applying to a specific translation unit with the
198 /// specified \p FileName.
199 ClangTidyOptions getOptions(llvm::StringRef FileName);
200};
201
202/// Implementation of the \c ClangTidyOptionsProvider interface, which
203/// returns the same options for all files.
205public:
207 ClangTidyOptions Options)
208 : GlobalOptions(std::move(GlobalOptions)),
209 DefaultOptions(std::move(Options)) {}
211 return GlobalOptions;
212 }
213 std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
214
215private:
216 ClangTidyGlobalOptions GlobalOptions;
217 ClangTidyOptions DefaultOptions;
218};
219
221protected:
222 // A pair of configuration file base name and a function parsing
223 // configuration from text in the corresponding format.
225 std::pair<std::string, std::function<llvm::ErrorOr<ClangTidyOptions>(
226 llvm::MemoryBufferRef)>>;
227
228 /// Configuration file handlers listed in the order of priority.
229 ///
230 /// Custom configuration file formats can be supported by constructing the
231 /// list of handlers and passing it to the appropriate \c FileOptionsProvider
232 /// constructor. E.g. initialization of a \c FileOptionsProvider with support
233 /// of a custom configuration file format for files named ".my-tidy-config"
234 /// could look similar to this:
235 /// \code
236 /// FileOptionsProvider::ConfigFileHandlers ConfigHandlers;
237 /// ConfigHandlers.emplace_back(".my-tidy-config", parseMyConfigFormat);
238 /// ConfigHandlers.emplace_back(".clang-tidy", parseConfiguration);
239 /// return std::make_unique<FileOptionsProvider>(
240 /// GlobalOptions, DefaultOptions, OverrideOptions, ConfigHandlers);
241 /// \endcode
242 ///
243 /// With the order of handlers shown above, the ".my-tidy-config" file would
244 /// take precedence over ".clang-tidy" if both reside in the same directory.
245 using ConfigFileHandlers = std::vector<ConfigFileHandler>;
246
248 ClangTidyOptions DefaultOptions,
250 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS);
251
253 ClangTidyOptions DefaultOptions,
256
257 void addRawFileOptions(llvm::StringRef AbsolutePath,
258 std::vector<OptionsSource> &CurOptions);
259
260 llvm::ErrorOr<llvm::SmallString<128>>
261 getNormalizedAbsolutePath(llvm::StringRef AbsolutePath);
262
263 /// Try to read configuration files from \p Directory using registered
264 /// \c ConfigHandlers.
265 std::optional<OptionsSource> tryReadConfigFile(llvm::StringRef Directory);
266
268 llvm::StringMap<size_t> Memorized;
269 llvm::SmallVector<OptionsSource, 4U> Storage;
273 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS;
274};
275
276/// Implementation of ClangTidyOptions interface, which is used for
277/// '-config' command-line option.
279public:
281 ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions,
283 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = nullptr);
284 std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
285
286private:
287 ClangTidyOptions ConfigOptions;
288};
289
290/// Implementation of the \c ClangTidyOptionsProvider interface, which
291/// tries to find a configuration file in the closest parent directory of each
292/// source file.
293///
294/// By default, files named ".clang-tidy" will be considered, and the
295/// \c clang::tidy::parseConfiguration function will be used for parsing, but a
296/// custom set of configuration file names and parsing functions can be
297/// specified using the appropriate constructor.
299public:
300 /// Initializes the \c FileOptionsProvider instance.
301 ///
302 /// \param GlobalOptions are just stored and returned to the caller of
303 /// \c getGlobalOptions.
304 ///
305 /// \param DefaultOptions are used for all settings not specified in a
306 /// configuration file.
307 ///
308 /// If any of the \param OverrideOptions fields are set, they will override
309 /// whatever options are read from the configuration file.
311 ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions,
313 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = nullptr);
314
315 /// Initializes the \c FileOptionsProvider instance with a custom set
316 /// of configuration file handlers.
317 ///
318 /// \param GlobalOptions are just stored and returned to the caller of
319 /// \c getGlobalOptions.
320 ///
321 /// \param DefaultOptions are used for all settings not specified in a
322 /// configuration file.
323 ///
324 /// If any of the \param OverrideOptions fields are set, they will override
325 /// whatever options are read from the configuration file.
326 ///
327 /// \param ConfigHandlers specifies a custom set of configuration file
328 /// handlers. Each handler is a pair of configuration file name and a function
329 /// that can parse configuration from this file type. The configuration files
330 /// in each directory are searched for in the order of appearance in
331 /// \p ConfigHandlers.
333 ClangTidyOptions DefaultOptions,
336
337 std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
338};
339
340/// Parses LineFilter from JSON and stores it to the \p Options.
341std::error_code parseLineFilter(llvm::StringRef LineFilter,
342 ClangTidyGlobalOptions &Options);
343
344/// Parses configuration from JSON and returns \c ClangTidyOptions or an
345/// error.
346llvm::ErrorOr<ClangTidyOptions>
347parseConfiguration(llvm::MemoryBufferRef Config);
348
349using DiagCallback = llvm::function_ref<void(const llvm::SMDiagnostic &)>;
350
351llvm::ErrorOr<ClangTidyOptions>
352parseConfigurationWithDiags(llvm::MemoryBufferRef Config, DiagCallback Handler);
353
354/// Serializes configuration to a YAML-encoded string.
355std::string configurationAsText(const ClangTidyOptions &Options);
356
357} // namespace clang::tidy
358
359#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYOPTIONS_H
static cl::opt< std::string > Directory(cl::Positional, cl::Required, cl::desc("<Search Root Directory>"))
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 and line ranges to output diagnostics from. The range is inclusive on both ends. Can be used together with -header-filter. The format of the list is a JSON array of objects. For example: [ {"name":"file1.cpp","lines":[[1,3],[5,7]]}, {"name":"file2.h"} ] This will output diagnostics from 'file1.cpp' only for the line ranges [1,3] and [5,7], as well as all from the entire 'file2.h'. )"), cl::init(""), cl::cat(ClangTidyCategory))
Abstract interface for retrieving various ClangTidy options.
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[]
virtual ~ClangTidyOptionsProvider()=default
virtual const ClangTidyGlobalOptions & getGlobalOptions()=0
Returns global options, which are independent of the file.
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.
const ClangTidyGlobalOptions & getGlobalOptions() override
Returns global options, which are independent of the file.
DefaultOptionsProvider(ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions Options)
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
std::pair< std::string, std::function< llvm::ErrorOr< ClangTidyOptions >( llvm::MemoryBufferRef)> > ConfigFileHandler
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.
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::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.
llvm::ErrorOr< ClangTidyOptions > parseConfigurationWithDiags(llvm::MemoryBufferRef Config, DiagCallback Handler)
llvm::function_ref< void(const llvm::SMDiagnostic &)> DiagCallback
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.
std::vector< FileFilter > LineFilter
Output warnings from certain line ranges of certain files only.
ClangTidyValue(llvm::StringRef Value, unsigned Priority=0)
unsigned Priority
Priority stores relative precedence of the value loaded from config files to disambiguate local vs gl...
std::optional< DiagnosticIDs::Level > Level
llvm::SmallVector< CustomCheckDiag > Diags
Contains options for clang-tidy.
std::pair< std::string, std::string > StringPair
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...
llvm::StringMap< ClangTidyValue > OptionMap
std::optional< bool > InheritParentConfig
Only used in the FileOptionsProvider and ConfigOptionsProvider.
std::vector< std::string > ArgList
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...
std::optional< ArgList > RemovedArgs
Remove command line arguments sent to the compiler matching this.
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.
llvm::SmallVector< CustomCheckValue > CustomCheckValueList
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< CustomCheckValueList > CustomChecks
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).
std::string Name
File name.
std::vector< LineRange > LineRanges
A list of line ranges in this file, for which we show warnings.
llvm::SmallVector< OptionsSource, 4U > Storage