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/Optional.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>
47 class DiagnosticBuilder;
48 class DiagnosticConsumer;
53 class StoredDiagnostic;
57 enum TokenKind : unsigned short;
61 /// Annotates a diagnostic with some code that should be
62 /// inserted, removed, or replaced to fix the problem.
64 /// This kind of hint should be used when we are certain that the
65 /// introduction, removal, or modification of a particular (small!)
66 /// amount of code will correct a compilation error. The compiler
67 /// should also provide full recovery from such errors, such that
68 /// suppressing the diagnostic output can still result in successful
72 /// Code that should be replaced to correct the error. Empty for an
74 CharSourceRange RemoveRange;
76 /// Code in the specific range that should be inserted in the insertion
78 CharSourceRange InsertFromRange;
80 /// The actual code to insert at the insertion location, as a
82 std::string CodeToInsert;
84 bool BeforePreviousInsertions = false;
86 /// Empty code modification hint, indicating that no code
87 /// modification is known.
88 FixItHint() = default;
91 return !RemoveRange.isValid();
94 /// Create a code modification hint that inserts the given
95 /// code string at a specific location.
96 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
98 bool BeforePreviousInsertions = false) {
101 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
102 Hint.CodeToInsert = std::string(Code);
103 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
107 /// Create a code modification hint that inserts the given
108 /// code from \p FromRange at a specific location.
109 static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
110 CharSourceRange FromRange,
111 bool BeforePreviousInsertions = false) {
114 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
115 Hint.InsertFromRange = FromRange;
116 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
120 /// Create a code modification hint that removes the given
122 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
124 Hint.RemoveRange = RemoveRange;
127 static FixItHint CreateRemoval(SourceRange RemoveRange) {
128 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
131 /// Create a code modification hint that replaces the given
132 /// source range with the given code string.
133 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
136 Hint.RemoveRange = RemoveRange;
137 Hint.CodeToInsert = std::string(Code);
141 static FixItHint CreateReplacement(SourceRange RemoveRange,
143 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
147 /// Concrete class used by the front-end to report problems and issues.
149 /// This massages the diagnostics (e.g. handling things like "report warnings
150 /// as errors" and passes them off to the DiagnosticConsumer for reporting to
151 /// the user. DiagnosticsEngine is tied to one translation unit and one
153 class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
155 /// The level of the diagnostic, after it has been through mapping.
157 Ignored = DiagnosticIDs::Ignored,
158 Note = DiagnosticIDs::Note,
159 Remark = DiagnosticIDs::Remark,
160 Warning = DiagnosticIDs::Warning,
161 Error = DiagnosticIDs::Error,
162 Fatal = DiagnosticIDs::Fatal
178 /// enum TokenKind : unsigned
199 /// NestedNameSpecifier *
205 /// pair<QualType, QualType>
212 /// Represents on argument value, which is a union discriminated
213 /// by ArgumentKind, with a value.
214 using ArgumentValue = std::pair<ArgumentKind, intptr_t>;
217 // Used by __extension__
218 unsigned char AllExtensionsSilenced = 0;
220 // Treat fatal errors like errors.
221 bool FatalsAsError = false;
223 // Suppress all diagnostics.
224 bool SuppressAllDiagnostics = false;
226 // Elide common types of templates.
227 bool ElideType = true;
229 // Print a tree when comparing templates.
230 bool PrintTemplateTree = false;
232 // Color printing is enabled.
233 bool ShowColors = false;
235 // Which overload candidates to show.
236 OverloadsShown ShowOverloads = Ovl_All;
238 // Cap of # errors emitted, 0 -> no limit.
239 unsigned ErrorLimit = 0;
241 // Cap on depth of template backtrace stack, 0 -> no limit.
242 unsigned TemplateBacktraceLimit = 0;
244 // Cap on depth of constexpr evaluation backtrace stack, 0 -> no limit.
245 unsigned ConstexprBacktraceLimit = 0;
247 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
248 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
249 DiagnosticConsumer *Client = nullptr;
250 std::unique_ptr<DiagnosticConsumer> Owner;
251 SourceManager *SourceMgr = nullptr;
253 /// Mapping information for diagnostics.
255 /// Mapping info is packed into four bits per diagnostic. The low three
256 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
257 /// The high bit is set when the mapping was established as a user mapping.
258 /// If the high bit is clear, then the low bits are set to the default
259 /// value, and should be mapped with -pedantic, -Werror, etc.
261 /// A new DiagState is created and kept around when diagnostic pragmas modify
262 /// the state so that we know what is the diagnostic state at any given
265 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
268 // "Global" configuration state that can actually vary between modules.
270 // Ignore all warnings: -w
271 unsigned IgnoreAllWarnings : 1;
273 // Enable all warnings.
274 unsigned EnableAllWarnings : 1;
276 // Treat warnings like errors.
277 unsigned WarningsAsErrors : 1;
279 // Treat errors like fatal errors.
280 unsigned ErrorsAsFatal : 1;
282 // Suppress warnings in system headers.
283 unsigned SuppressSystemWarnings : 1;
285 // Map extensions to warnings or errors?
286 diag::Severity ExtBehavior = diag::Severity::Ignored;
289 : IgnoreAllWarnings(false), EnableAllWarnings(false),
290 WarningsAsErrors(false), ErrorsAsFatal(false),
291 SuppressSystemWarnings(false) {}
293 using iterator = llvm::DenseMap<unsigned, DiagnosticMapping>::iterator;
294 using const_iterator =
295 llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator;
297 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
298 DiagMap[Diag] = Info;
301 DiagnosticMapping lookupMapping(diag::kind Diag) const {
302 return DiagMap.lookup(Diag);
305 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
307 const_iterator begin() const { return DiagMap.begin(); }
308 const_iterator end() const { return DiagMap.end(); }
311 /// Keeps and automatically disposes all DiagStates that we create.
312 std::list<DiagState> DiagStates;
314 /// A mapping from files to the diagnostic states for those files. Lazily
315 /// built on demand for files in which the diagnostic state has not changed.
318 /// Add an initial diagnostic state.
319 void appendFirst(DiagState *State);
321 /// Add a new latest state point.
322 void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
324 /// Look up the diagnostic state at a given source location.
325 DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
327 /// Determine whether this map is empty.
328 bool empty() const { return Files.empty(); }
330 /// Clear out this map.
333 FirstDiagState = CurDiagState = nullptr;
334 CurDiagStateLoc = SourceLocation();
337 /// Produce a debugging dump of the diagnostic state.
338 LLVM_DUMP_METHOD void dump(SourceManager &SrcMgr,
339 StringRef DiagName = StringRef()) const;
341 /// Grab the most-recently-added state point.
342 DiagState *getCurDiagState() const { return CurDiagState; }
344 /// Get the location at which a diagnostic state was last added.
345 SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
348 friend class ASTReader;
349 friend class ASTWriter;
351 /// Represents a point in source where the diagnostic state was
352 /// modified because of a pragma.
354 /// 'Loc' can be null if the point represents the diagnostic state
355 /// modifications done through the command-line.
356 struct DiagStatePoint {
360 DiagStatePoint(DiagState *State, unsigned Offset)
361 : State(State), Offset(Offset) {}
364 /// Description of the diagnostic states and state transitions for a
365 /// particular FileID.
367 /// The diagnostic state for the parent file. This is strictly redundant,
368 /// as looking up the DecomposedIncludedLoc for the FileID in the Files
369 /// map would give us this, but we cache it here for performance.
370 File *Parent = nullptr;
372 /// The offset of this file within its parent.
373 unsigned ParentOffset = 0;
375 /// Whether this file has any local (not imported from an AST file)
376 /// diagnostic state transitions.
377 bool HasLocalTransitions = false;
379 /// The points within the file where the state changes. There will always
380 /// be at least one of these (the state on entry to the file).
381 llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
383 DiagState *lookup(unsigned Offset) const;
386 /// The diagnostic states for each file.
387 mutable std::map<FileID, File> Files;
389 /// The initial diagnostic state.
390 DiagState *FirstDiagState;
392 /// The current diagnostic state.
393 DiagState *CurDiagState;
395 /// The location at which the current diagnostic state was established.
396 SourceLocation CurDiagStateLoc;
398 /// Get the diagnostic state information for a file.
399 File *getFile(SourceManager &SrcMgr, FileID ID) const;
402 DiagStateMap DiagStatesByLoc;
404 /// Keeps the DiagState that was active during each diagnostic 'push'
405 /// so we can get back at it when we 'pop'.
406 std::vector<DiagState *> DiagStateOnPushStack;
408 DiagState *GetCurDiagState() const {
409 return DiagStatesByLoc.getCurDiagState();
412 void PushDiagStatePoint(DiagState *State, SourceLocation L);
414 /// Finds the DiagStatePoint that contains the diagnostic state of
415 /// the given source location.
416 DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
417 return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
418 : DiagStatesByLoc.getCurDiagState();
421 /// Sticky flag set to \c true when an error is emitted.
424 /// Sticky flag set to \c true when an "uncompilable error" occurs.
425 /// I.e. an error that was not upgraded from a warning by -Werror.
426 bool UncompilableErrorOccurred;
428 /// Sticky flag set to \c true when a fatal error is emitted.
429 bool FatalErrorOccurred;
431 /// Indicates that an unrecoverable error has occurred.
432 bool UnrecoverableErrorOccurred;
434 /// Counts for DiagnosticErrorTrap to check whether an error occurred
435 /// during a parsing section, e.g. during parsing a function.
436 unsigned TrapNumErrorsOccurred;
437 unsigned TrapNumUnrecoverableErrorsOccurred;
439 /// The level of the last diagnostic emitted.
441 /// This is used to emit continuation diagnostics with the same level as the
442 /// diagnostic that they follow.
443 DiagnosticIDs::Level LastDiagLevel;
445 /// Number of warnings reported
446 unsigned NumWarnings;
448 /// Number of errors reported
451 /// A function pointer that converts an opaque diagnostic
452 /// argument to a strings.
454 /// This takes the modifiers and argument that was present in the diagnostic.
456 /// The PrevArgs array indicates the previous arguments formatted for this
457 /// diagnostic. Implementations of this function can use this information to
458 /// avoid redundancy across arguments.
460 /// This is a hack to avoid a layering violation between libbasic and libsema.
461 using ArgToStringFnTy = void (*)(
462 ArgumentKind Kind, intptr_t Val,
463 StringRef Modifier, StringRef Argument,
464 ArrayRef<ArgumentValue> PrevArgs,
465 SmallVectorImpl<char> &Output,
467 ArrayRef<intptr_t> QualTypeVals);
469 void *ArgToStringCookie = nullptr;
470 ArgToStringFnTy ArgToStringFn;
472 /// ID of the "delayed" diagnostic, which is a (typically
473 /// fatal) diagnostic that had to be delayed because it was found
474 /// while emitting another diagnostic.
475 unsigned DelayedDiagID;
477 /// First string argument for the delayed diagnostic.
478 std::string DelayedDiagArg1;
480 /// Second string argument for the delayed diagnostic.
481 std::string DelayedDiagArg2;
483 /// Third string argument for the delayed diagnostic.
484 std::string DelayedDiagArg3;
486 /// Optional flag value.
488 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
489 /// -Rpass=<value>. The content of this string is emitted after the flag name
491 std::string FlagValue;
494 explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
495 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
496 DiagnosticConsumer *client = nullptr,
497 bool ShouldOwnClient = true);
498 DiagnosticsEngine(const DiagnosticsEngine &) = delete;
499 DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
500 ~DiagnosticsEngine();
502 LLVM_DUMP_METHOD void dump() const;
503 LLVM_DUMP_METHOD void dump(StringRef DiagName) const;
505 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
509 /// Retrieve the diagnostic options.
510 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
512 using diag_mapping_range = llvm::iterator_range<DiagState::const_iterator>;
514 /// Get the current set of diagnostic mappings.
515 diag_mapping_range getDiagnosticMappings() const {
516 const DiagState &DS = *GetCurDiagState();
517 return diag_mapping_range(DS.begin(), DS.end());
520 DiagnosticConsumer *getClient() { return Client; }
521 const DiagnosticConsumer *getClient() const { return Client; }
523 /// Determine whether this \c DiagnosticsEngine object own its client.
524 bool ownsClient() const { return Owner != nullptr; }
526 /// Return the current diagnostic client along with ownership of that
528 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
530 bool hasSourceManager() const { return SourceMgr != nullptr; }
532 SourceManager &getSourceManager() const {
533 assert(SourceMgr && "SourceManager not set!");
537 void setSourceManager(SourceManager *SrcMgr) {
538 assert(DiagStatesByLoc.empty() &&
539 "Leftover diag state from a different SourceManager.");
543 //===--------------------------------------------------------------------===//
544 // DiagnosticsEngine characterization methods, used by a client to customize
545 // how diagnostics are emitted.
548 /// Copies the current DiagMappings and pushes the new copy
549 /// onto the top of the stack.
550 void pushMappings(SourceLocation Loc);
552 /// Pops the current DiagMappings off the top of the stack,
553 /// causing the new top of the stack to be the active mappings.
555 /// \returns \c true if the pop happens, \c false if there is only one
556 /// DiagMapping on the stack.
557 bool popMappings(SourceLocation Loc);
559 /// Set the diagnostic client associated with this diagnostic object.
561 /// \param ShouldOwnClient true if the diagnostic object should take
562 /// ownership of \c client.
563 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
565 /// Specify a limit for the number of errors we should
566 /// emit before giving up.
568 /// Zero disables the limit.
569 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
571 /// Specify the maximum number of template instantiation
572 /// notes to emit along with a given diagnostic.
573 void setTemplateBacktraceLimit(unsigned Limit) {
574 TemplateBacktraceLimit = Limit;
577 /// Retrieve the maximum number of template instantiation
578 /// notes to emit along with a given diagnostic.
579 unsigned getTemplateBacktraceLimit() const {
580 return TemplateBacktraceLimit;
583 /// Specify the maximum number of constexpr evaluation
584 /// notes to emit along with a given diagnostic.
585 void setConstexprBacktraceLimit(unsigned Limit) {
586 ConstexprBacktraceLimit = Limit;
589 /// Retrieve the maximum number of constexpr evaluation
590 /// notes to emit along with a given diagnostic.
591 unsigned getConstexprBacktraceLimit() const {
592 return ConstexprBacktraceLimit;
595 /// When set to true, any unmapped warnings are ignored.
597 /// If this and WarningsAsErrors are both set, then this one wins.
598 void setIgnoreAllWarnings(bool Val) {
599 GetCurDiagState()->IgnoreAllWarnings = Val;
601 bool getIgnoreAllWarnings() const {
602 return GetCurDiagState()->IgnoreAllWarnings;
605 /// When set to true, any unmapped ignored warnings are no longer
608 /// If this and IgnoreAllWarnings are both set, then that one wins.
609 void setEnableAllWarnings(bool Val) {
610 GetCurDiagState()->EnableAllWarnings = Val;
612 bool getEnableAllWarnings() const {
613 return GetCurDiagState()->EnableAllWarnings;
616 /// When set to true, any warnings reported are issued as errors.
617 void setWarningsAsErrors(bool Val) {
618 GetCurDiagState()->WarningsAsErrors = Val;
620 bool getWarningsAsErrors() const {
621 return GetCurDiagState()->WarningsAsErrors;
624 /// When set to true, any error reported is made a fatal error.
625 void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
626 bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
628 /// \brief When set to true, any fatal error reported is made an error.
630 /// This setting takes precedence over the setErrorsAsFatal setting above.
631 void setFatalsAsError(bool Val) { FatalsAsError = Val; }
632 bool getFatalsAsError() const { return FatalsAsError; }
634 /// When set to true mask warnings that come from system headers.
635 void setSuppressSystemWarnings(bool Val) {
636 GetCurDiagState()->SuppressSystemWarnings = Val;
638 bool getSuppressSystemWarnings() const {
639 return GetCurDiagState()->SuppressSystemWarnings;
642 /// Suppress all diagnostics, to silence the front end when we
643 /// know that we don't want any more diagnostics to be passed along to the
645 void setSuppressAllDiagnostics(bool Val) { SuppressAllDiagnostics = Val; }
646 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
648 /// Set type eliding, to skip outputting same types occurring in
650 void setElideType(bool Val) { ElideType = Val; }
651 bool getElideType() { return ElideType; }
653 /// Set tree printing, to outputting the template difference in a
655 void setPrintTemplateTree(bool Val) { PrintTemplateTree = Val; }
656 bool getPrintTemplateTree() { return PrintTemplateTree; }
658 /// Set color printing, so the type diffing will inject color markers
660 void setShowColors(bool Val) { ShowColors = Val; }
661 bool getShowColors() { return ShowColors; }
663 /// Specify which overload candidates to show when overload resolution
666 /// By default, we show all candidates.
667 void setShowOverloads(OverloadsShown Val) {
670 OverloadsShown getShowOverloads() const { return ShowOverloads; }
672 /// Pretend that the last diagnostic issued was ignored, so any
673 /// subsequent notes will be suppressed, or restore a prior ignoring
674 /// state after ignoring some diagnostics and their notes, possibly in
675 /// the middle of another diagnostic.
677 /// This can be used by clients who suppress diagnostics themselves.
678 void setLastDiagnosticIgnored(bool Ignored) {
679 if (LastDiagLevel == DiagnosticIDs::Fatal)
680 FatalErrorOccurred = true;
681 LastDiagLevel = Ignored ? DiagnosticIDs::Ignored : DiagnosticIDs::Warning;
684 /// Determine whether the previous diagnostic was ignored. This can
685 /// be used by clients that want to determine whether notes attached to a
686 /// diagnostic will be suppressed.
687 bool isLastDiagnosticIgnored() const {
688 return LastDiagLevel == DiagnosticIDs::Ignored;
691 /// Controls whether otherwise-unmapped extension diagnostics are
692 /// mapped onto ignore/warning/error.
694 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
695 void setExtensionHandlingBehavior(diag::Severity H) {
696 GetCurDiagState()->ExtBehavior = H;
698 diag::Severity getExtensionHandlingBehavior() const {
699 return GetCurDiagState()->ExtBehavior;
702 /// Counter bumped when an __extension__ block is/ encountered.
704 /// When non-zero, all extension diagnostics are entirely silenced, no
705 /// matter how they are mapped.
706 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
707 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
708 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
710 /// This allows the client to specify that certain warnings are
713 /// Notes can never be mapped, errors can only be mapped to fatal, and
714 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
716 /// \param Loc The source location that this change of diagnostic state should
717 /// take affect. It can be null if we are setting the latest state.
718 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
720 /// Change an entire diagnostic group (e.g. "unknown-pragmas") to
721 /// have the specified mapping.
723 /// \returns true (and ignores the request) if "Group" was unknown, false
726 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
727 /// state of the -Wfoo group and vice versa.
729 /// \param Loc The source location that this change of diagnostic state should
730 /// take affect. It can be null if we are setting the state from command-line.
731 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
733 SourceLocation Loc = SourceLocation());
735 /// Set the warning-as-error flag for the given diagnostic group.
737 /// This function always only operates on the current diagnostic state.
739 /// \returns True if the given group is unknown, false otherwise.
740 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
742 /// Set the error-as-fatal flag for the given diagnostic group.
744 /// This function always only operates on the current diagnostic state.
746 /// \returns True if the given group is unknown, false otherwise.
747 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
749 /// Add the specified mapping to all diagnostics of the specified
752 /// Mainly to be used by -Wno-everything to disable all warnings but allow
753 /// subsequent -W options to enable specific warnings.
754 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
755 SourceLocation Loc = SourceLocation());
757 bool hasErrorOccurred() const { return ErrorOccurred; }
759 /// Errors that actually prevent compilation, not those that are
760 /// upgraded from a warning by -Werror.
761 bool hasUncompilableErrorOccurred() const {
762 return UncompilableErrorOccurred;
764 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
766 /// Determine whether any kind of unrecoverable error has occurred.
767 bool hasUnrecoverableErrorOccurred() const {
768 return FatalErrorOccurred || UnrecoverableErrorOccurred;
771 unsigned getNumWarnings() const { return NumWarnings; }
773 void setNumWarnings(unsigned NumWarnings) {
774 this->NumWarnings = NumWarnings;
777 /// Return an ID for a diagnostic with the specified format string and
780 /// If this is the first request for this diagnostic, it is registered and
781 /// created, otherwise the existing ID is returned.
783 /// \param FormatString A fixed diagnostic format string that will be hashed
784 /// and mapped to a unique DiagID.
785 template <unsigned N>
786 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
787 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
788 StringRef(FormatString, N - 1));
791 /// Converts a diagnostic argument (as an intptr_t) into the string
792 /// that represents it.
793 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
794 StringRef Modifier, StringRef Argument,
795 ArrayRef<ArgumentValue> PrevArgs,
796 SmallVectorImpl<char> &Output,
797 ArrayRef<intptr_t> QualTypeVals) const {
798 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
799 ArgToStringCookie, QualTypeVals);
802 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
804 ArgToStringCookie = Cookie;
807 /// Note that the prior diagnostic was emitted by some other
808 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
809 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
810 LastDiagLevel = Other.LastDiagLevel;
813 /// Reset the state of the diagnostic object to its initial
817 //===--------------------------------------------------------------------===//
818 // DiagnosticsEngine classification and reporting interfaces.
821 /// Determine whether the diagnostic is known to be ignored.
823 /// This can be used to opportunistically avoid expensive checks when it's
824 /// known for certain that the diagnostic has been suppressed at the
825 /// specified location \p Loc.
827 /// \param Loc The source location we are interested in finding out the
828 /// diagnostic state. Can be null in order to query the latest state.
829 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
830 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
831 diag::Severity::Ignored;
834 /// Based on the way the client configured the DiagnosticsEngine
835 /// object, classify the specified diagnostic ID into a Level, consumable by
836 /// the DiagnosticConsumer.
838 /// To preserve invariant assumptions, this function should not be used to
839 /// influence parse or semantic analysis actions. Instead consider using
842 /// \param Loc The source location we are interested in finding out the
843 /// diagnostic state. Can be null in order to query the latest state.
844 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
845 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
848 /// Issue the message to the client.
850 /// This actually returns an instance of DiagnosticBuilder which emits the
851 /// diagnostics (through @c ProcessDiag) when it is destroyed.
853 /// \param DiagID A member of the @c diag::kind enum.
854 /// \param Loc Represents the source location associated with the diagnostic,
855 /// which can be an invalid location if no position information is available.
856 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
857 inline DiagnosticBuilder Report(unsigned DiagID);
859 void Report(const StoredDiagnostic &storedDiag);
861 /// Determine whethere there is already a diagnostic in flight.
862 bool isDiagnosticInFlight() const {
863 return CurDiagID != std::numeric_limits<unsigned>::max();
866 /// Set the "delayed" diagnostic that will be emitted once
867 /// the current diagnostic completes.
869 /// If a diagnostic is already in-flight but the front end must
870 /// report a problem (e.g., with an inconsistent file system
871 /// state), this routine sets a "delayed" diagnostic that will be
872 /// emitted after the current diagnostic completes. This should
873 /// only be used for fatal errors detected at inconvenient
874 /// times. If emitting a delayed diagnostic causes a second delayed
875 /// diagnostic to be introduced, that second delayed diagnostic
878 /// \param DiagID The ID of the diagnostic being delayed.
880 /// \param Arg1 A string argument that will be provided to the
881 /// diagnostic. A copy of this string will be stored in the
882 /// DiagnosticsEngine object itself.
884 /// \param Arg2 A string argument that will be provided to the
885 /// diagnostic. A copy of this string will be stored in the
886 /// DiagnosticsEngine object itself.
888 /// \param Arg3 A string argument that will be provided to the
889 /// diagnostic. A copy of this string will be stored in the
890 /// DiagnosticsEngine object itself.
891 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
892 StringRef Arg2 = "", StringRef Arg3 = "");
894 /// Clear out the current diagnostic.
895 void Clear() { CurDiagID = std::numeric_limits<unsigned>::max(); }
897 /// Return the value associated with this diagnostic flag.
898 StringRef getFlagValue() const { return FlagValue; }
901 // This is private state used by DiagnosticBuilder. We put it here instead of
902 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
903 // object. This implementation choice means that we can only have one
904 // diagnostic "in flight" at a time, but this seems to be a reasonable
905 // tradeoff to keep these objects small. Assertions verify that only one
906 // diagnostic is in flight at a time.
907 friend class Diagnostic;
908 friend class DiagnosticBuilder;
909 friend class DiagnosticErrorTrap;
910 friend class DiagnosticIDs;
911 friend class PartialDiagnostic;
913 /// Report the delayed diagnostic.
914 void ReportDelayed();
916 /// The location of the current diagnostic that is in flight.
917 SourceLocation CurDiagLoc;
919 /// The ID of the current diagnostic that is in flight.
921 /// This is set to std::numeric_limits<unsigned>::max() when there is no
922 /// diagnostic in flight.
926 /// The maximum number of arguments we can hold.
928 /// We currently only support up to 10 arguments (%0-%9). A single
929 /// diagnostic with more than that almost certainly has to be simplified
934 /// The number of entries in Arguments.
935 signed char NumDiagArgs;
937 /// Specifies whether an argument is in DiagArgumentsStr or
938 /// in DiagArguments.
940 /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
942 unsigned char DiagArgumentsKind[MaxArguments];
944 /// Holds the values of each string argument for the current
947 /// This is only used when the corresponding ArgumentKind is ak_std_string.
948 std::string DiagArgumentsStr[MaxArguments];
950 /// The values for the various substitution positions.
952 /// This is used when the argument is not an std::string. The specific
953 /// value is mangled into an intptr_t and the interpretation depends on
954 /// exactly what sort of argument kind it is.
955 intptr_t DiagArgumentsVal[MaxArguments];
957 /// The list of ranges added to this diagnostic.
958 SmallVector<CharSourceRange, 8> DiagRanges;
960 /// If valid, provides a hint with some code to insert, remove,
961 /// or modify at a particular position.
962 SmallVector<FixItHint, 8> DiagFixItHints;
964 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
965 bool isPragma = L.isValid();
966 DiagnosticMapping Mapping =
967 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
969 // If this is a pragma mapping, then set the diagnostic mapping flags so
970 // that we override command line options.
972 Mapping.setNoWarningAsError(true);
973 Mapping.setNoErrorAsFatal(true);
979 /// Used to report a diagnostic that is finally fully formed.
981 /// \returns true if the diagnostic was emitted, false if it was suppressed.
983 return Diags->ProcessDiag(*this);
986 /// @name Diagnostic Emission
989 friend class ASTReader;
990 friend class ASTWriter;
992 // Sema requires access to the following functions because the current design
993 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
994 // access us directly to ensure we minimize the emitted code for the common
995 // Sema::Diag() patterns.
998 /// Emit the current diagnostic and clear the diagnostic state.
1000 /// \param Force Emit the diagnostic regardless of suppression settings.
1001 bool EmitCurrentDiagnostic(bool Force = false);
1003 unsigned getCurrentDiagID() const { return CurDiagID; }
1005 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
1010 /// RAII class that determines when any errors have occurred
1011 /// between the time the instance was created and the time it was
1014 /// Note that you almost certainly do not want to use this. It's usually
1015 /// meaningless to ask whether a particular scope triggered an error message,
1016 /// because error messages outside that scope can mark things invalid (or cause
1017 /// us to reach an error limit), which can suppress errors within that scope.
1018 class DiagnosticErrorTrap {
1019 DiagnosticsEngine &Diag;
1021 unsigned NumUnrecoverableErrors;
1024 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
1025 : Diag(Diag) { reset(); }
1027 /// Determine whether any errors have occurred since this
1028 /// object instance was created.
1029 bool hasErrorOccurred() const {
1030 return Diag.TrapNumErrorsOccurred > NumErrors;
1033 /// Determine whether any unrecoverable errors have occurred since this
1034 /// object instance was created.
1035 bool hasUnrecoverableErrorOccurred() const {
1036 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
1039 /// Set to initial state of "no errors occurred".
1041 NumErrors = Diag.TrapNumErrorsOccurred;
1042 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
1046 //===----------------------------------------------------------------------===//
1047 // DiagnosticBuilder
1048 //===----------------------------------------------------------------------===//
1050 /// A little helper class used to produce diagnostics.
1052 /// This is constructed by the DiagnosticsEngine::Report method, and
1053 /// allows insertion of extra information (arguments and source ranges) into
1054 /// the currently "in flight" diagnostic. When the temporary for the builder
1055 /// is destroyed, the diagnostic is issued.
1057 /// Note that many of these will be created as temporary objects (many call
1058 /// sites), so we want them to be small and we never want their address taken.
1059 /// This ensures that compilers with somewhat reasonable optimizers will promote
1060 /// the common fields to registers, eliminating increments of the NumArgs field,
1062 class DiagnosticBuilder {
1063 friend class DiagnosticsEngine;
1064 friend class PartialDiagnostic;
1066 mutable DiagnosticsEngine *DiagObj = nullptr;
1067 mutable unsigned NumArgs = 0;
1069 /// Status variable indicating if this diagnostic is still active.
1071 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
1072 // but LLVM is not currently smart enough to eliminate the null check that
1073 // Emit() would end up with if we used that as our status variable.
1074 mutable bool IsActive = false;
1076 /// Flag indicating that this diagnostic is being emitted via a
1077 /// call to ForceEmit.
1078 mutable bool IsForceEmit = false;
1080 DiagnosticBuilder() = default;
1082 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
1083 : DiagObj(diagObj), IsActive(true) {
1084 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
1085 diagObj->DiagRanges.clear();
1086 diagObj->DiagFixItHints.clear();
1090 void FlushCounts() {
1091 DiagObj->NumDiagArgs = NumArgs;
1094 /// Clear out the current diagnostic.
1095 void Clear() const {
1098 IsForceEmit = false;
1101 /// Determine whether this diagnostic is still active.
1102 bool isActive() const { return IsActive; }
1104 /// Force the diagnostic builder to emit the diagnostic now.
1106 /// Once this function has been called, the DiagnosticBuilder object
1107 /// should not be used again before it is destroyed.
1109 /// \returns true if a diagnostic was emitted, false if the
1110 /// diagnostic was suppressed.
1112 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1113 // (or by a subclass, as in SemaDiagnosticBuilder).
1114 if (!isActive()) return false;
1116 // When emitting diagnostics, we set the final argument count into
1117 // the DiagnosticsEngine object.
1120 // Process the diagnostic.
1121 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
1123 // This diagnostic is dead.
1130 /// Copy constructor. When copied, this "takes" the diagnostic info from the
1131 /// input and neuters it.
1132 DiagnosticBuilder(const DiagnosticBuilder &D) {
1133 DiagObj = D.DiagObj;
1134 IsActive = D.IsActive;
1135 IsForceEmit = D.IsForceEmit;
1137 NumArgs = D.NumArgs;
1140 DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1142 /// Emits the diagnostic.
1143 ~DiagnosticBuilder() {
1147 /// Forces the diagnostic to be emitted.
1148 const DiagnosticBuilder &setForceEmit() const {
1153 /// Conversion of DiagnosticBuilder to bool always returns \c true.
1155 /// This allows is to be used in boolean error contexts (where \c true is
1156 /// used to indicate that an error has occurred), like:
1158 /// return Diag(...);
1160 operator bool() const { return true; }
1162 void AddString(StringRef S) const {
1163 assert(isActive() && "Clients must not add to cleared diagnostic!");
1164 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1165 "Too many arguments to diagnostic!");
1166 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
1167 DiagObj->DiagArgumentsStr[NumArgs++] = std::string(S);
1170 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1171 assert(isActive() && "Clients must not add to cleared diagnostic!");
1172 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1173 "Too many arguments to diagnostic!");
1174 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
1175 DiagObj->DiagArgumentsVal[NumArgs++] = V;
1178 void AddSourceRange(const CharSourceRange &R) const {
1179 assert(isActive() && "Clients must not add to cleared diagnostic!");
1180 DiagObj->DiagRanges.push_back(R);
1183 void AddFixItHint(const FixItHint &Hint) const {
1184 assert(isActive() && "Clients must not add to cleared diagnostic!");
1186 DiagObj->DiagFixItHints.push_back(Hint);
1189 void addFlagValue(StringRef V) const { DiagObj->FlagValue = std::string(V); }
1192 struct AddFlagValue {
1195 explicit AddFlagValue(StringRef V) : Val(V) {}
1198 /// Register a value for the flag in the current diagnostic. This
1199 /// value will be shown as the suffix "=value" after the flag name. It is
1200 /// useful in cases where the diagnostic flag accepts values (e.g.,
1201 /// -Rpass or -Wframe-larger-than).
1202 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1203 const AddFlagValue V) {
1204 DB.addFlagValue(V.Val);
1208 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1214 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1216 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1217 DiagnosticsEngine::ak_c_string);
1221 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
1222 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1226 // We use enable_if here to prevent that this overload is selected for
1227 // pointers or other arguments that are implicitly convertible to bool.
1228 template <typename T>
1229 inline std::enable_if_t<std::is_same<T, bool>::value, const DiagnosticBuilder &>
1230 operator<<(const DiagnosticBuilder &DB, T I) {
1231 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1235 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1237 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1241 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1243 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1247 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1248 const IdentifierInfo *II) {
1249 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1250 DiagnosticsEngine::ak_identifierinfo);
1254 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
1255 // so that we only match those arguments that are (statically) DeclContexts;
1256 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
1258 template <typename T>
1259 inline std::enable_if_t<
1260 std::is_same<std::remove_const_t<T>, DeclContext>::value,
1261 const DiagnosticBuilder &>
1262 operator<<(const DiagnosticBuilder &DB, T *DC) {
1263 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1264 DiagnosticsEngine::ak_declcontext);
1268 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1270 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1274 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1275 ArrayRef<SourceRange> Ranges) {
1276 for (SourceRange R : Ranges)
1277 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1281 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1282 const CharSourceRange &R) {
1283 DB.AddSourceRange(R);
1287 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1288 const FixItHint &Hint) {
1289 DB.AddFixItHint(Hint);
1293 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1294 ArrayRef<FixItHint> Hints) {
1295 for (const FixItHint &Hint : Hints)
1296 DB.AddFixItHint(Hint);
1300 inline const DiagnosticBuilder &
1301 operator<<(const DiagnosticBuilder &DB,
1302 const llvm::Optional<SourceRange> &Opt) {
1308 inline const DiagnosticBuilder &
1309 operator<<(const DiagnosticBuilder &DB,
1310 const llvm::Optional<CharSourceRange> &Opt) {
1316 inline const DiagnosticBuilder &
1317 operator<<(const DiagnosticBuilder &DB, const llvm::Optional<FixItHint> &Opt) {
1323 /// A nullability kind paired with a bit indicating whether it used a
1324 /// context-sensitive keyword.
1325 using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1327 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1328 DiagNullabilityKind nullability);
1330 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1332 assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
1333 "Multiple diagnostics in flight at once!");
1337 return DiagnosticBuilder(this);
1340 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1343 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1344 return Report(SourceLocation(), DiagID);
1347 //===----------------------------------------------------------------------===//
1349 //===----------------------------------------------------------------------===//
1351 /// A little helper class (which is basically a smart pointer that forwards
1352 /// info from DiagnosticsEngine) that allows clients to enquire about the
1353 /// currently in-flight diagnostic.
1355 const DiagnosticsEngine *DiagObj;
1356 StringRef StoredDiagMessage;
1359 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1360 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1361 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1363 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1364 unsigned getID() const { return DiagObj->CurDiagID; }
1365 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1366 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1367 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1369 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1371 /// Return the kind of the specified index.
1373 /// Based on the kind of argument, the accessors below can be used to get
1376 /// \pre Idx < getNumArgs()
1377 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1378 assert(Idx < getNumArgs() && "Argument index out of range!");
1379 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1382 /// Return the provided argument string specified by \p Idx.
1383 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1384 const std::string &getArgStdStr(unsigned Idx) const {
1385 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1386 "invalid argument accessor!");
1387 return DiagObj->DiagArgumentsStr[Idx];
1390 /// Return the specified C string argument.
1391 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1392 const char *getArgCStr(unsigned Idx) const {
1393 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1394 "invalid argument accessor!");
1395 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1398 /// Return the specified signed integer argument.
1399 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1400 int getArgSInt(unsigned Idx) const {
1401 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1402 "invalid argument accessor!");
1403 return (int)DiagObj->DiagArgumentsVal[Idx];
1406 /// Return the specified unsigned integer argument.
1407 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1408 unsigned getArgUInt(unsigned Idx) const {
1409 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1410 "invalid argument accessor!");
1411 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1414 /// Return the specified IdentifierInfo argument.
1415 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1416 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1417 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1418 "invalid argument accessor!");
1419 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1422 /// Return the specified non-string argument in an opaque form.
1423 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1424 intptr_t getRawArg(unsigned Idx) const {
1425 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1426 "invalid argument accessor!");
1427 return DiagObj->DiagArgumentsVal[Idx];
1430 /// Return the number of source ranges associated with this diagnostic.
1431 unsigned getNumRanges() const {
1432 return DiagObj->DiagRanges.size();
1435 /// \pre Idx < getNumRanges()
1436 const CharSourceRange &getRange(unsigned Idx) const {
1437 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1438 return DiagObj->DiagRanges[Idx];
1441 /// Return an array reference for this diagnostic's ranges.
1442 ArrayRef<CharSourceRange> getRanges() const {
1443 return DiagObj->DiagRanges;
1446 unsigned getNumFixItHints() const {
1447 return DiagObj->DiagFixItHints.size();
1450 const FixItHint &getFixItHint(unsigned Idx) const {
1451 assert(Idx < getNumFixItHints() && "Invalid index!");
1452 return DiagObj->DiagFixItHints[Idx];
1455 ArrayRef<FixItHint> getFixItHints() const {
1456 return DiagObj->DiagFixItHints;
1459 /// Format this diagnostic into a string, substituting the
1460 /// formal arguments into the %0 slots.
1462 /// The result is appended onto the \p OutStr array.
1463 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1465 /// Format the given format-string into the output buffer using the
1466 /// arguments stored in this diagnostic.
1467 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1468 SmallVectorImpl<char> &OutStr) const;
1472 * Represents a diagnostic in a form that can be retained until its
1473 * corresponding source manager is destroyed.
1475 class StoredDiagnostic {
1477 DiagnosticsEngine::Level Level;
1479 std::string Message;
1480 std::vector<CharSourceRange> Ranges;
1481 std::vector<FixItHint> FixIts;
1484 StoredDiagnostic() = default;
1485 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1486 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1488 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1489 StringRef Message, FullSourceLoc Loc,
1490 ArrayRef<CharSourceRange> Ranges,
1491 ArrayRef<FixItHint> Fixits);
1493 /// Evaluates true when this object stores a diagnostic.
1494 explicit operator bool() const { return !Message.empty(); }
1496 unsigned getID() const { return ID; }
1497 DiagnosticsEngine::Level getLevel() const { return Level; }
1498 const FullSourceLoc &getLocation() const { return Loc; }
1499 StringRef getMessage() const { return Message; }
1501 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1503 using range_iterator = std::vector<CharSourceRange>::const_iterator;
1505 range_iterator range_begin() const { return Ranges.begin(); }
1506 range_iterator range_end() const { return Ranges.end(); }
1507 unsigned range_size() const { return Ranges.size(); }
1509 ArrayRef<CharSourceRange> getRanges() const {
1510 return llvm::makeArrayRef(Ranges);
1513 using fixit_iterator = std::vector<FixItHint>::const_iterator;
1515 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1516 fixit_iterator fixit_end() const { return FixIts.end(); }
1517 unsigned fixit_size() const { return FixIts.size(); }
1519 ArrayRef<FixItHint> getFixIts() const {
1520 return llvm::makeArrayRef(FixIts);
1524 /// Abstract interface, implemented by clients of the front-end, which
1525 /// formats and prints fully processed diagnostics.
1526 class DiagnosticConsumer {
1528 unsigned NumWarnings = 0; ///< Number of warnings reported
1529 unsigned NumErrors = 0; ///< Number of errors reported
1532 DiagnosticConsumer() = default;
1533 virtual ~DiagnosticConsumer();
1535 unsigned getNumErrors() const { return NumErrors; }
1536 unsigned getNumWarnings() const { return NumWarnings; }
1537 virtual void clear() { NumWarnings = NumErrors = 0; }
1539 /// Callback to inform the diagnostic client that processing
1540 /// of a source file is beginning.
1542 /// Note that diagnostics may be emitted outside the processing of a source
1543 /// file, for example during the parsing of command line options. However,
1544 /// diagnostics with source range information are required to only be emitted
1545 /// in between BeginSourceFile() and EndSourceFile().
1547 /// \param LangOpts The language options for the source file being processed.
1548 /// \param PP The preprocessor object being used for the source; this is
1549 /// optional, e.g., it may not be present when processing AST source files.
1550 virtual void BeginSourceFile(const LangOptions &LangOpts,
1551 const Preprocessor *PP = nullptr) {}
1553 /// Callback to inform the diagnostic client that processing
1554 /// of a source file has ended.
1556 /// The diagnostic client should assume that any objects made available via
1557 /// BeginSourceFile() are inaccessible.
1558 virtual void EndSourceFile() {}
1560 /// Callback to inform the diagnostic client that processing of all
1561 /// source files has ended.
1562 virtual void finish() {}
1564 /// Indicates whether the diagnostics handled by this
1565 /// DiagnosticConsumer should be included in the number of diagnostics
1566 /// reported by DiagnosticsEngine.
1568 /// The default implementation returns true.
1569 virtual bool IncludeInDiagnosticCounts() const;
1571 /// Handle this diagnostic, reporting it to the user or
1572 /// capturing it to a log as needed.
1574 /// The default implementation just keeps track of the total number of
1575 /// warnings and errors.
1576 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1577 const Diagnostic &Info);
1580 /// A diagnostic client that ignores all diagnostics.
1581 class IgnoringDiagConsumer : public DiagnosticConsumer {
1582 virtual void anchor();
1584 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1585 const Diagnostic &Info) override {
1590 /// Diagnostic consumer that forwards diagnostics along to an
1591 /// existing, already-initialized diagnostic consumer.
1593 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1594 DiagnosticConsumer &Target;
1597 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1598 ~ForwardingDiagnosticConsumer() override;
1600 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1601 const Diagnostic &Info) override;
1602 void clear() override;
1604 bool IncludeInDiagnosticCounts() const override;
1607 // Struct used for sending info about how a type should be printed.
1608 struct TemplateDiffTypes {
1611 unsigned PrintTree : 1;
1612 unsigned PrintFromType : 1;
1613 unsigned ElideType : 1;
1614 unsigned ShowColors : 1;
1616 // The printer sets this variable to true if the template diff was used.
1617 unsigned TemplateDiffUsed : 1;
1620 /// Special character that the diagnostic printer will use to toggle the bold
1621 /// attribute. The character itself will be not be printed.
1622 const char ToggleHighlight = 127;
1624 /// ProcessWarningOptions - Initialize the diagnostic client and process the
1625 /// warning options specified on the command line.
1626 void ProcessWarningOptions(DiagnosticsEngine &Diags,
1627 const DiagnosticOptions &Opts,
1628 bool ReportDiags = true);
1630 } // namespace clang
1632 #endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H