Diagnostic.h revision 15221422eda7bac679e38b07512feda49715ef66
1//===--- Diagnostic.h - C Language Family Diagnostic Handling ---*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_DIAGNOSTIC_H
15#define LLVM_CLANG_DIAGNOSTIC_H
16
17#include "clang/Basic/SourceLocation.h"
18#include <string>
19#include <cassert>
20
21namespace llvm {
22  template <typename T> class SmallVectorImpl;
23}
24
25namespace clang {
26  class DiagnosticClient;
27  class SourceRange;
28  class SourceManager;
29  class DiagnosticBuilder;
30  class IdentifierInfo;
31
32  // Import the diagnostic enums themselves.
33  namespace diag {
34    // Start position for diagnostics.
35    enum {
36      DIAG_START_LEX      =                        300,
37      DIAG_START_PARSE    = DIAG_START_LEX      +  300,
38      DIAG_START_AST      = DIAG_START_PARSE    +  300,
39      DIAG_START_SEMA     = DIAG_START_AST      +  100,
40      DIAG_START_ANALYSIS = DIAG_START_SEMA     + 1000,
41      DIAG_UPPER_LIMIT    = DIAG_START_ANALYSIS +  100
42    };
43
44    class CustomDiagInfo;
45
46    /// diag::kind - All of the diagnostics that can be emitted by the frontend.
47    typedef unsigned kind;
48
49    // Get typedefs for common diagnostics.
50    enum {
51#define DIAG(ENUM,FLAGS,DESC) ENUM,
52#include "clang/Basic/DiagnosticCommonKinds.def"
53      NUM_BUILTIN_COMMON_DIAGNOSTICS
54#undef DIAG
55    };
56
57    /// Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs
58    /// to either MAP_IGNORE (nothing), MAP_WARNING (emit a warning), MAP_ERROR
59    /// (emit as an error), or MAP_DEFAULT (handle the default way).  It allows
60    /// clients to map errors to MAP_ERROR/MAP_DEFAULT or MAP_FATAL (stop
61    /// emitting diagnostics after this one).
62    enum Mapping {
63      MAP_DEFAULT = 0,     //< Do not map this diagnostic.
64      MAP_IGNORE  = 1,     //< Map this diagnostic to nothing, ignore it.
65      MAP_WARNING = 2,     //< Map this diagnostic to a warning.
66      MAP_ERROR   = 3,     //< Map this diagnostic to an error.
67      MAP_FATAL   = 4      //< Map this diagnostic to a fatal error.
68    };
69  }
70
71/// Diagnostic - This concrete class is used by the front-end to report
72/// problems and issues.  It massages the diagnostics (e.g. handling things like
73/// "report warnings as errors" and passes them off to the DiagnosticClient for
74/// reporting to the user.
75class Diagnostic {
76public:
77  /// Level - The level of the diagnostic, after it has been through mapping.
78  enum Level {
79    Ignored, Note, Warning, Error, Fatal
80  };
81
82  enum ArgumentKind {
83    ak_std_string,      // std::string
84    ak_c_string,        // const char *
85    ak_sint,            // int
86    ak_uint,            // unsigned
87    ak_identifierinfo,  // IdentifierInfo
88    ak_qualtype,        // QualType
89    ak_declarationname, // DeclarationName
90    ak_nameddecl        // NamedDecl *
91  };
92
93private:
94  bool IgnoreAllWarnings;     // Ignore all warnings: -w
95  bool WarningsAsErrors;      // Treat warnings like errors:
96  bool WarnOnExtensions;      // Enables warnings for gcc extensions: -pedantic.
97  bool ErrorOnExtensions;     // Error on extensions: -pedantic-errors.
98  bool SuppressSystemWarnings;// Suppress warnings in system headers.
99  DiagnosticClient *Client;
100
101  /// DiagMappings - Mapping information for diagnostics.  Mapping info is
102  /// packed into four bits per diagnostic.
103  unsigned char DiagMappings[diag::DIAG_UPPER_LIMIT/2];
104
105  /// ErrorOccurred / FatalErrorOccurred - This is set to true when an error or
106  /// fatal error is emitted, and is sticky.
107  bool ErrorOccurred;
108  bool FatalErrorOccurred;
109
110  unsigned NumDiagnostics;    // Number of diagnostics reported
111  unsigned NumErrors;         // Number of diagnostics that are errors
112
113  /// CustomDiagInfo - Information for uniquing and looking up custom diags.
114  diag::CustomDiagInfo *CustomDiagInfo;
115
116  /// ArgToStringFn - A function pointer that converts an opaque diagnostic
117  /// argument to a strings.  This takes the modifiers and argument that was
118  /// present in the diagnostic.
119  /// This is a hack to avoid a layering violation between libbasic and libsema.
120  typedef void (*ArgToStringFnTy)(ArgumentKind Kind, intptr_t Val,
121                                  const char *Modifier, unsigned ModifierLen,
122                                  const char *Argument, unsigned ArgumentLen,
123                                  llvm::SmallVectorImpl<char> &Output);
124  ArgToStringFnTy ArgToStringFn;
125public:
126  explicit Diagnostic(DiagnosticClient *client = 0);
127  ~Diagnostic();
128
129  //===--------------------------------------------------------------------===//
130  //  Diagnostic characterization methods, used by a client to customize how
131  //
132
133  DiagnosticClient *getClient() { return Client; };
134  const DiagnosticClient *getClient() const { return Client; };
135
136  void setClient(DiagnosticClient* client) { Client = client; }
137
138  /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
139  /// ignored.  If this and WarningsAsErrors are both set, then this one wins.
140  void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
141  bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
142
143  /// setWarningsAsErrors - When set to true, any warnings reported are issued
144  /// as errors.
145  void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
146  bool getWarningsAsErrors() const { return WarningsAsErrors; }
147
148  /// setWarnOnExtensions - When set to true, issue warnings on GCC extensions,
149  /// the equivalent of GCC's -pedantic.
150  void setWarnOnExtensions(bool Val) { WarnOnExtensions = Val; }
151  bool getWarnOnExtensions() const { return WarnOnExtensions; }
152
153  /// setErrorOnExtensions - When set to true issue errors for GCC extensions
154  /// instead of warnings.  This is the equivalent to GCC's -pedantic-errors.
155  void setErrorOnExtensions(bool Val) { ErrorOnExtensions = Val; }
156  bool getErrorOnExtensions() const { return ErrorOnExtensions; }
157
158  /// setSuppressSystemWarnings - When set to true mask warnings that
159  /// come from system headers.
160  void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
161  bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
162
163  /// setDiagnosticMapping - This allows the client to specify that certain
164  /// warnings are ignored.  Only NOTEs, WARNINGs, and EXTENSIONs can be mapped.
165  void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map) {
166    assert(Diag < diag::DIAG_UPPER_LIMIT &&
167           "Can only map builtin diagnostics");
168    assert((isBuiltinNoteWarningOrExtension(Diag) || Map == diag::MAP_FATAL) &&
169           "Cannot map errors!");
170    unsigned char &Slot = DiagMappings[Diag/2];
171    unsigned Bits = (Diag & 1)*4;
172    Slot &= ~(7 << Bits);
173    Slot |= Map << Bits;
174  }
175
176  /// getDiagnosticMapping - Return the mapping currently set for the specified
177  /// diagnostic.
178  diag::Mapping getDiagnosticMapping(diag::kind Diag) const {
179    return (diag::Mapping)((DiagMappings[Diag/2] >> (Diag & 1)*4) & 7);
180  }
181
182  bool hasErrorOccurred() const { return ErrorOccurred; }
183  bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
184
185  unsigned getNumErrors() const { return NumErrors; }
186  unsigned getNumDiagnostics() const { return NumDiagnostics; }
187
188  /// getCustomDiagID - Return an ID for a diagnostic with the specified message
189  /// and level.  If this is the first request for this diagnosic, it is
190  /// registered and created, otherwise the existing ID is returned.
191  unsigned getCustomDiagID(Level L, const char *Message);
192
193
194  /// ConvertArgToString - This method converts a diagnostic argument (as an
195  /// intptr_t) into the string that represents it.
196  void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
197                          const char *Modifier, unsigned ModLen,
198                          const char *Argument, unsigned ArgLen,
199                          llvm::SmallVectorImpl<char> &Output) const {
200    ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen, Output);
201  }
202
203  void SetArgToStringFn(ArgToStringFnTy Fn) {
204    ArgToStringFn = Fn;
205  }
206
207  //===--------------------------------------------------------------------===//
208  // Diagnostic classification and reporting interfaces.
209  //
210
211  /// getDescription - Given a diagnostic ID, return a description of the
212  /// issue.
213  const char *getDescription(unsigned DiagID) const;
214
215  /// isBuiltinNoteWarningOrExtension - Return true if the unmapped diagnostic
216  /// level of the specified diagnostic ID is a Note, Warning, or Extension.
217  /// Note that this only works on builtin diagnostics, not custom ones.
218  static bool isBuiltinNoteWarningOrExtension(unsigned DiagID);
219
220  /// getDiagnosticLevel - Based on the way the client configured the Diagnostic
221  /// object, classify the specified diagnostic ID into a Level, consumable by
222  /// the DiagnosticClient.
223  Level getDiagnosticLevel(unsigned DiagID) const;
224
225
226  /// Report - Issue the message to the client.  @c DiagID is a member of the
227  /// @c diag::kind enum.  This actually returns aninstance of DiagnosticBuilder
228  /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed.
229  /// @c Pos represents the source location associated with the diagnostic,
230  /// which can be an invalid location if no position information is available.
231  inline DiagnosticBuilder Report(FullSourceLoc Pos, unsigned DiagID);
232
233private:
234  // This is private state used by DiagnosticBuilder.  We put it here instead of
235  // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
236  // object.  This implementation choice means that we can only have one
237  // diagnostic "in flight" at a time, but this seems to be a reasonable
238  // tradeoff to keep these objects small.  Assertions verify that only one
239  // diagnostic is in flight at a time.
240  friend class DiagnosticBuilder;
241  friend class DiagnosticInfo;
242
243  /// CurDiagLoc - This is the location of the current diagnostic that is in
244  /// flight.
245  FullSourceLoc CurDiagLoc;
246
247  /// CurDiagID - This is the ID of the current diagnostic that is in flight.
248  /// This is set to ~0U when there is no diagnostic in flight.
249  unsigned CurDiagID;
250
251  enum {
252    /// MaxArguments - The maximum number of arguments we can hold. We currently
253    /// only support up to 10 arguments (%0-%9).  A single diagnostic with more
254    /// than that almost certainly has to be simplified anyway.
255    MaxArguments = 10
256  };
257
258  /// NumDiagArgs - This contains the number of entries in Arguments.
259  signed char NumDiagArgs;
260  /// NumRanges - This is the number of ranges in the DiagRanges array.
261  unsigned char NumDiagRanges;
262
263  /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
264  /// values, with one for each argument.  This specifies whether the argument
265  /// is in DiagArgumentsStr or in DiagArguments.
266  unsigned char DiagArgumentsKind[MaxArguments];
267
268  /// DiagArgumentsStr - This holds the values of each string argument for the
269  /// current diagnostic.  This value is only used when the corresponding
270  /// ArgumentKind is ak_std_string.
271  std::string DiagArgumentsStr[MaxArguments];
272
273  /// DiagArgumentsVal - The values for the various substitution positions. This
274  /// is used when the argument is not an std::string.  The specific value is
275  /// mangled into an intptr_t and the intepretation depends on exactly what
276  /// sort of argument kind it is.
277  intptr_t DiagArgumentsVal[MaxArguments];
278
279  /// DiagRanges - The list of ranges added to this diagnostic.  It currently
280  /// only support 10 ranges, could easily be extended if needed.
281  const SourceRange *DiagRanges[10];
282
283  /// ProcessDiag - This is the method used to report a diagnostic that is
284  /// finally fully formed.
285  void ProcessDiag();
286};
287
288//===----------------------------------------------------------------------===//
289// DiagnosticBuilder
290//===----------------------------------------------------------------------===//
291
292/// DiagnosticBuilder - This is a little helper class used to produce
293/// diagnostics.  This is constructed by the Diagnostic::Report method, and
294/// allows insertion of extra information (arguments and source ranges) into the
295/// currently "in flight" diagnostic.  When the temporary for the builder is
296/// destroyed, the diagnostic is issued.
297///
298/// Note that many of these will be created as temporary objects (many call
299/// sites), so we want them to be small and we never want their address taken.
300/// This ensures that compilers with somewhat reasonable optimizers will promote
301/// the common fields to registers, eliminating increments of the NumArgs field,
302/// for example.
303class DiagnosticBuilder {
304  mutable Diagnostic *DiagObj;
305  mutable unsigned NumArgs, NumRanges;
306
307  void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
308  friend class Diagnostic;
309  explicit DiagnosticBuilder(Diagnostic *diagObj)
310    : DiagObj(diagObj), NumArgs(0), NumRanges(0) {}
311public:
312
313  /// Copy constructor.  When copied, this "takes" the diagnostic info from the
314  /// input and neuters it.
315  DiagnosticBuilder(const DiagnosticBuilder &D) {
316    DiagObj = D.DiagObj;
317    D.DiagObj = 0;
318  }
319
320  /// Destructor - The dtor emits the diagnostic.
321  ~DiagnosticBuilder() {
322    // If DiagObj is null, then its soul was stolen by the copy ctor.
323    if (DiagObj == 0) return;
324
325    // When destroyed, the ~DiagnosticBuilder sets the final argument count into
326    // the Diagnostic object.
327    DiagObj->NumDiagArgs = NumArgs;
328    DiagObj->NumDiagRanges = NumRanges;
329
330    // Process the diagnostic, sending the accumulated information to the
331    // DiagnosticClient.
332    DiagObj->ProcessDiag();
333
334    // This diagnostic is no longer in flight.
335    DiagObj->CurDiagID = ~0U;
336  }
337
338  /// Operator bool: conversion of DiagnosticBuilder to bool always returns
339  /// true.  This allows is to be used in boolean error contexts like:
340  /// return Diag(...);
341  operator bool() const { return true; }
342
343  void AddString(const std::string &S) const {
344    assert(NumArgs < Diagnostic::MaxArguments &&
345           "Too many arguments to diagnostic!");
346    DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
347    DiagObj->DiagArgumentsStr[NumArgs++] = S;
348  }
349
350  void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
351    assert(NumArgs < Diagnostic::MaxArguments &&
352           "Too many arguments to diagnostic!");
353    DiagObj->DiagArgumentsKind[NumArgs] = Kind;
354    DiagObj->DiagArgumentsVal[NumArgs++] = V;
355  }
356
357  void AddSourceRange(const SourceRange &R) const {
358    assert(NumRanges <
359           sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
360           "Too many arguments to diagnostic!");
361    DiagObj->DiagRanges[NumRanges++] = &R;
362  }
363};
364
365inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
366                                           const std::string &S) {
367  DB.AddString(S);
368  return DB;
369}
370
371inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
372                                           const char *Str) {
373  DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
374                  Diagnostic::ak_c_string);
375  return DB;
376}
377
378inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
379  DB.AddTaggedVal(I, Diagnostic::ak_sint);
380  return DB;
381}
382
383inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
384  DB.AddTaggedVal(I, Diagnostic::ak_sint);
385  return DB;
386}
387
388inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
389                                           unsigned I) {
390  DB.AddTaggedVal(I, Diagnostic::ak_uint);
391  return DB;
392}
393
394inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
395                                           const IdentifierInfo *II) {
396  DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
397                  Diagnostic::ak_identifierinfo);
398  return DB;
399}
400
401inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
402                                           const SourceRange &R) {
403  DB.AddSourceRange(R);
404  return DB;
405}
406
407
408/// Report - Issue the message to the client.  DiagID is a member of the
409/// diag::kind enum.  This actually returns a new instance of DiagnosticBuilder
410/// which emits the diagnostics (through ProcessDiag) when it is destroyed.
411inline DiagnosticBuilder Diagnostic::Report(FullSourceLoc Loc, unsigned DiagID){
412  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
413  CurDiagLoc = Loc;
414  CurDiagID = DiagID;
415  return DiagnosticBuilder(this);
416}
417
418//===----------------------------------------------------------------------===//
419// DiagnosticInfo
420//===----------------------------------------------------------------------===//
421
422/// DiagnosticInfo - This is a little helper class (which is basically a smart
423/// pointer that forward info from Diagnostic) that allows clients ot enquire
424/// about the currently in-flight diagnostic.
425class DiagnosticInfo {
426  const Diagnostic *DiagObj;
427public:
428  explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
429
430  const Diagnostic *getDiags() const { return DiagObj; }
431  unsigned getID() const { return DiagObj->CurDiagID; }
432  const FullSourceLoc &getLocation() const { return DiagObj->CurDiagLoc; }
433
434  unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
435
436  /// getArgKind - Return the kind of the specified index.  Based on the kind
437  /// of argument, the accessors below can be used to get the value.
438  Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
439    assert(Idx < getNumArgs() && "Argument index out of range!");
440    return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
441  }
442
443  /// getArgStdStr - Return the provided argument string specified by Idx.
444  const std::string &getArgStdStr(unsigned Idx) const {
445    assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
446           "invalid argument accessor!");
447    return DiagObj->DiagArgumentsStr[Idx];
448  }
449
450  /// getArgCStr - Return the specified C string argument.
451  const char *getArgCStr(unsigned Idx) const {
452    assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
453           "invalid argument accessor!");
454    return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
455  }
456
457  /// getArgSInt - Return the specified signed integer argument.
458  int getArgSInt(unsigned Idx) const {
459    assert(getArgKind(Idx) == Diagnostic::ak_sint &&
460           "invalid argument accessor!");
461    return (int)DiagObj->DiagArgumentsVal[Idx];
462  }
463
464  /// getArgUInt - Return the specified unsigned integer argument.
465  unsigned getArgUInt(unsigned Idx) const {
466    assert(getArgKind(Idx) == Diagnostic::ak_uint &&
467           "invalid argument accessor!");
468    return (unsigned)DiagObj->DiagArgumentsVal[Idx];
469  }
470
471  /// getArgIdentifier - Return the specified IdentifierInfo argument.
472  const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
473    assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
474           "invalid argument accessor!");
475    return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
476  }
477
478  /// getRawArg - Return the specified non-string argument in an opaque form.
479  intptr_t getRawArg(unsigned Idx) const {
480    assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
481           "invalid argument accessor!");
482    return DiagObj->DiagArgumentsVal[Idx];
483  }
484
485
486  /// getNumRanges - Return the number of source ranges associated with this
487  /// diagnostic.
488  unsigned getNumRanges() const {
489    return DiagObj->NumDiagRanges;
490  }
491
492  const SourceRange &getRange(unsigned Idx) const {
493    assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
494    return *DiagObj->DiagRanges[Idx];
495  }
496
497
498  /// FormatDiagnostic - Format this diagnostic into a string, substituting the
499  /// formal arguments into the %0 slots.  The result is appended onto the Str
500  /// array.
501  void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
502};
503
504
505/// DiagnosticClient - This is an abstract interface implemented by clients of
506/// the front-end, which formats and prints fully processed diagnostics.
507class DiagnosticClient {
508public:
509  virtual ~DiagnosticClient();
510
511  /// IncludeInDiagnosticCounts - This method (whose default implementation
512  ///  returns true) indicates whether the diagnostics handled by this
513  ///  DiagnosticClient should be included in the number of diagnostics
514  ///  reported by Diagnostic.
515  virtual bool IncludeInDiagnosticCounts() const;
516
517  /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
518  /// capturing it to a log as needed.
519  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
520                                const DiagnosticInfo &Info) = 0;
521};
522
523}  // end namespace clang
524
525#endif
526