Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/ClangTidyOptions.h

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