1 //===- Diagnostic.h - C Language Family Diagnostic Handling -----*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 /// Defines the Diagnostic-related interfaces.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
15 #define LLVM_CLANG_BASIC_DIAGNOSTIC_H
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/IntrusiveRefCntPtr.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Error.h"
36 #include <type_traits>
43 class DiagnosticBuilder;
44 class DiagnosticConsumer;
49 class StoredDiagnostic;
53 enum TokenKind : unsigned short;
57 /// Annotates a diagnostic with some code that should be
58 /// inserted, removed, or replaced to fix the problem.
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
68 /// Code that should be replaced to correct the error. Empty for an
70 CharSourceRange RemoveRange;
72 /// Code in the specific range that should be inserted in the insertion
74 CharSourceRange InsertFromRange;
76 /// The actual code to insert at the insertion location, as a
78 std::string CodeToInsert;
80 bool BeforePreviousInsertions = false;
82 /// Empty code modification hint, indicating that no code
83 /// modification is known.
84 FixItHint() = default;
87 return !RemoveRange.isValid();
90 /// Create a code modification hint that inserts the given
91 /// code string at a specific location.
92 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
94 bool BeforePreviousInsertions = false) {
97 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
98 Hint.CodeToInsert = Code;
99 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
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) {
110 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
111 Hint.InsertFromRange = FromRange;
112 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
116 /// Create a code modification hint that removes the given
118 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
120 Hint.RemoveRange = RemoveRange;
123 static FixItHint CreateRemoval(SourceRange RemoveRange) {
124 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
127 /// Create a code modification hint that replaces the given
128 /// source range with the given code string.
129 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
132 Hint.RemoveRange = RemoveRange;
133 Hint.CodeToInsert = Code;
137 static FixItHint CreateReplacement(SourceRange RemoveRange,
139 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
143 /// Concrete class used by the front-end to report problems and issues.
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
149 class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
151 /// The level of the diagnostic, after it has been through mapping.
153 Ignored = DiagnosticIDs::Ignored,
154 Note = DiagnosticIDs::Note,
155 Remark = DiagnosticIDs::Remark,
156 Warning = DiagnosticIDs::Warning,
157 Error = DiagnosticIDs::Error,
158 Fatal = DiagnosticIDs::Fatal
174 /// enum TokenKind : unsigned
192 /// NestedNameSpecifier *
198 /// pair<QualType, QualType>
205 /// Represents on argument value, which is a union discriminated
206 /// by ArgumentKind, with a value.
207 using ArgumentValue = std::pair<ArgumentKind, intptr_t>;
210 // Used by __extension__
211 unsigned char AllExtensionsSilenced = 0;
213 // Treat fatal errors like errors.
214 bool FatalsAsError = false;
216 // Suppress all diagnostics.
217 bool SuppressAllDiagnostics = false;
219 // Elide common types of templates.
220 bool ElideType = true;
222 // Print a tree when comparing templates.
223 bool PrintTemplateTree = false;
225 // Color printing is enabled.
226 bool ShowColors = false;
228 // Which overload candidates to show.
229 OverloadsShown ShowOverloads = Ovl_All;
231 // Cap of # errors emitted, 0 -> no limit.
232 unsigned ErrorLimit = 0;
234 // Cap on depth of template backtrace stack, 0 -> no limit.
235 unsigned TemplateBacktraceLimit = 0;
237 // Cap on depth of constexpr evaluation backtrace stack, 0 -> no limit.
238 unsigned ConstexprBacktraceLimit = 0;
240 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
241 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
242 DiagnosticConsumer *Client = nullptr;
243 std::unique_ptr<DiagnosticConsumer> Owner;
244 SourceManager *SourceMgr = nullptr;
246 /// Mapping information for diagnostics.
248 /// Mapping info is packed into four bits per diagnostic. The low three
249 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
250 /// The high bit is set when the mapping was established as a user mapping.
251 /// If the high bit is clear, then the low bits are set to the default
252 /// value, and should be mapped with -pedantic, -Werror, etc.
254 /// A new DiagState is created and kept around when diagnostic pragmas modify
255 /// the state so that we know what is the diagnostic state at any given
258 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
261 // "Global" configuration state that can actually vary between modules.
263 // Ignore all warnings: -w
264 unsigned IgnoreAllWarnings : 1;
266 // Enable all warnings.
267 unsigned EnableAllWarnings : 1;
269 // Treat warnings like errors.
270 unsigned WarningsAsErrors : 1;
272 // Treat errors like fatal errors.
273 unsigned ErrorsAsFatal : 1;
275 // Suppress warnings in system headers.
276 unsigned SuppressSystemWarnings : 1;
278 // Map extensions to warnings or errors?
279 diag::Severity ExtBehavior = diag::Severity::Ignored;
282 : IgnoreAllWarnings(false), EnableAllWarnings(false),
283 WarningsAsErrors(false), ErrorsAsFatal(false),
284 SuppressSystemWarnings(false) {}
286 using iterator = llvm::DenseMap<unsigned, DiagnosticMapping>::iterator;
287 using const_iterator =
288 llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator;
290 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
291 DiagMap[Diag] = Info;
294 DiagnosticMapping lookupMapping(diag::kind Diag) const {
295 return DiagMap.lookup(Diag);
298 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
300 const_iterator begin() const { return DiagMap.begin(); }
301 const_iterator end() const { return DiagMap.end(); }
304 /// Keeps and automatically disposes all DiagStates that we create.
305 std::list<DiagState> DiagStates;
307 /// A mapping from files to the diagnostic states for those files. Lazily
308 /// built on demand for files in which the diagnostic state has not changed.
311 /// Add an initial diagnostic state.
312 void appendFirst(DiagState *State);
314 /// Add a new latest state point.
315 void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
317 /// Look up the diagnostic state at a given source location.
318 DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
320 /// Determine whether this map is empty.
321 bool empty() const { return Files.empty(); }
323 /// Clear out this map.
326 FirstDiagState = CurDiagState = nullptr;
327 CurDiagStateLoc = SourceLocation();
330 /// Produce a debugging dump of the diagnostic state.
331 LLVM_DUMP_METHOD void dump(SourceManager &SrcMgr,
332 StringRef DiagName = StringRef()) const;
334 /// Grab the most-recently-added state point.
335 DiagState *getCurDiagState() const { return CurDiagState; }
337 /// Get the location at which a diagnostic state was last added.
338 SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
341 friend class ASTReader;
342 friend class ASTWriter;
344 /// Represents a point in source where the diagnostic state was
345 /// modified because of a pragma.
347 /// 'Loc' can be null if the point represents the diagnostic state
348 /// modifications done through the command-line.
349 struct DiagStatePoint {
353 DiagStatePoint(DiagState *State, unsigned Offset)
354 : State(State), Offset(Offset) {}
357 /// Description of the diagnostic states and state transitions for a
358 /// particular FileID.
360 /// The diagnostic state for the parent file. This is strictly redundant,
361 /// as looking up the DecomposedIncludedLoc for the FileID in the Files
362 /// map would give us this, but we cache it here for performance.
363 File *Parent = nullptr;
365 /// The offset of this file within its parent.
366 unsigned ParentOffset = 0;
368 /// Whether this file has any local (not imported from an AST file)
369 /// diagnostic state transitions.
370 bool HasLocalTransitions = false;
372 /// The points within the file where the state changes. There will always
373 /// be at least one of these (the state on entry to the file).
374 llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
376 DiagState *lookup(unsigned Offset) const;
379 /// The diagnostic states for each file.
380 mutable std::map<FileID, File> Files;
382 /// The initial diagnostic state.
383 DiagState *FirstDiagState;
385 /// The current diagnostic state.
386 DiagState *CurDiagState;
388 /// The location at which the current diagnostic state was established.
389 SourceLocation CurDiagStateLoc;
391 /// Get the diagnostic state information for a file.
392 File *getFile(SourceManager &SrcMgr, FileID ID) const;
395 DiagStateMap DiagStatesByLoc;
397 /// Keeps the DiagState that was active during each diagnostic 'push'
398 /// so we can get back at it when we 'pop'.
399 std::vector<DiagState *> DiagStateOnPushStack;
401 DiagState *GetCurDiagState() const {
402 return DiagStatesByLoc.getCurDiagState();
405 void PushDiagStatePoint(DiagState *State, SourceLocation L);
407 /// Finds the DiagStatePoint that contains the diagnostic state of
408 /// the given source location.
409 DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
410 return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
411 : DiagStatesByLoc.getCurDiagState();
414 /// Sticky flag set to \c true when an error is emitted.
417 /// Sticky flag set to \c true when an "uncompilable error" occurs.
418 /// I.e. an error that was not upgraded from a warning by -Werror.
419 bool UncompilableErrorOccurred;
421 /// Sticky flag set to \c true when a fatal error is emitted.
422 bool FatalErrorOccurred;
424 /// Indicates that an unrecoverable error has occurred.
425 bool UnrecoverableErrorOccurred;
427 /// Counts for DiagnosticErrorTrap to check whether an error occurred
428 /// during a parsing section, e.g. during parsing a function.
429 unsigned TrapNumErrorsOccurred;
430 unsigned TrapNumUnrecoverableErrorsOccurred;
432 /// The level of the last diagnostic emitted.
434 /// This is used to emit continuation diagnostics with the same level as the
435 /// diagnostic that they follow.
436 DiagnosticIDs::Level LastDiagLevel;
438 /// Number of warnings reported
439 unsigned NumWarnings;
441 /// Number of errors reported
444 /// A function pointer that converts an opaque diagnostic
445 /// argument to a strings.
447 /// This takes the modifiers and argument that was present in the diagnostic.
449 /// The PrevArgs array indicates the previous arguments formatted for this
450 /// diagnostic. Implementations of this function can use this information to
451 /// avoid redundancy across arguments.
453 /// This is a hack to avoid a layering violation between libbasic and libsema.
454 using ArgToStringFnTy = void (*)(
455 ArgumentKind Kind, intptr_t Val,
456 StringRef Modifier, StringRef Argument,
457 ArrayRef<ArgumentValue> PrevArgs,
458 SmallVectorImpl<char> &Output,
460 ArrayRef<intptr_t> QualTypeVals);
462 void *ArgToStringCookie = nullptr;
463 ArgToStringFnTy ArgToStringFn;
465 /// ID of the "delayed" diagnostic, which is a (typically
466 /// fatal) diagnostic that had to be delayed because it was found
467 /// while emitting another diagnostic.
468 unsigned DelayedDiagID;
470 /// First string argument for the delayed diagnostic.
471 std::string DelayedDiagArg1;
473 /// Second string argument for the delayed diagnostic.
474 std::string DelayedDiagArg2;
476 /// Optional flag value.
478 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
479 /// -Rpass=<value>. The content of this string is emitted after the flag name
481 std::string FlagValue;
484 explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
485 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
486 DiagnosticConsumer *client = nullptr,
487 bool ShouldOwnClient = true);
488 DiagnosticsEngine(const DiagnosticsEngine &) = delete;
489 DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
490 ~DiagnosticsEngine();
492 LLVM_DUMP_METHOD void dump() const;
493 LLVM_DUMP_METHOD void dump(StringRef DiagName) const;
495 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
499 /// Retrieve the diagnostic options.
500 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
502 using diag_mapping_range = llvm::iterator_range<DiagState::const_iterator>;
504 /// Get the current set of diagnostic mappings.
505 diag_mapping_range getDiagnosticMappings() const {
506 const DiagState &DS = *GetCurDiagState();
507 return diag_mapping_range(DS.begin(), DS.end());
510 DiagnosticConsumer *getClient() { return Client; }
511 const DiagnosticConsumer *getClient() const { return Client; }
513 /// Determine whether this \c DiagnosticsEngine object own its client.
514 bool ownsClient() const { return Owner != nullptr; }
516 /// Return the current diagnostic client along with ownership of that
518 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
520 bool hasSourceManager() const { return SourceMgr != nullptr; }
522 SourceManager &getSourceManager() const {
523 assert(SourceMgr && "SourceManager not set!");
527 void setSourceManager(SourceManager *SrcMgr) {
528 assert(DiagStatesByLoc.empty() &&
529 "Leftover diag state from a different SourceManager.");
533 //===--------------------------------------------------------------------===//
534 // DiagnosticsEngine characterization methods, used by a client to customize
535 // how diagnostics are emitted.
538 /// Copies the current DiagMappings and pushes the new copy
539 /// onto the top of the stack.
540 void pushMappings(SourceLocation Loc);
542 /// Pops the current DiagMappings off the top of the stack,
543 /// causing the new top of the stack to be the active mappings.
545 /// \returns \c true if the pop happens, \c false if there is only one
546 /// DiagMapping on the stack.
547 bool popMappings(SourceLocation Loc);
549 /// Set the diagnostic client associated with this diagnostic object.
551 /// \param ShouldOwnClient true if the diagnostic object should take
552 /// ownership of \c client.
553 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
555 /// Specify a limit for the number of errors we should
556 /// emit before giving up.
558 /// Zero disables the limit.
559 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
561 /// Specify the maximum number of template instantiation
562 /// notes to emit along with a given diagnostic.
563 void setTemplateBacktraceLimit(unsigned Limit) {
564 TemplateBacktraceLimit = Limit;
567 /// Retrieve the maximum number of template instantiation
568 /// notes to emit along with a given diagnostic.
569 unsigned getTemplateBacktraceLimit() const {
570 return TemplateBacktraceLimit;
573 /// Specify the maximum number of constexpr evaluation
574 /// notes to emit along with a given diagnostic.
575 void setConstexprBacktraceLimit(unsigned Limit) {
576 ConstexprBacktraceLimit = Limit;
579 /// Retrieve the maximum number of constexpr evaluation
580 /// notes to emit along with a given diagnostic.
581 unsigned getConstexprBacktraceLimit() const {
582 return ConstexprBacktraceLimit;
585 /// When set to true, any unmapped warnings are ignored.
587 /// If this and WarningsAsErrors are both set, then this one wins.
588 void setIgnoreAllWarnings(bool Val) {
589 GetCurDiagState()->IgnoreAllWarnings = Val;
591 bool getIgnoreAllWarnings() const {
592 return GetCurDiagState()->IgnoreAllWarnings;
595 /// When set to true, any unmapped ignored warnings are no longer
598 /// If this and IgnoreAllWarnings are both set, then that one wins.
599 void setEnableAllWarnings(bool Val) {
600 GetCurDiagState()->EnableAllWarnings = Val;
602 bool getEnableAllWarnings() const {
603 return GetCurDiagState()->EnableAllWarnings;
606 /// When set to true, any warnings reported are issued as errors.
607 void setWarningsAsErrors(bool Val) {
608 GetCurDiagState()->WarningsAsErrors = Val;
610 bool getWarningsAsErrors() const {
611 return GetCurDiagState()->WarningsAsErrors;
614 /// When set to true, any error reported is made a fatal error.
615 void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
616 bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
618 /// \brief When set to true, any fatal error reported is made an error.
620 /// This setting takes precedence over the setErrorsAsFatal setting above.
621 void setFatalsAsError(bool Val) { FatalsAsError = Val; }
622 bool getFatalsAsError() const { return FatalsAsError; }
624 /// When set to true mask warnings that come from system headers.
625 void setSuppressSystemWarnings(bool Val) {
626 GetCurDiagState()->SuppressSystemWarnings = Val;
628 bool getSuppressSystemWarnings() const {
629 return GetCurDiagState()->SuppressSystemWarnings;
632 /// Suppress all diagnostics, to silence the front end when we
633 /// know that we don't want any more diagnostics to be passed along to the
635 void setSuppressAllDiagnostics(bool Val = true) {
636 SuppressAllDiagnostics = Val;
638 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
640 /// Set type eliding, to skip outputting same types occurring in
642 void setElideType(bool Val = true) { ElideType = Val; }
643 bool getElideType() { return ElideType; }
645 /// Set tree printing, to outputting the template difference in a
647 void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
648 bool getPrintTemplateTree() { return PrintTemplateTree; }
650 /// Set color printing, so the type diffing will inject color markers
652 void setShowColors(bool Val = false) { ShowColors = Val; }
653 bool getShowColors() { return ShowColors; }
655 /// Specify which overload candidates to show when overload resolution
658 /// By default, we show all candidates.
659 void setShowOverloads(OverloadsShown Val) {
662 OverloadsShown getShowOverloads() const { return ShowOverloads; }
664 /// Pretend that the last diagnostic issued was ignored, so any
665 /// subsequent notes will be suppressed, or restore a prior ignoring
666 /// state after ignoring some diagnostics and their notes, possibly in
667 /// the middle of another diagnostic.
669 /// This can be used by clients who suppress diagnostics themselves.
670 void setLastDiagnosticIgnored(bool Ignored = true) {
671 if (LastDiagLevel == DiagnosticIDs::Fatal)
672 FatalErrorOccurred = true;
673 LastDiagLevel = Ignored ? DiagnosticIDs::Ignored : DiagnosticIDs::Warning;
676 /// Determine whether the previous diagnostic was ignored. This can
677 /// be used by clients that want to determine whether notes attached to a
678 /// diagnostic will be suppressed.
679 bool isLastDiagnosticIgnored() const {
680 return LastDiagLevel == DiagnosticIDs::Ignored;
683 /// Controls whether otherwise-unmapped extension diagnostics are
684 /// mapped onto ignore/warning/error.
686 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
687 void setExtensionHandlingBehavior(diag::Severity H) {
688 GetCurDiagState()->ExtBehavior = H;
690 diag::Severity getExtensionHandlingBehavior() const {
691 return GetCurDiagState()->ExtBehavior;
694 /// Counter bumped when an __extension__ block is/ encountered.
696 /// When non-zero, all extension diagnostics are entirely silenced, no
697 /// matter how they are mapped.
698 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
699 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
700 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
702 /// This allows the client to specify that certain warnings are
705 /// Notes can never be mapped, errors can only be mapped to fatal, and
706 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
708 /// \param Loc The source location that this change of diagnostic state should
709 /// take affect. It can be null if we are setting the latest state.
710 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
712 /// Change an entire diagnostic group (e.g. "unknown-pragmas") to
713 /// have the specified mapping.
715 /// \returns true (and ignores the request) if "Group" was unknown, false
718 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
719 /// state of the -Wfoo group and vice versa.
721 /// \param Loc The source location that this change of diagnostic state should
722 /// take affect. It can be null if we are setting the state from command-line.
723 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
725 SourceLocation Loc = SourceLocation());
727 /// Set the warning-as-error flag for the given diagnostic group.
729 /// This function always only operates on the current diagnostic state.
731 /// \returns True if the given group is unknown, false otherwise.
732 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
734 /// Set the error-as-fatal flag for the given diagnostic group.
736 /// This function always only operates on the current diagnostic state.
738 /// \returns True if the given group is unknown, false otherwise.
739 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
741 /// Add the specified mapping to all diagnostics of the specified
744 /// Mainly to be used by -Wno-everything to disable all warnings but allow
745 /// subsequent -W options to enable specific warnings.
746 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
747 SourceLocation Loc = SourceLocation());
749 bool hasErrorOccurred() const { return ErrorOccurred; }
751 /// Errors that actually prevent compilation, not those that are
752 /// upgraded from a warning by -Werror.
753 bool hasUncompilableErrorOccurred() const {
754 return UncompilableErrorOccurred;
756 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
758 /// Determine whether any kind of unrecoverable error has occurred.
759 bool hasUnrecoverableErrorOccurred() const {
760 return FatalErrorOccurred || UnrecoverableErrorOccurred;
763 unsigned getNumWarnings() const { return NumWarnings; }
765 void setNumWarnings(unsigned NumWarnings) {
766 this->NumWarnings = NumWarnings;
769 /// Return an ID for a diagnostic with the specified format string and
772 /// If this is the first request for this diagnostic, it is registered and
773 /// created, otherwise the existing ID is returned.
775 /// \param FormatString A fixed diagnostic format string that will be hashed
776 /// and mapped to a unique DiagID.
777 template <unsigned N>
778 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
779 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
780 StringRef(FormatString, N - 1));
783 /// Converts a diagnostic argument (as an intptr_t) into the string
784 /// that represents it.
785 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
786 StringRef Modifier, StringRef Argument,
787 ArrayRef<ArgumentValue> PrevArgs,
788 SmallVectorImpl<char> &Output,
789 ArrayRef<intptr_t> QualTypeVals) const {
790 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
791 ArgToStringCookie, QualTypeVals);
794 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
796 ArgToStringCookie = Cookie;
799 /// Note that the prior diagnostic was emitted by some other
800 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
801 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
802 LastDiagLevel = Other.LastDiagLevel;
805 /// Reset the state of the diagnostic object to its initial
809 //===--------------------------------------------------------------------===//
810 // DiagnosticsEngine classification and reporting interfaces.
813 /// Determine whether the diagnostic is known to be ignored.
815 /// This can be used to opportunistically avoid expensive checks when it's
816 /// known for certain that the diagnostic has been suppressed at the
817 /// specified location \p Loc.
819 /// \param Loc The source location we are interested in finding out the
820 /// diagnostic state. Can be null in order to query the latest state.
821 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
822 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
823 diag::Severity::Ignored;
826 /// Based on the way the client configured the DiagnosticsEngine
827 /// object, classify the specified diagnostic ID into a Level, consumable by
828 /// the DiagnosticConsumer.
830 /// To preserve invariant assumptions, this function should not be used to
831 /// influence parse or semantic analysis actions. Instead consider using
834 /// \param Loc The source location we are interested in finding out the
835 /// diagnostic state. Can be null in order to query the latest state.
836 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
837 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
840 /// Issue the message to the client.
842 /// This actually returns an instance of DiagnosticBuilder which emits the
843 /// diagnostics (through @c ProcessDiag) when it is destroyed.
845 /// \param DiagID A member of the @c diag::kind enum.
846 /// \param Loc Represents the source location associated with the diagnostic,
847 /// which can be an invalid location if no position information is available.
848 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
849 inline DiagnosticBuilder Report(unsigned DiagID);
851 void Report(const StoredDiagnostic &storedDiag);
853 /// Determine whethere there is already a diagnostic in flight.
854 bool isDiagnosticInFlight() const {
855 return CurDiagID != std::numeric_limits<unsigned>::max();
858 /// Set the "delayed" diagnostic that will be emitted once
859 /// the current diagnostic completes.
861 /// If a diagnostic is already in-flight but the front end must
862 /// report a problem (e.g., with an inconsistent file system
863 /// state), this routine sets a "delayed" diagnostic that will be
864 /// emitted after the current diagnostic completes. This should
865 /// only be used for fatal errors detected at inconvenient
866 /// times. If emitting a delayed diagnostic causes a second delayed
867 /// diagnostic to be introduced, that second delayed diagnostic
870 /// \param DiagID The ID of the diagnostic being delayed.
872 /// \param Arg1 A string argument that will be provided to the
873 /// diagnostic. A copy of this string will be stored in the
874 /// DiagnosticsEngine object itself.
876 /// \param Arg2 A string argument that will be provided to the
877 /// diagnostic. A copy of this string will be stored in the
878 /// DiagnosticsEngine object itself.
879 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
880 StringRef Arg2 = "");
882 /// Clear out the current diagnostic.
883 void Clear() { CurDiagID = std::numeric_limits<unsigned>::max(); }
885 /// Return the value associated with this diagnostic flag.
886 StringRef getFlagValue() const { return FlagValue; }
889 // This is private state used by DiagnosticBuilder. We put it here instead of
890 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
891 // object. This implementation choice means that we can only have one
892 // diagnostic "in flight" at a time, but this seems to be a reasonable
893 // tradeoff to keep these objects small. Assertions verify that only one
894 // diagnostic is in flight at a time.
895 friend class Diagnostic;
896 friend class DiagnosticBuilder;
897 friend class DiagnosticErrorTrap;
898 friend class DiagnosticIDs;
899 friend class PartialDiagnostic;
901 /// Report the delayed diagnostic.
902 void ReportDelayed();
904 /// The location of the current diagnostic that is in flight.
905 SourceLocation CurDiagLoc;
907 /// The ID of the current diagnostic that is in flight.
909 /// This is set to std::numeric_limits<unsigned>::max() when there is no
910 /// diagnostic in flight.
914 /// The maximum number of arguments we can hold.
916 /// We currently only support up to 10 arguments (%0-%9). A single
917 /// diagnostic with more than that almost certainly has to be simplified
922 /// The number of entries in Arguments.
923 signed char NumDiagArgs;
925 /// Specifies whether an argument is in DiagArgumentsStr or
926 /// in DiagArguments.
928 /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
930 unsigned char DiagArgumentsKind[MaxArguments];
932 /// Holds the values of each string argument for the current
935 /// This is only used when the corresponding ArgumentKind is ak_std_string.
936 std::string DiagArgumentsStr[MaxArguments];
938 /// The values for the various substitution positions.
940 /// This is used when the argument is not an std::string. The specific
941 /// value is mangled into an intptr_t and the interpretation depends on
942 /// exactly what sort of argument kind it is.
943 intptr_t DiagArgumentsVal[MaxArguments];
945 /// The list of ranges added to this diagnostic.
946 SmallVector<CharSourceRange, 8> DiagRanges;
948 /// If valid, provides a hint with some code to insert, remove,
949 /// or modify at a particular position.
950 SmallVector<FixItHint, 8> DiagFixItHints;
952 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
953 bool isPragma = L.isValid();
954 DiagnosticMapping Mapping =
955 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
957 // If this is a pragma mapping, then set the diagnostic mapping flags so
958 // that we override command line options.
960 Mapping.setNoWarningAsError(true);
961 Mapping.setNoErrorAsFatal(true);
967 /// Used to report a diagnostic that is finally fully formed.
969 /// \returns true if the diagnostic was emitted, false if it was suppressed.
971 return Diags->ProcessDiag(*this);
974 /// @name Diagnostic Emission
977 friend class ASTReader;
978 friend class ASTWriter;
980 // Sema requires access to the following functions because the current design
981 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
982 // access us directly to ensure we minimize the emitted code for the common
983 // Sema::Diag() patterns.
986 /// Emit the current diagnostic and clear the diagnostic state.
988 /// \param Force Emit the diagnostic regardless of suppression settings.
989 bool EmitCurrentDiagnostic(bool Force = false);
991 unsigned getCurrentDiagID() const { return CurDiagID; }
993 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
998 /// RAII class that determines when any errors have occurred
999 /// between the time the instance was created and the time it was
1001 class DiagnosticErrorTrap {
1002 DiagnosticsEngine &Diag;
1004 unsigned NumUnrecoverableErrors;
1007 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
1008 : Diag(Diag) { reset(); }
1010 /// Determine whether any errors have occurred since this
1011 /// object instance was created.
1012 bool hasErrorOccurred() const {
1013 return Diag.TrapNumErrorsOccurred > NumErrors;
1016 /// Determine whether any unrecoverable errors have occurred since this
1017 /// object instance was created.
1018 bool hasUnrecoverableErrorOccurred() const {
1019 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
1022 /// Set to initial state of "no errors occurred".
1024 NumErrors = Diag.TrapNumErrorsOccurred;
1025 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
1029 //===----------------------------------------------------------------------===//
1030 // DiagnosticBuilder
1031 //===----------------------------------------------------------------------===//
1033 /// A little helper class used to produce diagnostics.
1035 /// This is constructed by the DiagnosticsEngine::Report method, and
1036 /// allows insertion of extra information (arguments and source ranges) into
1037 /// the currently "in flight" diagnostic. When the temporary for the builder
1038 /// is destroyed, the diagnostic is issued.
1040 /// Note that many of these will be created as temporary objects (many call
1041 /// sites), so we want them to be small and we never want their address taken.
1042 /// This ensures that compilers with somewhat reasonable optimizers will promote
1043 /// the common fields to registers, eliminating increments of the NumArgs field,
1045 class DiagnosticBuilder {
1046 friend class DiagnosticsEngine;
1047 friend class PartialDiagnostic;
1049 mutable DiagnosticsEngine *DiagObj = nullptr;
1050 mutable unsigned NumArgs = 0;
1052 /// Status variable indicating if this diagnostic is still active.
1054 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
1055 // but LLVM is not currently smart enough to eliminate the null check that
1056 // Emit() would end up with if we used that as our status variable.
1057 mutable bool IsActive = false;
1059 /// Flag indicating that this diagnostic is being emitted via a
1060 /// call to ForceEmit.
1061 mutable bool IsForceEmit = false;
1063 DiagnosticBuilder() = default;
1065 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
1066 : DiagObj(diagObj), IsActive(true) {
1067 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
1068 diagObj->DiagRanges.clear();
1069 diagObj->DiagFixItHints.clear();
1073 void FlushCounts() {
1074 DiagObj->NumDiagArgs = NumArgs;
1077 /// Clear out the current diagnostic.
1078 void Clear() const {
1081 IsForceEmit = false;
1084 /// Determine whether this diagnostic is still active.
1085 bool isActive() const { return IsActive; }
1087 /// Force the diagnostic builder to emit the diagnostic now.
1089 /// Once this function has been called, the DiagnosticBuilder object
1090 /// should not be used again before it is destroyed.
1092 /// \returns true if a diagnostic was emitted, false if the
1093 /// diagnostic was suppressed.
1095 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1096 // (or by a subclass, as in SemaDiagnosticBuilder).
1097 if (!isActive()) return false;
1099 // When emitting diagnostics, we set the final argument count into
1100 // the DiagnosticsEngine object.
1103 // Process the diagnostic.
1104 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
1106 // This diagnostic is dead.
1113 /// Copy constructor. When copied, this "takes" the diagnostic info from the
1114 /// input and neuters it.
1115 DiagnosticBuilder(const DiagnosticBuilder &D) {
1116 DiagObj = D.DiagObj;
1117 IsActive = D.IsActive;
1118 IsForceEmit = D.IsForceEmit;
1120 NumArgs = D.NumArgs;
1123 DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1125 /// Emits the diagnostic.
1126 ~DiagnosticBuilder() {
1130 /// Retrieve an empty diagnostic builder.
1131 static DiagnosticBuilder getEmpty() {
1135 /// Forces the diagnostic to be emitted.
1136 const DiagnosticBuilder &setForceEmit() const {
1141 /// Conversion of DiagnosticBuilder to bool always returns \c true.
1143 /// This allows is to be used in boolean error contexts (where \c true is
1144 /// used to indicate that an error has occurred), like:
1146 /// return Diag(...);
1148 operator bool() const { return true; }
1150 void AddString(StringRef S) const {
1151 assert(isActive() && "Clients must not add to cleared diagnostic!");
1152 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1153 "Too many arguments to diagnostic!");
1154 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
1155 DiagObj->DiagArgumentsStr[NumArgs++] = S;
1158 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1159 assert(isActive() && "Clients must not add to cleared diagnostic!");
1160 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1161 "Too many arguments to diagnostic!");
1162 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
1163 DiagObj->DiagArgumentsVal[NumArgs++] = V;
1166 void AddSourceRange(const CharSourceRange &R) const {
1167 assert(isActive() && "Clients must not add to cleared diagnostic!");
1168 DiagObj->DiagRanges.push_back(R);
1171 void AddFixItHint(const FixItHint &Hint) const {
1172 assert(isActive() && "Clients must not add to cleared diagnostic!");
1174 DiagObj->DiagFixItHints.push_back(Hint);
1177 void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
1180 struct AddFlagValue {
1183 explicit AddFlagValue(StringRef V) : Val(V) {}
1186 /// Register a value for the flag in the current diagnostic. This
1187 /// value will be shown as the suffix "=value" after the flag name. It is
1188 /// useful in cases where the diagnostic flag accepts values (e.g.,
1189 /// -Rpass or -Wframe-larger-than).
1190 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1191 const AddFlagValue V) {
1192 DB.addFlagValue(V.Val);
1196 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1202 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1204 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1205 DiagnosticsEngine::ak_c_string);
1209 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
1210 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1214 // We use enable_if here to prevent that this overload is selected for
1215 // pointers or other arguments that are implicitly convertible to bool.
1216 template <typename T>
1218 typename std::enable_if<std::is_same<T, bool>::value,
1219 const DiagnosticBuilder &>::type
1220 operator<<(const DiagnosticBuilder &DB, T I) {
1221 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1225 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1227 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1231 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1233 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1237 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1238 const IdentifierInfo *II) {
1239 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1240 DiagnosticsEngine::ak_identifierinfo);
1244 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
1245 // so that we only match those arguments that are (statically) DeclContexts;
1246 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
1248 template <typename T>
1249 inline typename std::enable_if<
1250 std::is_same<typename std::remove_const<T>::type, DeclContext>::value,
1251 const DiagnosticBuilder &>::type
1252 operator<<(const DiagnosticBuilder &DB, T *DC) {
1253 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1254 DiagnosticsEngine::ak_declcontext);
1258 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1260 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1264 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1265 ArrayRef<SourceRange> Ranges) {
1266 for (SourceRange R : Ranges)
1267 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1271 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1272 const CharSourceRange &R) {
1273 DB.AddSourceRange(R);
1277 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1278 const FixItHint &Hint) {
1279 DB.AddFixItHint(Hint);
1283 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1284 ArrayRef<FixItHint> Hints) {
1285 for (const FixItHint &Hint : Hints)
1286 DB.AddFixItHint(Hint);
1290 /// A nullability kind paired with a bit indicating whether it used a
1291 /// context-sensitive keyword.
1292 using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1294 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1295 DiagNullabilityKind nullability);
1297 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1299 assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
1300 "Multiple diagnostics in flight at once!");
1304 return DiagnosticBuilder(this);
1307 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1309 DB.AddString(toString(std::move(E)));
1313 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1314 return Report(SourceLocation(), DiagID);
1317 //===----------------------------------------------------------------------===//
1319 //===----------------------------------------------------------------------===//
1321 /// A little helper class (which is basically a smart pointer that forwards
1322 /// info from DiagnosticsEngine) that allows clients to enquire about the
1323 /// currently in-flight diagnostic.
1325 const DiagnosticsEngine *DiagObj;
1326 StringRef StoredDiagMessage;
1329 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1330 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1331 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1333 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1334 unsigned getID() const { return DiagObj->CurDiagID; }
1335 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1336 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1337 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1339 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1341 /// Return the kind of the specified index.
1343 /// Based on the kind of argument, the accessors below can be used to get
1346 /// \pre Idx < getNumArgs()
1347 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1348 assert(Idx < getNumArgs() && "Argument index out of range!");
1349 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1352 /// Return the provided argument string specified by \p Idx.
1353 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1354 const std::string &getArgStdStr(unsigned Idx) const {
1355 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1356 "invalid argument accessor!");
1357 return DiagObj->DiagArgumentsStr[Idx];
1360 /// Return the specified C string argument.
1361 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1362 const char *getArgCStr(unsigned Idx) const {
1363 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1364 "invalid argument accessor!");
1365 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1368 /// Return the specified signed integer argument.
1369 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1370 int getArgSInt(unsigned Idx) const {
1371 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1372 "invalid argument accessor!");
1373 return (int)DiagObj->DiagArgumentsVal[Idx];
1376 /// Return the specified unsigned integer argument.
1377 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1378 unsigned getArgUInt(unsigned Idx) const {
1379 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1380 "invalid argument accessor!");
1381 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1384 /// Return the specified IdentifierInfo argument.
1385 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1386 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1387 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1388 "invalid argument accessor!");
1389 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1392 /// Return the specified non-string argument in an opaque form.
1393 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1394 intptr_t getRawArg(unsigned Idx) const {
1395 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1396 "invalid argument accessor!");
1397 return DiagObj->DiagArgumentsVal[Idx];
1400 /// Return the number of source ranges associated with this diagnostic.
1401 unsigned getNumRanges() const {
1402 return DiagObj->DiagRanges.size();
1405 /// \pre Idx < getNumRanges()
1406 const CharSourceRange &getRange(unsigned Idx) const {
1407 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1408 return DiagObj->DiagRanges[Idx];
1411 /// Return an array reference for this diagnostic's ranges.
1412 ArrayRef<CharSourceRange> getRanges() const {
1413 return DiagObj->DiagRanges;
1416 unsigned getNumFixItHints() const {
1417 return DiagObj->DiagFixItHints.size();
1420 const FixItHint &getFixItHint(unsigned Idx) const {
1421 assert(Idx < getNumFixItHints() && "Invalid index!");
1422 return DiagObj->DiagFixItHints[Idx];
1425 ArrayRef<FixItHint> getFixItHints() const {
1426 return DiagObj->DiagFixItHints;
1429 /// Format this diagnostic into a string, substituting the
1430 /// formal arguments into the %0 slots.
1432 /// The result is appended onto the \p OutStr array.
1433 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1435 /// Format the given format-string into the output buffer using the
1436 /// arguments stored in this diagnostic.
1437 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1438 SmallVectorImpl<char> &OutStr) const;
1442 * Represents a diagnostic in a form that can be retained until its
1443 * corresponding source manager is destroyed.
1445 class StoredDiagnostic {
1447 DiagnosticsEngine::Level Level;
1449 std::string Message;
1450 std::vector<CharSourceRange> Ranges;
1451 std::vector<FixItHint> FixIts;
1454 StoredDiagnostic() = default;
1455 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1456 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1458 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1459 StringRef Message, FullSourceLoc Loc,
1460 ArrayRef<CharSourceRange> Ranges,
1461 ArrayRef<FixItHint> Fixits);
1463 /// Evaluates true when this object stores a diagnostic.
1464 explicit operator bool() const { return !Message.empty(); }
1466 unsigned getID() const { return ID; }
1467 DiagnosticsEngine::Level getLevel() const { return Level; }
1468 const FullSourceLoc &getLocation() const { return Loc; }
1469 StringRef getMessage() const { return Message; }
1471 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1473 using range_iterator = std::vector<CharSourceRange>::const_iterator;
1475 range_iterator range_begin() const { return Ranges.begin(); }
1476 range_iterator range_end() const { return Ranges.end(); }
1477 unsigned range_size() const { return Ranges.size(); }
1479 ArrayRef<CharSourceRange> getRanges() const {
1480 return llvm::makeArrayRef(Ranges);
1483 using fixit_iterator = std::vector<FixItHint>::const_iterator;
1485 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1486 fixit_iterator fixit_end() const { return FixIts.end(); }
1487 unsigned fixit_size() const { return FixIts.size(); }
1489 ArrayRef<FixItHint> getFixIts() const {
1490 return llvm::makeArrayRef(FixIts);
1494 /// Abstract interface, implemented by clients of the front-end, which
1495 /// formats and prints fully processed diagnostics.
1496 class DiagnosticConsumer {
1498 unsigned NumWarnings = 0; ///< Number of warnings reported
1499 unsigned NumErrors = 0; ///< Number of errors reported
1502 DiagnosticConsumer() = default;
1503 virtual ~DiagnosticConsumer();
1505 unsigned getNumErrors() const { return NumErrors; }
1506 unsigned getNumWarnings() const { return NumWarnings; }
1507 virtual void clear() { NumWarnings = NumErrors = 0; }
1509 /// Callback to inform the diagnostic client that processing
1510 /// of a source file is beginning.
1512 /// Note that diagnostics may be emitted outside the processing of a source
1513 /// file, for example during the parsing of command line options. However,
1514 /// diagnostics with source range information are required to only be emitted
1515 /// in between BeginSourceFile() and EndSourceFile().
1517 /// \param LangOpts The language options for the source file being processed.
1518 /// \param PP The preprocessor object being used for the source; this is
1519 /// optional, e.g., it may not be present when processing AST source files.
1520 virtual void BeginSourceFile(const LangOptions &LangOpts,
1521 const Preprocessor *PP = nullptr) {}
1523 /// Callback to inform the diagnostic client that processing
1524 /// of a source file has ended.
1526 /// The diagnostic client should assume that any objects made available via
1527 /// BeginSourceFile() are inaccessible.
1528 virtual void EndSourceFile() {}
1530 /// Callback to inform the diagnostic client that processing of all
1531 /// source files has ended.
1532 virtual void finish() {}
1534 /// Indicates whether the diagnostics handled by this
1535 /// DiagnosticConsumer should be included in the number of diagnostics
1536 /// reported by DiagnosticsEngine.
1538 /// The default implementation returns true.
1539 virtual bool IncludeInDiagnosticCounts() const;
1541 /// Handle this diagnostic, reporting it to the user or
1542 /// capturing it to a log as needed.
1544 /// The default implementation just keeps track of the total number of
1545 /// warnings and errors.
1546 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1547 const Diagnostic &Info);
1550 /// A diagnostic client that ignores all diagnostics.
1551 class IgnoringDiagConsumer : public DiagnosticConsumer {
1552 virtual void anchor();
1554 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1555 const Diagnostic &Info) override {
1560 /// Diagnostic consumer that forwards diagnostics along to an
1561 /// existing, already-initialized diagnostic consumer.
1563 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1564 DiagnosticConsumer &Target;
1567 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1568 ~ForwardingDiagnosticConsumer() override;
1570 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1571 const Diagnostic &Info) override;
1572 void clear() override;
1574 bool IncludeInDiagnosticCounts() const override;
1577 // Struct used for sending info about how a type should be printed.
1578 struct TemplateDiffTypes {
1581 unsigned PrintTree : 1;
1582 unsigned PrintFromType : 1;
1583 unsigned ElideType : 1;
1584 unsigned ShowColors : 1;
1586 // The printer sets this variable to true if the template diff was used.
1587 unsigned TemplateDiffUsed : 1;
1590 /// Special character that the diagnostic printer will use to toggle the bold
1591 /// attribute. The character itself will be not be printed.
1592 const char ToggleHighlight = 127;
1594 /// ProcessWarningOptions - Initialize the diagnostic client and process the
1595 /// warning options specified on the command line.
1596 void ProcessWarningOptions(DiagnosticsEngine &Diags,
1597 const DiagnosticOptions &Opts,
1598 bool ReportDiags = true);
1600 } // namespace clang
1602 #endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H