Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:36:49

0001 //===- Diagnostic.h - C Language Family Diagnostic Handling -----*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 /// \file
0010 /// Defines the Diagnostic-related interfaces.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
0015 #define LLVM_CLANG_BASIC_DIAGNOSTIC_H
0016 
0017 #include "clang/Basic/DiagnosticIDs.h"
0018 #include "clang/Basic/DiagnosticOptions.h"
0019 #include "clang/Basic/SourceLocation.h"
0020 #include "clang/Basic/Specifiers.h"
0021 #include "llvm/ADT/ArrayRef.h"
0022 #include "llvm/ADT/DenseMap.h"
0023 #include "llvm/ADT/FunctionExtras.h"
0024 #include "llvm/ADT/IntrusiveRefCntPtr.h"
0025 #include "llvm/ADT/SmallVector.h"
0026 #include "llvm/ADT/iterator_range.h"
0027 #include "llvm/Support/Compiler.h"
0028 #include <cassert>
0029 #include <cstdint>
0030 #include <limits>
0031 #include <list>
0032 #include <map>
0033 #include <memory>
0034 #include <optional>
0035 #include <string>
0036 #include <type_traits>
0037 #include <utility>
0038 #include <vector>
0039 
0040 namespace llvm {
0041 class Error;
0042 class raw_ostream;
0043 class MemoryBuffer;
0044 namespace vfs {
0045 class FileSystem;
0046 } // namespace vfs
0047 } // namespace llvm
0048 
0049 namespace clang {
0050 
0051 class DeclContext;
0052 class DiagnosticBuilder;
0053 class DiagnosticConsumer;
0054 class IdentifierInfo;
0055 class LangOptions;
0056 class Preprocessor;
0057 class SourceManager;
0058 class StoredDiagnostic;
0059 
0060 namespace tok {
0061 
0062 enum TokenKind : unsigned short;
0063 
0064 } // namespace tok
0065 
0066 /// Annotates a diagnostic with some code that should be
0067 /// inserted, removed, or replaced to fix the problem.
0068 ///
0069 /// This kind of hint should be used when we are certain that the
0070 /// introduction, removal, or modification of a particular (small!)
0071 /// amount of code will correct a compilation error. The compiler
0072 /// should also provide full recovery from such errors, such that
0073 /// suppressing the diagnostic output can still result in successful
0074 /// compilation.
0075 class FixItHint {
0076 public:
0077   /// Code that should be replaced to correct the error. Empty for an
0078   /// insertion hint.
0079   CharSourceRange RemoveRange;
0080 
0081   /// Code in the specific range that should be inserted in the insertion
0082   /// location.
0083   CharSourceRange InsertFromRange;
0084 
0085   /// The actual code to insert at the insertion location, as a
0086   /// string.
0087   std::string CodeToInsert;
0088 
0089   bool BeforePreviousInsertions = false;
0090 
0091   /// Empty code modification hint, indicating that no code
0092   /// modification is known.
0093   FixItHint() = default;
0094 
0095   bool isNull() const {
0096     return !RemoveRange.isValid();
0097   }
0098 
0099   /// Create a code modification hint that inserts the given
0100   /// code string at a specific location.
0101   static FixItHint CreateInsertion(SourceLocation InsertionLoc,
0102                                    StringRef Code,
0103                                    bool BeforePreviousInsertions = false) {
0104     FixItHint Hint;
0105     Hint.RemoveRange =
0106       CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
0107     Hint.CodeToInsert = std::string(Code);
0108     Hint.BeforePreviousInsertions = BeforePreviousInsertions;
0109     return Hint;
0110   }
0111 
0112   /// Create a code modification hint that inserts the given
0113   /// code from \p FromRange at a specific location.
0114   static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
0115                                             CharSourceRange FromRange,
0116                                         bool BeforePreviousInsertions = false) {
0117     FixItHint Hint;
0118     Hint.RemoveRange =
0119       CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
0120     Hint.InsertFromRange = FromRange;
0121     Hint.BeforePreviousInsertions = BeforePreviousInsertions;
0122     return Hint;
0123   }
0124 
0125   /// Create a code modification hint that removes the given
0126   /// source range.
0127   static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
0128     FixItHint Hint;
0129     Hint.RemoveRange = RemoveRange;
0130     return Hint;
0131   }
0132   static FixItHint CreateRemoval(SourceRange RemoveRange) {
0133     return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
0134   }
0135 
0136   /// Create a code modification hint that replaces the given
0137   /// source range with the given code string.
0138   static FixItHint CreateReplacement(CharSourceRange RemoveRange,
0139                                      StringRef Code) {
0140     FixItHint Hint;
0141     Hint.RemoveRange = RemoveRange;
0142     Hint.CodeToInsert = std::string(Code);
0143     return Hint;
0144   }
0145 
0146   static FixItHint CreateReplacement(SourceRange RemoveRange,
0147                                      StringRef Code) {
0148     return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
0149   }
0150 };
0151 
0152 struct DiagnosticStorage {
0153   enum {
0154     /// The maximum number of arguments we can hold. We
0155     /// currently only support up to 10 arguments (%0-%9).
0156     ///
0157     /// A single diagnostic with more than that almost certainly has to
0158     /// be simplified anyway.
0159     MaxArguments = 10
0160   };
0161 
0162   /// The number of entries in Arguments.
0163   unsigned char NumDiagArgs = 0;
0164 
0165   /// Specifies for each argument whether it is in DiagArgumentsStr
0166   /// or in DiagArguments.
0167   unsigned char DiagArgumentsKind[MaxArguments];
0168 
0169   /// The values for the various substitution positions.
0170   ///
0171   /// This is used when the argument is not an std::string. The specific value
0172   /// is mangled into an uint64_t and the interpretation depends on exactly
0173   /// what sort of argument kind it is.
0174   uint64_t DiagArgumentsVal[MaxArguments];
0175 
0176   /// The values for the various substitution positions that have
0177   /// string arguments.
0178   std::string DiagArgumentsStr[MaxArguments];
0179 
0180   /// The list of ranges added to this diagnostic.
0181   SmallVector<CharSourceRange, 8> DiagRanges;
0182 
0183   /// If valid, provides a hint with some code to insert, remove, or
0184   /// modify at a particular position.
0185   SmallVector<FixItHint, 6> FixItHints;
0186 
0187   DiagnosticStorage() = default;
0188 };
0189 
0190 /// An allocator for DiagnosticStorage objects, which uses a small cache to
0191 /// objects, used to reduce malloc()/free() traffic for partial diagnostics.
0192 class DiagStorageAllocator {
0193   static const unsigned NumCached = 16;
0194   DiagnosticStorage Cached[NumCached];
0195   DiagnosticStorage *FreeList[NumCached];
0196   unsigned NumFreeListEntries;
0197 
0198 public:
0199   DiagStorageAllocator();
0200   ~DiagStorageAllocator();
0201 
0202   /// Allocate new storage.
0203   DiagnosticStorage *Allocate() {
0204     if (NumFreeListEntries == 0)
0205       return new DiagnosticStorage;
0206 
0207     DiagnosticStorage *Result = FreeList[--NumFreeListEntries];
0208     Result->NumDiagArgs = 0;
0209     Result->DiagRanges.clear();
0210     Result->FixItHints.clear();
0211     return Result;
0212   }
0213 
0214   /// Free the given storage object.
0215   void Deallocate(DiagnosticStorage *S) {
0216     if (S >= Cached && S <= Cached + NumCached) {
0217       FreeList[NumFreeListEntries++] = S;
0218       return;
0219     }
0220 
0221     delete S;
0222   }
0223 };
0224 
0225 /// Concrete class used by the front-end to report problems and issues.
0226 ///
0227 /// This massages the diagnostics (e.g. handling things like "report warnings
0228 /// as errors" and passes them off to the DiagnosticConsumer for reporting to
0229 /// the user. DiagnosticsEngine is tied to one translation unit and one
0230 /// SourceManager.
0231 class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
0232 public:
0233   /// The level of the diagnostic, after it has been through mapping.
0234   enum Level {
0235     Ignored = DiagnosticIDs::Ignored,
0236     Note = DiagnosticIDs::Note,
0237     Remark = DiagnosticIDs::Remark,
0238     Warning = DiagnosticIDs::Warning,
0239     Error = DiagnosticIDs::Error,
0240     Fatal = DiagnosticIDs::Fatal
0241   };
0242 
0243   enum ArgumentKind {
0244     /// std::string
0245     ak_std_string,
0246 
0247     /// const char *
0248     ak_c_string,
0249 
0250     /// int
0251     ak_sint,
0252 
0253     /// unsigned
0254     ak_uint,
0255 
0256     /// enum TokenKind : unsigned
0257     ak_tokenkind,
0258 
0259     /// IdentifierInfo
0260     ak_identifierinfo,
0261 
0262     /// address space
0263     ak_addrspace,
0264 
0265     /// Qualifiers
0266     ak_qual,
0267 
0268     /// QualType
0269     ak_qualtype,
0270 
0271     /// DeclarationName
0272     ak_declarationname,
0273 
0274     /// NamedDecl *
0275     ak_nameddecl,
0276 
0277     /// NestedNameSpecifier *
0278     ak_nestednamespec,
0279 
0280     /// DeclContext *
0281     ak_declcontext,
0282 
0283     /// pair<QualType, QualType>
0284     ak_qualtype_pair,
0285 
0286     /// Attr *
0287     ak_attr
0288   };
0289 
0290   /// Represents on argument value, which is a union discriminated
0291   /// by ArgumentKind, with a value.
0292   using ArgumentValue = std::pair<ArgumentKind, intptr_t>;
0293 
0294 private:
0295   // Used by __extension__
0296   unsigned char AllExtensionsSilenced = 0;
0297 
0298   // Treat fatal errors like errors.
0299   bool FatalsAsError = false;
0300 
0301   // Suppress all diagnostics.
0302   bool SuppressAllDiagnostics = false;
0303 
0304   // Elide common types of templates.
0305   bool ElideType = true;
0306 
0307   // Print a tree when comparing templates.
0308   bool PrintTemplateTree = false;
0309 
0310   // Color printing is enabled.
0311   bool ShowColors = false;
0312 
0313   // Which overload candidates to show.
0314   OverloadsShown ShowOverloads = Ovl_All;
0315 
0316   // With Ovl_Best, the number of overload candidates to show when we encounter
0317   // an error.
0318   //
0319   // The value here is the number of candidates to show in the first nontrivial
0320   // error.  Future errors may show a different number of candidates.
0321   unsigned NumOverloadsToShow = 32;
0322 
0323   // Cap of # errors emitted, 0 -> no limit.
0324   unsigned ErrorLimit = 0;
0325 
0326   // Cap on depth of template backtrace stack, 0 -> no limit.
0327   unsigned TemplateBacktraceLimit = 0;
0328 
0329   // Cap on depth of constexpr evaluation backtrace stack, 0 -> no limit.
0330   unsigned ConstexprBacktraceLimit = 0;
0331 
0332   IntrusiveRefCntPtr<DiagnosticIDs> Diags;
0333   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
0334   DiagnosticConsumer *Client = nullptr;
0335   std::unique_ptr<DiagnosticConsumer> Owner;
0336   SourceManager *SourceMgr = nullptr;
0337 
0338   /// Mapping information for diagnostics.
0339   ///
0340   /// Mapping info is packed into four bits per diagnostic.  The low three
0341   /// bits are the mapping (an instance of diag::Severity), or zero if unset.
0342   /// The high bit is set when the mapping was established as a user mapping.
0343   /// If the high bit is clear, then the low bits are set to the default
0344   /// value, and should be mapped with -pedantic, -Werror, etc.
0345   ///
0346   /// A new DiagState is created and kept around when diagnostic pragmas modify
0347   /// the state so that we know what is the diagnostic state at any given
0348   /// source location.
0349   class DiagState {
0350     llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
0351 
0352   public:
0353     // "Global" configuration state that can actually vary between modules.
0354 
0355     // Ignore all warnings: -w
0356     LLVM_PREFERRED_TYPE(bool)
0357     unsigned IgnoreAllWarnings : 1;
0358 
0359     // Enable all warnings.
0360     LLVM_PREFERRED_TYPE(bool)
0361     unsigned EnableAllWarnings : 1;
0362 
0363     // Treat warnings like errors.
0364     LLVM_PREFERRED_TYPE(bool)
0365     unsigned WarningsAsErrors : 1;
0366 
0367     // Treat errors like fatal errors.
0368     LLVM_PREFERRED_TYPE(bool)
0369     unsigned ErrorsAsFatal : 1;
0370 
0371     // Suppress warnings in system headers.
0372     LLVM_PREFERRED_TYPE(bool)
0373     unsigned SuppressSystemWarnings : 1;
0374 
0375     // Map extensions to warnings or errors?
0376     diag::Severity ExtBehavior = diag::Severity::Ignored;
0377 
0378     DiagnosticIDs &DiagIDs;
0379 
0380     DiagState(DiagnosticIDs &DiagIDs)
0381         : IgnoreAllWarnings(false), EnableAllWarnings(false),
0382           WarningsAsErrors(false), ErrorsAsFatal(false),
0383           SuppressSystemWarnings(false), DiagIDs(DiagIDs) {}
0384 
0385     using iterator = llvm::DenseMap<unsigned, DiagnosticMapping>::iterator;
0386     using const_iterator =
0387         llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator;
0388 
0389     void setMapping(diag::kind Diag, DiagnosticMapping Info) {
0390       DiagMap[Diag] = Info;
0391     }
0392 
0393     DiagnosticMapping lookupMapping(diag::kind Diag) const {
0394       return DiagMap.lookup(Diag);
0395     }
0396 
0397     DiagnosticMapping &getOrAddMapping(diag::kind Diag);
0398 
0399     const_iterator begin() const { return DiagMap.begin(); }
0400     const_iterator end() const { return DiagMap.end(); }
0401   };
0402 
0403   /// Keeps and automatically disposes all DiagStates that we create.
0404   std::list<DiagState> DiagStates;
0405 
0406   /// A mapping from files to the diagnostic states for those files. Lazily
0407   /// built on demand for files in which the diagnostic state has not changed.
0408   class DiagStateMap {
0409   public:
0410     /// Add an initial diagnostic state.
0411     void appendFirst(DiagState *State);
0412 
0413     /// Add a new latest state point.
0414     void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
0415 
0416     /// Look up the diagnostic state at a given source location.
0417     DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
0418 
0419     /// Determine whether this map is empty.
0420     bool empty() const { return Files.empty(); }
0421 
0422     /// Clear out this map.
0423     void clear() {
0424       Files.clear();
0425       FirstDiagState = CurDiagState = nullptr;
0426       CurDiagStateLoc = SourceLocation();
0427     }
0428 
0429     /// Produce a debugging dump of the diagnostic state.
0430     LLVM_DUMP_METHOD void dump(SourceManager &SrcMgr,
0431                                StringRef DiagName = StringRef()) const;
0432 
0433     /// Grab the most-recently-added state point.
0434     DiagState *getCurDiagState() const { return CurDiagState; }
0435 
0436     /// Get the location at which a diagnostic state was last added.
0437     SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
0438 
0439   private:
0440     friend class ASTReader;
0441     friend class ASTWriter;
0442 
0443     /// Represents a point in source where the diagnostic state was
0444     /// modified because of a pragma.
0445     ///
0446     /// 'Loc' can be null if the point represents the diagnostic state
0447     /// modifications done through the command-line.
0448     struct DiagStatePoint {
0449       DiagState *State;
0450       unsigned Offset;
0451 
0452       DiagStatePoint(DiagState *State, unsigned Offset)
0453           : State(State), Offset(Offset) {}
0454     };
0455 
0456     /// Description of the diagnostic states and state transitions for a
0457     /// particular FileID.
0458     struct File {
0459       /// The diagnostic state for the parent file. This is strictly redundant,
0460       /// as looking up the DecomposedIncludedLoc for the FileID in the Files
0461       /// map would give us this, but we cache it here for performance.
0462       File *Parent = nullptr;
0463 
0464       /// The offset of this file within its parent.
0465       unsigned ParentOffset = 0;
0466 
0467       /// Whether this file has any local (not imported from an AST file)
0468       /// diagnostic state transitions.
0469       bool HasLocalTransitions = false;
0470 
0471       /// The points within the file where the state changes. There will always
0472       /// be at least one of these (the state on entry to the file).
0473       llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
0474 
0475       DiagState *lookup(unsigned Offset) const;
0476     };
0477 
0478     /// The diagnostic states for each file.
0479     mutable std::map<FileID, File> Files;
0480 
0481     /// The initial diagnostic state.
0482     DiagState *FirstDiagState;
0483 
0484     /// The current diagnostic state.
0485     DiagState *CurDiagState;
0486 
0487     /// The location at which the current diagnostic state was established.
0488     SourceLocation CurDiagStateLoc;
0489 
0490     /// Get the diagnostic state information for a file.
0491     File *getFile(SourceManager &SrcMgr, FileID ID) const;
0492   };
0493 
0494   DiagStateMap DiagStatesByLoc;
0495 
0496   /// Keeps the DiagState that was active during each diagnostic 'push'
0497   /// so we can get back at it when we 'pop'.
0498   std::vector<DiagState *> DiagStateOnPushStack;
0499 
0500   DiagState *GetCurDiagState() const {
0501     return DiagStatesByLoc.getCurDiagState();
0502   }
0503 
0504   void PushDiagStatePoint(DiagState *State, SourceLocation L);
0505 
0506   /// Finds the DiagStatePoint that contains the diagnostic state of
0507   /// the given source location.
0508   DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
0509     return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
0510                      : DiagStatesByLoc.getCurDiagState();
0511   }
0512 
0513   /// Sticky flag set to \c true when an error is emitted.
0514   bool ErrorOccurred;
0515 
0516   /// Sticky flag set to \c true when an "uncompilable error" occurs.
0517   /// I.e. an error that was not upgraded from a warning by -Werror.
0518   bool UncompilableErrorOccurred;
0519 
0520   /// Sticky flag set to \c true when a fatal error is emitted.
0521   bool FatalErrorOccurred;
0522 
0523   /// Indicates that an unrecoverable error has occurred.
0524   bool UnrecoverableErrorOccurred;
0525 
0526   /// Counts for DiagnosticErrorTrap to check whether an error occurred
0527   /// during a parsing section, e.g. during parsing a function.
0528   unsigned TrapNumErrorsOccurred;
0529   unsigned TrapNumUnrecoverableErrorsOccurred;
0530 
0531   /// The level of the last diagnostic emitted.
0532   ///
0533   /// This is used to emit continuation diagnostics with the same level as the
0534   /// diagnostic that they follow.
0535   DiagnosticIDs::Level LastDiagLevel;
0536 
0537   /// Number of warnings reported
0538   unsigned NumWarnings;
0539 
0540   /// Number of errors reported
0541   unsigned NumErrors;
0542 
0543   /// A function pointer that converts an opaque diagnostic
0544   /// argument to a strings.
0545   ///
0546   /// This takes the modifiers and argument that was present in the diagnostic.
0547   ///
0548   /// The PrevArgs array indicates the previous arguments formatted for this
0549   /// diagnostic.  Implementations of this function can use this information to
0550   /// avoid redundancy across arguments.
0551   ///
0552   /// This is a hack to avoid a layering violation between libbasic and libsema.
0553   using ArgToStringFnTy = void (*)(
0554       ArgumentKind Kind, intptr_t Val,
0555       StringRef Modifier, StringRef Argument,
0556       ArrayRef<ArgumentValue> PrevArgs,
0557       SmallVectorImpl<char> &Output,
0558       void *Cookie,
0559       ArrayRef<intptr_t> QualTypeVals);
0560 
0561   void *ArgToStringCookie = nullptr;
0562   ArgToStringFnTy ArgToStringFn;
0563 
0564   /// Whether the diagnostic should be suppressed in FilePath.
0565   llvm::unique_function<bool(diag::kind, SourceLocation /*DiagLoc*/,
0566                              const SourceManager &) const>
0567       DiagSuppressionMapping;
0568 
0569 public:
0570   explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
0571                              IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
0572                              DiagnosticConsumer *client = nullptr,
0573                              bool ShouldOwnClient = true);
0574   DiagnosticsEngine(const DiagnosticsEngine &) = delete;
0575   DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
0576   ~DiagnosticsEngine();
0577 
0578   friend void DiagnosticsTestHelper(DiagnosticsEngine &);
0579   LLVM_DUMP_METHOD void dump() const;
0580   LLVM_DUMP_METHOD void dump(StringRef DiagName) const;
0581 
0582   const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
0583     return Diags;
0584   }
0585 
0586   /// Retrieve the diagnostic options.
0587   DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
0588 
0589   using diag_mapping_range = llvm::iterator_range<DiagState::const_iterator>;
0590 
0591   /// Get the current set of diagnostic mappings.
0592   diag_mapping_range getDiagnosticMappings() const {
0593     const DiagState &DS = *GetCurDiagState();
0594     return diag_mapping_range(DS.begin(), DS.end());
0595   }
0596 
0597   DiagnosticConsumer *getClient() { return Client; }
0598   const DiagnosticConsumer *getClient() const { return Client; }
0599 
0600   /// Determine whether this \c DiagnosticsEngine object own its client.
0601   bool ownsClient() const { return Owner != nullptr; }
0602 
0603   /// Return the current diagnostic client along with ownership of that
0604   /// client.
0605   std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
0606 
0607   bool hasSourceManager() const { return SourceMgr != nullptr; }
0608 
0609   SourceManager &getSourceManager() const {
0610     assert(SourceMgr && "SourceManager not set!");
0611     return *SourceMgr;
0612   }
0613 
0614   void setSourceManager(SourceManager *SrcMgr) {
0615     assert(DiagStatesByLoc.empty() &&
0616            "Leftover diag state from a different SourceManager.");
0617     SourceMgr = SrcMgr;
0618   }
0619 
0620   //===--------------------------------------------------------------------===//
0621   //  DiagnosticsEngine characterization methods, used by a client to customize
0622   //  how diagnostics are emitted.
0623   //
0624 
0625   /// Copies the current DiagMappings and pushes the new copy
0626   /// onto the top of the stack.
0627   void pushMappings(SourceLocation Loc);
0628 
0629   /// Pops the current DiagMappings off the top of the stack,
0630   /// causing the new top of the stack to be the active mappings.
0631   ///
0632   /// \returns \c true if the pop happens, \c false if there is only one
0633   /// DiagMapping on the stack.
0634   bool popMappings(SourceLocation Loc);
0635 
0636   /// Set the diagnostic client associated with this diagnostic object.
0637   ///
0638   /// \param ShouldOwnClient true if the diagnostic object should take
0639   /// ownership of \c client.
0640   void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
0641 
0642   /// Specify a limit for the number of errors we should
0643   /// emit before giving up.
0644   ///
0645   /// Zero disables the limit.
0646   void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
0647 
0648   /// Specify the maximum number of template instantiation
0649   /// notes to emit along with a given diagnostic.
0650   void setTemplateBacktraceLimit(unsigned Limit) {
0651     TemplateBacktraceLimit = Limit;
0652   }
0653 
0654   /// Retrieve the maximum number of template instantiation
0655   /// notes to emit along with a given diagnostic.
0656   unsigned getTemplateBacktraceLimit() const {
0657     return TemplateBacktraceLimit;
0658   }
0659 
0660   /// Specify the maximum number of constexpr evaluation
0661   /// notes to emit along with a given diagnostic.
0662   void setConstexprBacktraceLimit(unsigned Limit) {
0663     ConstexprBacktraceLimit = Limit;
0664   }
0665 
0666   /// Retrieve the maximum number of constexpr evaluation
0667   /// notes to emit along with a given diagnostic.
0668   unsigned getConstexprBacktraceLimit() const {
0669     return ConstexprBacktraceLimit;
0670   }
0671 
0672   /// When set to true, any unmapped warnings are ignored.
0673   ///
0674   /// If this and WarningsAsErrors are both set, then this one wins.
0675   void setIgnoreAllWarnings(bool Val) {
0676     GetCurDiagState()->IgnoreAllWarnings = Val;
0677   }
0678   bool getIgnoreAllWarnings() const {
0679     return GetCurDiagState()->IgnoreAllWarnings;
0680   }
0681 
0682   /// When set to true, any unmapped ignored warnings are no longer
0683   /// ignored.
0684   ///
0685   /// If this and IgnoreAllWarnings are both set, then that one wins.
0686   void setEnableAllWarnings(bool Val) {
0687     GetCurDiagState()->EnableAllWarnings = Val;
0688   }
0689   bool getEnableAllWarnings() const {
0690     return GetCurDiagState()->EnableAllWarnings;
0691   }
0692 
0693   /// When set to true, any warnings reported are issued as errors.
0694   void setWarningsAsErrors(bool Val) {
0695     GetCurDiagState()->WarningsAsErrors = Val;
0696   }
0697   bool getWarningsAsErrors() const {
0698     return GetCurDiagState()->WarningsAsErrors;
0699   }
0700 
0701   /// When set to true, any error reported is made a fatal error.
0702   void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
0703   bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
0704 
0705   /// \brief When set to true, any fatal error reported is made an error.
0706   ///
0707   /// This setting takes precedence over the setErrorsAsFatal setting above.
0708   void setFatalsAsError(bool Val) { FatalsAsError = Val; }
0709   bool getFatalsAsError() const { return FatalsAsError; }
0710 
0711   /// When set to true mask warnings that come from system headers.
0712   void setSuppressSystemWarnings(bool Val) {
0713     GetCurDiagState()->SuppressSystemWarnings = Val;
0714   }
0715   bool getSuppressSystemWarnings() const {
0716     return GetCurDiagState()->SuppressSystemWarnings;
0717   }
0718 
0719   /// Suppress all diagnostics, to silence the front end when we
0720   /// know that we don't want any more diagnostics to be passed along to the
0721   /// client
0722   void setSuppressAllDiagnostics(bool Val) { SuppressAllDiagnostics = Val; }
0723   bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
0724 
0725   /// Set type eliding, to skip outputting same types occurring in
0726   /// template types.
0727   void setElideType(bool Val) { ElideType = Val; }
0728   bool getElideType() { return ElideType; }
0729 
0730   /// Set tree printing, to outputting the template difference in a
0731   /// tree format.
0732   void setPrintTemplateTree(bool Val) { PrintTemplateTree = Val; }
0733   bool getPrintTemplateTree() { return PrintTemplateTree; }
0734 
0735   /// Set color printing, so the type diffing will inject color markers
0736   /// into the output.
0737   void setShowColors(bool Val) { ShowColors = Val; }
0738   bool getShowColors() { return ShowColors; }
0739 
0740   /// Specify which overload candidates to show when overload resolution
0741   /// fails.
0742   ///
0743   /// By default, we show all candidates.
0744   void setShowOverloads(OverloadsShown Val) {
0745     ShowOverloads = Val;
0746   }
0747   OverloadsShown getShowOverloads() const { return ShowOverloads; }
0748 
0749   /// When a call or operator fails, print out up to this many candidate
0750   /// overloads as suggestions.
0751   ///
0752   /// With Ovl_Best, we set a high limit for the first nontrivial overload set
0753   /// we print, and a lower limit for later sets.  This way the user has a
0754   /// chance of diagnosing at least one callsite in their program without
0755   /// having to recompile with -fshow-overloads=all.
0756   unsigned getNumOverloadCandidatesToShow() const {
0757     switch (getShowOverloads()) {
0758     case Ovl_All:
0759       // INT_MAX rather than UINT_MAX so that we don't have to think about the
0760       // effect of implicit conversions on this value. In practice we'll never
0761       // hit 2^31 candidates anyway.
0762       return std::numeric_limits<int>::max();
0763     case Ovl_Best:
0764       return NumOverloadsToShow;
0765     }
0766     llvm_unreachable("invalid OverloadsShown kind");
0767   }
0768 
0769   /// Call this after showing N overload candidates.  This influences the value
0770   /// returned by later calls to getNumOverloadCandidatesToShow().
0771   void overloadCandidatesShown(unsigned N) {
0772     // Current heuristic: Start out with a large value for NumOverloadsToShow,
0773     // and then once we print one nontrivially-large overload set, decrease it
0774     // for future calls.
0775     if (N > 4) {
0776       NumOverloadsToShow = 4;
0777     }
0778   }
0779 
0780   /// Pretend that the last diagnostic issued was ignored, so any
0781   /// subsequent notes will be suppressed, or restore a prior ignoring
0782   /// state after ignoring some diagnostics and their notes, possibly in
0783   /// the middle of another diagnostic.
0784   ///
0785   /// This can be used by clients who suppress diagnostics themselves.
0786   void setLastDiagnosticIgnored(bool Ignored) {
0787     if (LastDiagLevel == DiagnosticIDs::Fatal)
0788       FatalErrorOccurred = true;
0789     LastDiagLevel = Ignored ? DiagnosticIDs::Ignored : DiagnosticIDs::Warning;
0790   }
0791 
0792   /// Determine whether the previous diagnostic was ignored. This can
0793   /// be used by clients that want to determine whether notes attached to a
0794   /// diagnostic will be suppressed.
0795   bool isLastDiagnosticIgnored() const {
0796     return LastDiagLevel == DiagnosticIDs::Ignored;
0797   }
0798 
0799   /// Controls whether otherwise-unmapped extension diagnostics are
0800   /// mapped onto ignore/warning/error.
0801   ///
0802   /// This corresponds to the GCC -pedantic and -pedantic-errors option.
0803   void setExtensionHandlingBehavior(diag::Severity H) {
0804     GetCurDiagState()->ExtBehavior = H;
0805   }
0806   diag::Severity getExtensionHandlingBehavior() const {
0807     return GetCurDiagState()->ExtBehavior;
0808   }
0809 
0810   /// Counter bumped when an __extension__  block is/ encountered.
0811   ///
0812   /// When non-zero, all extension diagnostics are entirely silenced, no
0813   /// matter how they are mapped.
0814   void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
0815   void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
0816   bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
0817 
0818   /// This allows the client to specify that certain warnings are
0819   /// ignored.
0820   ///
0821   /// Notes can never be mapped, errors can only be mapped to fatal, and
0822   /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
0823   ///
0824   /// \param Loc The source location that this change of diagnostic state should
0825   /// take affect. It can be null if we are setting the latest state.
0826   void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
0827 
0828   /// Change an entire diagnostic group (e.g. "unknown-pragmas") to
0829   /// have the specified mapping.
0830   ///
0831   /// \returns true (and ignores the request) if "Group" was unknown, false
0832   /// otherwise.
0833   ///
0834   /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
0835   /// state of the -Wfoo group and vice versa.
0836   ///
0837   /// \param Loc The source location that this change of diagnostic state should
0838   /// take affect. It can be null if we are setting the state from command-line.
0839   bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
0840                            diag::Severity Map,
0841                            SourceLocation Loc = SourceLocation());
0842   bool setSeverityForGroup(diag::Flavor Flavor, diag::Group Group,
0843                            diag::Severity Map,
0844                            SourceLocation Loc = SourceLocation());
0845 
0846   /// Set the warning-as-error flag for the given diagnostic group.
0847   ///
0848   /// This function always only operates on the current diagnostic state.
0849   ///
0850   /// \returns True if the given group is unknown, false otherwise.
0851   bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
0852 
0853   /// Set the error-as-fatal flag for the given diagnostic group.
0854   ///
0855   /// This function always only operates on the current diagnostic state.
0856   ///
0857   /// \returns True if the given group is unknown, false otherwise.
0858   bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
0859 
0860   /// Add the specified mapping to all diagnostics of the specified
0861   /// flavor.
0862   ///
0863   /// Mainly to be used by -Wno-everything to disable all warnings but allow
0864   /// subsequent -W options to enable specific warnings.
0865   void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
0866                          SourceLocation Loc = SourceLocation());
0867 
0868   bool hasErrorOccurred() const { return ErrorOccurred; }
0869 
0870   /// Errors that actually prevent compilation, not those that are
0871   /// upgraded from a warning by -Werror.
0872   bool hasUncompilableErrorOccurred() const {
0873     return UncompilableErrorOccurred;
0874   }
0875   bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
0876 
0877   /// Determine whether any kind of unrecoverable error has occurred.
0878   bool hasUnrecoverableErrorOccurred() const {
0879     return FatalErrorOccurred || UnrecoverableErrorOccurred;
0880   }
0881 
0882   unsigned getNumErrors() const { return NumErrors; }
0883   unsigned getNumWarnings() const { return NumWarnings; }
0884 
0885   void setNumWarnings(unsigned NumWarnings) {
0886     this->NumWarnings = NumWarnings;
0887   }
0888 
0889   /// Return an ID for a diagnostic with the specified format string and
0890   /// level.
0891   ///
0892   /// If this is the first request for this diagnostic, it is registered and
0893   /// created, otherwise the existing ID is returned.
0894   ///
0895   /// \param FormatString A fixed diagnostic format string that will be hashed
0896   /// and mapped to a unique DiagID.
0897   template <unsigned N>
0898   // TODO: Deprecate this once all uses are removed from Clang.
0899   // [[deprecated("Use a CustomDiagDesc instead of a Level")]]
0900   unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
0901     return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
0902                                   StringRef(FormatString, N - 1));
0903   }
0904 
0905   /// Converts a diagnostic argument (as an intptr_t) into the string
0906   /// that represents it.
0907   void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
0908                           StringRef Modifier, StringRef Argument,
0909                           ArrayRef<ArgumentValue> PrevArgs,
0910                           SmallVectorImpl<char> &Output,
0911                           ArrayRef<intptr_t> QualTypeVals) const {
0912     ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
0913                   ArgToStringCookie, QualTypeVals);
0914   }
0915 
0916   void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
0917     ArgToStringFn = Fn;
0918     ArgToStringCookie = Cookie;
0919   }
0920 
0921   /// Note that the prior diagnostic was emitted by some other
0922   /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
0923   void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
0924     LastDiagLevel = Other.LastDiagLevel;
0925   }
0926 
0927   /// Reset the state of the diagnostic object to its initial configuration.
0928   /// \param[in] soft - if true, doesn't reset the diagnostic mappings and state
0929   void Reset(bool soft = false);
0930 
0931   //===--------------------------------------------------------------------===//
0932   // DiagnosticsEngine classification and reporting interfaces.
0933   //
0934 
0935   /// Determine whether the diagnostic is known to be ignored.
0936   ///
0937   /// This can be used to opportunistically avoid expensive checks when it's
0938   /// known for certain that the diagnostic has been suppressed at the
0939   /// specified location \p Loc.
0940   ///
0941   /// \param Loc The source location we are interested in finding out the
0942   /// diagnostic state. Can be null in order to query the latest state.
0943   bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
0944     return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
0945            diag::Severity::Ignored;
0946   }
0947 
0948   /// Based on the way the client configured the DiagnosticsEngine
0949   /// object, classify the specified diagnostic ID into a Level, consumable by
0950   /// the DiagnosticConsumer.
0951   ///
0952   /// To preserve invariant assumptions, this function should not be used to
0953   /// influence parse or semantic analysis actions. Instead consider using
0954   /// \c isIgnored().
0955   ///
0956   /// \param Loc The source location we are interested in finding out the
0957   /// diagnostic state. Can be null in order to query the latest state.
0958   Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
0959     return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
0960   }
0961 
0962   /// Diagnostic suppression mappings can be used to suppress specific
0963   /// diagnostics in specific files.
0964   /// Mapping file is expected to be a special case list with sections denoting
0965   /// diagnostic groups and `src` entries for globs to suppress. `emit` category
0966   /// can be used to disable suppression. Longest glob that matches a filepath
0967   /// takes precedence. For example:
0968   ///   [unused]
0969   ///   src:clang/*
0970   ///   src:clang/foo/*=emit
0971   ///   src:clang/foo/bar/*
0972   ///
0973   /// Such a mappings file suppress all diagnostics produced by -Wunused in all
0974   /// sources under `clang/` directory apart from `clang/foo/`. Diagnostics
0975   /// under `clang/foo/bar/` will also be suppressed. Note that the FilePath is
0976   /// matched against the globs as-is.
0977   /// These take presumed locations into account, and can still be overriden by
0978   /// clang-diagnostics pragmas.
0979   void setDiagSuppressionMapping(llvm::MemoryBuffer &Input);
0980   bool isSuppressedViaMapping(diag::kind DiagId, SourceLocation DiagLoc) const;
0981 
0982   /// Issue the message to the client.
0983   ///
0984   /// This actually returns an instance of DiagnosticBuilder which emits the
0985   /// diagnostics (through @c ProcessDiag) when it is destroyed.
0986   ///
0987   /// \param DiagID A member of the @c diag::kind enum.
0988   /// \param Loc Represents the source location associated with the diagnostic,
0989   /// which can be an invalid location if no position information is available.
0990   inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
0991   inline DiagnosticBuilder Report(unsigned DiagID);
0992 
0993   void Report(const StoredDiagnostic &storedDiag);
0994 
0995 private:
0996   // This is private state used by DiagnosticBuilder.  We put it here instead of
0997   // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
0998   // object.  This implementation choice means that we can only have a few
0999   // diagnostics "in flight" at a time, but this seems to be a reasonable
1000   // tradeoff to keep these objects small.
1001   friend class Diagnostic;
1002   friend class DiagnosticBuilder;
1003   friend class DiagnosticErrorTrap;
1004   friend class DiagnosticIDs;
1005   friend class PartialDiagnostic;
1006 
1007   enum {
1008     /// The maximum number of arguments we can hold.
1009     ///
1010     /// We currently only support up to 10 arguments (%0-%9).  A single
1011     /// diagnostic with more than that almost certainly has to be simplified
1012     /// anyway.
1013     MaxArguments = DiagnosticStorage::MaxArguments,
1014   };
1015 
1016   DiagStorageAllocator DiagAllocator;
1017 
1018   DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
1019     bool isPragma = L.isValid();
1020     DiagnosticMapping Mapping =
1021         DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
1022 
1023     // If this is a pragma mapping, then set the diagnostic mapping flags so
1024     // that we override command line options.
1025     if (isPragma) {
1026       Mapping.setNoWarningAsError(true);
1027       Mapping.setNoErrorAsFatal(true);
1028     }
1029 
1030     return Mapping;
1031   }
1032 
1033   /// Used to report a diagnostic that is finally fully formed.
1034   ///
1035   /// \returns true if the diagnostic was emitted, false if it was suppressed.
1036   bool ProcessDiag(const DiagnosticBuilder &DiagBuilder) {
1037     return Diags->ProcessDiag(*this, DiagBuilder);
1038   }
1039 
1040   /// @name Diagnostic Emission
1041   /// @{
1042 protected:
1043   friend class ASTReader;
1044   friend class ASTWriter;
1045 
1046   // Sema requires access to the following functions because the current design
1047   // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
1048   // access us directly to ensure we minimize the emitted code for the common
1049   // Sema::Diag() patterns.
1050   friend class Sema;
1051 
1052   /// Emit the diagnostic
1053   ///
1054   /// \param Force Emit the diagnostic regardless of suppression settings.
1055   bool EmitDiagnostic(const DiagnosticBuilder &DB, bool Force = false);
1056 
1057   /// @}
1058 };
1059 
1060 /// RAII class that determines when any errors have occurred
1061 /// between the time the instance was created and the time it was
1062 /// queried.
1063 ///
1064 /// Note that you almost certainly do not want to use this. It's usually
1065 /// meaningless to ask whether a particular scope triggered an error message,
1066 /// because error messages outside that scope can mark things invalid (or cause
1067 /// us to reach an error limit), which can suppress errors within that scope.
1068 class DiagnosticErrorTrap {
1069   DiagnosticsEngine &Diag;
1070   unsigned NumErrors;
1071   unsigned NumUnrecoverableErrors;
1072 
1073 public:
1074   explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
1075       : Diag(Diag) { reset(); }
1076 
1077   /// Determine whether any errors have occurred since this
1078   /// object instance was created.
1079   bool hasErrorOccurred() const {
1080     return Diag.TrapNumErrorsOccurred > NumErrors;
1081   }
1082 
1083   /// Determine whether any unrecoverable errors have occurred since this
1084   /// object instance was created.
1085   bool hasUnrecoverableErrorOccurred() const {
1086     return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
1087   }
1088 
1089   /// Set to initial state of "no errors occurred".
1090   void reset() {
1091     NumErrors = Diag.TrapNumErrorsOccurred;
1092     NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
1093   }
1094 };
1095 
1096 /// The streaming interface shared between DiagnosticBuilder and
1097 /// PartialDiagnostic. This class is not intended to be constructed directly
1098 /// but only as base class of DiagnosticBuilder and PartialDiagnostic builder.
1099 ///
1100 /// Any new type of argument accepted by DiagnosticBuilder and PartialDiagnostic
1101 /// should be implemented as a '<<' operator of StreamingDiagnostic, e.g.
1102 ///
1103 /// const StreamingDiagnostic&
1104 /// operator<<(const StreamingDiagnostic&, NewArgType);
1105 ///
1106 class StreamingDiagnostic {
1107 public:
1108   using DiagStorageAllocator = clang::DiagStorageAllocator;
1109 
1110 protected:
1111   mutable DiagnosticStorage *DiagStorage = nullptr;
1112 
1113   /// Allocator used to allocate storage for this diagnostic.
1114   DiagStorageAllocator *Allocator = nullptr;
1115 
1116 public:
1117   /// Retrieve storage for this particular diagnostic.
1118   DiagnosticStorage *getStorage() const {
1119     if (DiagStorage)
1120       return DiagStorage;
1121 
1122     assert(Allocator);
1123     DiagStorage = Allocator->Allocate();
1124     return DiagStorage;
1125   }
1126 
1127   void freeStorage() {
1128     if (!DiagStorage)
1129       return;
1130 
1131     // The hot path for PartialDiagnostic is when we just used it to wrap an ID
1132     // (typically so we have the flexibility of passing a more complex
1133     // diagnostic into the callee, but that does not commonly occur).
1134     //
1135     // Split this out into a slow function for silly compilers (*cough*) which
1136     // can't do decent partial inlining.
1137     freeStorageSlow();
1138   }
1139 
1140   void freeStorageSlow() {
1141     if (!Allocator)
1142       return;
1143     Allocator->Deallocate(DiagStorage);
1144     DiagStorage = nullptr;
1145   }
1146 
1147   void AddTaggedVal(uint64_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1148     if (!DiagStorage)
1149       DiagStorage = getStorage();
1150 
1151     assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&
1152            "Too many arguments to diagnostic!");
1153     DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
1154     DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
1155   }
1156 
1157   void AddString(StringRef V) const {
1158     if (!DiagStorage)
1159       DiagStorage = getStorage();
1160 
1161     assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&
1162            "Too many arguments to diagnostic!");
1163     DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] =
1164         DiagnosticsEngine::ak_std_string;
1165     DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = std::string(V);
1166   }
1167 
1168   void AddSourceRange(const CharSourceRange &R) const {
1169     if (!DiagStorage)
1170       DiagStorage = getStorage();
1171 
1172     DiagStorage->DiagRanges.push_back(R);
1173   }
1174 
1175   void AddFixItHint(const FixItHint &Hint) const {
1176     if (Hint.isNull())
1177       return;
1178 
1179     if (!DiagStorage)
1180       DiagStorage = getStorage();
1181 
1182     DiagStorage->FixItHints.push_back(Hint);
1183   }
1184 
1185   /// Conversion of StreamingDiagnostic to bool always returns \c true.
1186   ///
1187   /// This allows is to be used in boolean error contexts (where \c true is
1188   /// used to indicate that an error has occurred), like:
1189   /// \code
1190   /// return Diag(...);
1191   /// \endcode
1192   operator bool() const { return true; }
1193 
1194 protected:
1195   StreamingDiagnostic() = default;
1196 
1197   /// Construct with a storage allocator which will manage the storage. The
1198   /// allocator is not a null pointer in this case.
1199   explicit StreamingDiagnostic(DiagStorageAllocator &Alloc)
1200       : Allocator(&Alloc) {}
1201 
1202   StreamingDiagnostic(const StreamingDiagnostic &Diag) = default;
1203   StreamingDiagnostic(StreamingDiagnostic &&Diag) = default;
1204 
1205   ~StreamingDiagnostic() { freeStorage(); }
1206 };
1207 
1208 //===----------------------------------------------------------------------===//
1209 // DiagnosticBuilder
1210 //===----------------------------------------------------------------------===//
1211 
1212 /// A little helper class used to produce diagnostics.
1213 ///
1214 /// This is constructed by the DiagnosticsEngine::Report method, and
1215 /// allows insertion of extra information (arguments and source ranges) into
1216 /// the currently "in flight" diagnostic.  When the temporary for the builder
1217 /// is destroyed, the diagnostic is issued.
1218 ///
1219 /// Note that many of these will be created as temporary objects (many call
1220 /// sites), so we want them to be small and we never want their address taken.
1221 /// This ensures that compilers with somewhat reasonable optimizers will promote
1222 /// the common fields to registers, eliminating increments of the NumArgs field,
1223 /// for example.
1224 class DiagnosticBuilder : public StreamingDiagnostic {
1225   friend class DiagnosticsEngine;
1226   friend class PartialDiagnostic;
1227   friend class Diagnostic;
1228 
1229   mutable DiagnosticsEngine *DiagObj = nullptr;
1230 
1231   SourceLocation DiagLoc;
1232   unsigned DiagID;
1233 
1234   /// Optional flag value.
1235   ///
1236   /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
1237   /// -Rpass=<value>. The content of this string is emitted after the flag name
1238   /// and '='.
1239   mutable std::string FlagValue;
1240 
1241   /// Status variable indicating if this diagnostic is still active.
1242   ///
1243   // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
1244   // but LLVM is not currently smart enough to eliminate the null check that
1245   // Emit() would end up with if we used that as our status variable.
1246   mutable bool IsActive = false;
1247 
1248   /// Flag indicating that this diagnostic is being emitted via a
1249   /// call to ForceEmit.
1250   mutable bool IsForceEmit = false;
1251 
1252   DiagnosticBuilder() = default;
1253 
1254   DiagnosticBuilder(DiagnosticsEngine *DiagObj, SourceLocation DiagLoc,
1255                     unsigned DiagID);
1256 
1257 protected:
1258   /// Clear out the current diagnostic.
1259   void Clear() const {
1260     DiagObj = nullptr;
1261     IsActive = false;
1262     IsForceEmit = false;
1263   }
1264 
1265   /// Determine whether this diagnostic is still active.
1266   bool isActive() const { return IsActive; }
1267 
1268   /// Force the diagnostic builder to emit the diagnostic now.
1269   ///
1270   /// Once this function has been called, the DiagnosticBuilder object
1271   /// should not be used again before it is destroyed.
1272   ///
1273   /// \returns true if a diagnostic was emitted, false if the
1274   /// diagnostic was suppressed.
1275   bool Emit() {
1276     // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1277     // (or by a subclass, as in SemaDiagnosticBuilder).
1278     if (!isActive()) return false;
1279 
1280     // Process the diagnostic.
1281     bool Result = DiagObj->EmitDiagnostic(*this, IsForceEmit);
1282 
1283     // This diagnostic is dead.
1284     Clear();
1285 
1286     return Result;
1287   }
1288 
1289 public:
1290   /// Copy constructor.  When copied, this "takes" the diagnostic info from the
1291   /// input and neuters it.
1292   DiagnosticBuilder(const DiagnosticBuilder &D);
1293 
1294   template <typename T> const DiagnosticBuilder &operator<<(const T &V) const {
1295     assert(isActive() && "Clients must not add to cleared diagnostic!");
1296     const StreamingDiagnostic &DB = *this;
1297     DB << V;
1298     return *this;
1299   }
1300 
1301   // It is necessary to limit this to rvalue reference to avoid calling this
1302   // function with a bitfield lvalue argument since non-const reference to
1303   // bitfield is not allowed.
1304   template <typename T,
1305             typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1306   const DiagnosticBuilder &operator<<(T &&V) const {
1307     assert(isActive() && "Clients must not add to cleared diagnostic!");
1308     const StreamingDiagnostic &DB = *this;
1309     DB << std::move(V);
1310     return *this;
1311   }
1312 
1313   DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1314 
1315   /// Emits the diagnostic.
1316   ~DiagnosticBuilder() { Emit(); }
1317 
1318   /// Forces the diagnostic to be emitted.
1319   const DiagnosticBuilder &setForceEmit() const {
1320     IsForceEmit = true;
1321     return *this;
1322   }
1323 
1324   void addFlagValue(StringRef V) const { FlagValue = std::string(V); }
1325 };
1326 
1327 struct AddFlagValue {
1328   StringRef Val;
1329 
1330   explicit AddFlagValue(StringRef V) : Val(V) {}
1331 };
1332 
1333 /// Register a value for the flag in the current diagnostic. This
1334 /// value will be shown as the suffix "=value" after the flag name. It is
1335 /// useful in cases where the diagnostic flag accepts values (e.g.,
1336 /// -Rpass or -Wframe-larger-than).
1337 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1338                                            const AddFlagValue V) {
1339   DB.addFlagValue(V.Val);
1340   return DB;
1341 }
1342 
1343 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1344                                              StringRef S) {
1345   DB.AddString(S);
1346   return DB;
1347 }
1348 
1349 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1350                                              const char *Str) {
1351   DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1352                   DiagnosticsEngine::ak_c_string);
1353   return DB;
1354 }
1355 
1356 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1357                                              int I) {
1358   DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1359   return DB;
1360 }
1361 
1362 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1363                                              long I) {
1364   DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1365   return DB;
1366 }
1367 
1368 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1369                                              long long I) {
1370   DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1371   return DB;
1372 }
1373 
1374 // We use enable_if here to prevent that this overload is selected for
1375 // pointers or other arguments that are implicitly convertible to bool.
1376 template <typename T>
1377 inline std::enable_if_t<std::is_same<T, bool>::value,
1378                         const StreamingDiagnostic &>
1379 operator<<(const StreamingDiagnostic &DB, T I) {
1380   DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1381   return DB;
1382 }
1383 
1384 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1385                                              unsigned I) {
1386   DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1387   return DB;
1388 }
1389 
1390 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1391                                              unsigned long I) {
1392   DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1393   return DB;
1394 }
1395 
1396 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1397                                              unsigned long long I) {
1398   DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1399   return DB;
1400 }
1401 
1402 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1403                                              tok::TokenKind I) {
1404   DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1405   return DB;
1406 }
1407 
1408 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1409                                              const IdentifierInfo *II) {
1410   DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1411                   DiagnosticsEngine::ak_identifierinfo);
1412   return DB;
1413 }
1414 
1415 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
1416 // so that we only match those arguments that are (statically) DeclContexts;
1417 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
1418 // match.
1419 template <typename T>
1420 inline std::enable_if_t<
1421     std::is_same<std::remove_const_t<T>, DeclContext>::value,
1422     const StreamingDiagnostic &>
1423 operator<<(const StreamingDiagnostic &DB, T *DC) {
1424   DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1425                   DiagnosticsEngine::ak_declcontext);
1426   return DB;
1427 }
1428 
1429 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1430                                              SourceLocation L) {
1431   DB.AddSourceRange(CharSourceRange::getTokenRange(L));
1432   return DB;
1433 }
1434 
1435 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1436                                              SourceRange R) {
1437   DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1438   return DB;
1439 }
1440 
1441 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1442                                              ArrayRef<SourceRange> Ranges) {
1443   for (SourceRange R : Ranges)
1444     DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1445   return DB;
1446 }
1447 
1448 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1449                                              const CharSourceRange &R) {
1450   DB.AddSourceRange(R);
1451   return DB;
1452 }
1453 
1454 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1455                                              const FixItHint &Hint) {
1456   DB.AddFixItHint(Hint);
1457   return DB;
1458 }
1459 
1460 inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1461                                              ArrayRef<FixItHint> Hints) {
1462   for (const FixItHint &Hint : Hints)
1463     DB.AddFixItHint(Hint);
1464   return DB;
1465 }
1466 
1467 inline const StreamingDiagnostic &
1468 operator<<(const StreamingDiagnostic &DB,
1469            const std::optional<SourceRange> &Opt) {
1470   if (Opt)
1471     DB << *Opt;
1472   return DB;
1473 }
1474 
1475 inline const StreamingDiagnostic &
1476 operator<<(const StreamingDiagnostic &DB,
1477            const std::optional<CharSourceRange> &Opt) {
1478   if (Opt)
1479     DB << *Opt;
1480   return DB;
1481 }
1482 
1483 inline const StreamingDiagnostic &
1484 operator<<(const StreamingDiagnostic &DB, const std::optional<FixItHint> &Opt) {
1485   if (Opt)
1486     DB << *Opt;
1487   return DB;
1488 }
1489 
1490 /// A nullability kind paired with a bit indicating whether it used a
1491 /// context-sensitive keyword.
1492 using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1493 
1494 const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1495                                       DiagNullabilityKind nullability);
1496 
1497 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1498                                                    unsigned DiagID) {
1499   return DiagnosticBuilder(this, Loc, DiagID);
1500 }
1501 
1502 const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1503                                       llvm::Error &&E);
1504 
1505 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1506   return Report(SourceLocation(), DiagID);
1507 }
1508 
1509 //===----------------------------------------------------------------------===//
1510 // Diagnostic
1511 //===----------------------------------------------------------------------===//
1512 
1513 /// A little helper class (which is basically a smart pointer that forwards
1514 /// info from DiagnosticsEngine and DiagnosticStorage) that allows clients to
1515 /// enquire about the diagnostic.
1516 class Diagnostic {
1517   const DiagnosticsEngine *DiagObj;
1518   SourceLocation DiagLoc;
1519   unsigned DiagID;
1520   std::string FlagValue;
1521   const DiagnosticStorage &DiagStorage;
1522   std::optional<StringRef> StoredDiagMessage;
1523 
1524 public:
1525   Diagnostic(const DiagnosticsEngine *DO, const DiagnosticBuilder &DiagBuilder);
1526   Diagnostic(const DiagnosticsEngine *DO, SourceLocation DiagLoc,
1527              unsigned DiagID, const DiagnosticStorage &DiagStorage,
1528              StringRef StoredDiagMessage);
1529 
1530   const DiagnosticsEngine *getDiags() const { return DiagObj; }
1531   unsigned getID() const { return DiagID; }
1532   const SourceLocation &getLocation() const { return DiagLoc; }
1533   bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1534   SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1535 
1536   unsigned getNumArgs() const { return DiagStorage.NumDiagArgs; }
1537 
1538   /// Return the kind of the specified index.
1539   ///
1540   /// Based on the kind of argument, the accessors below can be used to get
1541   /// the value.
1542   ///
1543   /// \pre Idx < getNumArgs()
1544   DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1545     assert(Idx < getNumArgs() && "Argument index out of range!");
1546     return (DiagnosticsEngine::ArgumentKind)DiagStorage.DiagArgumentsKind[Idx];
1547   }
1548 
1549   /// Return the provided argument string specified by \p Idx.
1550   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1551   const std::string &getArgStdStr(unsigned Idx) const {
1552     assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1553            "invalid argument accessor!");
1554     return DiagStorage.DiagArgumentsStr[Idx];
1555   }
1556 
1557   /// Return the specified C string argument.
1558   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1559   const char *getArgCStr(unsigned Idx) const {
1560     assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1561            "invalid argument accessor!");
1562     return reinterpret_cast<const char *>(DiagStorage.DiagArgumentsVal[Idx]);
1563   }
1564 
1565   /// Return the specified signed integer argument.
1566   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1567   int64_t getArgSInt(unsigned Idx) const {
1568     assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1569            "invalid argument accessor!");
1570     return (int64_t)DiagStorage.DiagArgumentsVal[Idx];
1571   }
1572 
1573   /// Return the specified unsigned integer argument.
1574   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1575   uint64_t getArgUInt(unsigned Idx) const {
1576     assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1577            "invalid argument accessor!");
1578     return DiagStorage.DiagArgumentsVal[Idx];
1579   }
1580 
1581   /// Return the specified IdentifierInfo argument.
1582   /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1583   const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1584     assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1585            "invalid argument accessor!");
1586     return reinterpret_cast<IdentifierInfo *>(
1587         DiagStorage.DiagArgumentsVal[Idx]);
1588   }
1589 
1590   /// Return the specified non-string argument in an opaque form.
1591   /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1592   uint64_t getRawArg(unsigned Idx) const {
1593     assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1594            "invalid argument accessor!");
1595     return DiagStorage.DiagArgumentsVal[Idx];
1596   }
1597 
1598   /// Return the number of source ranges associated with this diagnostic.
1599   unsigned getNumRanges() const { return DiagStorage.DiagRanges.size(); }
1600 
1601   /// \pre Idx < getNumRanges()
1602   const CharSourceRange &getRange(unsigned Idx) const {
1603     assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1604     return DiagStorage.DiagRanges[Idx];
1605   }
1606 
1607   /// Return an array reference for this diagnostic's ranges.
1608   ArrayRef<CharSourceRange> getRanges() const { return DiagStorage.DiagRanges; }
1609 
1610   unsigned getNumFixItHints() const { return DiagStorage.FixItHints.size(); }
1611 
1612   const FixItHint &getFixItHint(unsigned Idx) const {
1613     assert(Idx < getNumFixItHints() && "Invalid index!");
1614     return DiagStorage.FixItHints[Idx];
1615   }
1616 
1617   ArrayRef<FixItHint> getFixItHints() const { return DiagStorage.FixItHints; }
1618 
1619   /// Return the value associated with this diagnostic flag.
1620   StringRef getFlagValue() const { return FlagValue; }
1621 
1622   /// Format this diagnostic into a string, substituting the
1623   /// formal arguments into the %0 slots.
1624   ///
1625   /// The result is appended onto the \p OutStr array.
1626   void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1627 
1628   /// Format the given format-string into the output buffer using the
1629   /// arguments stored in this diagnostic.
1630   void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1631                         SmallVectorImpl<char> &OutStr) const;
1632 };
1633 
1634 /**
1635  * Represents a diagnostic in a form that can be retained until its
1636  * corresponding source manager is destroyed.
1637  */
1638 class StoredDiagnostic {
1639   unsigned ID;
1640   DiagnosticsEngine::Level Level;
1641   FullSourceLoc Loc;
1642   std::string Message;
1643   std::vector<CharSourceRange> Ranges;
1644   std::vector<FixItHint> FixIts;
1645 
1646 public:
1647   StoredDiagnostic() = default;
1648   StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1649   StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1650                    StringRef Message);
1651   StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1652                    StringRef Message, FullSourceLoc Loc,
1653                    ArrayRef<CharSourceRange> Ranges,
1654                    ArrayRef<FixItHint> Fixits);
1655 
1656   /// Evaluates true when this object stores a diagnostic.
1657   explicit operator bool() const { return !Message.empty(); }
1658 
1659   unsigned getID() const { return ID; }
1660   DiagnosticsEngine::Level getLevel() const { return Level; }
1661   const FullSourceLoc &getLocation() const { return Loc; }
1662   StringRef getMessage() const { return Message; }
1663 
1664   void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1665 
1666   using range_iterator = std::vector<CharSourceRange>::const_iterator;
1667 
1668   range_iterator range_begin() const { return Ranges.begin(); }
1669   range_iterator range_end() const { return Ranges.end(); }
1670   unsigned range_size() const { return Ranges.size(); }
1671 
1672   ArrayRef<CharSourceRange> getRanges() const { return llvm::ArrayRef(Ranges); }
1673 
1674   using fixit_iterator = std::vector<FixItHint>::const_iterator;
1675 
1676   fixit_iterator fixit_begin() const { return FixIts.begin(); }
1677   fixit_iterator fixit_end() const { return FixIts.end(); }
1678   unsigned fixit_size() const { return FixIts.size(); }
1679 
1680   ArrayRef<FixItHint> getFixIts() const { return llvm::ArrayRef(FixIts); }
1681 };
1682 
1683 // Simple debug printing of StoredDiagnostic.
1684 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const StoredDiagnostic &);
1685 
1686 /// Abstract interface, implemented by clients of the front-end, which
1687 /// formats and prints fully processed diagnostics.
1688 class DiagnosticConsumer {
1689 protected:
1690   unsigned NumWarnings = 0;       ///< Number of warnings reported
1691   unsigned NumErrors = 0;         ///< Number of errors reported
1692 
1693 public:
1694   DiagnosticConsumer() = default;
1695   virtual ~DiagnosticConsumer();
1696 
1697   unsigned getNumErrors() const { return NumErrors; }
1698   unsigned getNumWarnings() const { return NumWarnings; }
1699   virtual void clear() { NumWarnings = NumErrors = 0; }
1700 
1701   /// Callback to inform the diagnostic client that processing
1702   /// of a source file is beginning.
1703   ///
1704   /// Note that diagnostics may be emitted outside the processing of a source
1705   /// file, for example during the parsing of command line options. However,
1706   /// diagnostics with source range information are required to only be emitted
1707   /// in between BeginSourceFile() and EndSourceFile().
1708   ///
1709   /// \param LangOpts The language options for the source file being processed.
1710   /// \param PP The preprocessor object being used for the source; this is
1711   /// optional, e.g., it may not be present when processing AST source files.
1712   virtual void BeginSourceFile(const LangOptions &LangOpts,
1713                                const Preprocessor *PP = nullptr) {}
1714 
1715   /// Callback to inform the diagnostic client that processing
1716   /// of a source file has ended.
1717   ///
1718   /// The diagnostic client should assume that any objects made available via
1719   /// BeginSourceFile() are inaccessible.
1720   virtual void EndSourceFile() {}
1721 
1722   /// Callback to inform the diagnostic client that processing of all
1723   /// source files has ended.
1724   virtual void finish() {}
1725 
1726   /// Indicates whether the diagnostics handled by this
1727   /// DiagnosticConsumer should be included in the number of diagnostics
1728   /// reported by DiagnosticsEngine.
1729   ///
1730   /// The default implementation returns true.
1731   virtual bool IncludeInDiagnosticCounts() const;
1732 
1733   /// Handle this diagnostic, reporting it to the user or
1734   /// capturing it to a log as needed.
1735   ///
1736   /// The default implementation just keeps track of the total number of
1737   /// warnings and errors.
1738   virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1739                                 const Diagnostic &Info);
1740 };
1741 
1742 /// A diagnostic client that ignores all diagnostics.
1743 class IgnoringDiagConsumer : public DiagnosticConsumer {
1744   virtual void anchor();
1745 
1746   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1747                         const Diagnostic &Info) override {
1748     // Just ignore it.
1749   }
1750 };
1751 
1752 /// Diagnostic consumer that forwards diagnostics along to an
1753 /// existing, already-initialized diagnostic consumer.
1754 ///
1755 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1756   DiagnosticConsumer &Target;
1757 
1758 public:
1759   ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1760   ~ForwardingDiagnosticConsumer() override;
1761 
1762   void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1763                         const Diagnostic &Info) override;
1764   void clear() override;
1765 
1766   bool IncludeInDiagnosticCounts() const override;
1767 };
1768 
1769 // Struct used for sending info about how a type should be printed.
1770 struct TemplateDiffTypes {
1771   intptr_t FromType;
1772   intptr_t ToType;
1773   LLVM_PREFERRED_TYPE(bool)
1774   unsigned PrintTree : 1;
1775   LLVM_PREFERRED_TYPE(bool)
1776   unsigned PrintFromType : 1;
1777   LLVM_PREFERRED_TYPE(bool)
1778   unsigned ElideType : 1;
1779   LLVM_PREFERRED_TYPE(bool)
1780   unsigned ShowColors : 1;
1781 
1782   // The printer sets this variable to true if the template diff was used.
1783   LLVM_PREFERRED_TYPE(bool)
1784   unsigned TemplateDiffUsed : 1;
1785 };
1786 
1787 /// Special character that the diagnostic printer will use to toggle the bold
1788 /// attribute.  The character itself will be not be printed.
1789 const char ToggleHighlight = 127;
1790 
1791 /// ProcessWarningOptions - Initialize the diagnostic client and process the
1792 /// warning options specified on the command line.
1793 void ProcessWarningOptions(DiagnosticsEngine &Diags,
1794                            const DiagnosticOptions &Opts,
1795                            llvm::vfs::FileSystem &VFS, bool ReportDiags = true);
1796 void EscapeStringForDiagnostic(StringRef Str, SmallVectorImpl<char> &OutStr);
1797 } // namespace clang
1798 
1799 #endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H