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 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 
    340 public:
    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 
    684 private:
    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   /// @{
    781 protected:
    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.
    806 class DiagnosticErrorTrap {
    807   DiagnosticsEngine &Diag;
    808   unsigned NumErrors;
    809   unsigned NumUnrecoverableErrors;
    810 
    811 public:
    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.
    850 class 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 
    880 protected:
    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 
    922 public:
    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   bool hasMaxFixItHints() const {
    995     return NumFixits == DiagnosticsEngine::MaxFixItHints;
    996   }
    997 };
    998 
    999 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
   1000                                            StringRef S) {
   1001   DB.AddString(S);
   1002   return DB;
   1003 }
   1004 
   1005 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
   1006                                            const char *Str) {
   1007   DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
   1008                   DiagnosticsEngine::ak_c_string);
   1009   return DB;
   1010 }
   1011 
   1012 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
   1013   DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
   1014   return DB;
   1015 }
   1016 
   1017 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
   1018   DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
   1019   return DB;
   1020 }
   1021 
   1022 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
   1023                                            unsigned I) {
   1024   DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
   1025   return DB;
   1026 }
   1027 
   1028 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
   1029                                            const IdentifierInfo *II) {
   1030   DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
   1031                   DiagnosticsEngine::ak_identifierinfo);
   1032   return DB;
   1033 }
   1034 
   1035 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
   1036 // so that we only match those arguments that are (statically) DeclContexts;
   1037 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
   1038 // match.
   1039 template<typename T>
   1040 inline
   1041 typename llvm::enable_if<llvm::is_same<T, DeclContext>,
   1042                          const DiagnosticBuilder &>::type
   1043 operator<<(const DiagnosticBuilder &DB, T *DC) {
   1044   DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
   1045                   DiagnosticsEngine::ak_declcontext);
   1046   return DB;
   1047 }
   1048 
   1049 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
   1050                                            const SourceRange &R) {
   1051   DB.AddSourceRange(CharSourceRange::getTokenRange(R));
   1052   return DB;
   1053 }
   1054 
   1055 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
   1056                                            const CharSourceRange &R) {
   1057   DB.AddSourceRange(R);
   1058   return DB;
   1059 }
   1060 
   1061 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
   1062                                            const FixItHint &Hint) {
   1063   if (!Hint.isNull())
   1064     DB.AddFixItHint(Hint);
   1065   return DB;
   1066 }
   1067 
   1068 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
   1069                                             unsigned DiagID){
   1070   assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
   1071   CurDiagLoc = Loc;
   1072   CurDiagID = DiagID;
   1073   return DiagnosticBuilder(this);
   1074 }
   1075 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
   1076   return Report(SourceLocation(), DiagID);
   1077 }
   1078 
   1079 //===----------------------------------------------------------------------===//
   1080 // Diagnostic
   1081 //===----------------------------------------------------------------------===//
   1082 
   1083 /// A little helper class (which is basically a smart pointer that forwards
   1084 /// info from DiagnosticsEngine) that allows clients to enquire about the
   1085 /// currently in-flight diagnostic.
   1086 class Diagnostic {
   1087   const DiagnosticsEngine *DiagObj;
   1088   StringRef StoredDiagMessage;
   1089 public:
   1090   explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
   1091   Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
   1092     : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
   1093 
   1094   const DiagnosticsEngine *getDiags() const { return DiagObj; }
   1095   unsigned getID() const { return DiagObj->CurDiagID; }
   1096   const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
   1097   bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
   1098   SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
   1099 
   1100   unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
   1101 
   1102   /// \brief Return the kind of the specified index.
   1103   ///
   1104   /// Based on the kind of argument, the accessors below can be used to get
   1105   /// the value.
   1106   ///
   1107   /// \pre Idx < getNumArgs()
   1108   DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
   1109     assert(Idx < getNumArgs() && "Argument index out of range!");
   1110     return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
   1111   }
   1112 
   1113   /// \brief Return the provided argument string specified by \p Idx.
   1114   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
   1115   const std::string &getArgStdStr(unsigned Idx) const {
   1116     assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
   1117            "invalid argument accessor!");
   1118     return DiagObj->DiagArgumentsStr[Idx];
   1119   }
   1120 
   1121   /// \brief Return the specified C string argument.
   1122   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
   1123   const char *getArgCStr(unsigned Idx) const {
   1124     assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
   1125            "invalid argument accessor!");
   1126     return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
   1127   }
   1128 
   1129   /// \brief Return the specified signed integer argument.
   1130   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
   1131   int getArgSInt(unsigned Idx) const {
   1132     assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
   1133            "invalid argument accessor!");
   1134     return (int)DiagObj->DiagArgumentsVal[Idx];
   1135   }
   1136 
   1137   /// \brief Return the specified unsigned integer argument.
   1138   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
   1139   unsigned getArgUInt(unsigned Idx) const {
   1140     assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
   1141            "invalid argument accessor!");
   1142     return (unsigned)DiagObj->DiagArgumentsVal[Idx];
   1143   }
   1144 
   1145   /// \brief Return the specified IdentifierInfo argument.
   1146   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
   1147   const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
   1148     assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
   1149            "invalid argument accessor!");
   1150     return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
   1151   }
   1152 
   1153   /// \brief Return the specified non-string argument in an opaque form.
   1154   /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
   1155   intptr_t getRawArg(unsigned Idx) const {
   1156     assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
   1157            "invalid argument accessor!");
   1158     return DiagObj->DiagArgumentsVal[Idx];
   1159   }
   1160 
   1161   /// \brief Return the number of source ranges associated with this diagnostic.
   1162   unsigned getNumRanges() const {
   1163     return DiagObj->NumDiagRanges;
   1164   }
   1165 
   1166   /// \pre Idx < getNumRanges()
   1167   const CharSourceRange &getRange(unsigned Idx) const {
   1168     assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
   1169     return DiagObj->DiagRanges[Idx];
   1170   }
   1171 
   1172   /// \brief Return an array reference for this diagnostic's ranges.
   1173   ArrayRef<CharSourceRange> getRanges() const {
   1174     return llvm::makeArrayRef(DiagObj->DiagRanges, DiagObj->NumDiagRanges);
   1175   }
   1176 
   1177   unsigned getNumFixItHints() const {
   1178     return DiagObj->NumDiagFixItHints;
   1179   }
   1180 
   1181   const FixItHint &getFixItHint(unsigned Idx) const {
   1182     assert(Idx < getNumFixItHints() && "Invalid index!");
   1183     return DiagObj->DiagFixItHints[Idx];
   1184   }
   1185 
   1186   const FixItHint *getFixItHints() const {
   1187     return getNumFixItHints()? DiagObj->DiagFixItHints : 0;
   1188   }
   1189 
   1190   /// \brief Format this diagnostic into a string, substituting the
   1191   /// formal arguments into the %0 slots.
   1192   ///
   1193   /// The result is appended onto the \p OutStr array.
   1194   void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
   1195 
   1196   /// \brief Format the given format-string into the output buffer using the
   1197   /// arguments stored in this diagnostic.
   1198   void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
   1199                         SmallVectorImpl<char> &OutStr) const;
   1200 };
   1201 
   1202 /**
   1203  * \brief Represents a diagnostic in a form that can be retained until its
   1204  * corresponding source manager is destroyed.
   1205  */
   1206 class StoredDiagnostic {
   1207   unsigned ID;
   1208   DiagnosticsEngine::Level Level;
   1209   FullSourceLoc Loc;
   1210   std::string Message;
   1211   std::vector<CharSourceRange> Ranges;
   1212   std::vector<FixItHint> FixIts;
   1213 
   1214 public:
   1215   StoredDiagnostic();
   1216   StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
   1217   StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
   1218                    StringRef Message);
   1219   StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
   1220                    StringRef Message, FullSourceLoc Loc,
   1221                    ArrayRef<CharSourceRange> Ranges,
   1222                    ArrayRef<FixItHint> Fixits);
   1223   ~StoredDiagnostic();
   1224 
   1225   /// \brief Evaluates true when this object stores a diagnostic.
   1226   LLVM_EXPLICIT operator bool() const { return Message.size() > 0; }
   1227 
   1228   unsigned getID() const { return ID; }
   1229   DiagnosticsEngine::Level getLevel() const { return Level; }
   1230   const FullSourceLoc &getLocation() const { return Loc; }
   1231   StringRef getMessage() const { return Message; }
   1232 
   1233   void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
   1234 
   1235   typedef std::vector<CharSourceRange>::const_iterator range_iterator;
   1236   range_iterator range_begin() const { return Ranges.begin(); }
   1237   range_iterator range_end() const { return Ranges.end(); }
   1238   unsigned range_size() const { return Ranges.size(); }
   1239 
   1240   ArrayRef<CharSourceRange> getRanges() const {
   1241     return llvm::makeArrayRef(Ranges);
   1242   }
   1243 
   1244 
   1245   typedef std::vector<FixItHint>::const_iterator fixit_iterator;
   1246   fixit_iterator fixit_begin() const { return FixIts.begin(); }
   1247   fixit_iterator fixit_end() const { return FixIts.end(); }
   1248   unsigned fixit_size() const { return FixIts.size(); }
   1249 
   1250   ArrayRef<FixItHint> getFixIts() const {
   1251     return llvm::makeArrayRef(FixIts);
   1252   }
   1253 };
   1254 
   1255 /// \brief Abstract interface, implemented by clients of the front-end, which
   1256 /// formats and prints fully processed diagnostics.
   1257 class DiagnosticConsumer {
   1258 protected:
   1259   unsigned NumWarnings;       ///< Number of warnings reported
   1260   unsigned NumErrors;         ///< Number of errors reported
   1261 
   1262 public:
   1263   DiagnosticConsumer() : NumWarnings(0), NumErrors(0) { }
   1264 
   1265   unsigned getNumErrors() const { return NumErrors; }
   1266   unsigned getNumWarnings() const { return NumWarnings; }
   1267   virtual void clear() { NumWarnings = NumErrors = 0; }
   1268 
   1269   virtual ~DiagnosticConsumer();
   1270 
   1271   /// \brief Callback to inform the diagnostic client that processing
   1272   /// of a source file is beginning.
   1273   ///
   1274   /// Note that diagnostics may be emitted outside the processing of a source
   1275   /// file, for example during the parsing of command line options. However,
   1276   /// diagnostics with source range information are required to only be emitted
   1277   /// in between BeginSourceFile() and EndSourceFile().
   1278   ///
   1279   /// \param LangOpts The language options for the source file being processed.
   1280   /// \param PP The preprocessor object being used for the source; this is
   1281   /// optional, e.g., it may not be present when processing AST source files.
   1282   virtual void BeginSourceFile(const LangOptions &LangOpts,
   1283                                const Preprocessor *PP = 0) {}
   1284 
   1285   /// \brief Callback to inform the diagnostic client that processing
   1286   /// of a source file has ended.
   1287   ///
   1288   /// The diagnostic client should assume that any objects made available via
   1289   /// BeginSourceFile() are inaccessible.
   1290   virtual void EndSourceFile() {}
   1291 
   1292   /// \brief Callback to inform the diagnostic client that processing of all
   1293   /// source files has ended.
   1294   virtual void finish() {}
   1295 
   1296   /// \brief Indicates whether the diagnostics handled by this
   1297   /// DiagnosticConsumer should be included in the number of diagnostics
   1298   /// reported by DiagnosticsEngine.
   1299   ///
   1300   /// The default implementation returns true.
   1301   virtual bool IncludeInDiagnosticCounts() const;
   1302 
   1303   /// \brief Handle this diagnostic, reporting it to the user or
   1304   /// capturing it to a log as needed.
   1305   ///
   1306   /// The default implementation just keeps track of the total number of
   1307   /// warnings and errors.
   1308   virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
   1309                                 const Diagnostic &Info);
   1310 };
   1311 
   1312 /// \brief A diagnostic client that ignores all diagnostics.
   1313 class IgnoringDiagConsumer : public DiagnosticConsumer {
   1314   virtual void anchor();
   1315   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
   1316                         const Diagnostic &Info) {
   1317     // Just ignore it.
   1318   }
   1319 };
   1320 
   1321 /// \brief Diagnostic consumer that forwards diagnostics along to an
   1322 /// existing, already-initialized diagnostic consumer.
   1323 ///
   1324 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
   1325   DiagnosticConsumer &Target;
   1326 
   1327 public:
   1328   ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
   1329 
   1330   virtual ~ForwardingDiagnosticConsumer();
   1331 
   1332   virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
   1333                                 const Diagnostic &Info);
   1334   virtual void clear();
   1335 
   1336   virtual bool IncludeInDiagnosticCounts() const;
   1337 };
   1338 
   1339 // Struct used for sending info about how a type should be printed.
   1340 struct TemplateDiffTypes {
   1341   intptr_t FromType;
   1342   intptr_t ToType;
   1343   unsigned PrintTree : 1;
   1344   unsigned PrintFromType : 1;
   1345   unsigned ElideType : 1;
   1346   unsigned ShowColors : 1;
   1347   // The printer sets this variable to true if the template diff was used.
   1348   unsigned TemplateDiffUsed : 1;
   1349 };
   1350 
   1351 /// Special character that the diagnostic printer will use to toggle the bold
   1352 /// attribute.  The character itself will be not be printed.
   1353 const char ToggleHighlight = 127;
   1354 
   1355 }  // end namespace clang
   1356 
   1357 #endif
   1358