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