1 | //===--- ClangTidyDiagnosticConsumer.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_CLANGTIDYDIAGNOSTICCONSUMER_H |
10 | #define |
11 | |
12 | #include "ClangTidyOptions.h" |
13 | #include "ClangTidyProfiling.h" |
14 | #include "FileExtensionsSet.h" |
15 | #include "NoLintDirectiveHandler.h" |
16 | #include "clang/Basic/Diagnostic.h" |
17 | #include "clang/Tooling/Core/Diagnostic.h" |
18 | #include "llvm/ADT/DenseMap.h" |
19 | #include "llvm/ADT/StringSet.h" |
20 | #include "llvm/Support/Regex.h" |
21 | #include <optional> |
22 | |
23 | namespace clang { |
24 | |
25 | class ASTContext; |
26 | class SourceManager; |
27 | |
28 | namespace tidy { |
29 | class CachedGlobList; |
30 | |
31 | /// A detected error complete with information to display diagnostic and |
32 | /// automatic fix. |
33 | /// |
34 | /// This is used as an intermediate format to transport Diagnostics without a |
35 | /// dependency on a SourceManager. |
36 | /// |
37 | /// FIXME: Make Diagnostics flexible enough to support this directly. |
38 | struct ClangTidyError : tooling::Diagnostic { |
39 | ClangTidyError(StringRef CheckName, Level DiagLevel, StringRef BuildDirectory, |
40 | bool IsWarningAsError); |
41 | |
42 | bool IsWarningAsError; |
43 | std::vector<std::string> EnabledDiagnosticAliases; |
44 | }; |
45 | |
46 | /// Contains displayed and ignored diagnostic counters for a ClangTidy run. |
47 | struct ClangTidyStats { |
48 | unsigned ErrorsDisplayed = 0; |
49 | unsigned ErrorsIgnoredCheckFilter = 0; |
50 | unsigned ErrorsIgnoredNOLINT = 0; |
51 | unsigned ErrorsIgnoredNonUserCode = 0; |
52 | unsigned ErrorsIgnoredLineFilter = 0; |
53 | |
54 | unsigned errorsIgnored() const { |
55 | return ErrorsIgnoredNOLINT + ErrorsIgnoredCheckFilter + |
56 | ErrorsIgnoredNonUserCode + ErrorsIgnoredLineFilter; |
57 | } |
58 | }; |
59 | |
60 | /// Every \c ClangTidyCheck reports errors through a \c DiagnosticsEngine |
61 | /// provided by this context. |
62 | /// |
63 | /// A \c ClangTidyCheck always has access to the active context to report |
64 | /// warnings like: |
65 | /// \code |
66 | /// Context->Diag(Loc, "Single-argument constructors must be explicit") |
67 | /// << FixItHint::CreateInsertion(Loc, "explicit "); |
68 | /// \endcode |
69 | class ClangTidyContext { |
70 | public: |
71 | /// Initializes \c ClangTidyContext instance. |
72 | ClangTidyContext(std::unique_ptr<ClangTidyOptionsProvider> OptionsProvider, |
73 | bool AllowEnablingAnalyzerAlphaCheckers = false, |
74 | bool = false); |
75 | /// Sets the DiagnosticsEngine that diag() will emit diagnostics to. |
76 | // FIXME: this is required initialization, and should be a constructor param. |
77 | // Fix the context -> diag engine -> consumer -> context initialization cycle. |
78 | void setDiagnosticsEngine(std::unique_ptr<DiagnosticOptions> DiagOpts, |
79 | DiagnosticsEngine *DiagEngine) { |
80 | this->DiagOpts = std::move(DiagOpts); |
81 | this->DiagEngine = DiagEngine; |
82 | } |
83 | |
84 | ~ClangTidyContext(); |
85 | |
86 | ClangTidyContext(const ClangTidyContext &) = delete; |
87 | ClangTidyContext &operator=(const ClangTidyContext &) = delete; |
88 | |
89 | /// Report any errors detected using this method. |
90 | /// |
91 | /// This is still under heavy development and will likely change towards using |
92 | /// tablegen'd diagnostic IDs. |
93 | /// FIXME: Figure out a way to manage ID spaces. |
94 | DiagnosticBuilder diag(StringRef CheckName, SourceLocation Loc, |
95 | StringRef Description, |
96 | DiagnosticIDs::Level Level = DiagnosticIDs::Warning); |
97 | |
98 | DiagnosticBuilder diag(StringRef CheckName, StringRef Description, |
99 | DiagnosticIDs::Level Level = DiagnosticIDs::Warning); |
100 | |
101 | DiagnosticBuilder diag(const tooling::Diagnostic &Error); |
102 | |
103 | /// Report any errors to do with reading the configuration using this method. |
104 | DiagnosticBuilder |
105 | configurationDiag(StringRef Message, |
106 | DiagnosticIDs::Level Level = DiagnosticIDs::Warning); |
107 | |
108 | /// Check whether a given diagnostic should be suppressed due to the presence |
109 | /// of a "NOLINT" suppression comment. |
110 | /// This is exposed so that other tools that present clang-tidy diagnostics |
111 | /// (such as clangd) can respect the same suppression rules as clang-tidy. |
112 | /// This does not handle suppression of notes following a suppressed |
113 | /// diagnostic; that is left to the caller as it requires maintaining state in |
114 | /// between calls to this function. |
115 | /// If any NOLINT is malformed, e.g. a BEGIN without a subsequent END, output |
116 | /// \param NoLintErrors will return an error about it. |
117 | /// If \param AllowIO is false, the function does not attempt to read source |
118 | /// files from disk which are not already mapped into memory; such files are |
119 | /// treated as not containing a suppression comment. |
120 | /// \param EnableNoLintBlocks controls whether to honor NOLINTBEGIN/NOLINTEND |
121 | /// blocks; if false, only considers line-level disabling. |
122 | bool |
123 | shouldSuppressDiagnostic(DiagnosticsEngine::Level DiagLevel, |
124 | const Diagnostic &Info, |
125 | SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, |
126 | bool AllowIO = true, bool EnableNoLintBlocks = true); |
127 | |
128 | /// Sets the \c SourceManager of the used \c DiagnosticsEngine. |
129 | /// |
130 | /// This is called from the \c ClangTidyCheck base class. |
131 | void setSourceManager(SourceManager *SourceMgr); |
132 | |
133 | /// Should be called when starting to process new translation unit. |
134 | void setCurrentFile(StringRef File); |
135 | |
136 | /// Returns the main file name of the current translation unit. |
137 | StringRef getCurrentFile() const { return CurrentFile; } |
138 | |
139 | /// Sets ASTContext for the current translation unit. |
140 | void setASTContext(ASTContext *Context); |
141 | |
142 | /// Gets the language options from the AST context. |
143 | const LangOptions &getLangOpts() const { return LangOpts; } |
144 | |
145 | /// Returns the name of the clang-tidy check which produced this |
146 | /// diagnostic ID. |
147 | std::string getCheckName(unsigned DiagnosticID) const; |
148 | |
149 | /// Returns \c true if the check is enabled for the \c CurrentFile. |
150 | /// |
151 | /// The \c CurrentFile can be changed using \c setCurrentFile. |
152 | bool isCheckEnabled(StringRef CheckName) const; |
153 | |
154 | /// Returns \c true if the check should be upgraded to error for the |
155 | /// \c CurrentFile. |
156 | bool treatAsError(StringRef CheckName) const; |
157 | |
158 | /// Returns global options. |
159 | const ClangTidyGlobalOptions &getGlobalOptions() const; |
160 | |
161 | /// Returns options for \c CurrentFile. |
162 | /// |
163 | /// The \c CurrentFile can be changed using \c setCurrentFile. |
164 | const ClangTidyOptions &getOptions() const; |
165 | |
166 | /// Returns options for \c File. Does not change or depend on |
167 | /// \c CurrentFile. |
168 | ClangTidyOptions getOptionsForFile(StringRef File) const; |
169 | |
170 | const FileExtensionsSet &() const { |
171 | return HeaderFileExtensions; |
172 | } |
173 | |
174 | const FileExtensionsSet &getImplementationFileExtensions() const { |
175 | return ImplementationFileExtensions; |
176 | } |
177 | |
178 | /// Returns \c ClangTidyStats containing issued and ignored diagnostic |
179 | /// counters. |
180 | const ClangTidyStats &getStats() const { return Stats; } |
181 | |
182 | /// Control profile collection in clang-tidy. |
183 | void setEnableProfiling(bool Profile); |
184 | bool getEnableProfiling() const { return Profile; } |
185 | |
186 | /// Control storage of profile date. |
187 | void setProfileStoragePrefix(StringRef ProfilePrefix); |
188 | std::optional<ClangTidyProfiling::StorageParams> |
189 | getProfileStorageParams() const; |
190 | |
191 | /// Should be called when starting to process new translation unit. |
192 | void setCurrentBuildDirectory(StringRef BuildDirectory) { |
193 | CurrentBuildDirectory = std::string(BuildDirectory); |
194 | } |
195 | |
196 | /// Returns build directory of the current translation unit. |
197 | const std::string &getCurrentBuildDirectory() const { |
198 | return CurrentBuildDirectory; |
199 | } |
200 | |
201 | /// If the experimental alpha checkers from the static analyzer can be |
202 | /// enabled. |
203 | bool canEnableAnalyzerAlphaCheckers() const { |
204 | return AllowEnablingAnalyzerAlphaCheckers; |
205 | } |
206 | |
207 | // This method determines whether preprocessor-level module header parsing is |
208 | // enabled using the `--experimental-enable-module-headers-parsing` option. |
209 | bool () const { |
210 | return EnableModuleHeadersParsing; |
211 | } |
212 | |
213 | void setSelfContainedDiags(bool Value) { SelfContainedDiags = Value; } |
214 | |
215 | bool areDiagsSelfContained() const { return SelfContainedDiags; } |
216 | |
217 | using DiagLevelAndFormatString = std::pair<DiagnosticIDs::Level, std::string>; |
218 | DiagLevelAndFormatString getDiagLevelAndFormatString(unsigned DiagnosticID, |
219 | SourceLocation Loc) { |
220 | return {static_cast<DiagnosticIDs::Level>( |
221 | DiagEngine->getDiagnosticLevel(DiagID: DiagnosticID, Loc)), |
222 | std::string( |
223 | DiagEngine->getDiagnosticIDs()->getDescription(DiagID: DiagnosticID))}; |
224 | } |
225 | |
226 | void setOptionsCollector(llvm::StringSet<> *Collector) { |
227 | OptionsCollector = Collector; |
228 | } |
229 | llvm::StringSet<> *getOptionsCollector() const { return OptionsCollector; } |
230 | |
231 | private: |
232 | // Writes to Stats. |
233 | friend class ClangTidyDiagnosticConsumer; |
234 | |
235 | std::unique_ptr<DiagnosticOptions> DiagOpts = nullptr; |
236 | DiagnosticsEngine *DiagEngine = nullptr; |
237 | std::unique_ptr<ClangTidyOptionsProvider> OptionsProvider; |
238 | |
239 | std::string CurrentFile; |
240 | ClangTidyOptions CurrentOptions; |
241 | |
242 | std::unique_ptr<CachedGlobList> CheckFilter; |
243 | std::unique_ptr<CachedGlobList> WarningAsErrorFilter; |
244 | |
245 | FileExtensionsSet ; |
246 | FileExtensionsSet ImplementationFileExtensions; |
247 | |
248 | LangOptions LangOpts; |
249 | |
250 | ClangTidyStats Stats; |
251 | |
252 | std::string CurrentBuildDirectory; |
253 | |
254 | llvm::DenseMap<unsigned, std::string> CheckNamesByDiagnosticID; |
255 | |
256 | bool Profile = false; |
257 | std::string ProfilePrefix; |
258 | |
259 | bool AllowEnablingAnalyzerAlphaCheckers; |
260 | bool ; |
261 | |
262 | bool SelfContainedDiags = false; |
263 | |
264 | NoLintDirectiveHandler NoLintHandler; |
265 | llvm::StringSet<> *OptionsCollector = nullptr; |
266 | }; |
267 | |
268 | /// Gets the Fix attached to \p Diagnostic. |
269 | /// If there isn't a Fix attached to the diagnostic and \p AnyFix is true, Check |
270 | /// to see if exactly one note has a Fix and return it. Otherwise return |
271 | /// nullptr. |
272 | const llvm::StringMap<tooling::Replacements> * |
273 | getFixIt(const tooling::Diagnostic &Diagnostic, bool AnyFix); |
274 | |
275 | /// A diagnostic consumer that turns each \c Diagnostic into a |
276 | /// \c SourceManager-independent \c ClangTidyError. |
277 | // FIXME: If we move away from unit-tests, this can be moved to a private |
278 | // implementation file. |
279 | class ClangTidyDiagnosticConsumer : public DiagnosticConsumer { |
280 | public: |
281 | /// \param EnableNolintBlocks Enables diagnostic-disabling inside blocks of |
282 | /// code, delimited by NOLINTBEGIN and NOLINTEND. |
283 | ClangTidyDiagnosticConsumer(ClangTidyContext &Ctx, |
284 | DiagnosticsEngine *ExternalDiagEngine = nullptr, |
285 | bool RemoveIncompatibleErrors = true, |
286 | bool GetFixesFromNotes = false, |
287 | bool EnableNolintBlocks = true); |
288 | |
289 | // FIXME: The concept of converting between FixItHints and Replacements is |
290 | // more generic and should be pulled out into a more useful Diagnostics |
291 | // library. |
292 | void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, |
293 | const Diagnostic &Info) override; |
294 | |
295 | // Retrieve the diagnostics that were captured. |
296 | std::vector<ClangTidyError> take(); |
297 | |
298 | private: |
299 | void finalizeLastError(); |
300 | void removeIncompatibleErrors(); |
301 | void removeDuplicatedDiagnosticsOfAliasCheckers(); |
302 | |
303 | /// Returns the \c HeaderFilter constructed for the options set in the |
304 | /// context. |
305 | llvm::Regex *(); |
306 | |
307 | /// Returns the \c ExcludeHeaderFilter constructed for the options set in the |
308 | /// context. |
309 | llvm::Regex *(); |
310 | |
311 | /// Updates \c LastErrorRelatesToUserCode and LastErrorPassesLineFilter |
312 | /// according to the diagnostic \p Location. |
313 | void checkFilters(SourceLocation Location, const SourceManager &Sources); |
314 | bool passesLineFilter(StringRef FileName, unsigned LineNumber) const; |
315 | |
316 | void forwardDiagnostic(const Diagnostic &Info); |
317 | |
318 | ClangTidyContext &Context; |
319 | DiagnosticsEngine *ExternalDiagEngine; |
320 | bool RemoveIncompatibleErrors; |
321 | bool GetFixesFromNotes; |
322 | bool EnableNolintBlocks; |
323 | std::vector<ClangTidyError> Errors; |
324 | std::unique_ptr<llvm::Regex> ; |
325 | std::unique_ptr<llvm::Regex> ; |
326 | bool LastErrorRelatesToUserCode = false; |
327 | bool LastErrorPassesLineFilter = false; |
328 | bool LastErrorWasIgnored = false; |
329 | }; |
330 | |
331 | } // end namespace tidy |
332 | } // end namespace clang |
333 | |
334 | #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CLANGTIDYDIAGNOSTICCONSUMER_H |
335 | |