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:
173 static constexpr char OptionsSourceTypeDefaultBinary[] = "clang-tidy binary";
175 "command-line option '-checks'";
177 "command-line option '-config'";
178
179 virtual ~ClangTidyOptionsProvider() = default;
180
181 /// Returns global options, which are independent of the file.
183
184 /// ClangTidyOptions and its source.
185 //
186 /// clang-tidy has 3 types of the sources in order of increasing priority:
187 /// * clang-tidy binary.
188 /// * '-config' commandline option or a specific configuration file. If the
189 /// commandline option is specified, clang-tidy will ignore the
190 /// configuration file.
191 /// * '-checks' commandline option.
192 using OptionsSource = std::pair<ClangTidyOptions, std::string>;
193
194 /// Returns an ordered vector of OptionsSources, in order of increasing
195 /// priority.
196 virtual std::vector<OptionsSource>
197 getRawOptions(llvm::StringRef FileName) = 0;
198
199 /// Returns options applying to a specific translation unit with the
200 /// specified \p FileName.
201 ClangTidyOptions getOptions(llvm::StringRef FileName);
202};
203
204/// Implementation of the \c ClangTidyOptionsProvider interface, which
205/// returns the same options for all files.
207public:
209 ClangTidyOptions Options)
210 : GlobalOptions(std::move(GlobalOptions)),
211 DefaultOptions(std::move(Options)) {}
213 return GlobalOptions;
214 }
215 std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
216
217private:
218 ClangTidyGlobalOptions GlobalOptions;
219 ClangTidyOptions DefaultOptions;
220};
221
223protected:
224 // A pair of configuration file base name and a function parsing
225 // configuration from text in the corresponding format.
227 std::pair<std::string, std::function<llvm::ErrorOr<ClangTidyOptions>(
228 llvm::MemoryBufferRef)>>;
229
230 /// Configuration file handlers listed in the order of priority.
231 ///
232 /// Custom configuration file formats can be supported by constructing the
233 /// list of handlers and passing it to the appropriate \c FileOptionsProvider
234 /// constructor. E.g. initialization of a \c FileOptionsProvider with support
235 /// of a custom configuration file format for files named ".my-tidy-config"
236 /// could look similar to this:
237 /// \code
238 /// FileOptionsProvider::ConfigFileHandlers ConfigHandlers;
239 /// ConfigHandlers.emplace_back(".my-tidy-config", parseMyConfigFormat);
240 /// ConfigHandlers.emplace_back(".clang-tidy", parseConfiguration);
241 /// return std::make_unique<FileOptionsProvider>(
242 /// GlobalOptions, DefaultOptions, OverrideOptions, ConfigHandlers);
243 /// \endcode
244 ///
245 /// With the order of handlers shown above, the ".my-tidy-config" file would
246 /// take precedence over ".clang-tidy" if both reside in the same directory.
247 using ConfigFileHandlers = std::vector<ConfigFileHandler>;
248
250 ClangTidyOptions DefaultOptions,
252 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS);
253
255 ClangTidyOptions DefaultOptions,
258
259 void addRawFileOptions(llvm::StringRef AbsolutePath,
260 std::vector<OptionsSource> &CurOptions);
261
262 llvm::ErrorOr<llvm::SmallString<128>>
263 getNormalizedAbsolutePath(llvm::StringRef AbsolutePath);
264
265 /// Try to read configuration files from \p Directory using registered
266 /// \c ConfigHandlers.
267 std::optional<OptionsSource> tryReadConfigFile(llvm::StringRef Directory);
268
270 llvm::StringMap<size_t> Memorized;
271 llvm::SmallVector<OptionsSource, 4U> Storage;
275 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS;
276};
277
278/// Implementation of ClangTidyOptions interface, which is used for
279/// '-config' command-line option.
281public:
283 ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions,
285 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = nullptr);
286 std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
287
288private:
289 ClangTidyOptions ConfigOptions;
290};
291
292/// Implementation of the \c ClangTidyOptionsProvider interface, which
293/// tries to find a configuration file in the closest parent directory of each
294/// source file.
295///
296/// By default, files named ".clang-tidy" will be considered, and the
297/// \c clang::tidy::parseConfiguration function will be used for parsing, but a
298/// custom set of configuration file names and parsing functions can be
299/// specified using the appropriate constructor.
301public:
302 /// Initializes the \c FileOptionsProvider instance.
303 ///
304 /// \param GlobalOptions are just stored and returned to the caller of
305 /// \c getGlobalOptions.
306 ///
307 /// \param DefaultOptions are used for all settings not specified in a
308 /// configuration file.
309 ///
310 /// If any of the \param OverrideOptions fields are set, they will override
311 /// whatever options are read from the configuration file.
313 ClangTidyGlobalOptions GlobalOptions, ClangTidyOptions DefaultOptions,
315 llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = nullptr);
316
317 /// Initializes the \c FileOptionsProvider instance with a custom set
318 /// of configuration file handlers.
319 ///
320 /// \param GlobalOptions are just stored and returned to the caller of
321 /// \c getGlobalOptions.
322 ///
323 /// \param DefaultOptions are used for all settings not specified in a
324 /// configuration file.
325 ///
326 /// If any of the \param OverrideOptions fields are set, they will override
327 /// whatever options are read from the configuration file.
328 ///
329 /// \param ConfigHandlers specifies a custom set of configuration file
330 /// handlers. Each handler is a pair of configuration file name and a function
331 /// that can parse configuration from this file type. The configuration files
332 /// in each directory are searched for in the order of appearance in
333 /// \p ConfigHandlers.
335 ClangTidyOptions DefaultOptions,
338
339 std::vector<OptionsSource> getRawOptions(llvm::StringRef FileName) override;
340};
341
342/// Parses LineFilter from JSON and stores it to the \p Options.
343std::error_code parseLineFilter(llvm::StringRef LineFilter,
344 ClangTidyGlobalOptions &Options);
345
346/// Parses configuration from JSON and returns \c ClangTidyOptions or an
347/// error.
348llvm::ErrorOr<ClangTidyOptions>
349parseConfiguration(llvm::MemoryBufferRef Config);
350
351using DiagCallback = llvm::function_ref<void(const llvm::SMDiagnostic &)>;
352
353llvm::ErrorOr<ClangTidyOptions>
354parseConfigurationWithDiags(llvm::MemoryBufferRef Config, DiagCallback Handler);
355
356/// Serializes configuration to a YAML-encoded string.
357std::string configurationAsText(const ClangTidyOptions &Options);
358
359} // namespace clang::tidy
360
361#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.
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 constexpr char OptionsSourceTypeConfigCommandLineOption[]
virtual ~ClangTidyOptionsProvider()=default
static constexpr char OptionsSourceTypeCheckCommandLineOption[]
static constexpr char OptionsSourceTypeDefaultBinary[]
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