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