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