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