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