1 //===- Diagnostic.h - C Language Family Diagnostic Handling -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Defines the Diagnostic-related interfaces.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
16 #define LLVM_CLANG_BASIC_DIAGNOSTIC_H
18 #include "clang/Basic/DiagnosticIDs.h"
19 #include "clang/Basic/DiagnosticOptions.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Basic/Specifiers.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/IntrusiveRefCntPtr.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/iterator_range.h"
28 #include "llvm/Support/Compiler.h"
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
189 /// NestedNameSpecifier *
195 /// pair<QualType, QualType>
202 /// Represents on argument value, which is a union discriminated
203 /// by ArgumentKind, with a value.
204 using ArgumentValue = std::pair<ArgumentKind, intptr_t>;
207 // Used by __extension__
208 unsigned char AllExtensionsSilenced = 0;
210 // Suppress diagnostics after a fatal error?
211 bool SuppressAfterFatalError = true;
213 // Suppress all diagnostics.
214 bool SuppressAllDiagnostics = false;
216 // Elide common types of templates.
217 bool ElideType = true;
219 // Print a tree when comparing templates.
220 bool PrintTemplateTree = false;
222 // Color printing is enabled.
223 bool ShowColors = false;
225 // Which overload candidates to show.
226 OverloadsShown ShowOverloads = Ovl_All;
228 // Cap of # errors emitted, 0 -> no limit.
229 unsigned ErrorLimit = 0;
231 // Cap on depth of template backtrace stack, 0 -> no limit.
232 unsigned TemplateBacktraceLimit = 0;
234 // Cap on depth of constexpr evaluation backtrace stack, 0 -> no limit.
235 unsigned ConstexprBacktraceLimit = 0;
237 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
238 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
239 DiagnosticConsumer *Client = nullptr;
240 std::unique_ptr<DiagnosticConsumer> Owner;
241 SourceManager *SourceMgr = nullptr;
243 /// Mapping information for diagnostics.
245 /// Mapping info is packed into four bits per diagnostic. The low three
246 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
247 /// The high bit is set when the mapping was established as a user mapping.
248 /// If the high bit is clear, then the low bits are set to the default
249 /// value, and should be mapped with -pedantic, -Werror, etc.
251 /// A new DiagState is created and kept around when diagnostic pragmas modify
252 /// the state so that we know what is the diagnostic state at any given
255 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
258 // "Global" configuration state that can actually vary between modules.
260 // Ignore all warnings: -w
261 unsigned IgnoreAllWarnings : 1;
263 // Enable all warnings.
264 unsigned EnableAllWarnings : 1;
266 // Treat warnings like errors.
267 unsigned WarningsAsErrors : 1;
269 // Treat errors like fatal errors.
270 unsigned ErrorsAsFatal : 1;
272 // Suppress warnings in system headers.
273 unsigned SuppressSystemWarnings : 1;
275 // Map extensions to warnings or errors?
276 diag::Severity ExtBehavior = diag::Severity::Ignored;
279 : IgnoreAllWarnings(false), EnableAllWarnings(false),
280 WarningsAsErrors(false), ErrorsAsFatal(false),
281 SuppressSystemWarnings(false) {}
283 using iterator = llvm::DenseMap<unsigned, DiagnosticMapping>::iterator;
284 using const_iterator =
285 llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator;
287 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
288 DiagMap[Diag] = Info;
291 DiagnosticMapping lookupMapping(diag::kind Diag) const {
292 return DiagMap.lookup(Diag);
295 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
297 const_iterator begin() const { return DiagMap.begin(); }
298 const_iterator end() const { return DiagMap.end(); }
301 /// Keeps and automatically disposes all DiagStates that we create.
302 std::list<DiagState> DiagStates;
304 /// A mapping from files to the diagnostic states for those files. Lazily
305 /// built on demand for files in which the diagnostic state has not changed.
308 /// Add an initial diagnostic state.
309 void appendFirst(DiagState *State);
311 /// Add a new latest state point.
312 void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
314 /// Look up the diagnostic state at a given source location.
315 DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
317 /// Determine whether this map is empty.
318 bool empty() const { return Files.empty(); }
320 /// Clear out this map.
323 FirstDiagState = CurDiagState = nullptr;
324 CurDiagStateLoc = SourceLocation();
327 /// Produce a debugging dump of the diagnostic state.
328 LLVM_DUMP_METHOD void dump(SourceManager &SrcMgr,
329 StringRef DiagName = StringRef()) const;
331 /// Grab the most-recently-added state point.
332 DiagState *getCurDiagState() const { return CurDiagState; }
334 /// Get the location at which a diagnostic state was last added.
335 SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
338 friend class ASTReader;
339 friend class ASTWriter;
341 /// Represents a point in source where the diagnostic state was
342 /// modified because of a pragma.
344 /// 'Loc' can be null if the point represents the diagnostic state
345 /// modifications done through the command-line.
346 struct DiagStatePoint {
350 DiagStatePoint(DiagState *State, unsigned Offset)
351 : State(State), Offset(Offset) {}
354 /// Description of the diagnostic states and state transitions for a
355 /// particular FileID.
357 /// The diagnostic state for the parent file. This is strictly redundant,
358 /// as looking up the DecomposedIncludedLoc for the FileID in the Files
359 /// map would give us this, but we cache it here for performance.
360 File *Parent = nullptr;
362 /// The offset of this file within its parent.
363 unsigned ParentOffset = 0;
365 /// Whether this file has any local (not imported from an AST file)
366 /// diagnostic state transitions.
367 bool HasLocalTransitions = false;
369 /// The points within the file where the state changes. There will always
370 /// be at least one of these (the state on entry to the file).
371 llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
373 DiagState *lookup(unsigned Offset) const;
376 /// The diagnostic states for each file.
377 mutable std::map<FileID, File> Files;
379 /// The initial diagnostic state.
380 DiagState *FirstDiagState;
382 /// The current diagnostic state.
383 DiagState *CurDiagState;
385 /// The location at which the current diagnostic state was established.
386 SourceLocation CurDiagStateLoc;
388 /// Get the diagnostic state information for a file.
389 File *getFile(SourceManager &SrcMgr, FileID ID) const;
392 DiagStateMap DiagStatesByLoc;
394 /// Keeps the DiagState that was active during each diagnostic 'push'
395 /// so we can get back at it when we 'pop'.
396 std::vector<DiagState *> DiagStateOnPushStack;
398 DiagState *GetCurDiagState() const {
399 return DiagStatesByLoc.getCurDiagState();
402 void PushDiagStatePoint(DiagState *State, SourceLocation L);
404 /// Finds the DiagStatePoint that contains the diagnostic state of
405 /// the given source location.
406 DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
407 return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
408 : DiagStatesByLoc.getCurDiagState();
411 /// Sticky flag set to \c true when an error is emitted.
414 /// Sticky flag set to \c true when an "uncompilable error" occurs.
415 /// I.e. an error that was not upgraded from a warning by -Werror.
416 bool UncompilableErrorOccurred;
418 /// Sticky flag set to \c true when a fatal error is emitted.
419 bool FatalErrorOccurred;
421 /// Indicates that an unrecoverable error has occurred.
422 bool UnrecoverableErrorOccurred;
424 /// Counts for DiagnosticErrorTrap to check whether an error occurred
425 /// during a parsing section, e.g. during parsing a function.
426 unsigned TrapNumErrorsOccurred;
427 unsigned TrapNumUnrecoverableErrorsOccurred;
429 /// The level of the last diagnostic emitted.
431 /// This is used to emit continuation diagnostics with the same level as the
432 /// diagnostic that they follow.
433 DiagnosticIDs::Level LastDiagLevel;
435 /// Number of warnings reported
436 unsigned NumWarnings;
438 /// Number of errors reported
441 /// A function pointer that converts an opaque diagnostic
442 /// argument to a strings.
444 /// This takes the modifiers and argument that was present in the diagnostic.
446 /// The PrevArgs array indicates the previous arguments formatted for this
447 /// diagnostic. Implementations of this function can use this information to
448 /// avoid redundancy across arguments.
450 /// This is a hack to avoid a layering violation between libbasic and libsema.
451 using ArgToStringFnTy = void (*)(
452 ArgumentKind Kind, intptr_t Val,
453 StringRef Modifier, StringRef Argument,
454 ArrayRef<ArgumentValue> PrevArgs,
455 SmallVectorImpl<char> &Output,
457 ArrayRef<intptr_t> QualTypeVals);
459 void *ArgToStringCookie = nullptr;
460 ArgToStringFnTy ArgToStringFn;
462 /// ID of the "delayed" diagnostic, which is a (typically
463 /// fatal) diagnostic that had to be delayed because it was found
464 /// while emitting another diagnostic.
465 unsigned DelayedDiagID;
467 /// First string argument for the delayed diagnostic.
468 std::string DelayedDiagArg1;
470 /// Second string argument for the delayed diagnostic.
471 std::string DelayedDiagArg2;
473 /// Optional flag value.
475 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
476 /// -Rpass=<value>. The content of this string is emitted after the flag name
478 std::string FlagValue;
481 explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
482 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
483 DiagnosticConsumer *client = nullptr,
484 bool ShouldOwnClient = true);
485 DiagnosticsEngine(const DiagnosticsEngine &) = delete;
486 DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
487 ~DiagnosticsEngine();
489 LLVM_DUMP_METHOD void dump() const { DiagStatesByLoc.dump(*SourceMgr); }
490 LLVM_DUMP_METHOD void dump(StringRef DiagName) const {
491 DiagStatesByLoc.dump(*SourceMgr, DiagName);
494 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
498 /// Retrieve the diagnostic options.
499 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
501 using diag_mapping_range = llvm::iterator_range<DiagState::const_iterator>;
503 /// Get the current set of diagnostic mappings.
504 diag_mapping_range getDiagnosticMappings() const {
505 const DiagState &DS = *GetCurDiagState();
506 return diag_mapping_range(DS.begin(), DS.end());
509 DiagnosticConsumer *getClient() { return Client; }
510 const DiagnosticConsumer *getClient() const { return Client; }
512 /// Determine whether this \c DiagnosticsEngine object own its client.
513 bool ownsClient() const { return Owner != nullptr; }
515 /// Return the current diagnostic client along with ownership of that
517 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
519 bool hasSourceManager() const { return SourceMgr != nullptr; }
521 SourceManager &getSourceManager() const {
522 assert(SourceMgr && "SourceManager not set!");
526 void setSourceManager(SourceManager *SrcMgr) {
527 assert(DiagStatesByLoc.empty() &&
528 "Leftover diag state from a different SourceManager.");
532 //===--------------------------------------------------------------------===//
533 // DiagnosticsEngine characterization methods, used by a client to customize
534 // how diagnostics are emitted.
537 /// Copies the current DiagMappings and pushes the new copy
538 /// onto the top of the stack.
539 void pushMappings(SourceLocation Loc);
541 /// Pops the current DiagMappings off the top of the stack,
542 /// causing the new top of the stack to be the active mappings.
544 /// \returns \c true if the pop happens, \c false if there is only one
545 /// DiagMapping on the stack.
546 bool popMappings(SourceLocation Loc);
548 /// Set the diagnostic client associated with this diagnostic object.
550 /// \param ShouldOwnClient true if the diagnostic object should take
551 /// ownership of \c client.
552 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
554 /// Specify a limit for the number of errors we should
555 /// emit before giving up.
557 /// Zero disables the limit.
558 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
560 /// Specify the maximum number of template instantiation
561 /// notes to emit along with a given diagnostic.
562 void setTemplateBacktraceLimit(unsigned Limit) {
563 TemplateBacktraceLimit = Limit;
566 /// Retrieve the maximum number of template instantiation
567 /// notes to emit along with a given diagnostic.
568 unsigned getTemplateBacktraceLimit() const {
569 return TemplateBacktraceLimit;
572 /// Specify the maximum number of constexpr evaluation
573 /// notes to emit along with a given diagnostic.
574 void setConstexprBacktraceLimit(unsigned Limit) {
575 ConstexprBacktraceLimit = Limit;
578 /// Retrieve the maximum number of constexpr evaluation
579 /// notes to emit along with a given diagnostic.
580 unsigned getConstexprBacktraceLimit() const {
581 return ConstexprBacktraceLimit;
584 /// When set to true, any unmapped warnings are ignored.
586 /// If this and WarningsAsErrors are both set, then this one wins.
587 void setIgnoreAllWarnings(bool Val) {
588 GetCurDiagState()->IgnoreAllWarnings = Val;
590 bool getIgnoreAllWarnings() const {
591 return GetCurDiagState()->IgnoreAllWarnings;
594 /// When set to true, any unmapped ignored warnings are no longer
597 /// If this and IgnoreAllWarnings are both set, then that one wins.
598 void setEnableAllWarnings(bool Val) {
599 GetCurDiagState()->EnableAllWarnings = Val;
601 bool getEnableAllWarnings() const {
602 return GetCurDiagState()->EnableAllWarnings;
605 /// When set to true, any warnings reported are issued as errors.
606 void setWarningsAsErrors(bool Val) {
607 GetCurDiagState()->WarningsAsErrors = Val;
609 bool getWarningsAsErrors() const {
610 return GetCurDiagState()->WarningsAsErrors;
613 /// When set to true, any error reported is made a fatal error.
614 void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
615 bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
617 /// When set to true (the default), suppress further diagnostics after
619 void setSuppressAfterFatalError(bool Val) { SuppressAfterFatalError = Val; }
621 /// When set to true mask warnings that come from system headers.
622 void setSuppressSystemWarnings(bool Val) {
623 GetCurDiagState()->SuppressSystemWarnings = Val;
625 bool getSuppressSystemWarnings() const {
626 return GetCurDiagState()->SuppressSystemWarnings;
629 /// Suppress all diagnostics, to silence the front end when we
630 /// know that we don't want any more diagnostics to be passed along to the
632 void setSuppressAllDiagnostics(bool Val = true) {
633 SuppressAllDiagnostics = Val;
635 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
637 /// Set type eliding, to skip outputting same types occurring in
639 void setElideType(bool Val = true) { ElideType = Val; }
640 bool getElideType() { return ElideType; }
642 /// Set tree printing, to outputting the template difference in a
644 void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
645 bool getPrintTemplateTree() { return PrintTemplateTree; }
647 /// Set color printing, so the type diffing will inject color markers
649 void setShowColors(bool Val = false) { ShowColors = Val; }
650 bool getShowColors() { return ShowColors; }
652 /// Specify which overload candidates to show when overload resolution
655 /// By default, we show all candidates.
656 void setShowOverloads(OverloadsShown Val) {
659 OverloadsShown getShowOverloads() const { return ShowOverloads; }
661 /// Pretend that the last diagnostic issued was ignored, so any
662 /// subsequent notes will be suppressed, or restore a prior ignoring
663 /// state after ignoring some diagnostics and their notes, possibly in
664 /// the middle of another diagnostic.
666 /// This can be used by clients who suppress diagnostics themselves.
667 void setLastDiagnosticIgnored(bool Ignored = true) {
668 if (LastDiagLevel == DiagnosticIDs::Fatal)
669 FatalErrorOccurred = true;
670 LastDiagLevel = Ignored ? DiagnosticIDs::Ignored : DiagnosticIDs::Warning;
673 /// Determine whether the previous diagnostic was ignored. This can
674 /// be used by clients that want to determine whether notes attached to a
675 /// diagnostic will be suppressed.
676 bool isLastDiagnosticIgnored() const {
677 return LastDiagLevel == DiagnosticIDs::Ignored;
680 /// Controls whether otherwise-unmapped extension diagnostics are
681 /// mapped onto ignore/warning/error.
683 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
684 void setExtensionHandlingBehavior(diag::Severity H) {
685 GetCurDiagState()->ExtBehavior = H;
687 diag::Severity getExtensionHandlingBehavior() const {
688 return GetCurDiagState()->ExtBehavior;
691 /// Counter bumped when an __extension__ block is/ encountered.
693 /// When non-zero, all extension diagnostics are entirely silenced, no
694 /// matter how they are mapped.
695 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
696 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
697 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
699 /// This allows the client to specify that certain warnings are
702 /// Notes can never be mapped, errors can only be mapped to fatal, and
703 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
705 /// \param Loc The source location that this change of diagnostic state should
706 /// take affect. It can be null if we are setting the latest state.
707 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
709 /// Change an entire diagnostic group (e.g. "unknown-pragmas") to
710 /// have the specified mapping.
712 /// \returns true (and ignores the request) if "Group" was unknown, false
715 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
716 /// state of the -Wfoo group and vice versa.
718 /// \param Loc The source location that this change of diagnostic state should
719 /// take affect. It can be null if we are setting the state from command-line.
720 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
722 SourceLocation Loc = SourceLocation());
724 /// Set the warning-as-error flag for the given diagnostic group.
726 /// This function always only operates on the current diagnostic state.
728 /// \returns True if the given group is unknown, false otherwise.
729 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
731 /// Set the error-as-fatal flag for the given diagnostic group.
733 /// This function always only operates on the current diagnostic state.
735 /// \returns True if the given group is unknown, false otherwise.
736 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
738 /// Add the specified mapping to all diagnostics of the specified
741 /// Mainly to be used by -Wno-everything to disable all warnings but allow
742 /// subsequent -W options to enable specific warnings.
743 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
744 SourceLocation Loc = SourceLocation());
746 bool hasErrorOccurred() const { return ErrorOccurred; }
748 /// Errors that actually prevent compilation, not those that are
749 /// upgraded from a warning by -Werror.
750 bool hasUncompilableErrorOccurred() const {
751 return UncompilableErrorOccurred;
753 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
755 /// Determine whether any kind of unrecoverable error has occurred.
756 bool hasUnrecoverableErrorOccurred() const {
757 return FatalErrorOccurred || UnrecoverableErrorOccurred;
760 unsigned getNumWarnings() const { return NumWarnings; }
762 void setNumWarnings(unsigned NumWarnings) {
763 this->NumWarnings = NumWarnings;
766 /// Return an ID for a diagnostic with the specified format string and
769 /// If this is the first request for this diagnostic, it is registered and
770 /// created, otherwise the existing ID is returned.
772 /// \param FormatString A fixed diagnostic format string that will be hashed
773 /// and mapped to a unique DiagID.
774 template <unsigned N>
775 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
776 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
777 StringRef(FormatString, N - 1));
780 /// Converts a diagnostic argument (as an intptr_t) into the string
781 /// that represents it.
782 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
783 StringRef Modifier, StringRef Argument,
784 ArrayRef<ArgumentValue> PrevArgs,
785 SmallVectorImpl<char> &Output,
786 ArrayRef<intptr_t> QualTypeVals) const {
787 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
788 ArgToStringCookie, QualTypeVals);
791 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
793 ArgToStringCookie = Cookie;
796 /// Note that the prior diagnostic was emitted by some other
797 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
798 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
799 LastDiagLevel = Other.LastDiagLevel;
802 /// Reset the state of the diagnostic object to its initial
806 //===--------------------------------------------------------------------===//
807 // DiagnosticsEngine classification and reporting interfaces.
810 /// Determine whether the diagnostic is known to be ignored.
812 /// This can be used to opportunistically avoid expensive checks when it's
813 /// known for certain that the diagnostic has been suppressed at the
814 /// specified location \p Loc.
816 /// \param Loc The source location we are interested in finding out the
817 /// diagnostic state. Can be null in order to query the latest state.
818 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
819 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
820 diag::Severity::Ignored;
823 /// Based on the way the client configured the DiagnosticsEngine
824 /// object, classify the specified diagnostic ID into a Level, consumable by
825 /// the DiagnosticConsumer.
827 /// To preserve invariant assumptions, this function should not be used to
828 /// influence parse or semantic analysis actions. Instead consider using
831 /// \param Loc The source location we are interested in finding out the
832 /// diagnostic state. Can be null in order to query the latest state.
833 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
834 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
837 /// Issue the message to the client.
839 /// This actually returns an instance of DiagnosticBuilder which emits the
840 /// diagnostics (through @c ProcessDiag) when it is destroyed.
842 /// \param DiagID A member of the @c diag::kind enum.
843 /// \param Loc Represents the source location associated with the diagnostic,
844 /// which can be an invalid location if no position information is available.
845 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
846 inline DiagnosticBuilder Report(unsigned DiagID);
848 void Report(const StoredDiagnostic &storedDiag);
850 /// Determine whethere there is already a diagnostic in flight.
851 bool isDiagnosticInFlight() const {
852 return CurDiagID != std::numeric_limits<unsigned>::max();
855 /// Set the "delayed" diagnostic that will be emitted once
856 /// the current diagnostic completes.
858 /// If a diagnostic is already in-flight but the front end must
859 /// report a problem (e.g., with an inconsistent file system
860 /// state), this routine sets a "delayed" diagnostic that will be
861 /// emitted after the current diagnostic completes. This should
862 /// only be used for fatal errors detected at inconvenient
863 /// times. If emitting a delayed diagnostic causes a second delayed
864 /// diagnostic to be introduced, that second delayed diagnostic
867 /// \param DiagID The ID of the diagnostic being delayed.
869 /// \param Arg1 A string argument that will be provided to the
870 /// diagnostic. A copy of this string will be stored in the
871 /// DiagnosticsEngine object itself.
873 /// \param Arg2 A string argument that will be provided to the
874 /// diagnostic. A copy of this string will be stored in the
875 /// DiagnosticsEngine object itself.
876 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
877 StringRef Arg2 = "");
879 /// Clear out the current diagnostic.
880 void Clear() { CurDiagID = std::numeric_limits<unsigned>::max(); }
882 /// Return the value associated with this diagnostic flag.
883 StringRef getFlagValue() const { return FlagValue; }
886 // This is private state used by DiagnosticBuilder. We put it here instead of
887 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
888 // object. This implementation choice means that we can only have one
889 // diagnostic "in flight" at a time, but this seems to be a reasonable
890 // tradeoff to keep these objects small. Assertions verify that only one
891 // diagnostic is in flight at a time.
892 friend class Diagnostic;
893 friend class DiagnosticBuilder;
894 friend class DiagnosticErrorTrap;
895 friend class DiagnosticIDs;
896 friend class PartialDiagnostic;
898 /// Report the delayed diagnostic.
899 void ReportDelayed();
901 /// The location of the current diagnostic that is in flight.
902 SourceLocation CurDiagLoc;
904 /// The ID of the current diagnostic that is in flight.
906 /// This is set to std::numeric_limits<unsigned>::max() when there is no
907 /// diagnostic in flight.
911 /// The maximum number of arguments we can hold.
913 /// We currently only support up to 10 arguments (%0-%9). A single
914 /// diagnostic with more than that almost certainly has to be simplified
919 /// The number of entries in Arguments.
920 signed char NumDiagArgs;
922 /// Specifies whether an argument is in DiagArgumentsStr or
923 /// in DiagArguments.
925 /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
927 unsigned char DiagArgumentsKind[MaxArguments];
929 /// Holds the values of each string argument for the current
932 /// This is only used when the corresponding ArgumentKind is ak_std_string.
933 std::string DiagArgumentsStr[MaxArguments];
935 /// The values for the various substitution positions.
937 /// This is used when the argument is not an std::string. The specific
938 /// value is mangled into an intptr_t and the interpretation depends on
939 /// exactly what sort of argument kind it is.
940 intptr_t DiagArgumentsVal[MaxArguments];
942 /// The list of ranges added to this diagnostic.
943 SmallVector<CharSourceRange, 8> DiagRanges;
945 /// If valid, provides a hint with some code to insert, remove,
946 /// or modify at a particular position.
947 SmallVector<FixItHint, 8> DiagFixItHints;
949 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
950 bool isPragma = L.isValid();
951 DiagnosticMapping Mapping =
952 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
954 // If this is a pragma mapping, then set the diagnostic mapping flags so
955 // that we override command line options.
957 Mapping.setNoWarningAsError(true);
958 Mapping.setNoErrorAsFatal(true);
964 /// Used to report a diagnostic that is finally fully formed.
966 /// \returns true if the diagnostic was emitted, false if it was suppressed.
968 return Diags->ProcessDiag(*this);
971 /// @name Diagnostic Emission
974 friend class ASTReader;
975 friend class ASTWriter;
977 // Sema requires access to the following functions because the current design
978 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
979 // access us directly to ensure we minimize the emitted code for the common
980 // Sema::Diag() patterns.
983 /// Emit the current diagnostic and clear the diagnostic state.
985 /// \param Force Emit the diagnostic regardless of suppression settings.
986 bool EmitCurrentDiagnostic(bool Force = false);
988 unsigned getCurrentDiagID() const { return CurDiagID; }
990 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
995 /// RAII class that determines when any errors have occurred
996 /// between the time the instance was created and the time it was
998 class DiagnosticErrorTrap {
999 DiagnosticsEngine &Diag;
1001 unsigned NumUnrecoverableErrors;
1004 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
1005 : Diag(Diag) { reset(); }
1007 /// Determine whether any errors have occurred since this
1008 /// object instance was created.
1009 bool hasErrorOccurred() const {
1010 return Diag.TrapNumErrorsOccurred > NumErrors;
1013 /// Determine whether any unrecoverable errors have occurred since this
1014 /// object instance was created.
1015 bool hasUnrecoverableErrorOccurred() const {
1016 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
1019 /// Set to initial state of "no errors occurred".
1021 NumErrors = Diag.TrapNumErrorsOccurred;
1022 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
1026 //===----------------------------------------------------------------------===//
1027 // DiagnosticBuilder
1028 //===----------------------------------------------------------------------===//
1030 /// A little helper class used to produce diagnostics.
1032 /// This is constructed by the DiagnosticsEngine::Report method, and
1033 /// allows insertion of extra information (arguments and source ranges) into
1034 /// the currently "in flight" diagnostic. When the temporary for the builder
1035 /// is destroyed, the diagnostic is issued.
1037 /// Note that many of these will be created as temporary objects (many call
1038 /// sites), so we want them to be small and we never want their address taken.
1039 /// This ensures that compilers with somewhat reasonable optimizers will promote
1040 /// the common fields to registers, eliminating increments of the NumArgs field,
1042 class DiagnosticBuilder {
1043 friend class DiagnosticsEngine;
1044 friend class PartialDiagnostic;
1046 mutable DiagnosticsEngine *DiagObj = nullptr;
1047 mutable unsigned NumArgs = 0;
1049 /// Status variable indicating if this diagnostic is still active.
1051 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
1052 // but LLVM is not currently smart enough to eliminate the null check that
1053 // Emit() would end up with if we used that as our status variable.
1054 mutable bool IsActive = false;
1056 /// Flag indicating that this diagnostic is being emitted via a
1057 /// call to ForceEmit.
1058 mutable bool IsForceEmit = false;
1060 DiagnosticBuilder() = default;
1062 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
1063 : DiagObj(diagObj), IsActive(true) {
1064 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
1065 diagObj->DiagRanges.clear();
1066 diagObj->DiagFixItHints.clear();
1070 void FlushCounts() {
1071 DiagObj->NumDiagArgs = NumArgs;
1074 /// Clear out the current diagnostic.
1075 void Clear() const {
1078 IsForceEmit = false;
1081 /// Determine whether this diagnostic is still active.
1082 bool isActive() const { return IsActive; }
1084 /// Force the diagnostic builder to emit the diagnostic now.
1086 /// Once this function has been called, the DiagnosticBuilder object
1087 /// should not be used again before it is destroyed.
1089 /// \returns true if a diagnostic was emitted, false if the
1090 /// diagnostic was suppressed.
1092 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1093 // (or by a subclass, as in SemaDiagnosticBuilder).
1094 if (!isActive()) return false;
1096 // When emitting diagnostics, we set the final argument count into
1097 // the DiagnosticsEngine object.
1100 // Process the diagnostic.
1101 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
1103 // This diagnostic is dead.
1110 /// Copy constructor. When copied, this "takes" the diagnostic info from the
1111 /// input and neuters it.
1112 DiagnosticBuilder(const DiagnosticBuilder &D) {
1113 DiagObj = D.DiagObj;
1114 IsActive = D.IsActive;
1115 IsForceEmit = D.IsForceEmit;
1117 NumArgs = D.NumArgs;
1120 DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1122 /// Emits the diagnostic.
1123 ~DiagnosticBuilder() {
1127 /// Retrieve an empty diagnostic builder.
1128 static DiagnosticBuilder getEmpty() {
1132 /// Forces the diagnostic to be emitted.
1133 const DiagnosticBuilder &setForceEmit() const {
1138 /// Conversion of DiagnosticBuilder to bool always returns \c true.
1140 /// This allows is to be used in boolean error contexts (where \c true is
1141 /// used to indicate that an error has occurred), like:
1143 /// return Diag(...);
1145 operator bool() const { return true; }
1147 void AddString(StringRef S) const {
1148 assert(isActive() && "Clients must not add to cleared diagnostic!");
1149 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1150 "Too many arguments to diagnostic!");
1151 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
1152 DiagObj->DiagArgumentsStr[NumArgs++] = S;
1155 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1156 assert(isActive() && "Clients must not add to cleared diagnostic!");
1157 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1158 "Too many arguments to diagnostic!");
1159 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
1160 DiagObj->DiagArgumentsVal[NumArgs++] = V;
1163 void AddSourceRange(const CharSourceRange &R) const {
1164 assert(isActive() && "Clients must not add to cleared diagnostic!");
1165 DiagObj->DiagRanges.push_back(R);
1168 void AddFixItHint(const FixItHint &Hint) const {
1169 assert(isActive() && "Clients must not add to cleared diagnostic!");
1171 DiagObj->DiagFixItHints.push_back(Hint);
1174 void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
1177 struct AddFlagValue {
1180 explicit AddFlagValue(StringRef V) : Val(V) {}
1183 /// Register a value for the flag in the current diagnostic. This
1184 /// value will be shown as the suffix "=value" after the flag name. It is
1185 /// useful in cases where the diagnostic flag accepts values (e.g.,
1186 /// -Rpass or -Wframe-larger-than).
1187 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1188 const AddFlagValue V) {
1189 DB.addFlagValue(V.Val);
1193 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1199 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1201 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1202 DiagnosticsEngine::ak_c_string);
1206 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
1207 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1211 // We use enable_if here to prevent that this overload is selected for
1212 // pointers or other arguments that are implicitly convertible to bool.
1213 template <typename T>
1215 typename std::enable_if<std::is_same<T, bool>::value,
1216 const DiagnosticBuilder &>::type
1217 operator<<(const DiagnosticBuilder &DB, T I) {
1218 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1222 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1224 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1228 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1230 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1234 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1235 const IdentifierInfo *II) {
1236 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1237 DiagnosticsEngine::ak_identifierinfo);
1241 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
1242 // so that we only match those arguments that are (statically) DeclContexts;
1243 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
1245 template <typename T>
1246 inline typename std::enable_if<
1247 std::is_same<typename std::remove_const<T>::type, DeclContext>::value,
1248 const DiagnosticBuilder &>::type
1249 operator<<(const DiagnosticBuilder &DB, T *DC) {
1250 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1251 DiagnosticsEngine::ak_declcontext);
1255 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1257 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1261 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1262 ArrayRef<SourceRange> Ranges) {
1263 for (SourceRange R : Ranges)
1264 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1268 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1269 const CharSourceRange &R) {
1270 DB.AddSourceRange(R);
1274 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1275 const FixItHint &Hint) {
1276 DB.AddFixItHint(Hint);
1280 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1281 ArrayRef<FixItHint> Hints) {
1282 for (const FixItHint &Hint : Hints)
1283 DB.AddFixItHint(Hint);
1287 /// A nullability kind paired with a bit indicating whether it used a
1288 /// context-sensitive keyword.
1289 using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1291 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1292 DiagNullabilityKind nullability);
1294 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1296 assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
1297 "Multiple diagnostics in flight at once!");
1301 return DiagnosticBuilder(this);
1304 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1305 return Report(SourceLocation(), DiagID);
1308 //===----------------------------------------------------------------------===//
1310 //===----------------------------------------------------------------------===//
1312 /// A little helper class (which is basically a smart pointer that forwards
1313 /// info from DiagnosticsEngine) that allows clients to enquire about the
1314 /// currently in-flight diagnostic.
1316 const DiagnosticsEngine *DiagObj;
1317 StringRef StoredDiagMessage;
1320 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1321 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1322 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1324 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1325 unsigned getID() const { return DiagObj->CurDiagID; }
1326 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1327 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1328 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1330 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1332 /// Return the kind of the specified index.
1334 /// Based on the kind of argument, the accessors below can be used to get
1337 /// \pre Idx < getNumArgs()
1338 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1339 assert(Idx < getNumArgs() && "Argument index out of range!");
1340 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1343 /// Return the provided argument string specified by \p Idx.
1344 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1345 const std::string &getArgStdStr(unsigned Idx) const {
1346 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1347 "invalid argument accessor!");
1348 return DiagObj->DiagArgumentsStr[Idx];
1351 /// Return the specified C string argument.
1352 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1353 const char *getArgCStr(unsigned Idx) const {
1354 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1355 "invalid argument accessor!");
1356 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1359 /// Return the specified signed integer argument.
1360 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1361 int getArgSInt(unsigned Idx) const {
1362 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1363 "invalid argument accessor!");
1364 return (int)DiagObj->DiagArgumentsVal[Idx];
1367 /// Return the specified unsigned integer argument.
1368 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1369 unsigned getArgUInt(unsigned Idx) const {
1370 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1371 "invalid argument accessor!");
1372 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1375 /// Return the specified IdentifierInfo argument.
1376 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1377 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1378 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1379 "invalid argument accessor!");
1380 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1383 /// Return the specified non-string argument in an opaque form.
1384 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1385 intptr_t getRawArg(unsigned Idx) const {
1386 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1387 "invalid argument accessor!");
1388 return DiagObj->DiagArgumentsVal[Idx];
1391 /// Return the number of source ranges associated with this diagnostic.
1392 unsigned getNumRanges() const {
1393 return DiagObj->DiagRanges.size();
1396 /// \pre Idx < getNumRanges()
1397 const CharSourceRange &getRange(unsigned Idx) const {
1398 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1399 return DiagObj->DiagRanges[Idx];
1402 /// Return an array reference for this diagnostic's ranges.
1403 ArrayRef<CharSourceRange> getRanges() const {
1404 return DiagObj->DiagRanges;
1407 unsigned getNumFixItHints() const {
1408 return DiagObj->DiagFixItHints.size();
1411 const FixItHint &getFixItHint(unsigned Idx) const {
1412 assert(Idx < getNumFixItHints() && "Invalid index!");
1413 return DiagObj->DiagFixItHints[Idx];
1416 ArrayRef<FixItHint> getFixItHints() const {
1417 return DiagObj->DiagFixItHints;
1420 /// Format this diagnostic into a string, substituting the
1421 /// formal arguments into the %0 slots.
1423 /// The result is appended onto the \p OutStr array.
1424 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1426 /// Format the given format-string into the output buffer using the
1427 /// arguments stored in this diagnostic.
1428 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1429 SmallVectorImpl<char> &OutStr) const;
1433 * Represents a diagnostic in a form that can be retained until its
1434 * corresponding source manager is destroyed.
1436 class StoredDiagnostic {
1438 DiagnosticsEngine::Level Level;
1440 std::string Message;
1441 std::vector<CharSourceRange> Ranges;
1442 std::vector<FixItHint> FixIts;
1445 StoredDiagnostic() = default;
1446 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1447 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1449 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1450 StringRef Message, FullSourceLoc Loc,
1451 ArrayRef<CharSourceRange> Ranges,
1452 ArrayRef<FixItHint> Fixits);
1454 /// Evaluates true when this object stores a diagnostic.
1455 explicit operator bool() const { return !Message.empty(); }
1457 unsigned getID() const { return ID; }
1458 DiagnosticsEngine::Level getLevel() const { return Level; }
1459 const FullSourceLoc &getLocation() const { return Loc; }
1460 StringRef getMessage() const { return Message; }
1462 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1464 using range_iterator = std::vector<CharSourceRange>::const_iterator;
1466 range_iterator range_begin() const { return Ranges.begin(); }
1467 range_iterator range_end() const { return Ranges.end(); }
1468 unsigned range_size() const { return Ranges.size(); }
1470 ArrayRef<CharSourceRange> getRanges() const {
1471 return llvm::makeArrayRef(Ranges);
1474 using fixit_iterator = std::vector<FixItHint>::const_iterator;
1476 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1477 fixit_iterator fixit_end() const { return FixIts.end(); }
1478 unsigned fixit_size() const { return FixIts.size(); }
1480 ArrayRef<FixItHint> getFixIts() const {
1481 return llvm::makeArrayRef(FixIts);
1485 /// Abstract interface, implemented by clients of the front-end, which
1486 /// formats and prints fully processed diagnostics.
1487 class DiagnosticConsumer {
1489 unsigned NumWarnings = 0; ///< Number of warnings reported
1490 unsigned NumErrors = 0; ///< Number of errors reported
1493 DiagnosticConsumer() = default;
1494 virtual ~DiagnosticConsumer();
1496 unsigned getNumErrors() const { return NumErrors; }
1497 unsigned getNumWarnings() const { return NumWarnings; }
1498 virtual void clear() { NumWarnings = NumErrors = 0; }
1500 /// Callback to inform the diagnostic client that processing
1501 /// of a source file is beginning.
1503 /// Note that diagnostics may be emitted outside the processing of a source
1504 /// file, for example during the parsing of command line options. However,
1505 /// diagnostics with source range information are required to only be emitted
1506 /// in between BeginSourceFile() and EndSourceFile().
1508 /// \param LangOpts The language options for the source file being processed.
1509 /// \param PP The preprocessor object being used for the source; this is
1510 /// optional, e.g., it may not be present when processing AST source files.
1511 virtual void BeginSourceFile(const LangOptions &LangOpts,
1512 const Preprocessor *PP = nullptr) {}
1514 /// Callback to inform the diagnostic client that processing
1515 /// of a source file has ended.
1517 /// The diagnostic client should assume that any objects made available via
1518 /// BeginSourceFile() are inaccessible.
1519 virtual void EndSourceFile() {}
1521 /// Callback to inform the diagnostic client that processing of all
1522 /// source files has ended.
1523 virtual void finish() {}
1525 /// Indicates whether the diagnostics handled by this
1526 /// DiagnosticConsumer should be included in the number of diagnostics
1527 /// reported by DiagnosticsEngine.
1529 /// The default implementation returns true.
1530 virtual bool IncludeInDiagnosticCounts() const;
1532 /// Handle this diagnostic, reporting it to the user or
1533 /// capturing it to a log as needed.
1535 /// The default implementation just keeps track of the total number of
1536 /// warnings and errors.
1537 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1538 const Diagnostic &Info);
1541 /// A diagnostic client that ignores all diagnostics.
1542 class IgnoringDiagConsumer : public DiagnosticConsumer {
1543 virtual void anchor();
1545 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1546 const Diagnostic &Info) override {
1551 /// Diagnostic consumer that forwards diagnostics along to an
1552 /// existing, already-initialized diagnostic consumer.
1554 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1555 DiagnosticConsumer &Target;
1558 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1559 ~ForwardingDiagnosticConsumer() override;
1561 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1562 const Diagnostic &Info) override;
1563 void clear() override;
1565 bool IncludeInDiagnosticCounts() const override;
1568 // Struct used for sending info about how a type should be printed.
1569 struct TemplateDiffTypes {
1572 unsigned PrintTree : 1;
1573 unsigned PrintFromType : 1;
1574 unsigned ElideType : 1;
1575 unsigned ShowColors : 1;
1577 // The printer sets this variable to true if the template diff was used.
1578 unsigned TemplateDiffUsed : 1;
1581 /// Special character that the diagnostic printer will use to toggle the bold
1582 /// attribute. The character itself will be not be printed.
1583 const char ToggleHighlight = 127;
1585 /// ProcessWarningOptions - Initialize the diagnostic client and process the
1586 /// warning options specified on the command line.
1587 void ProcessWarningOptions(DiagnosticsEngine &Diags,
1588 const DiagnosticOptions &Opts,
1589 bool ReportDiags = true);
1591 } // namespace clang
1593 #endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H