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