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 /// \brief 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/iterator_range.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
35 #include <type_traits>
42 class DiagnosticBuilder;
43 class DiagnosticConsumer;
47 class StoredDiagnostic;
51 enum TokenKind : unsigned short;
53 } // end namespace tok
55 /// \brief Annotates a diagnostic with some code that should be
56 /// inserted, removed, or replaced to fix the problem.
58 /// This kind of hint should be used when we are certain that the
59 /// introduction, removal, or modification of a particular (small!)
60 /// amount of code will correct a compilation error. The compiler
61 /// should also provide full recovery from such errors, such that
62 /// suppressing the diagnostic output can still result in successful
66 /// \brief Code that should be replaced to correct the error. Empty for an
68 CharSourceRange RemoveRange;
70 /// \brief Code in the specific range that should be inserted in the insertion
72 CharSourceRange InsertFromRange;
74 /// \brief The actual code to insert at the insertion location, as a
76 std::string CodeToInsert;
78 bool BeforePreviousInsertions;
80 /// \brief Empty code modification hint, indicating that no code
81 /// modification is known.
82 FixItHint() : BeforePreviousInsertions(false) { }
85 return !RemoveRange.isValid();
88 /// \brief Create a code modification hint that inserts the given
89 /// code string at a specific location.
90 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
92 bool BeforePreviousInsertions = false) {
95 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
96 Hint.CodeToInsert = Code;
97 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
101 /// \brief Create a code modification hint that inserts the given
102 /// code from \p FromRange at a specific location.
103 static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
104 CharSourceRange FromRange,
105 bool BeforePreviousInsertions = false) {
108 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
109 Hint.InsertFromRange = FromRange;
110 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
114 /// \brief Create a code modification hint that removes the given
116 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
118 Hint.RemoveRange = RemoveRange;
121 static FixItHint CreateRemoval(SourceRange RemoveRange) {
122 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
125 /// \brief Create a code modification hint that replaces the given
126 /// source range with the given code string.
127 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
130 Hint.RemoveRange = RemoveRange;
131 Hint.CodeToInsert = Code;
135 static FixItHint CreateReplacement(SourceRange RemoveRange,
137 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
141 /// \brief Concrete class used by the front-end to report problems and issues.
143 /// This massages the diagnostics (e.g. handling things like "report warnings
144 /// as errors" and passes them off to the DiagnosticConsumer for reporting to
145 /// the user. DiagnosticsEngine is tied to one translation unit and one
147 class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
149 /// \brief The level of the diagnostic, after it has been through mapping.
151 Ignored = DiagnosticIDs::Ignored,
152 Note = DiagnosticIDs::Note,
153 Remark = DiagnosticIDs::Remark,
154 Warning = DiagnosticIDs::Warning,
155 Error = DiagnosticIDs::Error,
156 Fatal = DiagnosticIDs::Fatal
160 ak_std_string, ///< std::string
161 ak_c_string, ///< const char *
163 ak_uint, ///< unsigned
164 ak_tokenkind, ///< enum TokenKind : unsigned
165 ak_identifierinfo, ///< IdentifierInfo
166 ak_qualtype, ///< QualType
167 ak_declarationname, ///< DeclarationName
168 ak_nameddecl, ///< NamedDecl *
169 ak_nestednamespec, ///< NestedNameSpecifier *
170 ak_declcontext, ///< DeclContext *
171 ak_qualtype_pair, ///< pair<QualType, QualType>
175 /// \brief Represents on argument value, which is a union discriminated
176 /// by ArgumentKind, with a value.
177 typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
180 unsigned char AllExtensionsSilenced; // Used by __extension__
181 bool SuppressAfterFatalError; // Suppress diagnostics after a fatal error?
182 bool SuppressAllDiagnostics; // Suppress all diagnostics.
183 bool ElideType; // Elide common types of templates.
184 bool PrintTemplateTree; // Print a tree when comparing templates.
185 bool ShowColors; // Color printing is enabled.
186 OverloadsShown ShowOverloads; // Which overload candidates to show.
187 unsigned ErrorLimit; // Cap of # errors emitted, 0 -> no limit.
188 unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
190 unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation
191 // backtrace stack, 0 -> no limit.
192 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
193 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
194 DiagnosticConsumer *Client;
195 std::unique_ptr<DiagnosticConsumer> Owner;
196 SourceManager *SourceMgr;
198 /// \brief Mapping information for diagnostics.
200 /// Mapping info is packed into four bits per diagnostic. The low three
201 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
202 /// The high bit is set when the mapping was established as a user mapping.
203 /// If the high bit is clear, then the low bits are set to the default
204 /// value, and should be mapped with -pedantic, -Werror, etc.
206 /// A new DiagState is created and kept around when diagnostic pragmas modify
207 /// the state so that we know what is the diagnostic state at any given
210 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
213 // "Global" configuration state that can actually vary between modules.
214 unsigned IgnoreAllWarnings : 1; // Ignore all warnings: -w
215 unsigned EnableAllWarnings : 1; // Enable all warnings.
216 unsigned WarningsAsErrors : 1; // Treat warnings like errors.
217 unsigned ErrorsAsFatal : 1; // Treat errors like fatal errors.
218 unsigned SuppressSystemWarnings : 1; // Suppress warnings in system headers.
219 diag::Severity ExtBehavior; // Map extensions to warnings or errors?
222 : IgnoreAllWarnings(false), EnableAllWarnings(false),
223 WarningsAsErrors(false), ErrorsAsFatal(false),
224 SuppressSystemWarnings(false), ExtBehavior(diag::Severity::Ignored) {}
226 typedef llvm::DenseMap<unsigned, DiagnosticMapping>::iterator iterator;
227 typedef llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator
230 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
231 DiagMap[Diag] = Info;
233 DiagnosticMapping lookupMapping(diag::kind Diag) const {
234 return DiagMap.lookup(Diag);
237 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
239 const_iterator begin() const { return DiagMap.begin(); }
240 const_iterator end() const { return DiagMap.end(); }
243 /// \brief Keeps and automatically disposes all DiagStates that we create.
244 std::list<DiagState> DiagStates;
246 /// A mapping from files to the diagnostic states for those files. Lazily
247 /// built on demand for files in which the diagnostic state has not changed.
250 /// Add an initial diagnostic state.
251 void appendFirst(DiagState *State);
252 /// Add a new latest state point.
253 void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
254 /// Look up the diagnostic state at a given source location.
255 DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
256 /// Determine whether this map is empty.
257 bool empty() const { return Files.empty(); }
258 /// Clear out this map.
261 FirstDiagState = CurDiagState = nullptr;
262 CurDiagStateLoc = SourceLocation();
265 /// Grab the most-recently-added state point.
266 DiagState *getCurDiagState() const { return CurDiagState; }
267 /// Get the location at which a diagnostic state was last added.
268 SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
271 /// \brief Represents a point in source where the diagnostic state was
272 /// modified because of a pragma.
274 /// 'Loc' can be null if the point represents the diagnostic state
275 /// modifications done through the command-line.
276 struct DiagStatePoint {
279 DiagStatePoint(DiagState *State, unsigned Offset)
280 : State(State), Offset(Offset) { }
283 /// Description of the diagnostic states and state transitions for a
284 /// particular FileID.
286 /// The diagnostic state for the parent file. This is strictly redundant,
287 /// as looking up the DecomposedIncludedLoc for the FileID in the Files
288 /// map would give us this, but we cache it here for performance.
289 File *Parent = nullptr;
290 /// The offset of this file within its parent.
291 unsigned ParentOffset = 0;
292 /// Whether this file has any local (not imported from an AST file)
293 /// diagnostic state transitions.
294 bool HasLocalTransitions = false;
295 /// The points within the file where the state changes. There will always
296 /// be at least one of these (the state on entry to the file).
297 llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
299 DiagState *lookup(unsigned Offset) const;
302 /// The diagnostic states for each file.
303 mutable std::map<FileID, File> Files;
305 /// The initial diagnostic state.
306 DiagState *FirstDiagState;
307 /// The current diagnostic state.
308 DiagState *CurDiagState;
309 /// The location at which the current diagnostic state was established.
310 SourceLocation CurDiagStateLoc;
312 /// Get the diagnostic state information for a file.
313 File *getFile(SourceManager &SrcMgr, FileID ID) const;
315 friend class ASTReader;
316 friend class ASTWriter;
319 DiagStateMap DiagStatesByLoc;
321 /// \brief Keeps the DiagState that was active during each diagnostic 'push'
322 /// so we can get back at it when we 'pop'.
323 std::vector<DiagState *> DiagStateOnPushStack;
325 DiagState *GetCurDiagState() const {
326 return DiagStatesByLoc.getCurDiagState();
329 void PushDiagStatePoint(DiagState *State, SourceLocation L);
331 /// \brief Finds the DiagStatePoint that contains the diagnostic state of
332 /// the given source location.
333 DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
334 return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
335 : DiagStatesByLoc.getCurDiagState();
338 /// \brief Sticky flag set to \c true when an error is emitted.
341 /// \brief Sticky flag set to \c true when an "uncompilable error" occurs.
342 /// I.e. an error that was not upgraded from a warning by -Werror.
343 bool UncompilableErrorOccurred;
345 /// \brief Sticky flag set to \c true when a fatal error is emitted.
346 bool FatalErrorOccurred;
348 /// \brief Indicates that an unrecoverable error has occurred.
349 bool UnrecoverableErrorOccurred;
351 /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred
352 /// during a parsing section, e.g. during parsing a function.
353 unsigned TrapNumErrorsOccurred;
354 unsigned TrapNumUnrecoverableErrorsOccurred;
356 /// \brief The level of the last diagnostic emitted.
358 /// This is used to emit continuation diagnostics with the same level as the
359 /// diagnostic that they follow.
360 DiagnosticIDs::Level LastDiagLevel;
362 unsigned NumWarnings; ///< Number of warnings reported
363 unsigned NumErrors; ///< Number of errors reported
365 /// \brief A function pointer that converts an opaque diagnostic
366 /// argument to a strings.
368 /// This takes the modifiers and argument that was present in the diagnostic.
370 /// The PrevArgs array indicates the previous arguments formatted for this
371 /// diagnostic. Implementations of this function can use this information to
372 /// avoid redundancy across arguments.
374 /// This is a hack to avoid a layering violation between libbasic and libsema.
375 typedef void (*ArgToStringFnTy)(
376 ArgumentKind Kind, intptr_t Val,
377 StringRef Modifier, StringRef Argument,
378 ArrayRef<ArgumentValue> PrevArgs,
379 SmallVectorImpl<char> &Output,
381 ArrayRef<intptr_t> QualTypeVals);
382 void *ArgToStringCookie;
383 ArgToStringFnTy ArgToStringFn;
385 /// \brief ID of the "delayed" diagnostic, which is a (typically
386 /// fatal) diagnostic that had to be delayed because it was found
387 /// while emitting another diagnostic.
388 unsigned DelayedDiagID;
390 /// \brief First string argument for the delayed diagnostic.
391 std::string DelayedDiagArg1;
393 /// \brief Second string argument for the delayed diagnostic.
394 std::string DelayedDiagArg2;
396 /// \brief Optional flag value.
398 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
399 /// -Rpass=<value>. The content of this string is emitted after the flag name
401 std::string FlagValue;
404 explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
405 DiagnosticOptions *DiagOpts,
406 DiagnosticConsumer *client = nullptr,
407 bool ShouldOwnClient = true);
408 DiagnosticsEngine(const DiagnosticsEngine &) = delete;
409 DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
410 ~DiagnosticsEngine();
412 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
416 /// \brief Retrieve the diagnostic options.
417 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
419 typedef llvm::iterator_range<DiagState::const_iterator> diag_mapping_range;
421 /// \brief Get the current set of diagnostic mappings.
422 diag_mapping_range getDiagnosticMappings() const {
423 const DiagState &DS = *GetCurDiagState();
424 return diag_mapping_range(DS.begin(), DS.end());
427 DiagnosticConsumer *getClient() { return Client; }
428 const DiagnosticConsumer *getClient() const { return Client; }
430 /// \brief Determine whether this \c DiagnosticsEngine object own its client.
431 bool ownsClient() const { return Owner != nullptr; }
433 /// \brief Return the current diagnostic client along with ownership of that
435 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
437 bool hasSourceManager() const { return SourceMgr != nullptr; }
438 SourceManager &getSourceManager() const {
439 assert(SourceMgr && "SourceManager not set!");
442 void setSourceManager(SourceManager *SrcMgr) {
443 assert(DiagStatesByLoc.empty() &&
444 "Leftover diag state from a different SourceManager.");
448 //===--------------------------------------------------------------------===//
449 // DiagnosticsEngine characterization methods, used by a client to customize
450 // how diagnostics are emitted.
453 /// \brief Copies the current DiagMappings and pushes the new copy
454 /// onto the top of the stack.
455 void pushMappings(SourceLocation Loc);
457 /// \brief Pops the current DiagMappings off the top of the stack,
458 /// causing the new top of the stack to be the active mappings.
460 /// \returns \c true if the pop happens, \c false if there is only one
461 /// DiagMapping on the stack.
462 bool popMappings(SourceLocation Loc);
464 /// \brief Set the diagnostic client associated with this diagnostic object.
466 /// \param ShouldOwnClient true if the diagnostic object should take
467 /// ownership of \c client.
468 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
470 /// \brief Specify a limit for the number of errors we should
471 /// emit before giving up.
473 /// Zero disables the limit.
474 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
476 /// \brief Specify the maximum number of template instantiation
477 /// notes to emit along with a given diagnostic.
478 void setTemplateBacktraceLimit(unsigned Limit) {
479 TemplateBacktraceLimit = Limit;
482 /// \brief Retrieve the maximum number of template instantiation
483 /// notes to emit along with a given diagnostic.
484 unsigned getTemplateBacktraceLimit() const {
485 return TemplateBacktraceLimit;
488 /// \brief Specify the maximum number of constexpr evaluation
489 /// notes to emit along with a given diagnostic.
490 void setConstexprBacktraceLimit(unsigned Limit) {
491 ConstexprBacktraceLimit = Limit;
494 /// \brief Retrieve the maximum number of constexpr evaluation
495 /// notes to emit along with a given diagnostic.
496 unsigned getConstexprBacktraceLimit() const {
497 return ConstexprBacktraceLimit;
500 /// \brief When set to true, any unmapped warnings are ignored.
502 /// If this and WarningsAsErrors are both set, then this one wins.
503 void setIgnoreAllWarnings(bool Val) {
504 GetCurDiagState()->IgnoreAllWarnings = Val;
506 bool getIgnoreAllWarnings() const {
507 return GetCurDiagState()->IgnoreAllWarnings;
510 /// \brief When set to true, any unmapped ignored warnings are no longer
513 /// If this and IgnoreAllWarnings are both set, then that one wins.
514 void setEnableAllWarnings(bool Val) {
515 GetCurDiagState()->EnableAllWarnings = Val;
517 bool getEnableAllWarnings() const {
518 return GetCurDiagState()->EnableAllWarnings;
521 /// \brief When set to true, any warnings reported are issued as errors.
522 void setWarningsAsErrors(bool Val) {
523 GetCurDiagState()->WarningsAsErrors = Val;
525 bool getWarningsAsErrors() const {
526 return GetCurDiagState()->WarningsAsErrors;
529 /// \brief When set to true, any error reported is made a fatal error.
530 void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
531 bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
533 /// \brief When set to true (the default), suppress further diagnostics after
535 void setSuppressAfterFatalError(bool Val) { SuppressAfterFatalError = Val; }
537 /// \brief When set to true mask warnings that come from system headers.
538 void setSuppressSystemWarnings(bool Val) {
539 GetCurDiagState()->SuppressSystemWarnings = Val;
541 bool getSuppressSystemWarnings() const {
542 return GetCurDiagState()->SuppressSystemWarnings;
545 /// \brief Suppress all diagnostics, to silence the front end when we
546 /// know that we don't want any more diagnostics to be passed along to the
548 void setSuppressAllDiagnostics(bool Val = true) {
549 SuppressAllDiagnostics = Val;
551 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
553 /// \brief Set type eliding, to skip outputting same types occurring in
555 void setElideType(bool Val = true) { ElideType = Val; }
556 bool getElideType() { return ElideType; }
558 /// \brief Set tree printing, to outputting the template difference in a
560 void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
561 bool getPrintTemplateTree() { return PrintTemplateTree; }
563 /// \brief Set color printing, so the type diffing will inject color markers
565 void setShowColors(bool Val = false) { ShowColors = Val; }
566 bool getShowColors() { return ShowColors; }
568 /// \brief Specify which overload candidates to show when overload resolution
571 /// By default, we show all candidates.
572 void setShowOverloads(OverloadsShown Val) {
575 OverloadsShown getShowOverloads() const { return ShowOverloads; }
577 /// \brief Pretend that the last diagnostic issued was ignored, so any
578 /// subsequent notes will be suppressed, or restore a prior ignoring
579 /// state after ignoring some diagnostics and their notes, possibly in
580 /// the middle of another diagnostic.
582 /// This can be used by clients who suppress diagnostics themselves.
583 void setLastDiagnosticIgnored(bool Ignored = true) {
584 if (LastDiagLevel == DiagnosticIDs::Fatal)
585 FatalErrorOccurred = true;
586 LastDiagLevel = Ignored ? DiagnosticIDs::Ignored : DiagnosticIDs::Warning;
589 /// \brief Determine whether the previous diagnostic was ignored. This can
590 /// be used by clients that want to determine whether notes attached to a
591 /// diagnostic will be suppressed.
592 bool isLastDiagnosticIgnored() const {
593 return LastDiagLevel == DiagnosticIDs::Ignored;
596 /// \brief Controls whether otherwise-unmapped extension diagnostics are
597 /// mapped onto ignore/warning/error.
599 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
600 void setExtensionHandlingBehavior(diag::Severity H) {
601 GetCurDiagState()->ExtBehavior = H;
603 diag::Severity getExtensionHandlingBehavior() const {
604 return GetCurDiagState()->ExtBehavior;
607 /// \brief Counter bumped when an __extension__ block is/ encountered.
609 /// When non-zero, all extension diagnostics are entirely silenced, no
610 /// matter how they are mapped.
611 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
612 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
613 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
615 /// \brief This allows the client to specify that certain warnings are
618 /// Notes can never be mapped, errors can only be mapped to fatal, and
619 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
621 /// \param Loc The source location that this change of diagnostic state should
622 /// take affect. It can be null if we are setting the latest state.
623 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
625 /// \brief Change an entire diagnostic group (e.g. "unknown-pragmas") to
626 /// have the specified mapping.
628 /// \returns true (and ignores the request) if "Group" was unknown, false
631 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
632 /// state of the -Wfoo group and vice versa.
634 /// \param Loc The source location that this change of diagnostic state should
635 /// take affect. It can be null if we are setting the state from command-line.
636 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
638 SourceLocation Loc = SourceLocation());
640 /// \brief Set the warning-as-error flag for the given diagnostic group.
642 /// This function always only operates on the current diagnostic state.
644 /// \returns True if the given group is unknown, false otherwise.
645 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
647 /// \brief Set the error-as-fatal flag for the given diagnostic group.
649 /// This function always only operates on the current diagnostic state.
651 /// \returns True if the given group is unknown, false otherwise.
652 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
654 /// \brief Add the specified mapping to all diagnostics of the specified
657 /// Mainly to be used by -Wno-everything to disable all warnings but allow
658 /// subsequent -W options to enable specific warnings.
659 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
660 SourceLocation Loc = SourceLocation());
662 bool hasErrorOccurred() const { return ErrorOccurred; }
664 /// \brief Errors that actually prevent compilation, not those that are
665 /// upgraded from a warning by -Werror.
666 bool hasUncompilableErrorOccurred() const {
667 return UncompilableErrorOccurred;
669 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
671 /// \brief Determine whether any kind of unrecoverable error has occurred.
672 bool hasUnrecoverableErrorOccurred() const {
673 return FatalErrorOccurred || UnrecoverableErrorOccurred;
676 unsigned getNumWarnings() const { return NumWarnings; }
678 void setNumWarnings(unsigned NumWarnings) {
679 this->NumWarnings = NumWarnings;
682 /// \brief Return an ID for a diagnostic with the specified format string and
685 /// If this is the first request for this diagnostic, it is registered and
686 /// created, otherwise the existing ID is returned.
688 /// \param FormatString A fixed diagnostic format string that will be hashed
689 /// and mapped to a unique DiagID.
690 template <unsigned N>
691 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
692 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
693 StringRef(FormatString, N - 1));
696 /// \brief Converts a diagnostic argument (as an intptr_t) into the string
697 /// that represents it.
698 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
699 StringRef Modifier, StringRef Argument,
700 ArrayRef<ArgumentValue> PrevArgs,
701 SmallVectorImpl<char> &Output,
702 ArrayRef<intptr_t> QualTypeVals) const {
703 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
704 ArgToStringCookie, QualTypeVals);
707 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
709 ArgToStringCookie = Cookie;
712 /// \brief Note that the prior diagnostic was emitted by some other
713 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
714 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
715 LastDiagLevel = Other.LastDiagLevel;
718 /// \brief Reset the state of the diagnostic object to its initial
722 //===--------------------------------------------------------------------===//
723 // DiagnosticsEngine classification and reporting interfaces.
726 /// \brief Determine whether the diagnostic is known to be ignored.
728 /// This can be used to opportunistically avoid expensive checks when it's
729 /// known for certain that the diagnostic has been suppressed at the
730 /// specified location \p Loc.
732 /// \param Loc The source location we are interested in finding out the
733 /// diagnostic state. Can be null in order to query the latest state.
734 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
735 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
736 diag::Severity::Ignored;
739 /// \brief Based on the way the client configured the DiagnosticsEngine
740 /// object, classify the specified diagnostic ID into a Level, consumable by
741 /// the DiagnosticConsumer.
743 /// To preserve invariant assumptions, this function should not be used to
744 /// influence parse or semantic analysis actions. Instead consider using
747 /// \param Loc The source location we are interested in finding out the
748 /// diagnostic state. Can be null in order to query the latest state.
749 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
750 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
753 /// \brief Issue the message to the client.
755 /// This actually returns an instance of DiagnosticBuilder which emits the
756 /// diagnostics (through @c ProcessDiag) when it is destroyed.
758 /// \param DiagID A member of the @c diag::kind enum.
759 /// \param Loc Represents the source location associated with the diagnostic,
760 /// which can be an invalid location if no position information is available.
761 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
762 inline DiagnosticBuilder Report(unsigned DiagID);
764 void Report(const StoredDiagnostic &storedDiag);
766 /// \brief Determine whethere there is already a diagnostic in flight.
767 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
769 /// \brief Set the "delayed" diagnostic that will be emitted once
770 /// the current diagnostic completes.
772 /// If a diagnostic is already in-flight but the front end must
773 /// report a problem (e.g., with an inconsistent file system
774 /// state), this routine sets a "delayed" diagnostic that will be
775 /// emitted after the current diagnostic completes. This should
776 /// only be used for fatal errors detected at inconvenient
777 /// times. If emitting a delayed diagnostic causes a second delayed
778 /// diagnostic to be introduced, that second delayed diagnostic
781 /// \param DiagID The ID of the diagnostic being delayed.
783 /// \param Arg1 A string argument that will be provided to the
784 /// diagnostic. A copy of this string will be stored in the
785 /// DiagnosticsEngine object itself.
787 /// \param Arg2 A string argument that will be provided to the
788 /// diagnostic. A copy of this string will be stored in the
789 /// DiagnosticsEngine object itself.
790 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
791 StringRef Arg2 = "");
793 /// \brief Clear out the current diagnostic.
794 void Clear() { CurDiagID = ~0U; }
796 /// \brief Return the value associated with this diagnostic flag.
797 StringRef getFlagValue() const { return FlagValue; }
800 /// \brief Report the delayed diagnostic.
801 void ReportDelayed();
803 // This is private state used by DiagnosticBuilder. We put it here instead of
804 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
805 // object. This implementation choice means that we can only have one
806 // diagnostic "in flight" at a time, but this seems to be a reasonable
807 // tradeoff to keep these objects small. Assertions verify that only one
808 // diagnostic is in flight at a time.
809 friend class DiagnosticIDs;
810 friend class DiagnosticBuilder;
811 friend class Diagnostic;
812 friend class PartialDiagnostic;
813 friend class DiagnosticErrorTrap;
815 /// \brief The location of the current diagnostic that is in flight.
816 SourceLocation CurDiagLoc;
818 /// \brief The ID of the current diagnostic that is in flight.
820 /// This is set to ~0U when there is no diagnostic in flight.
824 /// \brief The maximum number of arguments we can hold.
826 /// We currently only support up to 10 arguments (%0-%9). A single
827 /// diagnostic with more than that almost certainly has to be simplified
832 /// \brief The number of entries in Arguments.
833 signed char NumDiagArgs;
835 /// \brief Specifies whether an argument is in DiagArgumentsStr or
836 /// in DiagArguments.
838 /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
840 unsigned char DiagArgumentsKind[MaxArguments];
842 /// \brief Holds the values of each string argument for the current
845 /// This is only used when the corresponding ArgumentKind is ak_std_string.
846 std::string DiagArgumentsStr[MaxArguments];
848 /// \brief The values for the various substitution positions.
850 /// This is used when the argument is not an std::string. The specific
851 /// value is mangled into an intptr_t and the interpretation depends on
852 /// exactly what sort of argument kind it is.
853 intptr_t DiagArgumentsVal[MaxArguments];
855 /// \brief The list of ranges added to this diagnostic.
856 SmallVector<CharSourceRange, 8> DiagRanges;
858 /// \brief If valid, provides a hint with some code to insert, remove,
859 /// or modify at a particular position.
860 SmallVector<FixItHint, 8> DiagFixItHints;
862 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
863 bool isPragma = L.isValid();
864 DiagnosticMapping Mapping =
865 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
867 // If this is a pragma mapping, then set the diagnostic mapping flags so
868 // that we override command line options.
870 Mapping.setNoWarningAsError(true);
871 Mapping.setNoErrorAsFatal(true);
877 /// \brief Used to report a diagnostic that is finally fully formed.
879 /// \returns true if the diagnostic was emitted, false if it was suppressed.
881 return Diags->ProcessDiag(*this);
884 /// @name Diagnostic Emission
887 // Sema requires access to the following functions because the current design
888 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
889 // access us directly to ensure we minimize the emitted code for the common
890 // Sema::Diag() patterns.
893 /// \brief Emit the current diagnostic and clear the diagnostic state.
895 /// \param Force Emit the diagnostic regardless of suppression settings.
896 bool EmitCurrentDiagnostic(bool Force = false);
898 unsigned getCurrentDiagID() const { return CurDiagID; }
900 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
904 friend class ASTReader;
905 friend class ASTWriter;
908 /// \brief RAII class that determines when any errors have occurred
909 /// between the time the instance was created and the time it was
911 class DiagnosticErrorTrap {
912 DiagnosticsEngine &Diag;
914 unsigned NumUnrecoverableErrors;
917 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
918 : Diag(Diag) { reset(); }
920 /// \brief Determine whether any errors have occurred since this
921 /// object instance was created.
922 bool hasErrorOccurred() const {
923 return Diag.TrapNumErrorsOccurred > NumErrors;
926 /// \brief Determine whether any unrecoverable errors have occurred since this
927 /// object instance was created.
928 bool hasUnrecoverableErrorOccurred() const {
929 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
932 /// \brief Set to initial state of "no errors occurred".
934 NumErrors = Diag.TrapNumErrorsOccurred;
935 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
939 //===----------------------------------------------------------------------===//
941 //===----------------------------------------------------------------------===//
943 /// \brief A little helper class used to produce diagnostics.
945 /// This is constructed by the DiagnosticsEngine::Report method, and
946 /// allows insertion of extra information (arguments and source ranges) into
947 /// the currently "in flight" diagnostic. When the temporary for the builder
948 /// is destroyed, the diagnostic is issued.
950 /// Note that many of these will be created as temporary objects (many call
951 /// sites), so we want them to be small and we never want their address taken.
952 /// This ensures that compilers with somewhat reasonable optimizers will promote
953 /// the common fields to registers, eliminating increments of the NumArgs field,
955 class DiagnosticBuilder {
956 mutable DiagnosticsEngine *DiagObj = nullptr;
957 mutable unsigned NumArgs = 0;
959 /// \brief Status variable indicating if this diagnostic is still active.
961 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
962 // but LLVM is not currently smart enough to eliminate the null check that
963 // Emit() would end up with if we used that as our status variable.
964 mutable bool IsActive = false;
966 /// \brief Flag indicating that this diagnostic is being emitted via a
967 /// call to ForceEmit.
968 mutable bool IsForceEmit = false;
970 friend class DiagnosticsEngine;
972 DiagnosticBuilder() = default;
974 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
975 : DiagObj(diagObj), IsActive(true) {
976 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
977 diagObj->DiagRanges.clear();
978 diagObj->DiagFixItHints.clear();
981 friend class PartialDiagnostic;
985 DiagObj->NumDiagArgs = NumArgs;
988 /// \brief Clear out the current diagnostic.
995 /// \brief Determine whether this diagnostic is still active.
996 bool isActive() const { return IsActive; }
998 /// \brief Force the diagnostic builder to emit the diagnostic now.
1000 /// Once this function has been called, the DiagnosticBuilder object
1001 /// should not be used again before it is destroyed.
1003 /// \returns true if a diagnostic was emitted, false if the
1004 /// diagnostic was suppressed.
1006 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1007 // (or by a subclass, as in SemaDiagnosticBuilder).
1008 if (!isActive()) return false;
1010 // When emitting diagnostics, we set the final argument count into
1011 // the DiagnosticsEngine object.
1014 // Process the diagnostic.
1015 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
1017 // This diagnostic is dead.
1024 /// Copy constructor. When copied, this "takes" the diagnostic info from the
1025 /// input and neuters it.
1026 DiagnosticBuilder(const DiagnosticBuilder &D) {
1027 DiagObj = D.DiagObj;
1028 IsActive = D.IsActive;
1029 IsForceEmit = D.IsForceEmit;
1031 NumArgs = D.NumArgs;
1034 DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1036 /// \brief Emits the diagnostic.
1037 ~DiagnosticBuilder() {
1041 /// \brief Retrieve an empty diagnostic builder.
1042 static DiagnosticBuilder getEmpty() {
1043 return DiagnosticBuilder();
1046 /// \brief Forces the diagnostic to be emitted.
1047 const DiagnosticBuilder &setForceEmit() const {
1052 /// \brief Conversion of DiagnosticBuilder to bool always returns \c true.
1054 /// This allows is to be used in boolean error contexts (where \c true is
1055 /// used to indicate that an error has occurred), like:
1057 /// return Diag(...);
1059 operator bool() const { return true; }
1061 void AddString(StringRef S) const {
1062 assert(isActive() && "Clients must not add to cleared diagnostic!");
1063 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1064 "Too many arguments to diagnostic!");
1065 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
1066 DiagObj->DiagArgumentsStr[NumArgs++] = S;
1069 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1070 assert(isActive() && "Clients must not add to cleared diagnostic!");
1071 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1072 "Too many arguments to diagnostic!");
1073 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
1074 DiagObj->DiagArgumentsVal[NumArgs++] = V;
1077 void AddSourceRange(const CharSourceRange &R) const {
1078 assert(isActive() && "Clients must not add to cleared diagnostic!");
1079 DiagObj->DiagRanges.push_back(R);
1082 void AddFixItHint(const FixItHint &Hint) const {
1083 assert(isActive() && "Clients must not add to cleared diagnostic!");
1085 DiagObj->DiagFixItHints.push_back(Hint);
1088 void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
1091 struct AddFlagValue {
1092 explicit AddFlagValue(StringRef V) : Val(V) {}
1096 /// \brief Register a value for the flag in the current diagnostic. This
1097 /// value will be shown as the suffix "=value" after the flag name. It is
1098 /// useful in cases where the diagnostic flag accepts values (e.g.,
1099 /// -Rpass or -Wframe-larger-than).
1100 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1101 const AddFlagValue V) {
1102 DB.addFlagValue(V.Val);
1106 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1112 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1114 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1115 DiagnosticsEngine::ak_c_string);
1119 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
1120 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1124 // We use enable_if here to prevent that this overload is selected for
1125 // pointers or other arguments that are implicitly convertible to bool.
1126 template <typename T>
1128 typename std::enable_if<std::is_same<T, bool>::value,
1129 const DiagnosticBuilder &>::type
1130 operator<<(const DiagnosticBuilder &DB, T I) {
1131 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1135 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1137 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1141 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1143 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1147 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1148 const IdentifierInfo *II) {
1149 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1150 DiagnosticsEngine::ak_identifierinfo);
1154 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
1155 // so that we only match those arguments that are (statically) DeclContexts;
1156 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
1158 template <typename T>
1159 inline typename std::enable_if<
1160 std::is_same<typename std::remove_const<T>::type, DeclContext>::value,
1161 const DiagnosticBuilder &>::type
1162 operator<<(const DiagnosticBuilder &DB, T *DC) {
1163 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1164 DiagnosticsEngine::ak_declcontext);
1168 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1170 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1174 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1175 ArrayRef<SourceRange> Ranges) {
1176 for (SourceRange R : Ranges)
1177 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1181 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1182 const CharSourceRange &R) {
1183 DB.AddSourceRange(R);
1187 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1188 const FixItHint &Hint) {
1189 DB.AddFixItHint(Hint);
1193 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1194 ArrayRef<FixItHint> Hints) {
1195 for (const FixItHint &Hint : Hints)
1196 DB.AddFixItHint(Hint);
1200 /// A nullability kind paired with a bit indicating whether it used a
1201 /// context-sensitive keyword.
1202 typedef std::pair<NullabilityKind, bool> DiagNullabilityKind;
1204 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1205 DiagNullabilityKind nullability);
1207 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1209 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
1213 return DiagnosticBuilder(this);
1216 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1217 return Report(SourceLocation(), DiagID);
1220 //===----------------------------------------------------------------------===//
1222 //===----------------------------------------------------------------------===//
1224 /// A little helper class (which is basically a smart pointer that forwards
1225 /// info from DiagnosticsEngine) that allows clients to enquire about the
1226 /// currently in-flight diagnostic.
1228 const DiagnosticsEngine *DiagObj;
1229 StringRef StoredDiagMessage;
1232 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1233 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1234 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1236 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1237 unsigned getID() const { return DiagObj->CurDiagID; }
1238 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1239 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1240 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1242 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1244 /// \brief Return the kind of the specified index.
1246 /// Based on the kind of argument, the accessors below can be used to get
1249 /// \pre Idx < getNumArgs()
1250 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1251 assert(Idx < getNumArgs() && "Argument index out of range!");
1252 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1255 /// \brief Return the provided argument string specified by \p Idx.
1256 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1257 const std::string &getArgStdStr(unsigned Idx) const {
1258 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1259 "invalid argument accessor!");
1260 return DiagObj->DiagArgumentsStr[Idx];
1263 /// \brief Return the specified C string argument.
1264 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1265 const char *getArgCStr(unsigned Idx) const {
1266 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1267 "invalid argument accessor!");
1268 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1271 /// \brief Return the specified signed integer argument.
1272 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1273 int getArgSInt(unsigned Idx) const {
1274 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1275 "invalid argument accessor!");
1276 return (int)DiagObj->DiagArgumentsVal[Idx];
1279 /// \brief Return the specified unsigned integer argument.
1280 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1281 unsigned getArgUInt(unsigned Idx) const {
1282 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1283 "invalid argument accessor!");
1284 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1287 /// \brief Return the specified IdentifierInfo argument.
1288 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1289 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1290 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1291 "invalid argument accessor!");
1292 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1295 /// \brief Return the specified non-string argument in an opaque form.
1296 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1297 intptr_t getRawArg(unsigned Idx) const {
1298 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1299 "invalid argument accessor!");
1300 return DiagObj->DiagArgumentsVal[Idx];
1303 /// \brief Return the number of source ranges associated with this diagnostic.
1304 unsigned getNumRanges() const {
1305 return DiagObj->DiagRanges.size();
1308 /// \pre Idx < getNumRanges()
1309 const CharSourceRange &getRange(unsigned Idx) const {
1310 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1311 return DiagObj->DiagRanges[Idx];
1314 /// \brief Return an array reference for this diagnostic's ranges.
1315 ArrayRef<CharSourceRange> getRanges() const {
1316 return DiagObj->DiagRanges;
1319 unsigned getNumFixItHints() const {
1320 return DiagObj->DiagFixItHints.size();
1323 const FixItHint &getFixItHint(unsigned Idx) const {
1324 assert(Idx < getNumFixItHints() && "Invalid index!");
1325 return DiagObj->DiagFixItHints[Idx];
1328 ArrayRef<FixItHint> getFixItHints() const {
1329 return DiagObj->DiagFixItHints;
1332 /// \brief Format this diagnostic into a string, substituting the
1333 /// formal arguments into the %0 slots.
1335 /// The result is appended onto the \p OutStr array.
1336 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1338 /// \brief Format the given format-string into the output buffer using the
1339 /// arguments stored in this diagnostic.
1340 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1341 SmallVectorImpl<char> &OutStr) const;
1345 * \brief Represents a diagnostic in a form that can be retained until its
1346 * corresponding source manager is destroyed.
1348 class StoredDiagnostic {
1350 DiagnosticsEngine::Level Level;
1352 std::string Message;
1353 std::vector<CharSourceRange> Ranges;
1354 std::vector<FixItHint> FixIts;
1357 StoredDiagnostic() = default;
1358 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1359 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1361 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1362 StringRef Message, FullSourceLoc Loc,
1363 ArrayRef<CharSourceRange> Ranges,
1364 ArrayRef<FixItHint> Fixits);
1366 /// \brief Evaluates true when this object stores a diagnostic.
1367 explicit operator bool() const { return !Message.empty(); }
1369 unsigned getID() const { return ID; }
1370 DiagnosticsEngine::Level getLevel() const { return Level; }
1371 const FullSourceLoc &getLocation() const { return Loc; }
1372 StringRef getMessage() const { return Message; }
1374 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1376 typedef std::vector<CharSourceRange>::const_iterator range_iterator;
1377 range_iterator range_begin() const { return Ranges.begin(); }
1378 range_iterator range_end() const { return Ranges.end(); }
1379 unsigned range_size() const { return Ranges.size(); }
1381 ArrayRef<CharSourceRange> getRanges() const {
1382 return llvm::makeArrayRef(Ranges);
1385 typedef std::vector<FixItHint>::const_iterator fixit_iterator;
1386 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1387 fixit_iterator fixit_end() const { return FixIts.end(); }
1388 unsigned fixit_size() const { return FixIts.size(); }
1390 ArrayRef<FixItHint> getFixIts() const {
1391 return llvm::makeArrayRef(FixIts);
1395 /// \brief Abstract interface, implemented by clients of the front-end, which
1396 /// formats and prints fully processed diagnostics.
1397 class DiagnosticConsumer {
1399 unsigned NumWarnings = 0; ///< Number of warnings reported
1400 unsigned NumErrors = 0; ///< Number of errors reported
1403 DiagnosticConsumer() = default;
1405 virtual ~DiagnosticConsumer();
1407 unsigned getNumErrors() const { return NumErrors; }
1408 unsigned getNumWarnings() const { return NumWarnings; }
1409 virtual void clear() { NumWarnings = NumErrors = 0; }
1411 /// \brief Callback to inform the diagnostic client that processing
1412 /// of a source file is beginning.
1414 /// Note that diagnostics may be emitted outside the processing of a source
1415 /// file, for example during the parsing of command line options. However,
1416 /// diagnostics with source range information are required to only be emitted
1417 /// in between BeginSourceFile() and EndSourceFile().
1419 /// \param LangOpts The language options for the source file being processed.
1420 /// \param PP The preprocessor object being used for the source; this is
1421 /// optional, e.g., it may not be present when processing AST source files.
1422 virtual void BeginSourceFile(const LangOptions &LangOpts,
1423 const Preprocessor *PP = nullptr) {}
1425 /// \brief Callback to inform the diagnostic client that processing
1426 /// of a source file has ended.
1428 /// The diagnostic client should assume that any objects made available via
1429 /// BeginSourceFile() are inaccessible.
1430 virtual void EndSourceFile() {}
1432 /// \brief Callback to inform the diagnostic client that processing of all
1433 /// source files has ended.
1434 virtual void finish() {}
1436 /// \brief Indicates whether the diagnostics handled by this
1437 /// DiagnosticConsumer should be included in the number of diagnostics
1438 /// reported by DiagnosticsEngine.
1440 /// The default implementation returns true.
1441 virtual bool IncludeInDiagnosticCounts() const;
1443 /// \brief Handle this diagnostic, reporting it to the user or
1444 /// capturing it to a log as needed.
1446 /// The default implementation just keeps track of the total number of
1447 /// warnings and errors.
1448 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1449 const Diagnostic &Info);
1452 /// \brief A diagnostic client that ignores all diagnostics.
1453 class IgnoringDiagConsumer : public DiagnosticConsumer {
1454 virtual void anchor();
1456 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1457 const Diagnostic &Info) override {
1462 /// \brief Diagnostic consumer that forwards diagnostics along to an
1463 /// existing, already-initialized diagnostic consumer.
1465 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1466 DiagnosticConsumer &Target;
1469 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1471 ~ForwardingDiagnosticConsumer() override;
1473 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1474 const Diagnostic &Info) override;
1475 void clear() override;
1477 bool IncludeInDiagnosticCounts() const override;
1480 // Struct used for sending info about how a type should be printed.
1481 struct TemplateDiffTypes {
1484 unsigned PrintTree : 1;
1485 unsigned PrintFromType : 1;
1486 unsigned ElideType : 1;
1487 unsigned ShowColors : 1;
1488 // The printer sets this variable to true if the template diff was used.
1489 unsigned TemplateDiffUsed : 1;
1492 /// Special character that the diagnostic printer will use to toggle the bold
1493 /// attribute. The character itself will be not be printed.
1494 const char ToggleHighlight = 127;
1497 /// ProcessWarningOptions - Initialize the diagnostic client and process the
1498 /// warning options specified on the command line.
1499 void ProcessWarningOptions(DiagnosticsEngine &Diags,
1500 const DiagnosticOptions &Opts,
1501 bool ReportDiags = true);
1503 } // end namespace clang
1505 #endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H