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