Diagnostic.h revision 92dd386e3f05d176b45a638199d51f536bd9d1c4
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  /// LastDiagLevel - This is the level of the last diagnostic emitted.  This is
111  /// used to emit continuation diagnostics with the same level as the
112  /// diagnostic that they follow.
113  Diagnostic::Level LastDiagLevel;
114
115  unsigned NumDiagnostics;    // Number of diagnostics reported
116  unsigned NumErrors;         // Number of diagnostics that are errors
117
118  /// CustomDiagInfo - Information for uniquing and looking up custom diags.
119  diag::CustomDiagInfo *CustomDiagInfo;
120
121  /// ArgToStringFn - A function pointer that converts an opaque diagnostic
122  /// argument to a strings.  This takes the modifiers and argument that was
123  /// present in the diagnostic.
124  /// This is a hack to avoid a layering violation between libbasic and libsema.
125  typedef void (*ArgToStringFnTy)(ArgumentKind Kind, intptr_t Val,
126                                  const char *Modifier, unsigned ModifierLen,
127                                  const char *Argument, unsigned ArgumentLen,
128                                  llvm::SmallVectorImpl<char> &Output,
129                                  void *Cookie);
130  void *ArgToStringCookie;
131  ArgToStringFnTy ArgToStringFn;
132public:
133  explicit Diagnostic(DiagnosticClient *client = 0);
134  ~Diagnostic();
135
136  //===--------------------------------------------------------------------===//
137  //  Diagnostic characterization methods, used by a client to customize how
138  //
139
140  DiagnosticClient *getClient() { return Client; };
141  const DiagnosticClient *getClient() const { return Client; };
142
143  void setClient(DiagnosticClient* client) { Client = client; }
144
145  /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
146  /// ignored.  If this and WarningsAsErrors are both set, then this one wins.
147  void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
148  bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
149
150  /// setWarningsAsErrors - When set to true, any warnings reported are issued
151  /// as errors.
152  void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
153  bool getWarningsAsErrors() const { return WarningsAsErrors; }
154
155  /// setWarnOnExtensions - When set to true, issue warnings on GCC extensions,
156  /// the equivalent of GCC's -pedantic.
157  void setWarnOnExtensions(bool Val) { WarnOnExtensions = Val; }
158  bool getWarnOnExtensions() const { return WarnOnExtensions; }
159
160  /// setErrorOnExtensions - When set to true issue errors for GCC extensions
161  /// instead of warnings.  This is the equivalent to GCC's -pedantic-errors.
162  void setErrorOnExtensions(bool Val) { ErrorOnExtensions = Val; }
163  bool getErrorOnExtensions() const { return ErrorOnExtensions; }
164
165  /// setSuppressSystemWarnings - When set to true mask warnings that
166  /// come from system headers.
167  void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
168  bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
169
170  /// setDiagnosticMapping - This allows the client to specify that certain
171  /// warnings are ignored.  Only WARNINGs and EXTENSIONs can be mapped.
172  void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map) {
173    assert(Diag < diag::DIAG_UPPER_LIMIT &&
174           "Can only map builtin diagnostics");
175    assert((isBuiltinWarningOrExtension(Diag) || Map == diag::MAP_FATAL) &&
176           "Cannot map errors!");
177    unsigned char &Slot = DiagMappings[Diag/2];
178    unsigned Bits = (Diag & 1)*4;
179    Slot &= ~(7 << Bits);
180    Slot |= Map << Bits;
181  }
182
183  /// getDiagnosticMapping - Return the mapping currently set for the specified
184  /// diagnostic.
185  diag::Mapping getDiagnosticMapping(diag::kind Diag) const {
186    return (diag::Mapping)((DiagMappings[Diag/2] >> (Diag & 1)*4) & 7);
187  }
188
189  bool hasErrorOccurred() const { return ErrorOccurred; }
190  bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
191
192  unsigned getNumErrors() const { return NumErrors; }
193  unsigned getNumDiagnostics() const { return NumDiagnostics; }
194
195  /// getCustomDiagID - Return an ID for a diagnostic with the specified message
196  /// and level.  If this is the first request for this diagnosic, it is
197  /// registered and created, otherwise the existing ID is returned.
198  unsigned getCustomDiagID(Level L, const char *Message);
199
200
201  /// ConvertArgToString - This method converts a diagnostic argument (as an
202  /// intptr_t) into the string that represents it.
203  void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
204                          const char *Modifier, unsigned ModLen,
205                          const char *Argument, unsigned ArgLen,
206                          llvm::SmallVectorImpl<char> &Output) const {
207    ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen, Output,
208                  ArgToStringCookie);
209  }
210
211  void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
212    ArgToStringFn = Fn;
213    ArgToStringCookie = Cookie;
214  }
215
216  //===--------------------------------------------------------------------===//
217  // Diagnostic classification and reporting interfaces.
218  //
219
220  /// getDescription - Given a diagnostic ID, return a description of the
221  /// issue.
222  const char *getDescription(unsigned DiagID) const;
223
224  /// isNoteWarningOrExtension - Return true if the unmapped diagnostic
225  /// level of the specified diagnostic ID is a Warning or Extension.
226  /// This only works on builtin diagnostics, not custom ones, and is not legal to
227  /// call on NOTEs.
228  static bool isBuiltinWarningOrExtension(unsigned DiagID);
229
230  /// getDiagnosticLevel - Based on the way the client configured the Diagnostic
231  /// object, classify the specified diagnostic ID into a Level, consumable by
232  /// the DiagnosticClient.
233  Level getDiagnosticLevel(unsigned DiagID) const;
234
235  /// Report - Issue the message to the client.  @c DiagID is a member of the
236  /// @c diag::kind enum.  This actually returns aninstance of DiagnosticBuilder
237  /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed.
238  /// @c Pos represents the source location associated with the diagnostic,
239  /// which can be an invalid location if no position information is available.
240  inline DiagnosticBuilder Report(FullSourceLoc Pos, unsigned DiagID);
241
242private:
243  /// getDiagnosticLevel - This is an internal implementation helper used when
244  /// DiagClass is already known.
245  Level getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const;
246
247  // This is private state used by DiagnosticBuilder.  We put it here instead of
248  // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
249  // object.  This implementation choice means that we can only have one
250  // diagnostic "in flight" at a time, but this seems to be a reasonable
251  // tradeoff to keep these objects small.  Assertions verify that only one
252  // diagnostic is in flight at a time.
253  friend class DiagnosticBuilder;
254  friend class DiagnosticInfo;
255
256  /// CurDiagLoc - This is the location of the current diagnostic that is in
257  /// flight.
258  FullSourceLoc CurDiagLoc;
259
260  /// CurDiagID - This is the ID of the current diagnostic that is in flight.
261  /// This is set to ~0U when there is no diagnostic in flight.
262  unsigned CurDiagID;
263
264  enum {
265    /// MaxArguments - The maximum number of arguments we can hold. We currently
266    /// only support up to 10 arguments (%0-%9).  A single diagnostic with more
267    /// than that almost certainly has to be simplified anyway.
268    MaxArguments = 10
269  };
270
271  /// NumDiagArgs - This contains the number of entries in Arguments.
272  signed char NumDiagArgs;
273  /// NumRanges - This is the number of ranges in the DiagRanges array.
274  unsigned char NumDiagRanges;
275
276  /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
277  /// values, with one for each argument.  This specifies whether the argument
278  /// is in DiagArgumentsStr or in DiagArguments.
279  unsigned char DiagArgumentsKind[MaxArguments];
280
281  /// DiagArgumentsStr - This holds the values of each string argument for the
282  /// current diagnostic.  This value is only used when the corresponding
283  /// ArgumentKind is ak_std_string.
284  std::string DiagArgumentsStr[MaxArguments];
285
286  /// DiagArgumentsVal - The values for the various substitution positions. This
287  /// is used when the argument is not an std::string.  The specific value is
288  /// mangled into an intptr_t and the intepretation depends on exactly what
289  /// sort of argument kind it is.
290  intptr_t DiagArgumentsVal[MaxArguments];
291
292  /// DiagRanges - The list of ranges added to this diagnostic.  It currently
293  /// only support 10 ranges, could easily be extended if needed.
294  const SourceRange *DiagRanges[10];
295
296  /// ProcessDiag - This is the method used to report a diagnostic that is
297  /// finally fully formed.
298  void ProcessDiag();
299};
300
301//===----------------------------------------------------------------------===//
302// DiagnosticBuilder
303//===----------------------------------------------------------------------===//
304
305/// DiagnosticBuilder - This is a little helper class used to produce
306/// diagnostics.  This is constructed by the Diagnostic::Report method, and
307/// allows insertion of extra information (arguments and source ranges) into the
308/// currently "in flight" diagnostic.  When the temporary for the builder is
309/// destroyed, the diagnostic is issued.
310///
311/// Note that many of these will be created as temporary objects (many call
312/// sites), so we want them to be small and we never want their address taken.
313/// This ensures that compilers with somewhat reasonable optimizers will promote
314/// the common fields to registers, eliminating increments of the NumArgs field,
315/// for example.
316class DiagnosticBuilder {
317  mutable Diagnostic *DiagObj;
318  mutable unsigned NumArgs, NumRanges;
319
320  void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
321  friend class Diagnostic;
322  explicit DiagnosticBuilder(Diagnostic *diagObj)
323    : DiagObj(diagObj), NumArgs(0), NumRanges(0) {}
324public:
325
326  /// Copy constructor.  When copied, this "takes" the diagnostic info from the
327  /// input and neuters it.
328  DiagnosticBuilder(const DiagnosticBuilder &D) {
329    DiagObj = D.DiagObj;
330    D.DiagObj = 0;
331  }
332
333  /// Destructor - The dtor emits the diagnostic.
334  ~DiagnosticBuilder() {
335    // If DiagObj is null, then its soul was stolen by the copy ctor.
336    if (DiagObj == 0) return;
337
338    // When destroyed, the ~DiagnosticBuilder sets the final argument count into
339    // the Diagnostic object.
340    DiagObj->NumDiagArgs = NumArgs;
341    DiagObj->NumDiagRanges = NumRanges;
342
343    // Process the diagnostic, sending the accumulated information to the
344    // DiagnosticClient.
345    DiagObj->ProcessDiag();
346
347    // This diagnostic is no longer in flight.
348    DiagObj->CurDiagID = ~0U;
349  }
350
351  /// Operator bool: conversion of DiagnosticBuilder to bool always returns
352  /// true.  This allows is to be used in boolean error contexts like:
353  /// return Diag(...);
354  operator bool() const { return true; }
355
356  void AddString(const std::string &S) const {
357    assert(NumArgs < Diagnostic::MaxArguments &&
358           "Too many arguments to diagnostic!");
359    DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
360    DiagObj->DiagArgumentsStr[NumArgs++] = S;
361  }
362
363  void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
364    assert(NumArgs < Diagnostic::MaxArguments &&
365           "Too many arguments to diagnostic!");
366    DiagObj->DiagArgumentsKind[NumArgs] = Kind;
367    DiagObj->DiagArgumentsVal[NumArgs++] = V;
368  }
369
370  void AddSourceRange(const SourceRange &R) const {
371    assert(NumRanges <
372           sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
373           "Too many arguments to diagnostic!");
374    DiagObj->DiagRanges[NumRanges++] = &R;
375  }
376};
377
378inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
379                                           const std::string &S) {
380  DB.AddString(S);
381  return DB;
382}
383
384inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
385                                           const char *Str) {
386  DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
387                  Diagnostic::ak_c_string);
388  return DB;
389}
390
391inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
392  DB.AddTaggedVal(I, Diagnostic::ak_sint);
393  return DB;
394}
395
396inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
397  DB.AddTaggedVal(I, Diagnostic::ak_sint);
398  return DB;
399}
400
401inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
402                                           unsigned I) {
403  DB.AddTaggedVal(I, Diagnostic::ak_uint);
404  return DB;
405}
406
407inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
408                                           const IdentifierInfo *II) {
409  DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
410                  Diagnostic::ak_identifierinfo);
411  return DB;
412}
413
414inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
415                                           const SourceRange &R) {
416  DB.AddSourceRange(R);
417  return DB;
418}
419
420
421/// Report - Issue the message to the client.  DiagID is a member of the
422/// diag::kind enum.  This actually returns a new instance of DiagnosticBuilder
423/// which emits the diagnostics (through ProcessDiag) when it is destroyed.
424inline DiagnosticBuilder Diagnostic::Report(FullSourceLoc Loc, unsigned DiagID){
425  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
426  CurDiagLoc = Loc;
427  CurDiagID = DiagID;
428  return DiagnosticBuilder(this);
429}
430
431//===----------------------------------------------------------------------===//
432// DiagnosticInfo
433//===----------------------------------------------------------------------===//
434
435/// DiagnosticInfo - This is a little helper class (which is basically a smart
436/// pointer that forward info from Diagnostic) that allows clients ot enquire
437/// about the currently in-flight diagnostic.
438class DiagnosticInfo {
439  const Diagnostic *DiagObj;
440public:
441  explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
442
443  const Diagnostic *getDiags() const { return DiagObj; }
444  unsigned getID() const { return DiagObj->CurDiagID; }
445  const FullSourceLoc &getLocation() const { return DiagObj->CurDiagLoc; }
446
447  unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
448
449  /// getArgKind - Return the kind of the specified index.  Based on the kind
450  /// of argument, the accessors below can be used to get the value.
451  Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
452    assert(Idx < getNumArgs() && "Argument index out of range!");
453    return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
454  }
455
456  /// getArgStdStr - Return the provided argument string specified by Idx.
457  const std::string &getArgStdStr(unsigned Idx) const {
458    assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
459           "invalid argument accessor!");
460    return DiagObj->DiagArgumentsStr[Idx];
461  }
462
463  /// getArgCStr - Return the specified C string argument.
464  const char *getArgCStr(unsigned Idx) const {
465    assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
466           "invalid argument accessor!");
467    return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
468  }
469
470  /// getArgSInt - Return the specified signed integer argument.
471  int getArgSInt(unsigned Idx) const {
472    assert(getArgKind(Idx) == Diagnostic::ak_sint &&
473           "invalid argument accessor!");
474    return (int)DiagObj->DiagArgumentsVal[Idx];
475  }
476
477  /// getArgUInt - Return the specified unsigned integer argument.
478  unsigned getArgUInt(unsigned Idx) const {
479    assert(getArgKind(Idx) == Diagnostic::ak_uint &&
480           "invalid argument accessor!");
481    return (unsigned)DiagObj->DiagArgumentsVal[Idx];
482  }
483
484  /// getArgIdentifier - Return the specified IdentifierInfo argument.
485  const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
486    assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
487           "invalid argument accessor!");
488    return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
489  }
490
491  /// getRawArg - Return the specified non-string argument in an opaque form.
492  intptr_t getRawArg(unsigned Idx) const {
493    assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
494           "invalid argument accessor!");
495    return DiagObj->DiagArgumentsVal[Idx];
496  }
497
498
499  /// getNumRanges - Return the number of source ranges associated with this
500  /// diagnostic.
501  unsigned getNumRanges() const {
502    return DiagObj->NumDiagRanges;
503  }
504
505  const SourceRange &getRange(unsigned Idx) const {
506    assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
507    return *DiagObj->DiagRanges[Idx];
508  }
509
510
511  /// FormatDiagnostic - Format this diagnostic into a string, substituting the
512  /// formal arguments into the %0 slots.  The result is appended onto the Str
513  /// array.
514  void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
515};
516
517
518/// DiagnosticClient - This is an abstract interface implemented by clients of
519/// the front-end, which formats and prints fully processed diagnostics.
520class DiagnosticClient {
521public:
522  virtual ~DiagnosticClient();
523
524  /// IncludeInDiagnosticCounts - This method (whose default implementation
525  ///  returns true) indicates whether the diagnostics handled by this
526  ///  DiagnosticClient should be included in the number of diagnostics
527  ///  reported by Diagnostic.
528  virtual bool IncludeInDiagnosticCounts() const;
529
530  /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
531  /// capturing it to a log as needed.
532  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
533                                const DiagnosticInfo &Info) = 0;
534};
535
536}  // end namespace clang
537
538#endif
539