Diagnostic.h revision 0304c6cb7fd3b2137213858b1e5ae85ef3f4f8e2
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 "llvm/ADT/StringRef.h"
19#include "llvm/Support/type_traits.h"
20#include <string>
21#include <vector>
22#include <cassert>
23
24namespace llvm {
25  template <typename T> class SmallVectorImpl;
26}
27
28namespace clang {
29  class DeclContext;
30  class DiagnosticBuilder;
31  class DiagnosticClient;
32  class IdentifierInfo;
33  class LangOptions;
34  class PartialDiagnostic;
35  class Preprocessor;
36  class SourceRange;
37
38  // Import the diagnostic enums themselves.
39  namespace diag {
40    // Start position for diagnostics.
41    enum {
42      DIAG_START_DRIVER   =                        300,
43      DIAG_START_FRONTEND = DIAG_START_DRIVER   +  100,
44      DIAG_START_LEX      = DIAG_START_FRONTEND +  100,
45      DIAG_START_PARSE    = DIAG_START_LEX      +  300,
46      DIAG_START_AST      = DIAG_START_PARSE    +  300,
47      DIAG_START_SEMA     = DIAG_START_AST      +  100,
48      DIAG_START_ANALYSIS = DIAG_START_SEMA     + 1100,
49      DIAG_UPPER_LIMIT    = DIAG_START_ANALYSIS +  100
50    };
51
52    class CustomDiagInfo;
53
54    /// diag::kind - All of the diagnostics that can be emitted by the frontend.
55    typedef unsigned kind;
56
57    // Get typedefs for common diagnostics.
58    enum {
59#define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,SFINAE) ENUM,
60#include "clang/Basic/DiagnosticCommonKinds.inc"
61      NUM_BUILTIN_COMMON_DIAGNOSTICS
62#undef DIAG
63    };
64
65    /// Enum values that allow the client to map NOTEs, WARNINGs, and EXTENSIONs
66    /// to either MAP_IGNORE (nothing), MAP_WARNING (emit a warning), MAP_ERROR
67    /// (emit as an error).  It allows clients to map errors to
68    /// MAP_ERROR/MAP_DEFAULT or MAP_FATAL (stop emitting diagnostics after this
69    /// one).
70    enum Mapping {
71      // NOTE: 0 means "uncomputed".
72      MAP_IGNORE  = 1,     //< Map this diagnostic to nothing, ignore it.
73      MAP_WARNING = 2,     //< Map this diagnostic to a warning.
74      MAP_ERROR   = 3,     //< Map this diagnostic to an error.
75      MAP_FATAL   = 4,     //< Map this diagnostic to a fatal error.
76
77      /// Map this diagnostic to "warning", but make it immune to -Werror.  This
78      /// happens when you specify -Wno-error=foo.
79      MAP_WARNING_NO_WERROR = 5
80    };
81  }
82
83/// \brief Annotates a diagnostic with some code that should be
84/// inserted, removed, or replaced to fix the problem.
85///
86/// This kind of hint should be used when we are certain that the
87/// introduction, removal, or modification of a particular (small!)
88/// amount of code will correct a compilation error. The compiler
89/// should also provide full recovery from such errors, such that
90/// suppressing the diagnostic output can still result in successful
91/// compilation.
92class CodeModificationHint {
93public:
94  /// \brief Tokens that should be removed to correct the error.
95  SourceRange RemoveRange;
96
97  /// \brief The location at which we should insert code to correct
98  /// the error.
99  SourceLocation InsertionLoc;
100
101  /// \brief The actual code to insert at the insertion location, as a
102  /// string.
103  std::string CodeToInsert;
104
105  /// \brief Empty code modification hint, indicating that no code
106  /// modification is known.
107  CodeModificationHint() : RemoveRange(), InsertionLoc() { }
108
109  bool isNull() const {
110    return !RemoveRange.isValid() && !InsertionLoc.isValid();
111  }
112
113  /// \brief Create a code modification hint that inserts the given
114  /// code string at a specific location.
115  static CodeModificationHint CreateInsertion(SourceLocation InsertionLoc,
116                                              llvm::StringRef Code) {
117    CodeModificationHint Hint;
118    Hint.InsertionLoc = InsertionLoc;
119    Hint.CodeToInsert = Code;
120    return Hint;
121  }
122
123  /// \brief Create a code modification hint that removes the given
124  /// source range.
125  static CodeModificationHint CreateRemoval(SourceRange RemoveRange) {
126    CodeModificationHint Hint;
127    Hint.RemoveRange = RemoveRange;
128    return Hint;
129  }
130
131  /// \brief Create a code modification hint that replaces the given
132  /// source range with the given code string.
133  static CodeModificationHint CreateReplacement(SourceRange RemoveRange,
134                                                llvm::StringRef Code) {
135    CodeModificationHint Hint;
136    Hint.RemoveRange = RemoveRange;
137    Hint.InsertionLoc = RemoveRange.getBegin();
138    Hint.CodeToInsert = Code;
139    return Hint;
140  }
141};
142
143/// Diagnostic - This concrete class is used by the front-end to report
144/// problems and issues.  It massages the diagnostics (e.g. handling things like
145/// "report warnings as errors" and passes them off to the DiagnosticClient for
146/// reporting to the user.
147class Diagnostic {
148public:
149  /// Level - The level of the diagnostic, after it has been through mapping.
150  enum Level {
151    Ignored, Note, Warning, Error, Fatal
152  };
153
154  /// ExtensionHandling - How do we handle otherwise-unmapped extension?  This
155  /// is controlled by -pedantic and -pedantic-errors.
156  enum ExtensionHandling {
157    Ext_Ignore, Ext_Warn, Ext_Error
158  };
159
160  enum ArgumentKind {
161    ak_std_string,      // std::string
162    ak_c_string,        // const char *
163    ak_sint,            // int
164    ak_uint,            // unsigned
165    ak_identifierinfo,  // IdentifierInfo
166    ak_qualtype,        // QualType
167    ak_declarationname, // DeclarationName
168    ak_nameddecl,       // NamedDecl *
169    ak_nestednamespec,  // NestedNameSpecifier *
170    ak_declcontext      // DeclContext *
171  };
172
173  /// ArgumentValue - This typedef represents on argument value, which is a
174  /// union discriminated by ArgumentKind, with a value.
175  typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
176
177private:
178  unsigned char AllExtensionsSilenced; // Used by __extension__
179  bool IgnoreAllWarnings;        // Ignore all warnings: -w
180  bool WarningsAsErrors;         // Treat warnings like errors:
181  bool SuppressSystemWarnings;   // Suppress warnings in system headers.
182  bool SuppressAllDiagnostics;   // Suppress all diagnostics.
183  ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors?
184  DiagnosticClient *Client;
185
186  /// DiagMappings - Mapping information for diagnostics.  Mapping info is
187  /// packed into four bits per diagnostic.  The low three bits are the mapping
188  /// (an instance of diag::Mapping), or zero if unset.  The high bit is set
189  /// when the mapping was established as a user mapping.  If the high bit is
190  /// clear, then the low bits are set to the default value, and should be
191  /// mapped with -pedantic, -Werror, etc.
192
193  typedef std::vector<unsigned char> DiagMappings;
194  mutable std::vector<DiagMappings> DiagMappingsStack;
195
196  /// ErrorOccurred / FatalErrorOccurred - This is set to true when an error or
197  /// fatal error is emitted, and is sticky.
198  bool ErrorOccurred;
199  bool FatalErrorOccurred;
200
201  /// LastDiagLevel - This is the level of the last diagnostic emitted.  This is
202  /// used to emit continuation diagnostics with the same level as the
203  /// diagnostic that they follow.
204  Diagnostic::Level LastDiagLevel;
205
206  unsigned NumDiagnostics;    // Number of diagnostics reported
207  unsigned NumErrors;         // Number of diagnostics that are errors
208
209  /// CustomDiagInfo - Information for uniquing and looking up custom diags.
210  diag::CustomDiagInfo *CustomDiagInfo;
211
212  /// ArgToStringFn - A function pointer that converts an opaque diagnostic
213  /// argument to a strings.  This takes the modifiers and argument that was
214  /// present in the diagnostic.
215  ///
216  /// The PrevArgs array (whose length is NumPrevArgs) indicates the previous
217  /// arguments formatted for this diagnostic.  Implementations of this function
218  /// can use this information to avoid redundancy across arguments.
219  ///
220  /// This is a hack to avoid a layering violation between libbasic and libsema.
221  typedef void (*ArgToStringFnTy)(ArgumentKind Kind, intptr_t Val,
222                                  const char *Modifier, unsigned ModifierLen,
223                                  const char *Argument, unsigned ArgumentLen,
224                                  const ArgumentValue *PrevArgs,
225                                  unsigned NumPrevArgs,
226                                  llvm::SmallVectorImpl<char> &Output,
227                                  void *Cookie);
228  void *ArgToStringCookie;
229  ArgToStringFnTy ArgToStringFn;
230public:
231  explicit Diagnostic(DiagnosticClient *client = 0);
232  ~Diagnostic();
233
234  //===--------------------------------------------------------------------===//
235  //  Diagnostic characterization methods, used by a client to customize how
236  //
237
238  DiagnosticClient *getClient() { return Client; }
239  const DiagnosticClient *getClient() const { return Client; }
240
241  /// pushMappings - Copies the current DiagMappings and pushes the new copy
242  /// onto the top of the stack.
243  void pushMappings();
244
245  /// popMappings - Pops the current DiagMappings off the top of the stack
246  /// causing the new top of the stack to be the active mappings. Returns
247  /// true if the pop happens, false if there is only one DiagMapping on the
248  /// stack.
249  bool popMappings();
250
251  void setClient(DiagnosticClient* client) { Client = client; }
252
253  /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
254  /// ignored.  If this and WarningsAsErrors are both set, then this one wins.
255  void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
256  bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
257
258  /// setWarningsAsErrors - When set to true, any warnings reported are issued
259  /// as errors.
260  void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
261  bool getWarningsAsErrors() const { return WarningsAsErrors; }
262
263  /// setSuppressSystemWarnings - When set to true mask warnings that
264  /// come from system headers.
265  void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
266  bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
267
268  /// \brief Suppress all diagnostics, to silence the front end when we
269  /// know that we don't want any more diagnostics to be passed along to the
270  /// client
271  void setSuppressAllDiagnostics(bool Val = true) {
272    SuppressAllDiagnostics = Val;
273  }
274  bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
275
276  /// \brief Pretend that the last diagnostic issued was ignored. This can
277  /// be used by clients who suppress diagnostics themselves.
278  void setLastDiagnosticIgnored() {
279    LastDiagLevel = Ignored;
280  }
281
282  /// setExtensionHandlingBehavior - This controls whether otherwise-unmapped
283  /// extension diagnostics are mapped onto ignore/warning/error.  This
284  /// corresponds to the GCC -pedantic and -pedantic-errors option.
285  void setExtensionHandlingBehavior(ExtensionHandling H) {
286    ExtBehavior = H;
287  }
288
289  /// AllExtensionsSilenced - This is a counter bumped when an __extension__
290  /// block is encountered.  When non-zero, all extension diagnostics are
291  /// entirely silenced, no matter how they are mapped.
292  void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
293  void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
294  bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
295
296  /// setDiagnosticMapping - This allows the client to specify that certain
297  /// warnings are ignored.  Notes can never be mapped, errors can only be
298  /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
299  void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map) {
300    assert(Diag < diag::DIAG_UPPER_LIMIT &&
301           "Can only map builtin diagnostics");
302    assert((isBuiltinWarningOrExtension(Diag) || Map == diag::MAP_FATAL) &&
303           "Cannot map errors!");
304    setDiagnosticMappingInternal(Diag, Map, true);
305  }
306
307  /// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
308  /// "unknown-pragmas" to have the specified mapping.  This returns true and
309  /// ignores the request if "Group" was unknown, false otherwise.
310  bool setDiagnosticGroupMapping(const char *Group, diag::Mapping Map);
311
312  bool hasErrorOccurred() const { return ErrorOccurred; }
313  bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
314
315  unsigned getNumErrors() const { return NumErrors; }
316  unsigned getNumDiagnostics() const { return NumDiagnostics; }
317
318  /// getCustomDiagID - Return an ID for a diagnostic with the specified message
319  /// and level.  If this is the first request for this diagnosic, it is
320  /// registered and created, otherwise the existing ID is returned.
321  unsigned getCustomDiagID(Level L, llvm::StringRef Message);
322
323
324  /// ConvertArgToString - This method converts a diagnostic argument (as an
325  /// intptr_t) into the string that represents it.
326  void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
327                          const char *Modifier, unsigned ModLen,
328                          const char *Argument, unsigned ArgLen,
329                          const ArgumentValue *PrevArgs, unsigned NumPrevArgs,
330                          llvm::SmallVectorImpl<char> &Output) const {
331    ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen,
332                  PrevArgs, NumPrevArgs, Output, ArgToStringCookie);
333  }
334
335  void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
336    ArgToStringFn = Fn;
337    ArgToStringCookie = Cookie;
338  }
339
340  //===--------------------------------------------------------------------===//
341  // Diagnostic classification and reporting interfaces.
342  //
343
344  /// getDescription - Given a diagnostic ID, return a description of the
345  /// issue.
346  const char *getDescription(unsigned DiagID) const;
347
348  /// isNoteWarningOrExtension - Return true if the unmapped diagnostic
349  /// level of the specified diagnostic ID is a Warning or Extension.
350  /// This only works on builtin diagnostics, not custom ones, and is not legal to
351  /// call on NOTEs.
352  static bool isBuiltinWarningOrExtension(unsigned DiagID);
353
354  /// \brief Determine whether the given built-in diagnostic ID is a
355  /// Note.
356  static bool isBuiltinNote(unsigned DiagID);
357
358  /// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
359  /// ID is for an extension of some sort.
360  ///
361  static bool isBuiltinExtensionDiag(unsigned DiagID);
362
363  /// getWarningOptionForDiag - Return the lowest-level warning option that
364  /// enables the specified diagnostic.  If there is no -Wfoo flag that controls
365  /// the diagnostic, this returns null.
366  static const char *getWarningOptionForDiag(unsigned DiagID);
367
368  /// \brief Determines whether the given built-in diagnostic ID is
369  /// for an error that is suppressed if it occurs during C++ template
370  /// argument deduction.
371  ///
372  /// When an error is suppressed due to SFINAE, the template argument
373  /// deduction fails but no diagnostic is emitted. Certain classes of
374  /// errors, such as those errors that involve C++ access control,
375  /// are not SFINAE errors.
376  static bool isBuiltinSFINAEDiag(unsigned DiagID);
377
378  /// getDiagnosticLevel - Based on the way the client configured the Diagnostic
379  /// object, classify the specified diagnostic ID into a Level, consumable by
380  /// the DiagnosticClient.
381  Level getDiagnosticLevel(unsigned DiagID) const;
382
383  /// Report - Issue the message to the client.  @c DiagID is a member of the
384  /// @c diag::kind enum.  This actually returns aninstance of DiagnosticBuilder
385  /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed.
386  /// @c Pos represents the source location associated with the diagnostic,
387  /// which can be an invalid location if no position information is available.
388  inline DiagnosticBuilder Report(FullSourceLoc Pos, unsigned DiagID);
389  inline DiagnosticBuilder Report(unsigned DiagID);
390
391  /// \brief Clear out the current diagnostic.
392  void Clear() { CurDiagID = ~0U; }
393
394private:
395  /// getDiagnosticMappingInfo - Return the mapping info currently set for the
396  /// specified builtin diagnostic.  This returns the high bit encoding, or zero
397  /// if the field is completely uninitialized.
398  unsigned getDiagnosticMappingInfo(diag::kind Diag) const {
399    const DiagMappings &currentMappings = DiagMappingsStack.back();
400    return (diag::Mapping)((currentMappings[Diag/2] >> (Diag & 1)*4) & 15);
401  }
402
403  void setDiagnosticMappingInternal(unsigned DiagId, unsigned Map,
404                                    bool isUser) const {
405    if (isUser) Map |= 8;  // Set the high bit for user mappings.
406    unsigned char &Slot = DiagMappingsStack.back()[DiagId/2];
407    unsigned Shift = (DiagId & 1)*4;
408    Slot &= ~(15 << Shift);
409    Slot |= Map << Shift;
410  }
411
412  /// getDiagnosticLevel - This is an internal implementation helper used when
413  /// DiagClass is already known.
414  Level getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const;
415
416  // This is private state used by DiagnosticBuilder.  We put it here instead of
417  // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
418  // object.  This implementation choice means that we can only have one
419  // diagnostic "in flight" at a time, but this seems to be a reasonable
420  // tradeoff to keep these objects small.  Assertions verify that only one
421  // diagnostic is in flight at a time.
422  friend class DiagnosticBuilder;
423  friend class DiagnosticInfo;
424
425  /// CurDiagLoc - This is the location of the current diagnostic that is in
426  /// flight.
427  FullSourceLoc CurDiagLoc;
428
429  /// CurDiagID - This is the ID of the current diagnostic that is in flight.
430  /// This is set to ~0U when there is no diagnostic in flight.
431  unsigned CurDiagID;
432
433  enum {
434    /// MaxArguments - The maximum number of arguments we can hold. We currently
435    /// only support up to 10 arguments (%0-%9).  A single diagnostic with more
436    /// than that almost certainly has to be simplified anyway.
437    MaxArguments = 10
438  };
439
440  /// NumDiagArgs - This contains the number of entries in Arguments.
441  signed char NumDiagArgs;
442  /// NumRanges - This is the number of ranges in the DiagRanges array.
443  unsigned char NumDiagRanges;
444  /// \brief The number of code modifications hints in the
445  /// CodeModificationHints array.
446  unsigned char NumCodeModificationHints;
447
448  /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
449  /// values, with one for each argument.  This specifies whether the argument
450  /// is in DiagArgumentsStr or in DiagArguments.
451  unsigned char DiagArgumentsKind[MaxArguments];
452
453  /// DiagArgumentsStr - This holds the values of each string argument for the
454  /// current diagnostic.  This value is only used when the corresponding
455  /// ArgumentKind is ak_std_string.
456  std::string DiagArgumentsStr[MaxArguments];
457
458  /// DiagArgumentsVal - The values for the various substitution positions. This
459  /// is used when the argument is not an std::string.  The specific value is
460  /// mangled into an intptr_t and the intepretation depends on exactly what
461  /// sort of argument kind it is.
462  intptr_t DiagArgumentsVal[MaxArguments];
463
464  /// DiagRanges - The list of ranges added to this diagnostic.  It currently
465  /// only support 10 ranges, could easily be extended if needed.
466  const SourceRange *DiagRanges[10];
467
468  enum { MaxCodeModificationHints = 3 };
469
470  /// CodeModificationHints - If valid, provides a hint with some code
471  /// to insert, remove, or modify at a particular position.
472  CodeModificationHint CodeModificationHints[MaxCodeModificationHints];
473
474  /// ProcessDiag - This is the method used to report a diagnostic that is
475  /// finally fully formed.
476  ///
477  /// \returns true if the diagnostic was emitted, false if it was
478  /// suppressed.
479  bool ProcessDiag();
480};
481
482//===----------------------------------------------------------------------===//
483// DiagnosticBuilder
484//===----------------------------------------------------------------------===//
485
486/// DiagnosticBuilder - This is a little helper class used to produce
487/// diagnostics.  This is constructed by the Diagnostic::Report method, and
488/// allows insertion of extra information (arguments and source ranges) into the
489/// currently "in flight" diagnostic.  When the temporary for the builder is
490/// destroyed, the diagnostic is issued.
491///
492/// Note that many of these will be created as temporary objects (many call
493/// sites), so we want them to be small and we never want their address taken.
494/// This ensures that compilers with somewhat reasonable optimizers will promote
495/// the common fields to registers, eliminating increments of the NumArgs field,
496/// for example.
497class DiagnosticBuilder {
498  mutable Diagnostic *DiagObj;
499  mutable unsigned NumArgs, NumRanges, NumCodeModificationHints;
500
501  void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
502  friend class Diagnostic;
503  explicit DiagnosticBuilder(Diagnostic *diagObj)
504    : DiagObj(diagObj), NumArgs(0), NumRanges(0),
505      NumCodeModificationHints(0) {}
506
507public:
508  /// Copy constructor.  When copied, this "takes" the diagnostic info from the
509  /// input and neuters it.
510  DiagnosticBuilder(const DiagnosticBuilder &D) {
511    DiagObj = D.DiagObj;
512    D.DiagObj = 0;
513    NumArgs = D.NumArgs;
514    NumRanges = D.NumRanges;
515    NumCodeModificationHints = D.NumCodeModificationHints;
516  }
517
518  /// \brief Simple enumeration value used to give a name to the
519  /// suppress-diagnostic constructor.
520  enum SuppressKind { Suppress };
521
522  /// \brief Create an empty DiagnosticBuilder object that represents
523  /// no actual diagnostic.
524  explicit DiagnosticBuilder(SuppressKind)
525    : DiagObj(0), NumArgs(0), NumRanges(0), NumCodeModificationHints(0) { }
526
527  /// \brief Force the diagnostic builder to emit the diagnostic now.
528  ///
529  /// Once this function has been called, the DiagnosticBuilder object
530  /// should not be used again before it is destroyed.
531  ///
532  /// \returns true if a diagnostic was emitted, false if the
533  /// diagnostic was suppressed.
534  bool Emit() {
535    // If DiagObj is null, then its soul was stolen by the copy ctor
536    // or the user called Emit().
537    if (DiagObj == 0) return false;
538
539    // When emitting diagnostics, we set the final argument count into
540    // the Diagnostic object.
541    DiagObj->NumDiagArgs = NumArgs;
542    DiagObj->NumDiagRanges = NumRanges;
543    DiagObj->NumCodeModificationHints = NumCodeModificationHints;
544
545    // Process the diagnostic, sending the accumulated information to the
546    // DiagnosticClient.
547    bool Emitted = DiagObj->ProcessDiag();
548
549    // Clear out the current diagnostic object.
550    DiagObj->Clear();
551
552    // This diagnostic is dead.
553    DiagObj = 0;
554
555    return Emitted;
556  }
557
558  /// Destructor - The dtor emits the diagnostic if it hasn't already
559  /// been emitted.
560  ~DiagnosticBuilder() { Emit(); }
561
562  /// Operator bool: conversion of DiagnosticBuilder to bool always returns
563  /// true.  This allows is to be used in boolean error contexts like:
564  /// return Diag(...);
565  operator bool() const { return true; }
566
567  void AddString(llvm::StringRef S) const {
568    assert(NumArgs < Diagnostic::MaxArguments &&
569           "Too many arguments to diagnostic!");
570    if (DiagObj) {
571      DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
572      DiagObj->DiagArgumentsStr[NumArgs++] = S;
573    }
574  }
575
576  void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
577    assert(NumArgs < Diagnostic::MaxArguments &&
578           "Too many arguments to diagnostic!");
579    if (DiagObj) {
580      DiagObj->DiagArgumentsKind[NumArgs] = Kind;
581      DiagObj->DiagArgumentsVal[NumArgs++] = V;
582    }
583  }
584
585  void AddSourceRange(const SourceRange &R) const {
586    assert(NumRanges <
587           sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
588           "Too many arguments to diagnostic!");
589    if (DiagObj)
590      DiagObj->DiagRanges[NumRanges++] = &R;
591  }
592
593  void AddCodeModificationHint(const CodeModificationHint &Hint) const {
594    if (Hint.isNull())
595      return;
596
597    assert(NumCodeModificationHints < Diagnostic::MaxCodeModificationHints &&
598           "Too many code modification hints!");
599    if (DiagObj)
600      DiagObj->CodeModificationHints[NumCodeModificationHints++] = Hint;
601  }
602};
603
604inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
605                                           llvm::StringRef S) {
606  DB.AddString(S);
607  return DB;
608}
609
610inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
611                                           const char *Str) {
612  DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
613                  Diagnostic::ak_c_string);
614  return DB;
615}
616
617inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
618  DB.AddTaggedVal(I, Diagnostic::ak_sint);
619  return DB;
620}
621
622inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
623  DB.AddTaggedVal(I, Diagnostic::ak_sint);
624  return DB;
625}
626
627inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
628                                           unsigned I) {
629  DB.AddTaggedVal(I, Diagnostic::ak_uint);
630  return DB;
631}
632
633inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
634                                           const IdentifierInfo *II) {
635  DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
636                  Diagnostic::ak_identifierinfo);
637  return DB;
638}
639
640// Adds a DeclContext to the diagnostic. The enable_if template magic is here
641// so that we only match those arguments that are (statically) DeclContexts;
642// other arguments that derive from DeclContext (e.g., RecordDecls) will not
643// match.
644template<typename T>
645inline
646typename llvm::enable_if<llvm::is_same<T, DeclContext>,
647                         const DiagnosticBuilder &>::type
648operator<<(const DiagnosticBuilder &DB, T *DC) {
649  DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
650                  Diagnostic::ak_declcontext);
651  return DB;
652}
653
654inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
655                                           const SourceRange &R) {
656  DB.AddSourceRange(R);
657  return DB;
658}
659
660inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
661                                           const CodeModificationHint &Hint) {
662  DB.AddCodeModificationHint(Hint);
663  return DB;
664}
665
666/// Report - Issue the message to the client.  DiagID is a member of the
667/// diag::kind enum.  This actually returns a new instance of DiagnosticBuilder
668/// which emits the diagnostics (through ProcessDiag) when it is destroyed.
669inline DiagnosticBuilder Diagnostic::Report(FullSourceLoc Loc, unsigned DiagID){
670  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
671  CurDiagLoc = Loc;
672  CurDiagID = DiagID;
673  return DiagnosticBuilder(this);
674}
675inline DiagnosticBuilder Diagnostic::Report(unsigned DiagID) {
676  return Report(FullSourceLoc(), DiagID);
677}
678
679//===----------------------------------------------------------------------===//
680// DiagnosticInfo
681//===----------------------------------------------------------------------===//
682
683/// DiagnosticInfo - This is a little helper class (which is basically a smart
684/// pointer that forward info from Diagnostic) that allows clients to enquire
685/// about the currently in-flight diagnostic.
686class DiagnosticInfo {
687  const Diagnostic *DiagObj;
688public:
689  explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
690
691  const Diagnostic *getDiags() const { return DiagObj; }
692  unsigned getID() const { return DiagObj->CurDiagID; }
693  const FullSourceLoc &getLocation() const { return DiagObj->CurDiagLoc; }
694
695  unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
696
697  /// getArgKind - Return the kind of the specified index.  Based on the kind
698  /// of argument, the accessors below can be used to get the value.
699  Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
700    assert(Idx < getNumArgs() && "Argument index out of range!");
701    return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
702  }
703
704  /// getArgStdStr - Return the provided argument string specified by Idx.
705  const std::string &getArgStdStr(unsigned Idx) const {
706    assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
707           "invalid argument accessor!");
708    return DiagObj->DiagArgumentsStr[Idx];
709  }
710
711  /// getArgCStr - Return the specified C string argument.
712  const char *getArgCStr(unsigned Idx) const {
713    assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
714           "invalid argument accessor!");
715    return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
716  }
717
718  /// getArgSInt - Return the specified signed integer argument.
719  int getArgSInt(unsigned Idx) const {
720    assert(getArgKind(Idx) == Diagnostic::ak_sint &&
721           "invalid argument accessor!");
722    return (int)DiagObj->DiagArgumentsVal[Idx];
723  }
724
725  /// getArgUInt - Return the specified unsigned integer argument.
726  unsigned getArgUInt(unsigned Idx) const {
727    assert(getArgKind(Idx) == Diagnostic::ak_uint &&
728           "invalid argument accessor!");
729    return (unsigned)DiagObj->DiagArgumentsVal[Idx];
730  }
731
732  /// getArgIdentifier - Return the specified IdentifierInfo argument.
733  const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
734    assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
735           "invalid argument accessor!");
736    return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
737  }
738
739  /// getRawArg - Return the specified non-string argument in an opaque form.
740  intptr_t getRawArg(unsigned Idx) const {
741    assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
742           "invalid argument accessor!");
743    return DiagObj->DiagArgumentsVal[Idx];
744  }
745
746
747  /// getNumRanges - Return the number of source ranges associated with this
748  /// diagnostic.
749  unsigned getNumRanges() const {
750    return DiagObj->NumDiagRanges;
751  }
752
753  const SourceRange &getRange(unsigned Idx) const {
754    assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
755    return *DiagObj->DiagRanges[Idx];
756  }
757
758  unsigned getNumCodeModificationHints() const {
759    return DiagObj->NumCodeModificationHints;
760  }
761
762  const CodeModificationHint &getCodeModificationHint(unsigned Idx) const {
763    return DiagObj->CodeModificationHints[Idx];
764  }
765
766  const CodeModificationHint *getCodeModificationHints() const {
767    return DiagObj->NumCodeModificationHints?
768             &DiagObj->CodeModificationHints[0] : 0;
769  }
770
771  /// FormatDiagnostic - Format this diagnostic into a string, substituting the
772  /// formal arguments into the %0 slots.  The result is appended onto the Str
773  /// array.
774  void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
775};
776
777/// DiagnosticClient - This is an abstract interface implemented by clients of
778/// the front-end, which formats and prints fully processed diagnostics.
779class DiagnosticClient {
780public:
781  virtual ~DiagnosticClient();
782
783  /// BeginSourceFile - Callback to inform the diagnostic client that processing
784  /// of a source file is beginning.
785  ///
786  /// Note that diagnostics may be emitted outside the processing of a source
787  /// file, for example during the parsing of command line options. However,
788  /// diagnostics with source range information are required to only be emitted
789  /// in between BeginSourceFile() and EndSourceFile().
790  ///
791  /// \arg LO - The language options for the source file being processed.
792  /// \arg PP - The preprocessor object being used for the source; this optional
793  /// and may not be present, for example when processing AST source files.
794  virtual void BeginSourceFile(const LangOptions &LangOpts,
795                               const Preprocessor *PP = 0) {}
796
797  /// EndSourceFile - Callback to inform the diagnostic client that processing
798  /// of a source file has ended. The diagnostic client should assume that any
799  /// objects made available via \see BeginSourceFile() are inaccessible.
800  virtual void EndSourceFile() {}
801
802  /// IncludeInDiagnosticCounts - This method (whose default implementation
803  /// returns true) indicates whether the diagnostics handled by this
804  /// DiagnosticClient should be included in the number of diagnostics reported
805  /// by Diagnostic.
806  virtual bool IncludeInDiagnosticCounts() const;
807
808  /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
809  /// capturing it to a log as needed.
810  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
811                                const DiagnosticInfo &Info) = 0;
812};
813
814}  // end namespace clang
815
816#endif
817