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