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