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