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