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