1 //===--- DiagnosticIDs.h - Diagnostic IDs Handling --------------*- 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 /// \file
10 /// Defines the Diagnostic IDs-related interfaces.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_BASIC_DIAGNOSTICIDS_H
15 #define LLVM_CLANG_BASIC_DIAGNOSTICIDS_H
16 
17 #include "clang/Basic/LLVM.h"
18 #include "llvm/ADT/IntrusiveRefCntPtr.h"
19 #include "llvm/ADT/StringRef.h"
20 #include <optional>
21 #include <vector>
22 
23 namespace clang {
24   class DiagnosticsEngine;
25   class SourceLocation;
26 
27   // Import the diagnostic enums themselves.
28   namespace diag {
29     enum class Group;
30 
31     // Size of each of the diagnostic categories.
32     enum {
33       DIAG_SIZE_COMMON        =  300,
34       DIAG_SIZE_DRIVER        =  300,
35       DIAG_SIZE_FRONTEND      =  150,
36       DIAG_SIZE_SERIALIZATION =  120,
37       DIAG_SIZE_LEX           =  400,
38       DIAG_SIZE_PARSE         =  700,
39       DIAG_SIZE_AST           =  300,
40       DIAG_SIZE_COMMENT       =  100,
41       DIAG_SIZE_CROSSTU       =  100,
42       DIAG_SIZE_SEMA          = 4500,
43       DIAG_SIZE_ANALYSIS      =  100,
44       DIAG_SIZE_REFACTORING   = 1000,
45     };
46     // Start position for diagnostics.
47     enum {
48       DIAG_START_COMMON        =                          0,
49       DIAG_START_DRIVER        = DIAG_START_COMMON        + static_cast<int>(DIAG_SIZE_COMMON),
50       DIAG_START_FRONTEND      = DIAG_START_DRIVER        + static_cast<int>(DIAG_SIZE_DRIVER),
51       DIAG_START_SERIALIZATION = DIAG_START_FRONTEND      + static_cast<int>(DIAG_SIZE_FRONTEND),
52       DIAG_START_LEX           = DIAG_START_SERIALIZATION + static_cast<int>(DIAG_SIZE_SERIALIZATION),
53       DIAG_START_PARSE         = DIAG_START_LEX           + static_cast<int>(DIAG_SIZE_LEX),
54       DIAG_START_AST           = DIAG_START_PARSE         + static_cast<int>(DIAG_SIZE_PARSE),
55       DIAG_START_COMMENT       = DIAG_START_AST           + static_cast<int>(DIAG_SIZE_AST),
56       DIAG_START_CROSSTU       = DIAG_START_COMMENT       + static_cast<int>(DIAG_SIZE_COMMENT),
57       DIAG_START_SEMA          = DIAG_START_CROSSTU       + static_cast<int>(DIAG_SIZE_CROSSTU),
58       DIAG_START_ANALYSIS      = DIAG_START_SEMA          + static_cast<int>(DIAG_SIZE_SEMA),
59       DIAG_START_REFACTORING   = DIAG_START_ANALYSIS      + static_cast<int>(DIAG_SIZE_ANALYSIS),
60       DIAG_UPPER_LIMIT         = DIAG_START_REFACTORING   + static_cast<int>(DIAG_SIZE_REFACTORING)
61     };
62 
63     class CustomDiagInfo;
64 
65     /// All of the diagnostics that can be emitted by the frontend.
66     typedef unsigned kind;
67 
68     // Get typedefs for common diagnostics.
69     enum {
70 #define DIAG(ENUM, FLAGS, DEFAULT_MAPPING, DESC, GROUP, SFINAE, CATEGORY,      \
71              NOWERROR, SHOWINSYSHEADER, SHOWINSYSMACRO, DEFFERABLE)            \
72   ENUM,
73 #define COMMONSTART
74 #include "clang/Basic/DiagnosticCommonKinds.inc"
75       NUM_BUILTIN_COMMON_DIAGNOSTICS
76 #undef DIAG
77     };
78 
79     /// Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs
80     /// to either Ignore (nothing), Remark (emit a remark), Warning
81     /// (emit a warning) or Error (emit as an error).  It allows clients to
82     /// map ERRORs to Error or Fatal (stop emitting diagnostics after this one).
83     enum class Severity {
84       // NOTE: 0 means "uncomputed".
85       Ignored = 1, ///< Do not present this diagnostic, ignore it.
86       Remark = 2,  ///< Present this diagnostic as a remark.
87       Warning = 3, ///< Present this diagnostic as a warning.
88       Error = 4,   ///< Present this diagnostic as an error.
89       Fatal = 5    ///< Present this diagnostic as a fatal error.
90     };
91 
92     /// Flavors of diagnostics we can emit. Used to filter for a particular
93     /// kind of diagnostic (for instance, for -W/-R flags).
94     enum class Flavor {
95       WarningOrError, ///< A diagnostic that indicates a problem or potential
96                       ///< problem. Can be made fatal by -Werror.
97       Remark          ///< A diagnostic that indicates normal progress through
98                       ///< compilation.
99     };
100   }
101 
102 class DiagnosticMapping {
103   unsigned Severity : 3;
104   unsigned IsUser : 1;
105   unsigned IsPragma : 1;
106   unsigned HasNoWarningAsError : 1;
107   unsigned HasNoErrorAsFatal : 1;
108   unsigned WasUpgradedFromWarning : 1;
109 
110 public:
111   static DiagnosticMapping Make(diag::Severity Severity, bool IsUser,
112                                 bool IsPragma) {
113     DiagnosticMapping Result;
114     Result.Severity = (unsigned)Severity;
115     Result.IsUser = IsUser;
116     Result.IsPragma = IsPragma;
117     Result.HasNoWarningAsError = 0;
118     Result.HasNoErrorAsFatal = 0;
119     Result.WasUpgradedFromWarning = 0;
120     return Result;
121   }
122 
123   diag::Severity getSeverity() const { return (diag::Severity)Severity; }
124   void setSeverity(diag::Severity Value) { Severity = (unsigned)Value; }
125 
126   bool isUser() const { return IsUser; }
127   bool isPragma() const { return IsPragma; }
128 
129   bool isErrorOrFatal() const {
130     return getSeverity() == diag::Severity::Error ||
131            getSeverity() == diag::Severity::Fatal;
132   }
133 
134   bool hasNoWarningAsError() const { return HasNoWarningAsError; }
135   void setNoWarningAsError(bool Value) { HasNoWarningAsError = Value; }
136 
137   bool hasNoErrorAsFatal() const { return HasNoErrorAsFatal; }
138   void setNoErrorAsFatal(bool Value) { HasNoErrorAsFatal = Value; }
139 
140   /// Whether this mapping attempted to map the diagnostic to a warning, but
141   /// was overruled because the diagnostic was already mapped to an error or
142   /// fatal error.
143   bool wasUpgradedFromWarning() const { return WasUpgradedFromWarning; }
144   void setUpgradedFromWarning(bool Value) { WasUpgradedFromWarning = Value; }
145 
146   /// Serialize this mapping as a raw integer.
147   unsigned serialize() const {
148     return (IsUser << 7) | (IsPragma << 6) | (HasNoWarningAsError << 5) |
149            (HasNoErrorAsFatal << 4) | (WasUpgradedFromWarning << 3) | Severity;
150   }
151   /// Deserialize a mapping.
152   static DiagnosticMapping deserialize(unsigned Bits) {
153     DiagnosticMapping Result;
154     Result.IsUser = (Bits >> 7) & 1;
155     Result.IsPragma = (Bits >> 6) & 1;
156     Result.HasNoWarningAsError = (Bits >> 5) & 1;
157     Result.HasNoErrorAsFatal = (Bits >> 4) & 1;
158     Result.WasUpgradedFromWarning = (Bits >> 3) & 1;
159     Result.Severity = Bits & 0x7;
160     return Result;
161   }
162 
163   bool operator==(DiagnosticMapping Other) const {
164     return serialize() == Other.serialize();
165   }
166 };
167 
168 /// Used for handling and querying diagnostic IDs.
169 ///
170 /// Can be used and shared by multiple Diagnostics for multiple translation units.
171 class DiagnosticIDs : public RefCountedBase<DiagnosticIDs> {
172 public:
173   /// The level of the diagnostic, after it has been through mapping.
174   enum Level {
175     Ignored, Note, Remark, Warning, Error, Fatal
176   };
177 
178 private:
179   /// Information for uniquing and looking up custom diags.
180   std::unique_ptr<diag::CustomDiagInfo> CustomDiagInfo;
181 
182 public:
183   DiagnosticIDs();
184   ~DiagnosticIDs();
185 
186   /// Return an ID for a diagnostic with the specified format string and
187   /// level.
188   ///
189   /// If this is the first request for this diagnostic, it is registered and
190   /// created, otherwise the existing ID is returned.
191 
192   // FIXME: Replace this function with a create-only facilty like
193   // createCustomDiagIDFromFormatString() to enforce safe usage. At the time of
194   // writing, nearly all callers of this function were invalid.
195   unsigned getCustomDiagID(Level L, StringRef FormatString);
196 
197   //===--------------------------------------------------------------------===//
198   // Diagnostic classification and reporting interfaces.
199   //
200 
201   /// Given a diagnostic ID, return a description of the issue.
202   StringRef getDescription(unsigned DiagID) const;
203 
204   /// Return true if the unmapped diagnostic levelof the specified
205   /// diagnostic ID is a Warning or Extension.
206   ///
207   /// This only works on builtin diagnostics, not custom ones, and is not
208   /// legal to call on NOTEs.
209   static bool isBuiltinWarningOrExtension(unsigned DiagID);
210 
211   /// Return true if the specified diagnostic is mapped to errors by
212   /// default.
213   static bool isDefaultMappingAsError(unsigned DiagID);
214 
215   /// Get the default mapping for this diagnostic.
216   static DiagnosticMapping getDefaultMapping(unsigned DiagID);
217 
218   /// Determine whether the given built-in diagnostic ID is a Note.
219   static bool isBuiltinNote(unsigned DiagID);
220 
221   /// Determine whether the given built-in diagnostic ID is for an
222   /// extension of some sort.
223   static bool isBuiltinExtensionDiag(unsigned DiagID) {
224     bool ignored;
225     return isBuiltinExtensionDiag(DiagID, ignored);
226   }
227 
228   /// Determine whether the given built-in diagnostic ID is for an
229   /// extension of some sort, and whether it is enabled by default.
230   ///
231   /// This also returns EnabledByDefault, which is set to indicate whether the
232   /// diagnostic is ignored by default (in which case -pedantic enables it) or
233   /// treated as a warning/error by default.
234   ///
235   static bool isBuiltinExtensionDiag(unsigned DiagID, bool &EnabledByDefault);
236 
237   /// Given a group ID, returns the flag that toggles the group.
238   /// For example, for Group::DeprecatedDeclarations, returns
239   /// "deprecated-declarations".
240   static StringRef getWarningOptionForGroup(diag::Group);
241 
242   /// Given a diagnostic group ID, return its documentation.
243   static StringRef getWarningOptionDocumentation(diag::Group GroupID);
244 
245   /// Given a group ID, returns the flag that toggles the group.
246   /// For example, for "deprecated-declarations", returns
247   /// Group::DeprecatedDeclarations.
248   static std::optional<diag::Group> getGroupForWarningOption(StringRef);
249 
250   /// Return the lowest-level group that contains the specified diagnostic.
251   static std::optional<diag::Group> getGroupForDiag(unsigned DiagID);
252 
253   /// Return the lowest-level warning option that enables the specified
254   /// diagnostic.
255   ///
256   /// If there is no -Wfoo flag that controls the diagnostic, this returns null.
257   static StringRef getWarningOptionForDiag(unsigned DiagID);
258 
259   /// Return the category number that a specified \p DiagID belongs to,
260   /// or 0 if no category.
261   static unsigned getCategoryNumberForDiag(unsigned DiagID);
262 
263   /// Return the number of diagnostic categories.
264   static unsigned getNumberOfCategories();
265 
266   /// Given a category ID, return the name of the category.
267   static StringRef getCategoryNameFromID(unsigned CategoryID);
268 
269   /// Return true if a given diagnostic falls into an ARC diagnostic
270   /// category.
271   static bool isARCDiagnostic(unsigned DiagID);
272 
273   /// Enumeration describing how the emission of a diagnostic should
274   /// be treated when it occurs during C++ template argument deduction.
275   enum SFINAEResponse {
276     /// The diagnostic should not be reported, but it should cause
277     /// template argument deduction to fail.
278     ///
279     /// The vast majority of errors that occur during template argument
280     /// deduction fall into this category.
281     SFINAE_SubstitutionFailure,
282 
283     /// The diagnostic should be suppressed entirely.
284     ///
285     /// Warnings generally fall into this category.
286     SFINAE_Suppress,
287 
288     /// The diagnostic should be reported.
289     ///
290     /// The diagnostic should be reported. Various fatal errors (e.g.,
291     /// template instantiation depth exceeded) fall into this category.
292     SFINAE_Report,
293 
294     /// The diagnostic is an access-control diagnostic, which will be
295     /// substitution failures in some contexts and reported in others.
296     SFINAE_AccessControl
297   };
298 
299   /// Determines whether the given built-in diagnostic ID is
300   /// for an error that is suppressed if it occurs during C++ template
301   /// argument deduction.
302   ///
303   /// When an error is suppressed due to SFINAE, the template argument
304   /// deduction fails but no diagnostic is emitted. Certain classes of
305   /// errors, such as those errors that involve C++ access control,
306   /// are not SFINAE errors.
307   static SFINAEResponse getDiagnosticSFINAEResponse(unsigned DiagID);
308 
309   /// Whether the diagnostic message can be deferred.
310   ///
311   /// For single source offloading languages, a diagnostic message occurred
312   /// in a device host function may be deferred until the function is sure
313   /// to be emitted.
314   static bool isDeferrable(unsigned DiagID);
315 
316   /// Get the string of all diagnostic flags.
317   ///
318   /// \returns A list of all diagnostics flags as they would be written in a
319   /// command line invocation including their `no-` variants. For example:
320   /// `{"-Wempty-body", "-Wno-empty-body", ...}`
321   static std::vector<std::string> getDiagnosticFlags();
322 
323   /// Get the set of all diagnostic IDs in the group with the given name.
324   ///
325   /// \param[out] Diags - On return, the diagnostics in the group.
326   /// \returns \c true if the given group is unknown, \c false otherwise.
327   bool getDiagnosticsInGroup(diag::Flavor Flavor, StringRef Group,
328                              SmallVectorImpl<diag::kind> &Diags) const;
329 
330   /// Get the set of all diagnostic IDs.
331   static void getAllDiagnostics(diag::Flavor Flavor,
332                                 std::vector<diag::kind> &Diags);
333 
334   /// Get the diagnostic option with the closest edit distance to the
335   /// given group name.
336   static StringRef getNearestOption(diag::Flavor Flavor, StringRef Group);
337 
338 private:
339   /// Classify the specified diagnostic ID into a Level, consumable by
340   /// the DiagnosticClient.
341   ///
342   /// The classification is based on the way the client configured the
343   /// DiagnosticsEngine object.
344   ///
345   /// \param Loc The source location for which we are interested in finding out
346   /// the diagnostic state. Can be null in order to query the latest state.
347   DiagnosticIDs::Level
348   getDiagnosticLevel(unsigned DiagID, SourceLocation Loc,
349                      const DiagnosticsEngine &Diag) const LLVM_READONLY;
350 
351   diag::Severity
352   getDiagnosticSeverity(unsigned DiagID, SourceLocation Loc,
353                         const DiagnosticsEngine &Diag) const LLVM_READONLY;
354 
355   /// Used to report a diagnostic that is finally fully formed.
356   ///
357   /// \returns \c true if the diagnostic was emitted, \c false if it was
358   /// suppressed.
359   bool ProcessDiag(DiagnosticsEngine &Diag) const;
360 
361   /// Used to emit a diagnostic that is finally fully formed,
362   /// ignoring suppression.
363   void EmitDiag(DiagnosticsEngine &Diag, Level DiagLevel) const;
364 
365   /// Whether the diagnostic may leave the AST in a state where some
366   /// invariants can break.
367   bool isUnrecoverable(unsigned DiagID) const;
368 
369   friend class DiagnosticsEngine;
370 };
371 
372 }  // end namespace clang
373 
374 #endif
375