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