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