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