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