Diagnostic.h revision 3bc172bc6a787842db6fea351cf6929539fca70d
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) 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  /// getDiagnosticLevel - Based on the way the client configured the Diagnostic
317  /// object, classify the specified diagnostic ID into a Level, consumable by
318  /// the DiagnosticClient.
319  Level getDiagnosticLevel(unsigned DiagID) const;
320
321  /// Report - Issue the message to the client.  @c DiagID is a member of the
322  /// @c diag::kind enum.  This actually returns aninstance of DiagnosticBuilder
323  /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed.
324  /// @c Pos represents the source location associated with the diagnostic,
325  /// which can be an invalid location if no position information is available.
326  inline DiagnosticBuilder Report(FullSourceLoc Pos, unsigned DiagID);
327
328  /// \brief Clear out the current diagnostic.
329  void Clear() { CurDiagID = ~0U; }
330
331private:
332  /// getDiagnosticMappingInfo - Return the mapping info currently set for the
333  /// specified builtin diagnostic.  This returns the high bit encoding, or zero
334  /// if the field is completely uninitialized.
335  unsigned getDiagnosticMappingInfo(diag::kind Diag) const {
336    return (diag::Mapping)((DiagMappings[Diag/2] >> (Diag & 1)*4) & 15);
337  }
338
339  void setDiagnosticMappingInternal(unsigned DiagId, unsigned Map,
340                                    bool isUser) const {
341    if (isUser) Map |= 8;  // Set the high bit for user mappings.
342    unsigned char &Slot = DiagMappings[DiagId/2];
343    unsigned Shift = (DiagId & 1)*4;
344    Slot &= ~(15 << Shift);
345    Slot |= Map << Shift;
346  }
347
348  /// getDiagnosticLevel - This is an internal implementation helper used when
349  /// DiagClass is already known.
350  Level getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const;
351
352  // This is private state used by DiagnosticBuilder.  We put it here instead of
353  // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
354  // object.  This implementation choice means that we can only have one
355  // diagnostic "in flight" at a time, but this seems to be a reasonable
356  // tradeoff to keep these objects small.  Assertions verify that only one
357  // diagnostic is in flight at a time.
358  friend class DiagnosticBuilder;
359  friend class DiagnosticInfo;
360
361  /// CurDiagLoc - This is the location of the current diagnostic that is in
362  /// flight.
363  FullSourceLoc CurDiagLoc;
364
365  /// CurDiagID - This is the ID of the current diagnostic that is in flight.
366  /// This is set to ~0U when there is no diagnostic in flight.
367  unsigned CurDiagID;
368
369  enum {
370    /// MaxArguments - The maximum number of arguments we can hold. We currently
371    /// only support up to 10 arguments (%0-%9).  A single diagnostic with more
372    /// than that almost certainly has to be simplified anyway.
373    MaxArguments = 10
374  };
375
376  /// NumDiagArgs - This contains the number of entries in Arguments.
377  signed char NumDiagArgs;
378  /// NumRanges - This is the number of ranges in the DiagRanges array.
379  unsigned char NumDiagRanges;
380  /// \brief The number of code modifications hints in the
381  /// CodeModificationHints array.
382  unsigned char NumCodeModificationHints;
383
384  /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
385  /// values, with one for each argument.  This specifies whether the argument
386  /// is in DiagArgumentsStr or in DiagArguments.
387  unsigned char DiagArgumentsKind[MaxArguments];
388
389  /// DiagArgumentsStr - This holds the values of each string argument for the
390  /// current diagnostic.  This value is only used when the corresponding
391  /// ArgumentKind is ak_std_string.
392  std::string DiagArgumentsStr[MaxArguments];
393
394  /// DiagArgumentsVal - The values for the various substitution positions. This
395  /// is used when the argument is not an std::string.  The specific value is
396  /// mangled into an intptr_t and the intepretation depends on exactly what
397  /// sort of argument kind it is.
398  intptr_t DiagArgumentsVal[MaxArguments];
399
400  /// DiagRanges - The list of ranges added to this diagnostic.  It currently
401  /// only support 10 ranges, could easily be extended if needed.
402  const SourceRange *DiagRanges[10];
403
404  enum { MaxCodeModificationHints = 3 };
405
406  /// CodeModificationHints - If valid, provides a hint with some code
407  /// to insert, remove, or modify at a particular position.
408  CodeModificationHint CodeModificationHints[MaxCodeModificationHints];
409
410  /// ProcessDiag - This is the method used to report a diagnostic that is
411  /// finally fully formed.
412  void ProcessDiag();
413};
414
415//===----------------------------------------------------------------------===//
416// DiagnosticBuilder
417//===----------------------------------------------------------------------===//
418
419/// DiagnosticBuilder - This is a little helper class used to produce
420/// diagnostics.  This is constructed by the Diagnostic::Report method, and
421/// allows insertion of extra information (arguments and source ranges) into the
422/// currently "in flight" diagnostic.  When the temporary for the builder is
423/// destroyed, the diagnostic is issued.
424///
425/// Note that many of these will be created as temporary objects (many call
426/// sites), so we want them to be small and we never want their address taken.
427/// This ensures that compilers with somewhat reasonable optimizers will promote
428/// the common fields to registers, eliminating increments of the NumArgs field,
429/// for example.
430class DiagnosticBuilder {
431  mutable Diagnostic *DiagObj;
432  mutable unsigned NumArgs, NumRanges, NumCodeModificationHints;
433
434  void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
435  friend class Diagnostic;
436  explicit DiagnosticBuilder(Diagnostic *diagObj)
437    : DiagObj(diagObj), NumArgs(0), NumRanges(0),
438      NumCodeModificationHints(0) {}
439
440public:
441  /// Copy constructor.  When copied, this "takes" the diagnostic info from the
442  /// input and neuters it.
443  DiagnosticBuilder(const DiagnosticBuilder &D) {
444    DiagObj = D.DiagObj;
445    D.DiagObj = 0;
446    NumArgs = D.NumArgs;
447    NumRanges = D.NumRanges;
448    NumCodeModificationHints = D.NumCodeModificationHints;
449  }
450
451  /// \brief Force the diagnostic builder to emit the diagnostic now.
452  ///
453  /// Once this function has been called, the DiagnosticBuilder object
454  /// should not be used again before it is destroyed.
455  void Emit() {
456    // If DiagObj is null, then its soul was stolen by the copy ctor
457    // or the user called Emit().
458    if (DiagObj == 0) return;
459
460    // When emitting diagnostics, we set the final argument count into
461    // the Diagnostic object.
462    DiagObj->NumDiagArgs = NumArgs;
463    DiagObj->NumDiagRanges = NumRanges;
464    DiagObj->NumCodeModificationHints = NumCodeModificationHints;
465
466    // Process the diagnostic, sending the accumulated information to the
467    // DiagnosticClient.
468    DiagObj->ProcessDiag();
469
470    // Clear out the current diagnostic object.
471    DiagObj->Clear();
472
473    // This diagnostic is dead.
474    DiagObj = 0;
475  }
476
477  /// Destructor - The dtor emits the diagnostic if it hasn't already
478  /// been emitted.
479  ~DiagnosticBuilder() { Emit(); }
480
481  /// Operator bool: conversion of DiagnosticBuilder to bool always returns
482  /// true.  This allows is to be used in boolean error contexts like:
483  /// return Diag(...);
484  operator bool() const { return true; }
485
486  void AddString(const std::string &S) const {
487    assert(NumArgs < Diagnostic::MaxArguments &&
488           "Too many arguments to diagnostic!");
489    DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
490    DiagObj->DiagArgumentsStr[NumArgs++] = S;
491  }
492
493  void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
494    assert(NumArgs < Diagnostic::MaxArguments &&
495           "Too many arguments to diagnostic!");
496    DiagObj->DiagArgumentsKind[NumArgs] = Kind;
497    DiagObj->DiagArgumentsVal[NumArgs++] = V;
498  }
499
500  void AddSourceRange(const SourceRange &R) const {
501    assert(NumRanges <
502           sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
503           "Too many arguments to diagnostic!");
504    DiagObj->DiagRanges[NumRanges++] = &R;
505  }
506
507  void AddCodeModificationHint(const CodeModificationHint &Hint) const {
508    assert(NumCodeModificationHints < Diagnostic::MaxCodeModificationHints &&
509           "Too many code modification hints!");
510    DiagObj->CodeModificationHints[NumCodeModificationHints++] = Hint;
511  }
512};
513
514inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
515                                           const std::string &S) {
516  DB.AddString(S);
517  return DB;
518}
519
520inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
521                                           const char *Str) {
522  DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
523                  Diagnostic::ak_c_string);
524  return DB;
525}
526
527inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
528  DB.AddTaggedVal(I, Diagnostic::ak_sint);
529  return DB;
530}
531
532inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
533  DB.AddTaggedVal(I, Diagnostic::ak_sint);
534  return DB;
535}
536
537inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
538                                           unsigned I) {
539  DB.AddTaggedVal(I, Diagnostic::ak_uint);
540  return DB;
541}
542
543inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
544                                           const IdentifierInfo *II) {
545  DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
546                  Diagnostic::ak_identifierinfo);
547  return DB;
548}
549
550inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
551                                           const SourceRange &R) {
552  DB.AddSourceRange(R);
553  return DB;
554}
555
556inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
557                                           const CodeModificationHint &Hint) {
558  DB.AddCodeModificationHint(Hint);
559  return DB;
560}
561
562/// Report - Issue the message to the client.  DiagID is a member of the
563/// diag::kind enum.  This actually returns a new instance of DiagnosticBuilder
564/// which emits the diagnostics (through ProcessDiag) when it is destroyed.
565inline DiagnosticBuilder Diagnostic::Report(FullSourceLoc Loc, unsigned DiagID){
566  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
567  CurDiagLoc = Loc;
568  CurDiagID = DiagID;
569  return DiagnosticBuilder(this);
570}
571
572//===----------------------------------------------------------------------===//
573// DiagnosticInfo
574//===----------------------------------------------------------------------===//
575
576/// DiagnosticInfo - This is a little helper class (which is basically a smart
577/// pointer that forward info from Diagnostic) that allows clients to enquire
578/// about the currently in-flight diagnostic.
579class DiagnosticInfo {
580  const Diagnostic *DiagObj;
581public:
582  explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
583
584  const Diagnostic *getDiags() const { return DiagObj; }
585  unsigned getID() const { return DiagObj->CurDiagID; }
586  const FullSourceLoc &getLocation() const { return DiagObj->CurDiagLoc; }
587
588  unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
589
590  /// getArgKind - Return the kind of the specified index.  Based on the kind
591  /// of argument, the accessors below can be used to get the value.
592  Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
593    assert(Idx < getNumArgs() && "Argument index out of range!");
594    return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
595  }
596
597  /// getArgStdStr - Return the provided argument string specified by Idx.
598  const std::string &getArgStdStr(unsigned Idx) const {
599    assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
600           "invalid argument accessor!");
601    return DiagObj->DiagArgumentsStr[Idx];
602  }
603
604  /// getArgCStr - Return the specified C string argument.
605  const char *getArgCStr(unsigned Idx) const {
606    assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
607           "invalid argument accessor!");
608    return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
609  }
610
611  /// getArgSInt - Return the specified signed integer argument.
612  int getArgSInt(unsigned Idx) const {
613    assert(getArgKind(Idx) == Diagnostic::ak_sint &&
614           "invalid argument accessor!");
615    return (int)DiagObj->DiagArgumentsVal[Idx];
616  }
617
618  /// getArgUInt - Return the specified unsigned integer argument.
619  unsigned getArgUInt(unsigned Idx) const {
620    assert(getArgKind(Idx) == Diagnostic::ak_uint &&
621           "invalid argument accessor!");
622    return (unsigned)DiagObj->DiagArgumentsVal[Idx];
623  }
624
625  /// getArgIdentifier - Return the specified IdentifierInfo argument.
626  const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
627    assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
628           "invalid argument accessor!");
629    return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
630  }
631
632  /// getRawArg - Return the specified non-string argument in an opaque form.
633  intptr_t getRawArg(unsigned Idx) const {
634    assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
635           "invalid argument accessor!");
636    return DiagObj->DiagArgumentsVal[Idx];
637  }
638
639
640  /// getNumRanges - Return the number of source ranges associated with this
641  /// diagnostic.
642  unsigned getNumRanges() const {
643    return DiagObj->NumDiagRanges;
644  }
645
646  const SourceRange &getRange(unsigned Idx) const {
647    assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
648    return *DiagObj->DiagRanges[Idx];
649  }
650
651  unsigned getNumCodeModificationHints() const {
652    return DiagObj->NumCodeModificationHints;
653  }
654
655  const CodeModificationHint &getCodeModificationHint(unsigned Idx) const {
656    return DiagObj->CodeModificationHints[Idx];
657  }
658
659  const CodeModificationHint *getCodeModificationHints() const {
660    return DiagObj->NumCodeModificationHints?
661             &DiagObj->CodeModificationHints[0] : 0;
662  }
663
664  /// FormatDiagnostic - Format this diagnostic into a string, substituting the
665  /// formal arguments into the %0 slots.  The result is appended onto the Str
666  /// array.
667  void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
668};
669
670/// DiagnosticClient - This is an abstract interface implemented by clients of
671/// the front-end, which formats and prints fully processed diagnostics.
672class DiagnosticClient {
673public:
674  virtual ~DiagnosticClient();
675
676  /// setLangOptions - This is set by clients of diagnostics when they know the
677  /// language parameters of the diagnostics that may be sent through.  Note
678  /// that this can change over time if a DiagClient has multiple languages sent
679  /// through it.  It may also be set to null (e.g. when processing command line
680  /// options).
681  virtual void setLangOptions(const LangOptions *LO) {}
682
683  /// IncludeInDiagnosticCounts - This method (whose default implementation
684  ///  returns true) indicates whether the diagnostics handled by this
685  ///  DiagnosticClient should be included in the number of diagnostics
686  ///  reported by Diagnostic.
687  virtual bool IncludeInDiagnosticCounts() const;
688
689  /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
690  /// capturing it to a log as needed.
691  virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
692                                const DiagnosticInfo &Info) = 0;
693};
694
695}  // end namespace clang
696
697#endif
698