clang API Documentation

Diagnostic.h
Go to the documentation of this file.
00001 //===--- Diagnostic.h - C Language Family Diagnostic Handling ---*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 ///
00010 /// \file
00011 /// \brief Defines the Diagnostic-related interfaces.
00012 ///
00013 //===----------------------------------------------------------------------===//
00014 
00015 #ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
00016 #define LLVM_CLANG_BASIC_DIAGNOSTIC_H
00017 
00018 #include "clang/Basic/DiagnosticIDs.h"
00019 #include "clang/Basic/DiagnosticOptions.h"
00020 #include "clang/Basic/SourceLocation.h"
00021 #include "llvm/ADT/ArrayRef.h"
00022 #include "llvm/ADT/DenseMap.h"
00023 #include "llvm/ADT/IntrusiveRefCntPtr.h"
00024 #include "llvm/ADT/iterator_range.h"
00025 #include <list>
00026 #include <vector>
00027 
00028 namespace clang {
00029   class DeclContext;
00030   class DiagnosticBuilder;
00031   class DiagnosticConsumer;
00032   class DiagnosticErrorTrap;
00033   class DiagnosticOptions;
00034   class IdentifierInfo;
00035   class LangOptions;
00036   class Preprocessor;
00037   class StoredDiagnostic;
00038   namespace tok {
00039   enum TokenKind : unsigned short;
00040   }
00041 
00042 /// \brief Annotates a diagnostic with some code that should be
00043 /// inserted, removed, or replaced to fix the problem.
00044 ///
00045 /// This kind of hint should be used when we are certain that the
00046 /// introduction, removal, or modification of a particular (small!)
00047 /// amount of code will correct a compilation error. The compiler
00048 /// should also provide full recovery from such errors, such that
00049 /// suppressing the diagnostic output can still result in successful
00050 /// compilation.
00051 class FixItHint {
00052 public:
00053   /// \brief Code that should be replaced to correct the error. Empty for an
00054   /// insertion hint.
00055   CharSourceRange RemoveRange;
00056 
00057   /// \brief Code in the specific range that should be inserted in the insertion
00058   /// location.
00059   CharSourceRange InsertFromRange;
00060 
00061   /// \brief The actual code to insert at the insertion location, as a
00062   /// string.
00063   std::string CodeToInsert;
00064 
00065   bool BeforePreviousInsertions;
00066 
00067   /// \brief Empty code modification hint, indicating that no code
00068   /// modification is known.
00069   FixItHint() : BeforePreviousInsertions(false) { }
00070 
00071   bool isNull() const {
00072     return !RemoveRange.isValid();
00073   }
00074   
00075   /// \brief Create a code modification hint that inserts the given
00076   /// code string at a specific location.
00077   static FixItHint CreateInsertion(SourceLocation InsertionLoc,
00078                                    StringRef Code,
00079                                    bool BeforePreviousInsertions = false) {
00080     FixItHint Hint;
00081     Hint.RemoveRange =
00082       CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
00083     Hint.CodeToInsert = Code;
00084     Hint.BeforePreviousInsertions = BeforePreviousInsertions;
00085     return Hint;
00086   }
00087   
00088   /// \brief Create a code modification hint that inserts the given
00089   /// code from \p FromRange at a specific location.
00090   static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
00091                                             CharSourceRange FromRange,
00092                                         bool BeforePreviousInsertions = false) {
00093     FixItHint Hint;
00094     Hint.RemoveRange =
00095       CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
00096     Hint.InsertFromRange = FromRange;
00097     Hint.BeforePreviousInsertions = BeforePreviousInsertions;
00098     return Hint;
00099   }
00100 
00101   /// \brief Create a code modification hint that removes the given
00102   /// source range.
00103   static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
00104     FixItHint Hint;
00105     Hint.RemoveRange = RemoveRange;
00106     return Hint;
00107   }
00108   static FixItHint CreateRemoval(SourceRange RemoveRange) {
00109     return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
00110   }
00111   
00112   /// \brief Create a code modification hint that replaces the given
00113   /// source range with the given code string.
00114   static FixItHint CreateReplacement(CharSourceRange RemoveRange,
00115                                      StringRef Code) {
00116     FixItHint Hint;
00117     Hint.RemoveRange = RemoveRange;
00118     Hint.CodeToInsert = Code;
00119     return Hint;
00120   }
00121   
00122   static FixItHint CreateReplacement(SourceRange RemoveRange,
00123                                      StringRef Code) {
00124     return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
00125   }
00126 };
00127 
00128 /// \brief Concrete class used by the front-end to report problems and issues.
00129 ///
00130 /// This massages the diagnostics (e.g. handling things like "report warnings
00131 /// as errors" and passes them off to the DiagnosticConsumer for reporting to
00132 /// the user. DiagnosticsEngine is tied to one translation unit and one
00133 /// SourceManager.
00134 class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
00135   DiagnosticsEngine(const DiagnosticsEngine &) LLVM_DELETED_FUNCTION;
00136   void operator=(const DiagnosticsEngine &) LLVM_DELETED_FUNCTION;
00137 
00138 public:
00139   /// \brief The level of the diagnostic, after it has been through mapping.
00140   enum Level {
00141     Ignored = DiagnosticIDs::Ignored,
00142     Note = DiagnosticIDs::Note,
00143     Remark = DiagnosticIDs::Remark,
00144     Warning = DiagnosticIDs::Warning,
00145     Error = DiagnosticIDs::Error,
00146     Fatal = DiagnosticIDs::Fatal
00147   };
00148 
00149   enum ArgumentKind {
00150     ak_std_string,      ///< std::string
00151     ak_c_string,        ///< const char *
00152     ak_sint,            ///< int
00153     ak_uint,            ///< unsigned
00154     ak_tokenkind,       ///< enum TokenKind : unsigned
00155     ak_identifierinfo,  ///< IdentifierInfo
00156     ak_qualtype,        ///< QualType
00157     ak_declarationname, ///< DeclarationName
00158     ak_nameddecl,       ///< NamedDecl *
00159     ak_nestednamespec,  ///< NestedNameSpecifier *
00160     ak_declcontext,     ///< DeclContext *
00161     ak_qualtype_pair,   ///< pair<QualType, QualType>
00162     ak_attr             ///< Attr *
00163   };
00164 
00165   /// \brief Represents on argument value, which is a union discriminated
00166   /// by ArgumentKind, with a value.
00167   typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
00168 
00169 private:
00170   unsigned char AllExtensionsSilenced; // Used by __extension__
00171   bool IgnoreAllWarnings;        // Ignore all warnings: -w
00172   bool WarningsAsErrors;         // Treat warnings like errors.
00173   bool EnableAllWarnings;        // Enable all warnings.
00174   bool ErrorsAsFatal;            // Treat errors like fatal errors.
00175   bool SuppressSystemWarnings;   // Suppress warnings in system headers.
00176   bool SuppressAllDiagnostics;   // Suppress all diagnostics.
00177   bool ElideType;                // Elide common types of templates.
00178   bool PrintTemplateTree;        // Print a tree when comparing templates.
00179   bool ShowColors;               // Color printing is enabled.
00180   OverloadsShown ShowOverloads;  // Which overload candidates to show.
00181   unsigned ErrorLimit;           // Cap of # errors emitted, 0 -> no limit.
00182   unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
00183                                    // 0 -> no limit.
00184   unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation
00185                                     // backtrace stack, 0 -> no limit.
00186   diag::Severity ExtBehavior;       // Map extensions to warnings or errors?
00187   IntrusiveRefCntPtr<DiagnosticIDs> Diags;
00188   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
00189   DiagnosticConsumer *Client;
00190   std::unique_ptr<DiagnosticConsumer> Owner;
00191   SourceManager *SourceMgr;
00192 
00193   /// \brief Mapping information for diagnostics.
00194   ///
00195   /// Mapping info is packed into four bits per diagnostic.  The low three
00196   /// bits are the mapping (an instance of diag::Severity), or zero if unset.
00197   /// The high bit is set when the mapping was established as a user mapping.
00198   /// If the high bit is clear, then the low bits are set to the default
00199   /// value, and should be mapped with -pedantic, -Werror, etc.
00200   ///
00201   /// A new DiagState is created and kept around when diagnostic pragmas modify
00202   /// the state so that we know what is the diagnostic state at any given
00203   /// source location.
00204   class DiagState {
00205     llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
00206 
00207   public:
00208     typedef llvm::DenseMap<unsigned, DiagnosticMapping>::iterator iterator;
00209     typedef llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator
00210     const_iterator;
00211 
00212     void setMapping(diag::kind Diag, DiagnosticMapping Info) {
00213       DiagMap[Diag] = Info;
00214     }
00215 
00216     DiagnosticMapping &getOrAddMapping(diag::kind Diag);
00217 
00218     const_iterator begin() const { return DiagMap.begin(); }
00219     const_iterator end() const { return DiagMap.end(); }
00220   };
00221 
00222   /// \brief Keeps and automatically disposes all DiagStates that we create.
00223   std::list<DiagState> DiagStates;
00224 
00225   /// \brief Represents a point in source where the diagnostic state was
00226   /// modified because of a pragma.
00227   ///
00228   /// 'Loc' can be null if the point represents the diagnostic state
00229   /// modifications done through the command-line.
00230   struct DiagStatePoint {
00231     DiagState *State;
00232     FullSourceLoc Loc;
00233     DiagStatePoint(DiagState *State, FullSourceLoc Loc)
00234       : State(State), Loc(Loc) { } 
00235     
00236     bool operator<(const DiagStatePoint &RHS) const {
00237       // If Loc is invalid it means it came from <command-line>, in which case
00238       // we regard it as coming before any valid source location.
00239       if (RHS.Loc.isInvalid())
00240         return false;
00241       if (Loc.isInvalid())
00242         return true;
00243       return Loc.isBeforeInTranslationUnitThan(RHS.Loc);
00244     }
00245   };
00246 
00247   /// \brief A sorted vector of all DiagStatePoints representing changes in
00248   /// diagnostic state due to diagnostic pragmas.
00249   ///
00250   /// The vector is always sorted according to the SourceLocation of the
00251   /// DiagStatePoint.
00252   typedef std::vector<DiagStatePoint> DiagStatePointsTy;
00253   mutable DiagStatePointsTy DiagStatePoints;
00254 
00255   /// \brief Keeps the DiagState that was active during each diagnostic 'push'
00256   /// so we can get back at it when we 'pop'.
00257   std::vector<DiagState *> DiagStateOnPushStack;
00258 
00259   DiagState *GetCurDiagState() const {
00260     assert(!DiagStatePoints.empty());
00261     return DiagStatePoints.back().State;
00262   }
00263 
00264   void PushDiagStatePoint(DiagState *State, SourceLocation L) {
00265     FullSourceLoc Loc(L, getSourceManager());
00266     // Make sure that DiagStatePoints is always sorted according to Loc.
00267     assert(Loc.isValid() && "Adding invalid loc point");
00268     assert(!DiagStatePoints.empty() &&
00269            (DiagStatePoints.back().Loc.isInvalid() ||
00270             DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) &&
00271            "Previous point loc comes after or is the same as new one");
00272     DiagStatePoints.push_back(DiagStatePoint(State, Loc));
00273   }
00274 
00275   /// \brief Finds the DiagStatePoint that contains the diagnostic state of
00276   /// the given source location.
00277   DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const;
00278 
00279   /// \brief Sticky flag set to \c true when an error is emitted.
00280   bool ErrorOccurred;
00281 
00282   /// \brief Sticky flag set to \c true when an "uncompilable error" occurs.
00283   /// I.e. an error that was not upgraded from a warning by -Werror.
00284   bool UncompilableErrorOccurred;
00285 
00286   /// \brief Sticky flag set to \c true when a fatal error is emitted.
00287   bool FatalErrorOccurred;
00288 
00289   /// \brief Indicates that an unrecoverable error has occurred.
00290   bool UnrecoverableErrorOccurred;
00291   
00292   /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred
00293   /// during a parsing section, e.g. during parsing a function.
00294   unsigned TrapNumErrorsOccurred;
00295   unsigned TrapNumUnrecoverableErrorsOccurred;
00296 
00297   /// \brief The level of the last diagnostic emitted.
00298   ///
00299   /// This is used to emit continuation diagnostics with the same level as the
00300   /// diagnostic that they follow.
00301   DiagnosticIDs::Level LastDiagLevel;
00302 
00303   unsigned NumWarnings;         ///< Number of warnings reported
00304   unsigned NumErrors;           ///< Number of errors reported
00305 
00306   /// \brief A function pointer that converts an opaque diagnostic
00307   /// argument to a strings.
00308   ///
00309   /// This takes the modifiers and argument that was present in the diagnostic.
00310   ///
00311   /// The PrevArgs array indicates the previous arguments formatted for this
00312   /// diagnostic.  Implementations of this function can use this information to
00313   /// avoid redundancy across arguments.
00314   ///
00315   /// This is a hack to avoid a layering violation between libbasic and libsema.
00316   typedef void (*ArgToStringFnTy)(
00317       ArgumentKind Kind, intptr_t Val,
00318       StringRef Modifier, StringRef Argument,
00319       ArrayRef<ArgumentValue> PrevArgs,
00320       SmallVectorImpl<char> &Output,
00321       void *Cookie,
00322       ArrayRef<intptr_t> QualTypeVals);
00323   void *ArgToStringCookie;
00324   ArgToStringFnTy ArgToStringFn;
00325 
00326   /// \brief ID of the "delayed" diagnostic, which is a (typically
00327   /// fatal) diagnostic that had to be delayed because it was found
00328   /// while emitting another diagnostic.
00329   unsigned DelayedDiagID;
00330 
00331   /// \brief First string argument for the delayed diagnostic.
00332   std::string DelayedDiagArg1;
00333 
00334   /// \brief Second string argument for the delayed diagnostic.
00335   std::string DelayedDiagArg2;
00336 
00337   /// \brief Optional flag value.
00338   ///
00339   /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
00340   /// -Rpass=<value>. The content of this string is emitted after the flag name
00341   /// and '='.
00342   std::string FlagValue;
00343 
00344 public:
00345   explicit DiagnosticsEngine(
00346                       const IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
00347                       DiagnosticOptions *DiagOpts,
00348                       DiagnosticConsumer *client = nullptr,
00349                       bool ShouldOwnClient = true);
00350 
00351   const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
00352     return Diags;
00353   }
00354 
00355   /// \brief Retrieve the diagnostic options.
00356   DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
00357 
00358   typedef llvm::iterator_range<DiagState::const_iterator> diag_mapping_range;
00359 
00360   /// \brief Get the current set of diagnostic mappings.
00361   diag_mapping_range getDiagnosticMappings() const {
00362     const DiagState &DS = *GetCurDiagState();
00363     return diag_mapping_range(DS.begin(), DS.end());
00364   }
00365 
00366   DiagnosticConsumer *getClient() { return Client; }
00367   const DiagnosticConsumer *getClient() const { return Client; }
00368 
00369   /// \brief Determine whether this \c DiagnosticsEngine object own its client.
00370   bool ownsClient() const { return Owner != nullptr; }
00371 
00372   /// \brief Return the current diagnostic client along with ownership of that
00373   /// client.
00374   std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
00375 
00376   bool hasSourceManager() const { return SourceMgr != nullptr; }
00377   SourceManager &getSourceManager() const {
00378     assert(SourceMgr && "SourceManager not set!");
00379     return *SourceMgr;
00380   }
00381   void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
00382 
00383   //===--------------------------------------------------------------------===//
00384   //  DiagnosticsEngine characterization methods, used by a client to customize
00385   //  how diagnostics are emitted.
00386   //
00387 
00388   /// \brief Copies the current DiagMappings and pushes the new copy
00389   /// onto the top of the stack.
00390   void pushMappings(SourceLocation Loc);
00391 
00392   /// \brief Pops the current DiagMappings off the top of the stack,
00393   /// causing the new top of the stack to be the active mappings.
00394   ///
00395   /// \returns \c true if the pop happens, \c false if there is only one
00396   /// DiagMapping on the stack.
00397   bool popMappings(SourceLocation Loc);
00398 
00399   /// \brief Set the diagnostic client associated with this diagnostic object.
00400   ///
00401   /// \param ShouldOwnClient true if the diagnostic object should take
00402   /// ownership of \c client.
00403   void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
00404 
00405   /// \brief Specify a limit for the number of errors we should
00406   /// emit before giving up.
00407   ///
00408   /// Zero disables the limit.
00409   void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
00410   
00411   /// \brief Specify the maximum number of template instantiation
00412   /// notes to emit along with a given diagnostic.
00413   void setTemplateBacktraceLimit(unsigned Limit) {
00414     TemplateBacktraceLimit = Limit;
00415   }
00416 
00417   /// \brief Retrieve the maximum number of template instantiation
00418   /// notes to emit along with a given diagnostic.
00419   unsigned getTemplateBacktraceLimit() const {
00420     return TemplateBacktraceLimit;
00421   }
00422 
00423   /// \brief Specify the maximum number of constexpr evaluation
00424   /// notes to emit along with a given diagnostic.
00425   void setConstexprBacktraceLimit(unsigned Limit) {
00426     ConstexprBacktraceLimit = Limit;
00427   }
00428 
00429   /// \brief Retrieve the maximum number of constexpr evaluation
00430   /// notes to emit along with a given diagnostic.
00431   unsigned getConstexprBacktraceLimit() const {
00432     return ConstexprBacktraceLimit;
00433   }
00434 
00435   /// \brief When set to true, any unmapped warnings are ignored.
00436   ///
00437   /// If this and WarningsAsErrors are both set, then this one wins.
00438   void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
00439   bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
00440 
00441   /// \brief When set to true, any unmapped ignored warnings are no longer
00442   /// ignored.
00443   ///
00444   /// If this and IgnoreAllWarnings are both set, then that one wins.
00445   void setEnableAllWarnings(bool Val) { EnableAllWarnings = Val; }
00446   bool getEnableAllWarnings() const { return EnableAllWarnings; }
00447 
00448   /// \brief When set to true, any warnings reported are issued as errors.
00449   void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
00450   bool getWarningsAsErrors() const { return WarningsAsErrors; }
00451 
00452   /// \brief When set to true, any error reported is made a fatal error.
00453   void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
00454   bool getErrorsAsFatal() const { return ErrorsAsFatal; }
00455 
00456   /// \brief When set to true mask warnings that come from system headers.
00457   void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
00458   bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
00459 
00460   /// \brief Suppress all diagnostics, to silence the front end when we 
00461   /// know that we don't want any more diagnostics to be passed along to the
00462   /// client
00463   void setSuppressAllDiagnostics(bool Val = true) { 
00464     SuppressAllDiagnostics = Val; 
00465   }
00466   bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
00467 
00468   /// \brief Set type eliding, to skip outputting same types occurring in
00469   /// template types.
00470   void setElideType(bool Val = true) { ElideType = Val; }
00471   bool getElideType() { return ElideType; }
00472  
00473   /// \brief Set tree printing, to outputting the template difference in a
00474   /// tree format.
00475   void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
00476   bool getPrintTemplateTree() { return PrintTemplateTree; }
00477  
00478   /// \brief Set color printing, so the type diffing will inject color markers
00479   /// into the output.
00480   void setShowColors(bool Val = false) { ShowColors = Val; }
00481   bool getShowColors() { return ShowColors; }
00482 
00483   /// \brief Specify which overload candidates to show when overload resolution
00484   /// fails.
00485   ///
00486   /// By default, we show all candidates.
00487   void setShowOverloads(OverloadsShown Val) {
00488     ShowOverloads = Val;
00489   }
00490   OverloadsShown getShowOverloads() const { return ShowOverloads; }
00491   
00492   /// \brief Pretend that the last diagnostic issued was ignored, so any
00493   /// subsequent notes will be suppressed.
00494   ///
00495   /// This can be used by clients who suppress diagnostics themselves.
00496   void setLastDiagnosticIgnored() {
00497     if (LastDiagLevel == DiagnosticIDs::Fatal)
00498       FatalErrorOccurred = true;
00499     LastDiagLevel = DiagnosticIDs::Ignored;
00500   }
00501 
00502   /// \brief Determine whether the previous diagnostic was ignored. This can
00503   /// be used by clients that want to determine whether notes attached to a
00504   /// diagnostic will be suppressed.
00505   bool isLastDiagnosticIgnored() const {
00506     return LastDiagLevel == DiagnosticIDs::Ignored;
00507   }
00508 
00509   /// \brief Controls whether otherwise-unmapped extension diagnostics are
00510   /// mapped onto ignore/warning/error. 
00511   ///
00512   /// This corresponds to the GCC -pedantic and -pedantic-errors option.
00513   void setExtensionHandlingBehavior(diag::Severity H) { ExtBehavior = H; }
00514   diag::Severity getExtensionHandlingBehavior() const { return ExtBehavior; }
00515 
00516   /// \brief Counter bumped when an __extension__  block is/ encountered.
00517   ///
00518   /// When non-zero, all extension diagnostics are entirely silenced, no
00519   /// matter how they are mapped.
00520   void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
00521   void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
00522   bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
00523 
00524   /// \brief This allows the client to specify that certain warnings are
00525   /// ignored.
00526   ///
00527   /// Notes can never be mapped, errors can only be mapped to fatal, and
00528   /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
00529   ///
00530   /// \param Loc The source location that this change of diagnostic state should
00531   /// take affect. It can be null if we are setting the latest state.
00532   void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
00533 
00534   /// \brief Change an entire diagnostic group (e.g. "unknown-pragmas") to
00535   /// have the specified mapping.
00536   ///
00537   /// \returns true (and ignores the request) if "Group" was unknown, false
00538   /// otherwise.
00539   ///
00540   /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
00541   /// state of the -Wfoo group and vice versa.
00542   ///
00543   /// \param Loc The source location that this change of diagnostic state should
00544   /// take affect. It can be null if we are setting the state from command-line.
00545   bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
00546                            diag::Severity Map,
00547                            SourceLocation Loc = SourceLocation());
00548 
00549   /// \brief Set the warning-as-error flag for the given diagnostic group.
00550   ///
00551   /// This function always only operates on the current diagnostic state.
00552   ///
00553   /// \returns True if the given group is unknown, false otherwise.
00554   bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
00555 
00556   /// \brief Set the error-as-fatal flag for the given diagnostic group.
00557   ///
00558   /// This function always only operates on the current diagnostic state.
00559   ///
00560   /// \returns True if the given group is unknown, false otherwise.
00561   bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
00562 
00563   /// \brief Add the specified mapping to all diagnostics of the specified
00564   /// flavor.
00565   ///
00566   /// Mainly to be used by -Wno-everything to disable all warnings but allow
00567   /// subsequent -W options to enable specific warnings.
00568   void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
00569                          SourceLocation Loc = SourceLocation());
00570 
00571   bool hasErrorOccurred() const { return ErrorOccurred; }
00572 
00573   /// \brief Errors that actually prevent compilation, not those that are
00574   /// upgraded from a warning by -Werror.
00575   bool hasUncompilableErrorOccurred() const {
00576     return UncompilableErrorOccurred;
00577   }
00578   bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
00579   
00580   /// \brief Determine whether any kind of unrecoverable error has occurred.
00581   bool hasUnrecoverableErrorOccurred() const {
00582     return FatalErrorOccurred || UnrecoverableErrorOccurred;
00583   }
00584   
00585   unsigned getNumWarnings() const { return NumWarnings; }
00586 
00587   void setNumWarnings(unsigned NumWarnings) {
00588     this->NumWarnings = NumWarnings;
00589   }
00590 
00591   /// \brief Return an ID for a diagnostic with the specified format string and
00592   /// level.
00593   ///
00594   /// If this is the first request for this diagnostic, it is registered and
00595   /// created, otherwise the existing ID is returned.
00596   ///
00597   /// \param FormatString A fixed diagnostic format string that will be hashed
00598   /// and mapped to a unique DiagID.
00599   template <unsigned N>
00600   unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
00601     return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
00602                                   StringRef(FormatString, N - 1));
00603   }
00604 
00605   /// \brief Converts a diagnostic argument (as an intptr_t) into the string
00606   /// that represents it.
00607   void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
00608                           StringRef Modifier, StringRef Argument,
00609                           ArrayRef<ArgumentValue> PrevArgs,
00610                           SmallVectorImpl<char> &Output,
00611                           ArrayRef<intptr_t> QualTypeVals) const {
00612     ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
00613                   ArgToStringCookie, QualTypeVals);
00614   }
00615 
00616   void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
00617     ArgToStringFn = Fn;
00618     ArgToStringCookie = Cookie;
00619   }
00620 
00621   /// \brief Note that the prior diagnostic was emitted by some other
00622   /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
00623   void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
00624     LastDiagLevel = Other.LastDiagLevel;
00625   }
00626 
00627   /// \brief Reset the state of the diagnostic object to its initial 
00628   /// configuration.
00629   void Reset();
00630   
00631   //===--------------------------------------------------------------------===//
00632   // DiagnosticsEngine classification and reporting interfaces.
00633   //
00634 
00635   /// \brief Determine whether the diagnostic is known to be ignored.
00636   ///
00637   /// This can be used to opportunistically avoid expensive checks when it's
00638   /// known for certain that the diagnostic has been suppressed at the
00639   /// specified location \p Loc.
00640   ///
00641   /// \param Loc The source location we are interested in finding out the
00642   /// diagnostic state. Can be null in order to query the latest state.
00643   bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
00644     return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
00645            diag::Severity::Ignored;
00646   }
00647 
00648   /// \brief Based on the way the client configured the DiagnosticsEngine
00649   /// object, classify the specified diagnostic ID into a Level, consumable by
00650   /// the DiagnosticConsumer.
00651   ///
00652   /// To preserve invariant assumptions, this function should not be used to
00653   /// influence parse or semantic analysis actions. Instead consider using
00654   /// \c isIgnored().
00655   ///
00656   /// \param Loc The source location we are interested in finding out the
00657   /// diagnostic state. Can be null in order to query the latest state.
00658   Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
00659     return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
00660   }
00661 
00662   /// \brief Issue the message to the client.
00663   ///
00664   /// This actually returns an instance of DiagnosticBuilder which emits the
00665   /// diagnostics (through @c ProcessDiag) when it is destroyed.
00666   ///
00667   /// \param DiagID A member of the @c diag::kind enum.
00668   /// \param Loc Represents the source location associated with the diagnostic,
00669   /// which can be an invalid location if no position information is available.
00670   inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
00671   inline DiagnosticBuilder Report(unsigned DiagID);
00672 
00673   void Report(const StoredDiagnostic &storedDiag);
00674 
00675   /// \brief Determine whethere there is already a diagnostic in flight.
00676   bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
00677 
00678   /// \brief Set the "delayed" diagnostic that will be emitted once
00679   /// the current diagnostic completes.
00680   ///
00681   ///  If a diagnostic is already in-flight but the front end must
00682   ///  report a problem (e.g., with an inconsistent file system
00683   ///  state), this routine sets a "delayed" diagnostic that will be
00684   ///  emitted after the current diagnostic completes. This should
00685   ///  only be used for fatal errors detected at inconvenient
00686   ///  times. If emitting a delayed diagnostic causes a second delayed
00687   ///  diagnostic to be introduced, that second delayed diagnostic
00688   ///  will be ignored.
00689   ///
00690   /// \param DiagID The ID of the diagnostic being delayed.
00691   ///
00692   /// \param Arg1 A string argument that will be provided to the
00693   /// diagnostic. A copy of this string will be stored in the
00694   /// DiagnosticsEngine object itself.
00695   ///
00696   /// \param Arg2 A string argument that will be provided to the
00697   /// diagnostic. A copy of this string will be stored in the
00698   /// DiagnosticsEngine object itself.
00699   void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
00700                             StringRef Arg2 = "");
00701   
00702   /// \brief Clear out the current diagnostic.
00703   void Clear() { CurDiagID = ~0U; }
00704 
00705   /// \brief Return the value associated with this diagnostic flag.
00706   StringRef getFlagValue() const { return FlagValue; }
00707 
00708 private:
00709   /// \brief Report the delayed diagnostic.
00710   void ReportDelayed();
00711 
00712   // This is private state used by DiagnosticBuilder.  We put it here instead of
00713   // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
00714   // object.  This implementation choice means that we can only have one
00715   // diagnostic "in flight" at a time, but this seems to be a reasonable
00716   // tradeoff to keep these objects small.  Assertions verify that only one
00717   // diagnostic is in flight at a time.
00718   friend class DiagnosticIDs;
00719   friend class DiagnosticBuilder;
00720   friend class Diagnostic;
00721   friend class PartialDiagnostic;
00722   friend class DiagnosticErrorTrap;
00723   
00724   /// \brief The location of the current diagnostic that is in flight.
00725   SourceLocation CurDiagLoc;
00726 
00727   /// \brief The ID of the current diagnostic that is in flight.
00728   ///
00729   /// This is set to ~0U when there is no diagnostic in flight.
00730   unsigned CurDiagID;
00731 
00732   enum {
00733     /// \brief The maximum number of arguments we can hold.
00734     ///
00735     /// We currently only support up to 10 arguments (%0-%9).  A single
00736     /// diagnostic with more than that almost certainly has to be simplified
00737     /// anyway.
00738     MaxArguments = 10,
00739   };
00740 
00741   /// \brief The number of entries in Arguments.
00742   signed char NumDiagArgs;
00743 
00744   /// \brief Specifies whether an argument is in DiagArgumentsStr or
00745   /// in DiagArguments.
00746   ///
00747   /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
00748   /// argument.
00749   unsigned char DiagArgumentsKind[MaxArguments];
00750 
00751   /// \brief Holds the values of each string argument for the current
00752   /// diagnostic.
00753   ///
00754   /// This is only used when the corresponding ArgumentKind is ak_std_string.
00755   std::string DiagArgumentsStr[MaxArguments];
00756 
00757   /// \brief The values for the various substitution positions.
00758   ///
00759   /// This is used when the argument is not an std::string.  The specific
00760   /// value is mangled into an intptr_t and the interpretation depends on
00761   /// exactly what sort of argument kind it is.
00762   intptr_t DiagArgumentsVal[MaxArguments];
00763 
00764   /// \brief The list of ranges added to this diagnostic.
00765   SmallVector<CharSourceRange, 8> DiagRanges;
00766 
00767   /// \brief If valid, provides a hint with some code to insert, remove,
00768   /// or modify at a particular position.
00769   SmallVector<FixItHint, 8> DiagFixItHints;
00770 
00771   DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
00772     bool isPragma = L.isValid();
00773     DiagnosticMapping Mapping =
00774         DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
00775 
00776     // If this is a pragma mapping, then set the diagnostic mapping flags so
00777     // that we override command line options.
00778     if (isPragma) {
00779       Mapping.setNoWarningAsError(true);
00780       Mapping.setNoErrorAsFatal(true);
00781     }
00782 
00783     return Mapping;
00784   }
00785 
00786   /// \brief Used to report a diagnostic that is finally fully formed.
00787   ///
00788   /// \returns true if the diagnostic was emitted, false if it was suppressed.
00789   bool ProcessDiag() {
00790     return Diags->ProcessDiag(*this);
00791   }
00792 
00793   /// @name Diagnostic Emission
00794   /// @{
00795 protected:
00796   // Sema requires access to the following functions because the current design
00797   // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
00798   // access us directly to ensure we minimize the emitted code for the common
00799   // Sema::Diag() patterns.
00800   friend class Sema;
00801 
00802   /// \brief Emit the current diagnostic and clear the diagnostic state.
00803   ///
00804   /// \param Force Emit the diagnostic regardless of suppression settings.
00805   bool EmitCurrentDiagnostic(bool Force = false);
00806 
00807   unsigned getCurrentDiagID() const { return CurDiagID; }
00808 
00809   SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
00810 
00811   /// @}
00812 
00813   friend class ASTReader;
00814   friend class ASTWriter;
00815 };
00816 
00817 /// \brief RAII class that determines when any errors have occurred
00818 /// between the time the instance was created and the time it was
00819 /// queried.
00820 class DiagnosticErrorTrap {
00821   DiagnosticsEngine &Diag;
00822   unsigned NumErrors;
00823   unsigned NumUnrecoverableErrors;
00824 
00825 public:
00826   explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
00827     : Diag(Diag) { reset(); }
00828 
00829   /// \brief Determine whether any errors have occurred since this
00830   /// object instance was created.
00831   bool hasErrorOccurred() const {
00832     return Diag.TrapNumErrorsOccurred > NumErrors;
00833   }
00834 
00835   /// \brief Determine whether any unrecoverable errors have occurred since this
00836   /// object instance was created.
00837   bool hasUnrecoverableErrorOccurred() const {
00838     return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
00839   }
00840 
00841   /// \brief Set to initial state of "no errors occurred".
00842   void reset() {
00843     NumErrors = Diag.TrapNumErrorsOccurred;
00844     NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
00845   }
00846 };
00847 
00848 //===----------------------------------------------------------------------===//
00849 // DiagnosticBuilder
00850 //===----------------------------------------------------------------------===//
00851 
00852 /// \brief A little helper class used to produce diagnostics.
00853 ///
00854 /// This is constructed by the DiagnosticsEngine::Report method, and
00855 /// allows insertion of extra information (arguments and source ranges) into
00856 /// the currently "in flight" diagnostic.  When the temporary for the builder
00857 /// is destroyed, the diagnostic is issued.
00858 ///
00859 /// Note that many of these will be created as temporary objects (many call
00860 /// sites), so we want them to be small and we never want their address taken.
00861 /// This ensures that compilers with somewhat reasonable optimizers will promote
00862 /// the common fields to registers, eliminating increments of the NumArgs field,
00863 /// for example.
00864 class DiagnosticBuilder {
00865   mutable DiagnosticsEngine *DiagObj;
00866   mutable unsigned NumArgs;
00867 
00868   /// \brief Status variable indicating if this diagnostic is still active.
00869   ///
00870   // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
00871   // but LLVM is not currently smart enough to eliminate the null check that
00872   // Emit() would end up with if we used that as our status variable.
00873   mutable bool IsActive;
00874 
00875   /// \brief Flag indicating that this diagnostic is being emitted via a
00876   /// call to ForceEmit.
00877   mutable bool IsForceEmit;
00878 
00879   void operator=(const DiagnosticBuilder &) LLVM_DELETED_FUNCTION;
00880   friend class DiagnosticsEngine;
00881 
00882   DiagnosticBuilder()
00883       : DiagObj(nullptr), NumArgs(0), IsActive(false), IsForceEmit(false) {}
00884 
00885   explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
00886       : DiagObj(diagObj), NumArgs(0), IsActive(true), IsForceEmit(false) {
00887     assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
00888     diagObj->DiagRanges.clear();
00889     diagObj->DiagFixItHints.clear();
00890   }
00891 
00892   friend class PartialDiagnostic;
00893   
00894 protected:
00895   void FlushCounts() {
00896     DiagObj->NumDiagArgs = NumArgs;
00897   }
00898 
00899   /// \brief Clear out the current diagnostic.
00900   void Clear() const {
00901     DiagObj = nullptr;
00902     IsActive = false;
00903     IsForceEmit = false;
00904   }
00905 
00906   /// \brief Determine whether this diagnostic is still active.
00907   bool isActive() const { return IsActive; }
00908 
00909   /// \brief Force the diagnostic builder to emit the diagnostic now.
00910   ///
00911   /// Once this function has been called, the DiagnosticBuilder object
00912   /// should not be used again before it is destroyed.
00913   ///
00914   /// \returns true if a diagnostic was emitted, false if the
00915   /// diagnostic was suppressed.
00916   bool Emit() {
00917     // If this diagnostic is inactive, then its soul was stolen by the copy ctor
00918     // (or by a subclass, as in SemaDiagnosticBuilder).
00919     if (!isActive()) return false;
00920 
00921     // When emitting diagnostics, we set the final argument count into
00922     // the DiagnosticsEngine object.
00923     FlushCounts();
00924 
00925     // Process the diagnostic.
00926     bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
00927 
00928     // This diagnostic is dead.
00929     Clear();
00930 
00931     return Result;
00932   }
00933   
00934 public:
00935   /// Copy constructor.  When copied, this "takes" the diagnostic info from the
00936   /// input and neuters it.
00937   DiagnosticBuilder(const DiagnosticBuilder &D) {
00938     DiagObj = D.DiagObj;
00939     IsActive = D.IsActive;
00940     IsForceEmit = D.IsForceEmit;
00941     D.Clear();
00942     NumArgs = D.NumArgs;
00943   }
00944 
00945   /// \brief Retrieve an empty diagnostic builder.
00946   static DiagnosticBuilder getEmpty() {
00947     return DiagnosticBuilder();
00948   }
00949 
00950   /// \brief Emits the diagnostic.
00951   ~DiagnosticBuilder() {
00952     Emit();
00953   }
00954   
00955   /// \brief Forces the diagnostic to be emitted.
00956   const DiagnosticBuilder &setForceEmit() const {
00957     IsForceEmit = true;
00958     return *this;
00959   }
00960 
00961   /// \brief Conversion of DiagnosticBuilder to bool always returns \c true.
00962   ///
00963   /// This allows is to be used in boolean error contexts (where \c true is
00964   /// used to indicate that an error has occurred), like:
00965   /// \code
00966   /// return Diag(...);
00967   /// \endcode
00968   operator bool() const { return true; }
00969 
00970   void AddString(StringRef S) const {
00971     assert(isActive() && "Clients must not add to cleared diagnostic!");
00972     assert(NumArgs < DiagnosticsEngine::MaxArguments &&
00973            "Too many arguments to diagnostic!");
00974     DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
00975     DiagObj->DiagArgumentsStr[NumArgs++] = S;
00976   }
00977 
00978   void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
00979     assert(isActive() && "Clients must not add to cleared diagnostic!");
00980     assert(NumArgs < DiagnosticsEngine::MaxArguments &&
00981            "Too many arguments to diagnostic!");
00982     DiagObj->DiagArgumentsKind[NumArgs] = Kind;
00983     DiagObj->DiagArgumentsVal[NumArgs++] = V;
00984   }
00985 
00986   void AddSourceRange(const CharSourceRange &R) const {
00987     assert(isActive() && "Clients must not add to cleared diagnostic!");
00988     DiagObj->DiagRanges.push_back(R);
00989   }
00990 
00991   void AddFixItHint(const FixItHint &Hint) const {
00992     assert(isActive() && "Clients must not add to cleared diagnostic!");
00993     DiagObj->DiagFixItHints.push_back(Hint);
00994   }
00995 
00996   void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
00997 };
00998 
00999 struct AddFlagValue {
01000   explicit AddFlagValue(StringRef V) : Val(V) {}
01001   StringRef Val;
01002 };
01003 
01004 /// \brief Register a value for the flag in the current diagnostic. This
01005 /// value will be shown as the suffix "=value" after the flag name. It is
01006 /// useful in cases where the diagnostic flag accepts values (e.g.,
01007 /// -Rpass or -Wframe-larger-than).
01008 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
01009                                            const AddFlagValue V) {
01010   DB.addFlagValue(V.Val);
01011   return DB;
01012 }
01013 
01014 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
01015                                            StringRef S) {
01016   DB.AddString(S);
01017   return DB;
01018 }
01019 
01020 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
01021                                            const char *Str) {
01022   DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
01023                   DiagnosticsEngine::ak_c_string);
01024   return DB;
01025 }
01026 
01027 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
01028   DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
01029   return DB;
01030 }
01031 
01032 // We use enable_if here to prevent that this overload is selected for
01033 // pointers or other arguments that are implicitly convertible to bool.
01034 template <typename T>
01035 inline
01036 typename std::enable_if<std::is_same<T, bool>::value,
01037                         const DiagnosticBuilder &>::type
01038 operator<<(const DiagnosticBuilder &DB, T I) {
01039   DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
01040   return DB;
01041 }
01042 
01043 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
01044                                            unsigned I) {
01045   DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
01046   return DB;
01047 }
01048 
01049 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
01050                                            tok::TokenKind I) {
01051   DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
01052   return DB;
01053 }
01054 
01055 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
01056                                            const IdentifierInfo *II) {
01057   DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
01058                   DiagnosticsEngine::ak_identifierinfo);
01059   return DB;
01060 }
01061 
01062 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
01063 // so that we only match those arguments that are (statically) DeclContexts;
01064 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
01065 // match.
01066 template<typename T>
01067 inline
01068 typename std::enable_if<std::is_same<T, DeclContext>::value,
01069                         const DiagnosticBuilder &>::type
01070 operator<<(const DiagnosticBuilder &DB, T *DC) {
01071   DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
01072                   DiagnosticsEngine::ak_declcontext);
01073   return DB;
01074 }
01075 
01076 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
01077                                            const SourceRange &R) {
01078   DB.AddSourceRange(CharSourceRange::getTokenRange(R));
01079   return DB;
01080 }
01081 
01082 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
01083                                            ArrayRef<SourceRange> Ranges) {
01084   for (const SourceRange &R: Ranges)
01085     DB.AddSourceRange(CharSourceRange::getTokenRange(R));
01086   return DB;
01087 }
01088 
01089 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
01090                                            const CharSourceRange &R) {
01091   DB.AddSourceRange(R);
01092   return DB;
01093 }
01094 
01095 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
01096                                            const FixItHint &Hint) {
01097   if (!Hint.isNull())
01098     DB.AddFixItHint(Hint);
01099   return DB;
01100 }
01101 
01102 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
01103                                                    unsigned DiagID) {
01104   assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
01105   CurDiagLoc = Loc;
01106   CurDiagID = DiagID;
01107   FlagValue.clear();
01108   return DiagnosticBuilder(this);
01109 }
01110 
01111 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
01112   return Report(SourceLocation(), DiagID);
01113 }
01114 
01115 //===----------------------------------------------------------------------===//
01116 // Diagnostic
01117 //===----------------------------------------------------------------------===//
01118 
01119 /// A little helper class (which is basically a smart pointer that forwards
01120 /// info from DiagnosticsEngine) that allows clients to enquire about the
01121 /// currently in-flight diagnostic.
01122 class Diagnostic {
01123   const DiagnosticsEngine *DiagObj;
01124   StringRef StoredDiagMessage;
01125 public:
01126   explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
01127   Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
01128     : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
01129 
01130   const DiagnosticsEngine *getDiags() const { return DiagObj; }
01131   unsigned getID() const { return DiagObj->CurDiagID; }
01132   const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
01133   bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
01134   SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
01135 
01136   unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
01137 
01138   /// \brief Return the kind of the specified index.
01139   ///
01140   /// Based on the kind of argument, the accessors below can be used to get
01141   /// the value.
01142   ///
01143   /// \pre Idx < getNumArgs()
01144   DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
01145     assert(Idx < getNumArgs() && "Argument index out of range!");
01146     return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
01147   }
01148 
01149   /// \brief Return the provided argument string specified by \p Idx.
01150   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
01151   const std::string &getArgStdStr(unsigned Idx) const {
01152     assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
01153            "invalid argument accessor!");
01154     return DiagObj->DiagArgumentsStr[Idx];
01155   }
01156 
01157   /// \brief Return the specified C string argument.
01158   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
01159   const char *getArgCStr(unsigned Idx) const {
01160     assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
01161            "invalid argument accessor!");
01162     return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
01163   }
01164 
01165   /// \brief Return the specified signed integer argument.
01166   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
01167   int getArgSInt(unsigned Idx) const {
01168     assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
01169            "invalid argument accessor!");
01170     return (int)DiagObj->DiagArgumentsVal[Idx];
01171   }
01172 
01173   /// \brief Return the specified unsigned integer argument.
01174   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
01175   unsigned getArgUInt(unsigned Idx) const {
01176     assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
01177            "invalid argument accessor!");
01178     return (unsigned)DiagObj->DiagArgumentsVal[Idx];
01179   }
01180 
01181   /// \brief Return the specified IdentifierInfo argument.
01182   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
01183   const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
01184     assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
01185            "invalid argument accessor!");
01186     return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
01187   }
01188 
01189   /// \brief Return the specified non-string argument in an opaque form.
01190   /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
01191   intptr_t getRawArg(unsigned Idx) const {
01192     assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
01193            "invalid argument accessor!");
01194     return DiagObj->DiagArgumentsVal[Idx];
01195   }
01196 
01197   /// \brief Return the number of source ranges associated with this diagnostic.
01198   unsigned getNumRanges() const {
01199     return DiagObj->DiagRanges.size();
01200   }
01201 
01202   /// \pre Idx < getNumRanges()
01203   const CharSourceRange &getRange(unsigned Idx) const {
01204     assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
01205     return DiagObj->DiagRanges[Idx];
01206   }
01207 
01208   /// \brief Return an array reference for this diagnostic's ranges.
01209   ArrayRef<CharSourceRange> getRanges() const {
01210     return DiagObj->DiagRanges;
01211   }
01212 
01213   unsigned getNumFixItHints() const {
01214     return DiagObj->DiagFixItHints.size();
01215   }
01216 
01217   const FixItHint &getFixItHint(unsigned Idx) const {
01218     assert(Idx < getNumFixItHints() && "Invalid index!");
01219     return DiagObj->DiagFixItHints[Idx];
01220   }
01221 
01222   ArrayRef<FixItHint> getFixItHints() const {
01223     return DiagObj->DiagFixItHints;
01224   }
01225 
01226   /// \brief Format this diagnostic into a string, substituting the
01227   /// formal arguments into the %0 slots.
01228   ///
01229   /// The result is appended onto the \p OutStr array.
01230   void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
01231 
01232   /// \brief Format the given format-string into the output buffer using the
01233   /// arguments stored in this diagnostic.
01234   void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
01235                         SmallVectorImpl<char> &OutStr) const;
01236 };
01237 
01238 /**
01239  * \brief Represents a diagnostic in a form that can be retained until its 
01240  * corresponding source manager is destroyed. 
01241  */
01242 class StoredDiagnostic {
01243   unsigned ID;
01244   DiagnosticsEngine::Level Level;
01245   FullSourceLoc Loc;
01246   std::string Message;
01247   std::vector<CharSourceRange> Ranges;
01248   std::vector<FixItHint> FixIts;
01249 
01250 public:
01251   StoredDiagnostic();
01252   StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
01253   StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 
01254                    StringRef Message);
01255   StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 
01256                    StringRef Message, FullSourceLoc Loc,
01257                    ArrayRef<CharSourceRange> Ranges,
01258                    ArrayRef<FixItHint> Fixits);
01259   ~StoredDiagnostic();
01260 
01261   /// \brief Evaluates true when this object stores a diagnostic.
01262   LLVM_EXPLICIT operator bool() const { return Message.size() > 0; }
01263 
01264   unsigned getID() const { return ID; }
01265   DiagnosticsEngine::Level getLevel() const { return Level; }
01266   const FullSourceLoc &getLocation() const { return Loc; }
01267   StringRef getMessage() const { return Message; }
01268 
01269   void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
01270 
01271   typedef std::vector<CharSourceRange>::const_iterator range_iterator;
01272   range_iterator range_begin() const { return Ranges.begin(); }
01273   range_iterator range_end() const { return Ranges.end(); }
01274   unsigned range_size() const { return Ranges.size(); }
01275   
01276   ArrayRef<CharSourceRange> getRanges() const {
01277     return llvm::makeArrayRef(Ranges);
01278   }
01279 
01280 
01281   typedef std::vector<FixItHint>::const_iterator fixit_iterator;
01282   fixit_iterator fixit_begin() const { return FixIts.begin(); }
01283   fixit_iterator fixit_end() const { return FixIts.end(); }
01284   unsigned fixit_size() const { return FixIts.size(); }
01285   
01286   ArrayRef<FixItHint> getFixIts() const {
01287     return llvm::makeArrayRef(FixIts);
01288   }
01289 };
01290 
01291 /// \brief Abstract interface, implemented by clients of the front-end, which
01292 /// formats and prints fully processed diagnostics.
01293 class DiagnosticConsumer {
01294 protected:
01295   unsigned NumWarnings;       ///< Number of warnings reported
01296   unsigned NumErrors;         ///< Number of errors reported
01297   
01298 public:
01299   DiagnosticConsumer() : NumWarnings(0), NumErrors(0) { }
01300 
01301   unsigned getNumErrors() const { return NumErrors; }
01302   unsigned getNumWarnings() const { return NumWarnings; }
01303   virtual void clear() { NumWarnings = NumErrors = 0; }
01304 
01305   virtual ~DiagnosticConsumer();
01306 
01307   /// \brief Callback to inform the diagnostic client that processing
01308   /// of a source file is beginning.
01309   ///
01310   /// Note that diagnostics may be emitted outside the processing of a source
01311   /// file, for example during the parsing of command line options. However,
01312   /// diagnostics with source range information are required to only be emitted
01313   /// in between BeginSourceFile() and EndSourceFile().
01314   ///
01315   /// \param LangOpts The language options for the source file being processed.
01316   /// \param PP The preprocessor object being used for the source; this is 
01317   /// optional, e.g., it may not be present when processing AST source files.
01318   virtual void BeginSourceFile(const LangOptions &LangOpts,
01319                                const Preprocessor *PP = nullptr) {}
01320 
01321   /// \brief Callback to inform the diagnostic client that processing
01322   /// of a source file has ended.
01323   ///
01324   /// The diagnostic client should assume that any objects made available via
01325   /// BeginSourceFile() are inaccessible.
01326   virtual void EndSourceFile() {}
01327 
01328   /// \brief Callback to inform the diagnostic client that processing of all
01329   /// source files has ended.
01330   virtual void finish() {}
01331 
01332   /// \brief Indicates whether the diagnostics handled by this
01333   /// DiagnosticConsumer should be included in the number of diagnostics
01334   /// reported by DiagnosticsEngine.
01335   ///
01336   /// The default implementation returns true.
01337   virtual bool IncludeInDiagnosticCounts() const;
01338 
01339   /// \brief Handle this diagnostic, reporting it to the user or
01340   /// capturing it to a log as needed.
01341   ///
01342   /// The default implementation just keeps track of the total number of
01343   /// warnings and errors.
01344   virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
01345                                 const Diagnostic &Info);
01346 };
01347 
01348 /// \brief A diagnostic client that ignores all diagnostics.
01349 class IgnoringDiagConsumer : public DiagnosticConsumer {
01350   virtual void anchor();
01351   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
01352                         const Diagnostic &Info) override {
01353     // Just ignore it.
01354   }
01355 };
01356 
01357 /// \brief Diagnostic consumer that forwards diagnostics along to an
01358 /// existing, already-initialized diagnostic consumer.
01359 ///
01360 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
01361   DiagnosticConsumer &Target;
01362 
01363 public:
01364   ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
01365 
01366   virtual ~ForwardingDiagnosticConsumer();
01367 
01368   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
01369                         const Diagnostic &Info) override;
01370   void clear() override;
01371 
01372   bool IncludeInDiagnosticCounts() const override;
01373 };
01374 
01375 // Struct used for sending info about how a type should be printed.
01376 struct TemplateDiffTypes {
01377   intptr_t FromType;
01378   intptr_t ToType;
01379   unsigned PrintTree : 1;
01380   unsigned PrintFromType : 1;
01381   unsigned ElideType : 1;
01382   unsigned ShowColors : 1;
01383   // The printer sets this variable to true if the template diff was used.
01384   unsigned TemplateDiffUsed : 1;
01385 };
01386 
01387 /// Special character that the diagnostic printer will use to toggle the bold
01388 /// attribute.  The character itself will be not be printed.
01389 const char ToggleHighlight = 127;
01390 
01391 
01392 /// ProcessWarningOptions - Initialize the diagnostic client and process the
01393 /// warning options specified on the command line.
01394 void ProcessWarningOptions(DiagnosticsEngine &Diags,
01395                            const DiagnosticOptions &Opts,
01396                            bool ReportDiags = true);
01397 
01398 }  // end namespace clang
01399 
01400 #endif