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