Diagnostic.h revision efce31f51d6e7e31e125f96c20f6cdab3ead0a47
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/DiagnosticIDs.h"
18#include "clang/Basic/SourceLocation.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/IntrusiveRefCntPtr.h"
22#include "llvm/ADT/OwningPtr.h"
23#include "llvm/Support/type_traits.h"
24
25#include <vector>
26#include <list>
27
28namespace clang {
29  class DiagnosticConsumer;
30  class DiagnosticBuilder;
31  class IdentifierInfo;
32  class DeclContext;
33  class LangOptions;
34  class Preprocessor;
35  class DiagnosticErrorTrap;
36  class StoredDiagnostic;
37
38/// \brief Annotates a diagnostic with some code that should be
39/// inserted, removed, or replaced to fix the problem.
40///
41/// This kind of hint should be used when we are certain that the
42/// introduction, removal, or modification of a particular (small!)
43/// amount of code will correct a compilation error. The compiler
44/// should also provide full recovery from such errors, such that
45/// suppressing the diagnostic output can still result in successful
46/// compilation.
47class FixItHint {
48public:
49  /// \brief Code that should be replaced to correct the error. Empty for an
50  /// insertion hint.
51  CharSourceRange RemoveRange;
52
53  /// \brief Code in the specific range that should be inserted in the insertion
54  /// location.
55  CharSourceRange InsertFromRange;
56
57  /// \brief The actual code to insert at the insertion location, as a
58  /// string.
59  std::string CodeToInsert;
60
61  bool BeforePreviousInsertions;
62
63  /// \brief Empty code modification hint, indicating that no code
64  /// modification is known.
65  FixItHint() : BeforePreviousInsertions(false) { }
66
67  bool isNull() const {
68    return !RemoveRange.isValid();
69  }
70
71  /// \brief Create a code modification hint that inserts the given
72  /// code string at a specific location.
73  static FixItHint CreateInsertion(SourceLocation InsertionLoc,
74                                   StringRef Code,
75                                   bool BeforePreviousInsertions = false) {
76    FixItHint Hint;
77    Hint.RemoveRange =
78      CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false);
79    Hint.CodeToInsert = Code;
80    Hint.BeforePreviousInsertions = BeforePreviousInsertions;
81    return Hint;
82  }
83
84  /// \brief Create a code modification hint that inserts the given
85  /// code from \arg FromRange at a specific location.
86  static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
87                                            CharSourceRange FromRange,
88                                        bool BeforePreviousInsertions = false) {
89    FixItHint Hint;
90    Hint.RemoveRange =
91      CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false);
92    Hint.InsertFromRange = FromRange;
93    Hint.BeforePreviousInsertions = BeforePreviousInsertions;
94    return Hint;
95  }
96
97  /// \brief Create a code modification hint that removes the given
98  /// source range.
99  static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
100    FixItHint Hint;
101    Hint.RemoveRange = RemoveRange;
102    return Hint;
103  }
104  static FixItHint CreateRemoval(SourceRange RemoveRange) {
105    return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
106  }
107
108  /// \brief Create a code modification hint that replaces the given
109  /// source range with the given code string.
110  static FixItHint CreateReplacement(CharSourceRange RemoveRange,
111                                     StringRef Code) {
112    FixItHint Hint;
113    Hint.RemoveRange = RemoveRange;
114    Hint.CodeToInsert = Code;
115    return Hint;
116  }
117
118  static FixItHint CreateReplacement(SourceRange RemoveRange,
119                                     StringRef Code) {
120    return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
121  }
122};
123
124/// DiagnosticsEngine - This concrete class is used by the front-end to report
125/// problems and issues.  It massages the diagnostics (e.g. handling things like
126/// "report warnings as errors" and passes them off to the DiagnosticConsumer
127/// for reporting to the user. DiagnosticsEngine is tied to one translation unit
128/// and one SourceManager.
129class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
130public:
131  /// Level - The level of the diagnostic, after it has been through mapping.
132  enum Level {
133    Ignored = DiagnosticIDs::Ignored,
134    Note = DiagnosticIDs::Note,
135    Warning = DiagnosticIDs::Warning,
136    Error = DiagnosticIDs::Error,
137    Fatal = DiagnosticIDs::Fatal
138  };
139
140  /// ExtensionHandling - How do we handle otherwise-unmapped extension?  This
141  /// is controlled by -pedantic and -pedantic-errors.
142  enum ExtensionHandling {
143    Ext_Ignore, Ext_Warn, Ext_Error
144  };
145
146  enum ArgumentKind {
147    ak_std_string,      // std::string
148    ak_c_string,        // const char *
149    ak_sint,            // int
150    ak_uint,            // unsigned
151    ak_identifierinfo,  // IdentifierInfo
152    ak_qualtype,        // QualType
153    ak_declarationname, // DeclarationName
154    ak_nameddecl,       // NamedDecl *
155    ak_nestednamespec,  // NestedNameSpecifier *
156    ak_declcontext      // DeclContext *
157  };
158
159  /// Specifies which overload candidates to display when overload resolution
160  /// fails.
161  enum OverloadsShown {
162    Ovl_All,  ///< Show all overloads.
163    Ovl_Best  ///< Show just the "best" overload candidates.
164  };
165
166  /// ArgumentValue - This typedef represents on argument value, which is a
167  /// union discriminated by ArgumentKind, with a value.
168  typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
169
170private:
171  unsigned char AllExtensionsSilenced; // Used by __extension__
172  bool IgnoreAllWarnings;        // Ignore all warnings: -w
173  bool WarningsAsErrors;         // Treat warnings like errors.
174  bool EnableAllWarnings;        // Enable all warnings.
175  bool ErrorsAsFatal;            // Treat errors like fatal errors.
176  bool SuppressSystemWarnings;   // Suppress warnings in system headers.
177  bool SuppressAllDiagnostics;   // Suppress all diagnostics.
178  OverloadsShown ShowOverloads;  // Which overload candidates to show.
179  unsigned ErrorLimit;           // Cap of # errors emitted, 0 -> no limit.
180  unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
181                                   // 0 -> no limit.
182  unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation
183                                    // backtrace stack, 0 -> no limit.
184  ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors?
185  IntrusiveRefCntPtr<DiagnosticIDs> Diags;
186  DiagnosticConsumer *Client;
187  bool OwnsDiagClient;
188  SourceManager *SourceMgr;
189
190  /// \brief Mapping information for diagnostics.  Mapping info is
191  /// packed into four bits per diagnostic.  The low three bits are the mapping
192  /// (an instance of diag::Mapping), or zero if unset.  The high bit is set
193  /// when the mapping was established as a user mapping.  If the high bit is
194  /// clear, then the low bits are set to the default value, and should be
195  /// mapped with -pedantic, -Werror, etc.
196  ///
197  /// A new DiagState is created and kept around when diagnostic pragmas modify
198  /// the state so that we know what is the diagnostic state at any given
199  /// source location.
200  class DiagState {
201    llvm::DenseMap<unsigned, DiagnosticMappingInfo> DiagMap;
202
203  public:
204    typedef llvm::DenseMap<unsigned, DiagnosticMappingInfo>::iterator
205      iterator;
206    typedef llvm::DenseMap<unsigned, DiagnosticMappingInfo>::const_iterator
207      const_iterator;
208
209    void setMappingInfo(diag::kind Diag, DiagnosticMappingInfo Info) {
210      DiagMap[Diag] = Info;
211    }
212
213    DiagnosticMappingInfo &getOrAddMappingInfo(diag::kind Diag);
214
215    const_iterator begin() const { return DiagMap.begin(); }
216    const_iterator end() const { return DiagMap.end(); }
217  };
218
219  /// \brief Keeps and automatically disposes all DiagStates that we create.
220  std::list<DiagState> DiagStates;
221
222  /// \brief Represents a point in source where the diagnostic state was
223  /// modified because of a pragma. 'Loc' can be null if the point represents
224  /// the diagnostic state modifications done through the command-line.
225  struct DiagStatePoint {
226    DiagState *State;
227    FullSourceLoc Loc;
228    DiagStatePoint(DiagState *State, FullSourceLoc Loc)
229      : State(State), Loc(Loc) { }
230
231    bool operator<(const DiagStatePoint &RHS) const {
232      // If Loc is invalid it means it came from <command-line>, in which case
233      // we regard it as coming before any valid source location.
234      if (RHS.Loc.isInvalid())
235        return false;
236      if (Loc.isInvalid())
237        return true;
238      return Loc.isBeforeInTranslationUnitThan(RHS.Loc);
239    }
240  };
241
242  /// \brief A vector of all DiagStatePoints representing changes in diagnostic
243  /// state due to diagnostic pragmas. The vector is always sorted according to
244  /// the SourceLocation of the DiagStatePoint.
245  typedef std::vector<DiagStatePoint> DiagStatePointsTy;
246  mutable DiagStatePointsTy DiagStatePoints;
247
248  /// \brief Keeps the DiagState that was active during each diagnostic 'push'
249  /// so we can get back at it when we 'pop'.
250  std::vector<DiagState *> DiagStateOnPushStack;
251
252  DiagState *GetCurDiagState() const {
253    assert(!DiagStatePoints.empty());
254    return DiagStatePoints.back().State;
255  }
256
257  void PushDiagStatePoint(DiagState *State, SourceLocation L) {
258    FullSourceLoc Loc(L, *SourceMgr);
259    // Make sure that DiagStatePoints is always sorted according to Loc.
260    assert((Loc.isValid() || DiagStatePoints.empty()) &&
261           "Adding invalid loc point after another point");
262    assert((Loc.isInvalid() || DiagStatePoints.empty() ||
263            DiagStatePoints.back().Loc.isInvalid() ||
264            DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) &&
265           "Previous point loc comes after or is the same as new one");
266    DiagStatePoints.push_back(DiagStatePoint(State,
267                                             FullSourceLoc(Loc, *SourceMgr)));
268  }
269
270  /// \brief Finds the DiagStatePoint that contains the diagnostic state of
271  /// the given source location.
272  DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const;
273
274  /// ErrorOccurred / FatalErrorOccurred - This is set to true when an error or
275  /// fatal error is emitted, and is sticky.
276  bool ErrorOccurred;
277  bool FatalErrorOccurred;
278
279  /// \brief Indicates that an unrecoverable error has occurred.
280  bool UnrecoverableErrorOccurred;
281
282  /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred
283  /// during a parsing section, e.g. during parsing a function.
284  unsigned TrapNumErrorsOccurred;
285  unsigned TrapNumUnrecoverableErrorsOccurred;
286
287  /// LastDiagLevel - This is the level of the last diagnostic emitted.  This is
288  /// used to emit continuation diagnostics with the same level as the
289  /// diagnostic that they follow.
290  DiagnosticIDs::Level LastDiagLevel;
291
292  unsigned NumWarnings;       // Number of warnings reported
293  unsigned NumErrors;         // Number of errors reported
294  unsigned NumErrorsSuppressed; // Number of errors suppressed
295
296  /// ArgToStringFn - A function pointer that converts an opaque diagnostic
297  /// argument to a strings.  This takes the modifiers and argument that was
298  /// present in the diagnostic.
299  ///
300  /// The PrevArgs array (whose length is NumPrevArgs) indicates the previous
301  /// arguments formatted for this diagnostic.  Implementations of this function
302  /// can use this information to avoid redundancy across arguments.
303  ///
304  /// This is a hack to avoid a layering violation between libbasic and libsema.
305  typedef void (*ArgToStringFnTy)(
306      ArgumentKind Kind, intptr_t Val,
307      const char *Modifier, unsigned ModifierLen,
308      const char *Argument, unsigned ArgumentLen,
309      const ArgumentValue *PrevArgs,
310      unsigned NumPrevArgs,
311      SmallVectorImpl<char> &Output,
312      void *Cookie,
313      ArrayRef<intptr_t> QualTypeVals);
314  void *ArgToStringCookie;
315  ArgToStringFnTy ArgToStringFn;
316
317  /// \brief ID of the "delayed" diagnostic, which is a (typically
318  /// fatal) diagnostic that had to be delayed because it was found
319  /// while emitting another diagnostic.
320  unsigned DelayedDiagID;
321
322  /// \brief First string argument for the delayed diagnostic.
323  std::string DelayedDiagArg1;
324
325  /// \brief Second string argument for the delayed diagnostic.
326  std::string DelayedDiagArg2;
327
328public:
329  explicit DiagnosticsEngine(
330                      const IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
331                      DiagnosticConsumer *client = 0,
332                      bool ShouldOwnClient = true);
333  ~DiagnosticsEngine();
334
335  const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
336    return Diags;
337  }
338
339  DiagnosticConsumer *getClient() { return Client; }
340  const DiagnosticConsumer *getClient() const { return Client; }
341
342  /// \brief Determine whether this \c DiagnosticsEngine object own its client.
343  bool ownsClient() const { return OwnsDiagClient; }
344
345  /// \brief Return the current diagnostic client along with ownership of that
346  /// client.
347  DiagnosticConsumer *takeClient() {
348    OwnsDiagClient = false;
349    return Client;
350  }
351
352  bool hasSourceManager() const { return SourceMgr != 0; }
353  SourceManager &getSourceManager() const {
354    assert(SourceMgr && "SourceManager not set!");
355    return *SourceMgr;
356  }
357  void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
358
359  //===--------------------------------------------------------------------===//
360  //  DiagnosticsEngine characterization methods, used by a client to customize
361  //  how diagnostics are emitted.
362  //
363
364  /// pushMappings - Copies the current DiagMappings and pushes the new copy
365  /// onto the top of the stack.
366  void pushMappings(SourceLocation Loc);
367
368  /// popMappings - Pops the current DiagMappings off the top of the stack
369  /// causing the new top of the stack to be the active mappings. Returns
370  /// true if the pop happens, false if there is only one DiagMapping on the
371  /// stack.
372  bool popMappings(SourceLocation Loc);
373
374  /// \brief Set the diagnostic client associated with this diagnostic object.
375  ///
376  /// \param ShouldOwnClient true if the diagnostic object should take
377  /// ownership of \c client.
378  void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
379
380  /// setErrorLimit - Specify a limit for the number of errors we should
381  /// emit before giving up.  Zero disables the limit.
382  void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
383
384  /// \brief Specify the maximum number of template instantiation
385  /// notes to emit along with a given diagnostic.
386  void setTemplateBacktraceLimit(unsigned Limit) {
387    TemplateBacktraceLimit = Limit;
388  }
389
390  /// \brief Retrieve the maximum number of template instantiation
391  /// notes to emit along with a given diagnostic.
392  unsigned getTemplateBacktraceLimit() const {
393    return TemplateBacktraceLimit;
394  }
395
396  /// \brief Specify the maximum number of constexpr evaluation
397  /// notes to emit along with a given diagnostic.
398  void setConstexprBacktraceLimit(unsigned Limit) {
399    ConstexprBacktraceLimit = Limit;
400  }
401
402  /// \brief Retrieve the maximum number of constexpr evaluation
403  /// notes to emit along with a given diagnostic.
404  unsigned getConstexprBacktraceLimit() const {
405    return ConstexprBacktraceLimit;
406  }
407
408  /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
409  /// ignored.  If this and WarningsAsErrors are both set, then this one wins.
410  void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
411  bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
412
413  /// setEnableAllWarnings - When set to true, any unmapped ignored warnings
414  /// are no longer ignored.  If this and IgnoreAllWarnings are both set,
415  /// then that one wins.
416  void setEnableAllWarnings(bool Val) { EnableAllWarnings = Val; }
417  bool getEnableAllWarnngs() const { return EnableAllWarnings; }
418
419  /// setWarningsAsErrors - When set to true, any warnings reported are issued
420  /// as errors.
421  void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
422  bool getWarningsAsErrors() const { return WarningsAsErrors; }
423
424  /// setErrorsAsFatal - When set to true, any error reported is made a
425  /// fatal error.
426  void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
427  bool getErrorsAsFatal() const { return ErrorsAsFatal; }
428
429  /// setSuppressSystemWarnings - When set to true mask warnings that
430  /// come from system headers.
431  void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
432  bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
433
434  /// \brief Suppress all diagnostics, to silence the front end when we
435  /// know that we don't want any more diagnostics to be passed along to the
436  /// client
437  void setSuppressAllDiagnostics(bool Val = true) {
438    SuppressAllDiagnostics = Val;
439  }
440  bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
441
442  /// \brief Specify which overload candidates to show when overload resolution
443  /// fails.  By default, we show all candidates.
444  void setShowOverloads(OverloadsShown Val) {
445    ShowOverloads = Val;
446  }
447  OverloadsShown getShowOverloads() const { return ShowOverloads; }
448
449  /// \brief Pretend that the last diagnostic issued was ignored. This can
450  /// be used by clients who suppress diagnostics themselves.
451  void setLastDiagnosticIgnored() {
452    LastDiagLevel = DiagnosticIDs::Ignored;
453  }
454
455  /// setExtensionHandlingBehavior - This controls whether otherwise-unmapped
456  /// extension diagnostics are mapped onto ignore/warning/error.  This
457  /// corresponds to the GCC -pedantic and -pedantic-errors option.
458  void setExtensionHandlingBehavior(ExtensionHandling H) {
459    ExtBehavior = H;
460  }
461  ExtensionHandling getExtensionHandlingBehavior() const { return ExtBehavior; }
462
463  /// AllExtensionsSilenced - This is a counter bumped when an __extension__
464  /// block is encountered.  When non-zero, all extension diagnostics are
465  /// entirely silenced, no matter how they are mapped.
466  void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
467  void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
468  bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
469
470  /// \brief This allows the client to specify that certain warnings are
471  /// ignored.
472  ///
473  /// Notes can never be mapped, errors can only be mapped to fatal, and
474  /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
475  ///
476  /// \param Loc The source location that this change of diagnostic state should
477  /// take affect. It can be null if we are setting the latest state.
478  void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
479                            SourceLocation Loc);
480
481  /// \brief Change an entire diagnostic group (e.g. "unknown-pragmas") to
482  /// have the specified mapping.
483  ///
484  /// \returns true (and ignores the request) if "Group" was unknown, false
485  /// otherwise.
486  ///
487  /// \param Loc The source location that this change of diagnostic state should
488  /// take affect. It can be null if we are setting the state from command-line.
489  bool setDiagnosticGroupMapping(StringRef Group, diag::Mapping Map,
490                                 SourceLocation Loc = SourceLocation());
491
492  /// \brief Set the warning-as-error flag for the given diagnostic.
493  ///
494  /// This function always only operates on the current diagnostic state.
495  void setDiagnosticWarningAsError(diag::kind Diag, bool Enabled);
496
497  /// \brief Set the warning-as-error flag for the given diagnostic group.
498  ///
499  /// This function always only operates on the current diagnostic state.
500  ///
501  /// \returns True if the given group is unknown, false otherwise.
502  bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
503
504  /// \brief Set the error-as-fatal flag for the given diagnostic.
505  ///
506  /// This function always only operates on the current diagnostic state.
507  void setDiagnosticErrorAsFatal(diag::kind Diag, bool Enabled);
508
509  /// \brief Set the error-as-fatal flag for the given diagnostic group.
510  ///
511  /// This function always only operates on the current diagnostic state.
512  ///
513  /// \returns True if the given group is unknown, false otherwise.
514  bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
515
516  /// \brief Add the specified mapping to all diagnostics.
517  ///
518  /// Mainly to be used by -Wno-everything to disable all warnings but allow
519  /// subsequent -W options to enable specific warnings.
520  void setMappingToAllDiagnostics(diag::Mapping Map,
521                                  SourceLocation Loc = SourceLocation());
522
523  bool hasErrorOccurred() const { return ErrorOccurred; }
524  bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
525
526  /// \brief Determine whether any kind of unrecoverable error has occurred.
527  bool hasUnrecoverableErrorOccurred() const {
528    return FatalErrorOccurred || UnrecoverableErrorOccurred;
529  }
530
531  unsigned getNumWarnings() const { return NumWarnings; }
532
533  void setNumWarnings(unsigned NumWarnings) {
534    this->NumWarnings = NumWarnings;
535  }
536
537  /// \brief Return an ID for a diagnostic with the specified message and level.
538  ///
539  /// If this is the first request for this diagnosic, it is registered and
540  /// created, otherwise the existing ID is returned.
541  unsigned getCustomDiagID(Level L, StringRef Message) {
542    return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message);
543  }
544
545  /// \brief Converts a diagnostic argument (as an intptr_t) into the string
546  /// that represents it.
547  void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
548                          const char *Modifier, unsigned ModLen,
549                          const char *Argument, unsigned ArgLen,
550                          const ArgumentValue *PrevArgs, unsigned NumPrevArgs,
551                          SmallVectorImpl<char> &Output,
552                          SmallVectorImpl<intptr_t> &QualTypeVals) const {
553    ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen,
554                  PrevArgs, NumPrevArgs, Output, ArgToStringCookie,
555                  QualTypeVals);
556  }
557
558  void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
559    ArgToStringFn = Fn;
560    ArgToStringCookie = Cookie;
561  }
562
563  /// \brief Reset the state of the diagnostic object to its initial
564  /// configuration.
565  void Reset();
566
567  //===--------------------------------------------------------------------===//
568  // DiagnosticsEngine classification and reporting interfaces.
569  //
570
571  /// \brief Based on the way the client configured the DiagnosticsEngine
572  /// object, classify the specified diagnostic ID into a Level, consumable by
573  /// the DiagnosticConsumer.
574  ///
575  /// \param Loc The source location we are interested in finding out the
576  /// diagnostic state. Can be null in order to query the latest state.
577  Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
578    return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
579  }
580
581  /// \brief Issue the message to the client.
582  ///
583  /// This actually returns an instance of DiagnosticBuilder which emits the
584  /// diagnostics (through @c ProcessDiag) when it is destroyed.
585  ///
586  /// \param DiagID A member of the @c diag::kind enum.
587  /// \param Loc Represents the source location associated with the diagnostic,
588  /// which can be an invalid location if no position information is available.
589  inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
590  inline DiagnosticBuilder Report(unsigned DiagID);
591
592  void Report(const StoredDiagnostic &storedDiag);
593
594  /// \brief Determine whethere there is already a diagnostic in flight.
595  bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
596
597  /// \brief Set the "delayed" diagnostic that will be emitted once
598  /// the current diagnostic completes.
599  ///
600  ///  If a diagnostic is already in-flight but the front end must
601  ///  report a problem (e.g., with an inconsistent file system
602  ///  state), this routine sets a "delayed" diagnostic that will be
603  ///  emitted after the current diagnostic completes. This should
604  ///  only be used for fatal errors detected at inconvenient
605  ///  times. If emitting a delayed diagnostic causes a second delayed
606  ///  diagnostic to be introduced, that second delayed diagnostic
607  ///  will be ignored.
608  ///
609  /// \param DiagID The ID of the diagnostic being delayed.
610  ///
611  /// \param Arg1 A string argument that will be provided to the
612  /// diagnostic. A copy of this string will be stored in the
613  /// DiagnosticsEngine object itself.
614  ///
615  /// \param Arg2 A string argument that will be provided to the
616  /// diagnostic. A copy of this string will be stored in the
617  /// DiagnosticsEngine object itself.
618  void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
619                            StringRef Arg2 = "");
620
621  /// \brief Clear out the current diagnostic.
622  void Clear() { CurDiagID = ~0U; }
623
624private:
625  /// \brief Report the delayed diagnostic.
626  void ReportDelayed();
627
628  // This is private state used by DiagnosticBuilder.  We put it here instead of
629  // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
630  // object.  This implementation choice means that we can only have one
631  // diagnostic "in flight" at a time, but this seems to be a reasonable
632  // tradeoff to keep these objects small.  Assertions verify that only one
633  // diagnostic is in flight at a time.
634  friend class DiagnosticIDs;
635  friend class DiagnosticBuilder;
636  friend class Diagnostic;
637  friend class PartialDiagnostic;
638  friend class DiagnosticErrorTrap;
639
640  /// \brief The location of the current diagnostic that is in flight.
641  SourceLocation CurDiagLoc;
642
643  /// \brief The ID of the current diagnostic that is in flight.
644  ///
645  /// This is set to ~0U when there is no diagnostic in flight.
646  unsigned CurDiagID;
647
648  enum {
649    /// \brief The maximum number of arguments we can hold.
650    ///
651    /// We currently
652    /// only support up to 10 arguments (%0-%9).  A single diagnostic with more
653    /// than that almost certainly has to be simplified anyway.
654    MaxArguments = 10,
655
656    /// \brief The maximum number of ranges we can hold.
657    MaxRanges = 10,
658
659    /// \brief The maximum number of ranges we can hold.
660    MaxFixItHints = 10
661  };
662
663  /// \brief The number of entries in Arguments.
664  signed char NumDiagArgs;
665  /// \brief The number of ranges in the DiagRanges array.
666  unsigned char NumDiagRanges;
667  /// \brief The number of hints in the DiagFixItHints array.
668  unsigned char NumDiagFixItHints;
669
670  /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
671  /// values, with one for each argument.  This specifies whether the argument
672  /// is in DiagArgumentsStr or in DiagArguments.
673  unsigned char DiagArgumentsKind[MaxArguments];
674
675  /// \brief holds the values of each string argument for the current
676  /// diagnostic.
677  ///
678  /// This is only used when the corresponding ArgumentKind is ak_std_string.
679  std::string DiagArgumentsStr[MaxArguments];
680
681  /// \brief The values for the various substitution positions.
682  ///
683  /// This is used when the argument is not an std::string.  The specific
684  /// value is mangled into an intptr_t and the interpretation depends on
685  /// exactly what sort of argument kind it is.
686  intptr_t DiagArgumentsVal[MaxArguments];
687
688  /// \brief The list of ranges added to this diagnostic.
689  CharSourceRange DiagRanges[MaxRanges];
690
691  /// \brief If valid, provides a hint with some code to insert, remove,
692  /// or modify at a particular position.
693  FixItHint DiagFixItHints[MaxFixItHints];
694
695  DiagnosticMappingInfo makeMappingInfo(diag::Mapping Map, SourceLocation L) {
696    bool isPragma = L.isValid();
697    DiagnosticMappingInfo MappingInfo = DiagnosticMappingInfo::Make(
698      Map, /*IsUser=*/true, isPragma);
699
700    // If this is a pragma mapping, then set the diagnostic mapping flags so
701    // that we override command line options.
702    if (isPragma) {
703      MappingInfo.setNoWarningAsError(true);
704      MappingInfo.setNoErrorAsFatal(true);
705    }
706
707    return MappingInfo;
708  }
709
710  /// \brief Used to report a diagnostic that is finally fully formed.
711  ///
712  /// \returns true if the diagnostic was emitted, false if it was suppressed.
713  bool ProcessDiag() {
714    return Diags->ProcessDiag(*this);
715  }
716
717  /// @name Diagnostic Emission
718  /// @{
719protected:
720  // Sema requires access to the following functions because the current design
721  // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
722  // access us directly to ensure we minimize the emitted code for the common
723  // Sema::Diag() patterns.
724  friend class Sema;
725
726  /// \brief Emit the current diagnostic and clear the diagnostic state.
727  bool EmitCurrentDiagnostic();
728
729  unsigned getCurrentDiagID() const { return CurDiagID; }
730
731  SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
732
733  /// @}
734
735  friend class ASTReader;
736  friend class ASTWriter;
737};
738
739/// \brief RAII class that determines when any errors have occurred
740/// between the time the instance was created and the time it was
741/// queried.
742class DiagnosticErrorTrap {
743  DiagnosticsEngine &Diag;
744  unsigned NumErrors;
745  unsigned NumUnrecoverableErrors;
746
747public:
748  explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
749    : Diag(Diag) { reset(); }
750
751  /// \brief Determine whether any errors have occurred since this
752  /// object instance was created.
753  bool hasErrorOccurred() const {
754    return Diag.TrapNumErrorsOccurred > NumErrors;
755  }
756
757  /// \brief Determine whether any unrecoverable errors have occurred since this
758  /// object instance was created.
759  bool hasUnrecoverableErrorOccurred() const {
760    return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
761  }
762
763  // Set to initial state of "no errors occurred".
764  void reset() {
765    NumErrors = Diag.TrapNumErrorsOccurred;
766    NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
767  }
768};
769
770//===----------------------------------------------------------------------===//
771// DiagnosticBuilder
772//===----------------------------------------------------------------------===//
773
774/// \brief A little helper class used to produce diagnostics.
775///
776/// This is constructed by the DiagnosticsEngine::Report method, and
777/// allows insertion of extra information (arguments and source ranges) into
778/// the currently "in flight" diagnostic.  When the temporary for the builder
779/// is destroyed, the diagnostic is issued.
780///
781/// Note that many of these will be created as temporary objects (many call
782/// sites), so we want them to be small and we never want their address taken.
783/// This ensures that compilers with somewhat reasonable optimizers will promote
784/// the common fields to registers, eliminating increments of the NumArgs field,
785/// for example.
786class DiagnosticBuilder {
787  mutable DiagnosticsEngine *DiagObj;
788  mutable unsigned NumArgs, NumRanges, NumFixits;
789
790  /// \brief Status variable indicating if this diagnostic is still active.
791  ///
792  // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
793  // but LLVM is not currently smart enough to eliminate the null check that
794  // Emit() would end up with if we used that as our status variable.
795  mutable bool IsActive;
796
797  void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
798  friend class DiagnosticsEngine;
799
800  DiagnosticBuilder()
801    : DiagObj(0), NumArgs(0), NumRanges(0), NumFixits(0), IsActive(false) { }
802
803  explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
804    : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixits(0), IsActive(true) {
805    assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
806  }
807
808  friend class PartialDiagnostic;
809
810protected:
811  void FlushCounts() {
812    DiagObj->NumDiagArgs = NumArgs;
813    DiagObj->NumDiagRanges = NumRanges;
814    DiagObj->NumDiagFixItHints = NumFixits;
815  }
816
817  /// \brief Clear out the current diagnostic.
818  void Clear() const {
819    DiagObj = 0;
820    IsActive = false;
821  }
822
823  /// \brief Determine whether this diagnostic is still active.
824  bool isActive() const { return IsActive; }
825
826  /// \brief Force the diagnostic builder to emit the diagnostic now.
827  ///
828  /// Once this function has been called, the DiagnosticBuilder object
829  /// should not be used again before it is destroyed.
830  ///
831  /// \returns true if a diagnostic was emitted, false if the
832  /// diagnostic was suppressed.
833  bool Emit() {
834    // If this diagnostic is inactive, then its soul was stolen by the copy ctor
835    // (or by a subclass, as in SemaDiagnosticBuilder).
836    if (!isActive()) return false;
837
838    // When emitting diagnostics, we set the final argument count into
839    // the DiagnosticsEngine object.
840    FlushCounts();
841
842    // Process the diagnostic.
843    bool Result = DiagObj->EmitCurrentDiagnostic();
844
845    // This diagnostic is dead.
846    Clear();
847
848    return Result;
849  }
850
851public:
852  /// Copy constructor.  When copied, this "takes" the diagnostic info from the
853  /// input and neuters it.
854  DiagnosticBuilder(const DiagnosticBuilder &D) {
855    DiagObj = D.DiagObj;
856    IsActive = D.IsActive;
857    D.Clear();
858    NumArgs = D.NumArgs;
859    NumRanges = D.NumRanges;
860    NumFixits = D.NumFixits;
861  }
862
863  /// \brief Retrieve an empty diagnostic builder.
864  static DiagnosticBuilder getEmpty() {
865    return DiagnosticBuilder();
866  }
867
868  /// \brief Emits the diagnostic.
869  ~DiagnosticBuilder() {
870    Emit();
871  }
872
873  /// Operator bool: conversion of DiagnosticBuilder to bool always returns
874  /// true.  This allows is to be used in boolean error contexts like:
875  /// return Diag(...);
876  operator bool() const { return true; }
877
878  void AddString(StringRef S) const {
879    assert(isActive() && "Clients must not add to cleared diagnostic!");
880    assert(NumArgs < DiagnosticsEngine::MaxArguments &&
881           "Too many arguments to diagnostic!");
882    DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
883    DiagObj->DiagArgumentsStr[NumArgs++] = S;
884  }
885
886  void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
887    assert(isActive() && "Clients must not add to cleared diagnostic!");
888    assert(NumArgs < DiagnosticsEngine::MaxArguments &&
889           "Too many arguments to diagnostic!");
890    DiagObj->DiagArgumentsKind[NumArgs] = Kind;
891    DiagObj->DiagArgumentsVal[NumArgs++] = V;
892  }
893
894  void AddSourceRange(const CharSourceRange &R) const {
895    assert(isActive() && "Clients must not add to cleared diagnostic!");
896    assert(NumRanges < DiagnosticsEngine::MaxRanges &&
897           "Too many arguments to diagnostic!");
898    DiagObj->DiagRanges[NumRanges++] = R;
899  }
900
901  void AddFixItHint(const FixItHint &Hint) const {
902    assert(isActive() && "Clients must not add to cleared diagnostic!");
903    assert(NumFixits < DiagnosticsEngine::MaxFixItHints &&
904           "Too many arguments to diagnostic!");
905    DiagObj->DiagFixItHints[NumFixits++] = Hint;
906  }
907};
908
909inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
910                                           StringRef S) {
911  DB.AddString(S);
912  return DB;
913}
914
915inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
916                                           const char *Str) {
917  DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
918                  DiagnosticsEngine::ak_c_string);
919  return DB;
920}
921
922inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
923  DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
924  return DB;
925}
926
927inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
928  DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
929  return DB;
930}
931
932inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
933                                           unsigned I) {
934  DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
935  return DB;
936}
937
938inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
939                                           const IdentifierInfo *II) {
940  DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
941                  DiagnosticsEngine::ak_identifierinfo);
942  return DB;
943}
944
945// Adds a DeclContext to the diagnostic. The enable_if template magic is here
946// so that we only match those arguments that are (statically) DeclContexts;
947// other arguments that derive from DeclContext (e.g., RecordDecls) will not
948// match.
949template<typename T>
950inline
951typename llvm::enable_if<llvm::is_same<T, DeclContext>,
952                         const DiagnosticBuilder &>::type
953operator<<(const DiagnosticBuilder &DB, T *DC) {
954  DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
955                  DiagnosticsEngine::ak_declcontext);
956  return DB;
957}
958
959inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
960                                           const SourceRange &R) {
961  DB.AddSourceRange(CharSourceRange::getTokenRange(R));
962  return DB;
963}
964
965inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
966                                           const CharSourceRange &R) {
967  DB.AddSourceRange(R);
968  return DB;
969}
970
971inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
972                                           const FixItHint &Hint) {
973  if (!Hint.isNull())
974    DB.AddFixItHint(Hint);
975  return DB;
976}
977
978inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
979                                            unsigned DiagID){
980  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
981  CurDiagLoc = Loc;
982  CurDiagID = DiagID;
983  return DiagnosticBuilder(this);
984}
985inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
986  return Report(SourceLocation(), DiagID);
987}
988
989//===----------------------------------------------------------------------===//
990// Diagnostic
991//===----------------------------------------------------------------------===//
992
993/// A little helper class (which is basically a smart pointer that forwards
994/// info from DiagnosticsEngine) that allows clients to enquire about the
995/// currently in-flight diagnostic.
996class Diagnostic {
997  const DiagnosticsEngine *DiagObj;
998  StringRef StoredDiagMessage;
999public:
1000  explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1001  Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1002    : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1003
1004  const DiagnosticsEngine *getDiags() const { return DiagObj; }
1005  unsigned getID() const { return DiagObj->CurDiagID; }
1006  const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1007  bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1008  SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1009
1010  unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1011
1012  /// getArgKind - Return the kind of the specified index.  Based on the kind
1013  /// of argument, the accessors below can be used to get the value.
1014  DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1015    assert(Idx < getNumArgs() && "Argument index out of range!");
1016    return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1017  }
1018
1019  /// getArgStdStr - Return the provided argument string specified by Idx.
1020  const std::string &getArgStdStr(unsigned Idx) const {
1021    assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1022           "invalid argument accessor!");
1023    return DiagObj->DiagArgumentsStr[Idx];
1024  }
1025
1026  /// getArgCStr - Return the specified C string argument.
1027  const char *getArgCStr(unsigned Idx) const {
1028    assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1029           "invalid argument accessor!");
1030    return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1031  }
1032
1033  /// getArgSInt - Return the specified signed integer argument.
1034  int getArgSInt(unsigned Idx) const {
1035    assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1036           "invalid argument accessor!");
1037    return (int)DiagObj->DiagArgumentsVal[Idx];
1038  }
1039
1040  /// getArgUInt - Return the specified unsigned integer argument.
1041  unsigned getArgUInt(unsigned Idx) const {
1042    assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1043           "invalid argument accessor!");
1044    return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1045  }
1046
1047  /// getArgIdentifier - Return the specified IdentifierInfo argument.
1048  const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1049    assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1050           "invalid argument accessor!");
1051    return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1052  }
1053
1054  /// getRawArg - Return the specified non-string argument in an opaque form.
1055  intptr_t getRawArg(unsigned Idx) const {
1056    assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1057           "invalid argument accessor!");
1058    return DiagObj->DiagArgumentsVal[Idx];
1059  }
1060
1061
1062  /// getNumRanges - Return the number of source ranges associated with this
1063  /// diagnostic.
1064  unsigned getNumRanges() const {
1065    return DiagObj->NumDiagRanges;
1066  }
1067
1068  const CharSourceRange &getRange(unsigned Idx) const {
1069    assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
1070    return DiagObj->DiagRanges[Idx];
1071  }
1072
1073  /// \brief Return an array reference for this diagnostic's ranges.
1074  ArrayRef<CharSourceRange> getRanges() const {
1075    return llvm::makeArrayRef(DiagObj->DiagRanges, DiagObj->NumDiagRanges);
1076  }
1077
1078  unsigned getNumFixItHints() const {
1079    return DiagObj->NumDiagFixItHints;
1080  }
1081
1082  const FixItHint &getFixItHint(unsigned Idx) const {
1083    assert(Idx < getNumFixItHints() && "Invalid index!");
1084    return DiagObj->DiagFixItHints[Idx];
1085  }
1086
1087  const FixItHint *getFixItHints() const {
1088    return getNumFixItHints()? DiagObj->DiagFixItHints : 0;
1089  }
1090
1091  /// FormatDiagnostic - Format this diagnostic into a string, substituting the
1092  /// formal arguments into the %0 slots.  The result is appended onto the Str
1093  /// array.
1094  void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1095
1096  /// FormatDiagnostic - Format the given format-string into the
1097  /// output buffer using the arguments stored in this diagnostic.
1098  void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1099                        SmallVectorImpl<char> &OutStr) const;
1100};
1101
1102/**
1103 * \brief Represents a diagnostic in a form that can be retained until its
1104 * corresponding source manager is destroyed.
1105 */
1106class StoredDiagnostic {
1107  unsigned ID;
1108  DiagnosticsEngine::Level Level;
1109  FullSourceLoc Loc;
1110  std::string Message;
1111  std::vector<CharSourceRange> Ranges;
1112  std::vector<FixItHint> FixIts;
1113
1114public:
1115  StoredDiagnostic();
1116  StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1117  StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1118                   StringRef Message);
1119  StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1120                   StringRef Message, FullSourceLoc Loc,
1121                   ArrayRef<CharSourceRange> Ranges,
1122                   ArrayRef<FixItHint> Fixits);
1123  ~StoredDiagnostic();
1124
1125  /// \brief Evaluates true when this object stores a diagnostic.
1126  operator bool() const { return Message.size() > 0; }
1127
1128  unsigned getID() const { return ID; }
1129  DiagnosticsEngine::Level getLevel() const { return Level; }
1130  const FullSourceLoc &getLocation() const { return Loc; }
1131  StringRef getMessage() const { return Message; }
1132
1133  void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1134
1135  typedef std::vector<CharSourceRange>::const_iterator range_iterator;
1136  range_iterator range_begin() const { return Ranges.begin(); }
1137  range_iterator range_end() const { return Ranges.end(); }
1138  unsigned range_size() const { return Ranges.size(); }
1139
1140  ArrayRef<CharSourceRange> getRanges() const {
1141    return llvm::makeArrayRef(Ranges);
1142  }
1143
1144
1145  typedef std::vector<FixItHint>::const_iterator fixit_iterator;
1146  fixit_iterator fixit_begin() const { return FixIts.begin(); }
1147  fixit_iterator fixit_end() const { return FixIts.end(); }
1148  unsigned fixit_size() const { return FixIts.size(); }
1149
1150  ArrayRef<FixItHint> getFixIts() const {
1151    return llvm::makeArrayRef(FixIts);
1152  }
1153};
1154
1155/// DiagnosticConsumer - This is an abstract interface implemented by clients of
1156/// the front-end, which formats and prints fully processed diagnostics.
1157class DiagnosticConsumer {
1158protected:
1159  unsigned NumWarnings;       // Number of warnings reported
1160  unsigned NumErrors;         // Number of errors reported
1161
1162public:
1163  DiagnosticConsumer() : NumWarnings(0), NumErrors(0) { }
1164
1165  unsigned getNumErrors() const { return NumErrors; }
1166  unsigned getNumWarnings() const { return NumWarnings; }
1167  virtual void clear() { NumWarnings = NumErrors = 0; }
1168
1169  virtual ~DiagnosticConsumer();
1170
1171  /// BeginSourceFile - Callback to inform the diagnostic client that processing
1172  /// of a source file is beginning.
1173  ///
1174  /// Note that diagnostics may be emitted outside the processing of a source
1175  /// file, for example during the parsing of command line options. However,
1176  /// diagnostics with source range information are required to only be emitted
1177  /// in between BeginSourceFile() and EndSourceFile().
1178  ///
1179  /// \arg LO - The language options for the source file being processed.
1180  /// \arg PP - The preprocessor object being used for the source; this optional
1181  /// and may not be present, for example when processing AST source files.
1182  virtual void BeginSourceFile(const LangOptions &LangOpts,
1183                               const Preprocessor *PP = 0) {}
1184
1185  /// EndSourceFile - Callback to inform the diagnostic client that processing
1186  /// of a source file has ended. The diagnostic client should assume that any
1187  /// objects made available via \see BeginSourceFile() are inaccessible.
1188  virtual void EndSourceFile() {}
1189
1190  /// \brief Callback to inform the diagnostic client that processing of all
1191  /// source files has ended.
1192  virtual void finish() {}
1193
1194  /// IncludeInDiagnosticCounts - This method (whose default implementation
1195  /// returns true) indicates whether the diagnostics handled by this
1196  /// DiagnosticConsumer should be included in the number of diagnostics
1197  /// reported by DiagnosticsEngine.
1198  virtual bool IncludeInDiagnosticCounts() const;
1199
1200  /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
1201  /// capturing it to a log as needed.
1202  ///
1203  /// Default implementation just keeps track of the total number of warnings
1204  /// and errors.
1205  virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1206                                const Diagnostic &Info);
1207
1208  /// \brief Clone the diagnostic consumer, producing an equivalent consumer
1209  /// that can be used in a different context.
1210  virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const = 0;
1211};
1212
1213/// IgnoringDiagConsumer - This is a diagnostic client that just ignores all
1214/// diags.
1215class IgnoringDiagConsumer : public DiagnosticConsumer {
1216  virtual void anchor();
1217  void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1218                        const Diagnostic &Info) {
1219    // Just ignore it.
1220  }
1221  DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
1222    return new IgnoringDiagConsumer();
1223  }
1224};
1225
1226}  // end namespace clang
1227
1228#endif
1229