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"
31 class DiagnosticBuilder;
32 class DiagnosticConsumer;
33 class DiagnosticErrorTrap;
34 class DiagnosticOptions;
38 class StoredDiagnostic;
40 enum TokenKind : unsigned short;
43 /// \brief Annotates a diagnostic with some code that should be
44 /// inserted, removed, or replaced to fix the problem.
46 /// This kind of hint should be used when we are certain that the
47 /// introduction, removal, or modification of a particular (small!)
48 /// amount of code will correct a compilation error. The compiler
49 /// should also provide full recovery from such errors, such that
50 /// suppressing the diagnostic output can still result in successful
54 /// \brief Code that should be replaced to correct the error. Empty for an
56 CharSourceRange RemoveRange;
58 /// \brief Code in the specific range that should be inserted in the insertion
60 CharSourceRange InsertFromRange;
62 /// \brief The actual code to insert at the insertion location, as a
64 std::string CodeToInsert;
66 bool BeforePreviousInsertions;
68 /// \brief Empty code modification hint, indicating that no code
69 /// modification is known.
70 FixItHint() : BeforePreviousInsertions(false) { }
73 return !RemoveRange.isValid();
76 /// \brief Create a code modification hint that inserts the given
77 /// code string at a specific location.
78 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
80 bool BeforePreviousInsertions = false) {
83 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
84 Hint.CodeToInsert = Code;
85 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
89 /// \brief Create a code modification hint that inserts the given
90 /// code from \p FromRange at a specific location.
91 static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
92 CharSourceRange FromRange,
93 bool BeforePreviousInsertions = false) {
96 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
97 Hint.InsertFromRange = FromRange;
98 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
102 /// \brief Create a code modification hint that removes the given
104 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
106 Hint.RemoveRange = RemoveRange;
109 static FixItHint CreateRemoval(SourceRange RemoveRange) {
110 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
113 /// \brief Create a code modification hint that replaces the given
114 /// source range with the given code string.
115 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
118 Hint.RemoveRange = RemoveRange;
119 Hint.CodeToInsert = Code;
123 static FixItHint CreateReplacement(SourceRange RemoveRange,
125 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
129 /// \brief Concrete class used by the front-end to report problems and issues.
131 /// This massages the diagnostics (e.g. handling things like "report warnings
132 /// as errors" and passes them off to the DiagnosticConsumer for reporting to
133 /// the user. DiagnosticsEngine is tied to one translation unit and one
135 class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
136 DiagnosticsEngine(const DiagnosticsEngine &) = delete;
137 void operator=(const DiagnosticsEngine &) = delete;
140 /// \brief The level of the diagnostic, after it has been through mapping.
142 Ignored = DiagnosticIDs::Ignored,
143 Note = DiagnosticIDs::Note,
144 Remark = DiagnosticIDs::Remark,
145 Warning = DiagnosticIDs::Warning,
146 Error = DiagnosticIDs::Error,
147 Fatal = DiagnosticIDs::Fatal
151 ak_std_string, ///< std::string
152 ak_c_string, ///< const char *
154 ak_uint, ///< unsigned
155 ak_tokenkind, ///< enum TokenKind : unsigned
156 ak_identifierinfo, ///< IdentifierInfo
157 ak_qualtype, ///< QualType
158 ak_declarationname, ///< DeclarationName
159 ak_nameddecl, ///< NamedDecl *
160 ak_nestednamespec, ///< NestedNameSpecifier *
161 ak_declcontext, ///< DeclContext *
162 ak_qualtype_pair, ///< pair<QualType, QualType>
166 /// \brief Represents on argument value, which is a union discriminated
167 /// by ArgumentKind, with a value.
168 typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
171 unsigned char AllExtensionsSilenced; // Used by __extension__
172 bool IgnoreAllWarnings; // Ignore all warnings: -w
173 bool WarningsAsErrors; // Treat warnings like errors.
174 bool EnableAllWarnings; // Enable all warnings.
175 bool ErrorsAsFatal; // Treat errors like fatal errors.
176 bool SuppressSystemWarnings; // Suppress warnings in system headers.
177 bool SuppressAllDiagnostics; // Suppress all diagnostics.
178 bool ElideType; // Elide common types of templates.
179 bool PrintTemplateTree; // Print a tree when comparing templates.
180 bool ShowColors; // Color printing is enabled.
181 OverloadsShown ShowOverloads; // Which overload candidates to show.
182 unsigned ErrorLimit; // Cap of # errors emitted, 0 -> no limit.
183 unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
185 unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation
186 // backtrace stack, 0 -> no limit.
187 diag::Severity ExtBehavior; // Map extensions to warnings or errors?
188 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
189 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
190 DiagnosticConsumer *Client;
191 std::unique_ptr<DiagnosticConsumer> Owner;
192 SourceManager *SourceMgr;
194 /// \brief Mapping information for diagnostics.
196 /// Mapping info is packed into four bits per diagnostic. The low three
197 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
198 /// The high bit is set when the mapping was established as a user mapping.
199 /// If the high bit is clear, then the low bits are set to the default
200 /// value, and should be mapped with -pedantic, -Werror, etc.
202 /// A new DiagState is created and kept around when diagnostic pragmas modify
203 /// the state so that we know what is the diagnostic state at any given
206 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
209 typedef llvm::DenseMap<unsigned, DiagnosticMapping>::iterator iterator;
210 typedef llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator
213 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
214 DiagMap[Diag] = Info;
217 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
219 const_iterator begin() const { return DiagMap.begin(); }
220 const_iterator end() const { return DiagMap.end(); }
223 /// \brief Keeps and automatically disposes all DiagStates that we create.
224 std::list<DiagState> DiagStates;
226 /// \brief Represents a point in source where the diagnostic state was
227 /// modified because of a pragma.
229 /// 'Loc' can be null if the point represents the diagnostic state
230 /// modifications done through the command-line.
231 struct DiagStatePoint {
234 DiagStatePoint(DiagState *State, FullSourceLoc Loc)
235 : State(State), Loc(Loc) { }
237 bool operator<(const DiagStatePoint &RHS) const {
238 // If Loc is invalid it means it came from <command-line>, in which case
239 // we regard it as coming before any valid source location.
240 if (RHS.Loc.isInvalid())
244 return Loc.isBeforeInTranslationUnitThan(RHS.Loc);
248 /// \brief A sorted vector of all DiagStatePoints representing changes in
249 /// diagnostic state due to diagnostic pragmas.
251 /// The vector is always sorted according to the SourceLocation of the
253 typedef std::vector<DiagStatePoint> DiagStatePointsTy;
254 mutable DiagStatePointsTy DiagStatePoints;
256 /// \brief Keeps the DiagState that was active during each diagnostic 'push'
257 /// so we can get back at it when we 'pop'.
258 std::vector<DiagState *> DiagStateOnPushStack;
260 DiagState *GetCurDiagState() const {
261 assert(!DiagStatePoints.empty());
262 return DiagStatePoints.back().State;
265 void PushDiagStatePoint(DiagState *State, SourceLocation L) {
266 FullSourceLoc Loc(L, getSourceManager());
267 // Make sure that DiagStatePoints is always sorted according to Loc.
268 assert(Loc.isValid() && "Adding invalid loc point");
269 assert(!DiagStatePoints.empty() &&
270 (DiagStatePoints.back().Loc.isInvalid() ||
271 DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) &&
272 "Previous point loc comes after or is the same as new one");
273 DiagStatePoints.push_back(DiagStatePoint(State, Loc));
276 /// \brief Finds the DiagStatePoint that contains the diagnostic state of
277 /// the given source location.
278 DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const;
280 /// \brief Sticky flag set to \c true when an error is emitted.
283 /// \brief Sticky flag set to \c true when an "uncompilable error" occurs.
284 /// I.e. an error that was not upgraded from a warning by -Werror.
285 bool UncompilableErrorOccurred;
287 /// \brief Sticky flag set to \c true when a fatal error is emitted.
288 bool FatalErrorOccurred;
290 /// \brief Indicates that an unrecoverable error has occurred.
291 bool UnrecoverableErrorOccurred;
293 /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred
294 /// during a parsing section, e.g. during parsing a function.
295 unsigned TrapNumErrorsOccurred;
296 unsigned TrapNumUnrecoverableErrorsOccurred;
298 /// \brief The level of the last diagnostic emitted.
300 /// This is used to emit continuation diagnostics with the same level as the
301 /// diagnostic that they follow.
302 DiagnosticIDs::Level LastDiagLevel;
304 unsigned NumWarnings; ///< Number of warnings reported
305 unsigned NumErrors; ///< Number of errors reported
307 /// \brief A function pointer that converts an opaque diagnostic
308 /// argument to a strings.
310 /// This takes the modifiers and argument that was present in the diagnostic.
312 /// The PrevArgs array indicates the previous arguments formatted for this
313 /// diagnostic. Implementations of this function can use this information to
314 /// avoid redundancy across arguments.
316 /// This is a hack to avoid a layering violation between libbasic and libsema.
317 typedef void (*ArgToStringFnTy)(
318 ArgumentKind Kind, intptr_t Val,
319 StringRef Modifier, StringRef Argument,
320 ArrayRef<ArgumentValue> PrevArgs,
321 SmallVectorImpl<char> &Output,
323 ArrayRef<intptr_t> QualTypeVals);
324 void *ArgToStringCookie;
325 ArgToStringFnTy ArgToStringFn;
327 /// \brief ID of the "delayed" diagnostic, which is a (typically
328 /// fatal) diagnostic that had to be delayed because it was found
329 /// while emitting another diagnostic.
330 unsigned DelayedDiagID;
332 /// \brief First string argument for the delayed diagnostic.
333 std::string DelayedDiagArg1;
335 /// \brief Second string argument for the delayed diagnostic.
336 std::string DelayedDiagArg2;
338 /// \brief Optional flag value.
340 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
341 /// -Rpass=<value>. The content of this string is emitted after the flag name
343 std::string FlagValue;
346 explicit DiagnosticsEngine(
347 const IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
348 DiagnosticOptions *DiagOpts,
349 DiagnosticConsumer *client = nullptr,
350 bool ShouldOwnClient = true);
351 ~DiagnosticsEngine();
353 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
357 /// \brief Retrieve the diagnostic options.
358 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
360 typedef llvm::iterator_range<DiagState::const_iterator> diag_mapping_range;
362 /// \brief Get the current set of diagnostic mappings.
363 diag_mapping_range getDiagnosticMappings() const {
364 const DiagState &DS = *GetCurDiagState();
365 return diag_mapping_range(DS.begin(), DS.end());
368 DiagnosticConsumer *getClient() { return Client; }
369 const DiagnosticConsumer *getClient() const { return Client; }
371 /// \brief Determine whether this \c DiagnosticsEngine object own its client.
372 bool ownsClient() const { return Owner != nullptr; }
374 /// \brief Return the current diagnostic client along with ownership of that
376 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
378 bool hasSourceManager() const { return SourceMgr != nullptr; }
379 SourceManager &getSourceManager() const {
380 assert(SourceMgr && "SourceManager not set!");
383 void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
385 //===--------------------------------------------------------------------===//
386 // DiagnosticsEngine characterization methods, used by a client to customize
387 // how diagnostics are emitted.
390 /// \brief Copies the current DiagMappings and pushes the new copy
391 /// onto the top of the stack.
392 void pushMappings(SourceLocation Loc);
394 /// \brief Pops the current DiagMappings off the top of the stack,
395 /// causing the new top of the stack to be the active mappings.
397 /// \returns \c true if the pop happens, \c false if there is only one
398 /// DiagMapping on the stack.
399 bool popMappings(SourceLocation Loc);
401 /// \brief Set the diagnostic client associated with this diagnostic object.
403 /// \param ShouldOwnClient true if the diagnostic object should take
404 /// ownership of \c client.
405 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
407 /// \brief Specify a limit for the number of errors we should
408 /// emit before giving up.
410 /// Zero disables the limit.
411 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
413 /// \brief Specify the maximum number of template instantiation
414 /// notes to emit along with a given diagnostic.
415 void setTemplateBacktraceLimit(unsigned Limit) {
416 TemplateBacktraceLimit = Limit;
419 /// \brief Retrieve the maximum number of template instantiation
420 /// notes to emit along with a given diagnostic.
421 unsigned getTemplateBacktraceLimit() const {
422 return TemplateBacktraceLimit;
425 /// \brief Specify the maximum number of constexpr evaluation
426 /// notes to emit along with a given diagnostic.
427 void setConstexprBacktraceLimit(unsigned Limit) {
428 ConstexprBacktraceLimit = Limit;
431 /// \brief Retrieve the maximum number of constexpr evaluation
432 /// notes to emit along with a given diagnostic.
433 unsigned getConstexprBacktraceLimit() const {
434 return ConstexprBacktraceLimit;
437 /// \brief When set to true, any unmapped warnings are ignored.
439 /// If this and WarningsAsErrors are both set, then this one wins.
440 void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
441 bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
443 /// \brief When set to true, any unmapped ignored warnings are no longer
446 /// If this and IgnoreAllWarnings are both set, then that one wins.
447 void setEnableAllWarnings(bool Val) { EnableAllWarnings = Val; }
448 bool getEnableAllWarnings() const { return EnableAllWarnings; }
450 /// \brief When set to true, any warnings reported are issued as errors.
451 void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
452 bool getWarningsAsErrors() const { return WarningsAsErrors; }
454 /// \brief When set to true, any error reported is made a fatal error.
455 void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
456 bool getErrorsAsFatal() const { return ErrorsAsFatal; }
458 /// \brief When set to true mask warnings that come from system headers.
459 void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
460 bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
462 /// \brief Suppress all diagnostics, to silence the front end when we
463 /// know that we don't want any more diagnostics to be passed along to the
465 void setSuppressAllDiagnostics(bool Val = true) {
466 SuppressAllDiagnostics = Val;
468 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
470 /// \brief Set type eliding, to skip outputting same types occurring in
472 void setElideType(bool Val = true) { ElideType = Val; }
473 bool getElideType() { return ElideType; }
475 /// \brief Set tree printing, to outputting the template difference in a
477 void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
478 bool getPrintTemplateTree() { return PrintTemplateTree; }
480 /// \brief Set color printing, so the type diffing will inject color markers
482 void setShowColors(bool Val = false) { ShowColors = Val; }
483 bool getShowColors() { return ShowColors; }
485 /// \brief Specify which overload candidates to show when overload resolution
488 /// By default, we show all candidates.
489 void setShowOverloads(OverloadsShown Val) {
492 OverloadsShown getShowOverloads() const { return ShowOverloads; }
494 /// \brief Pretend that the last diagnostic issued was ignored, so any
495 /// subsequent notes will be suppressed.
497 /// This can be used by clients who suppress diagnostics themselves.
498 void setLastDiagnosticIgnored() {
499 if (LastDiagLevel == DiagnosticIDs::Fatal)
500 FatalErrorOccurred = true;
501 LastDiagLevel = DiagnosticIDs::Ignored;
504 /// \brief Determine whether the previous diagnostic was ignored. This can
505 /// be used by clients that want to determine whether notes attached to a
506 /// diagnostic will be suppressed.
507 bool isLastDiagnosticIgnored() const {
508 return LastDiagLevel == DiagnosticIDs::Ignored;
511 /// \brief Controls whether otherwise-unmapped extension diagnostics are
512 /// mapped onto ignore/warning/error.
514 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
515 void setExtensionHandlingBehavior(diag::Severity H) { ExtBehavior = H; }
516 diag::Severity getExtensionHandlingBehavior() const { return ExtBehavior; }
518 /// \brief Counter bumped when an __extension__ block is/ encountered.
520 /// When non-zero, all extension diagnostics are entirely silenced, no
521 /// matter how they are mapped.
522 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
523 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
524 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
526 /// \brief This allows the client to specify that certain warnings are
529 /// Notes can never be mapped, errors can only be mapped to fatal, and
530 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
532 /// \param Loc The source location that this change of diagnostic state should
533 /// take affect. It can be null if we are setting the latest state.
534 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
536 /// \brief Change an entire diagnostic group (e.g. "unknown-pragmas") to
537 /// have the specified mapping.
539 /// \returns true (and ignores the request) if "Group" was unknown, false
542 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
543 /// state of the -Wfoo group and vice versa.
545 /// \param Loc The source location that this change of diagnostic state should
546 /// take affect. It can be null if we are setting the state from command-line.
547 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
549 SourceLocation Loc = SourceLocation());
551 /// \brief Set the warning-as-error flag for the given diagnostic group.
553 /// This function always only operates on the current diagnostic state.
555 /// \returns True if the given group is unknown, false otherwise.
556 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
558 /// \brief Set the error-as-fatal flag for the given diagnostic group.
560 /// This function always only operates on the current diagnostic state.
562 /// \returns True if the given group is unknown, false otherwise.
563 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
565 /// \brief Add the specified mapping to all diagnostics of the specified
568 /// Mainly to be used by -Wno-everything to disable all warnings but allow
569 /// subsequent -W options to enable specific warnings.
570 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
571 SourceLocation Loc = SourceLocation());
573 bool hasErrorOccurred() const { return ErrorOccurred; }
575 /// \brief Errors that actually prevent compilation, not those that are
576 /// upgraded from a warning by -Werror.
577 bool hasUncompilableErrorOccurred() const {
578 return UncompilableErrorOccurred;
580 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
582 /// \brief Determine whether any kind of unrecoverable error has occurred.
583 bool hasUnrecoverableErrorOccurred() const {
584 return FatalErrorOccurred || UnrecoverableErrorOccurred;
587 unsigned getNumWarnings() const { return NumWarnings; }
589 void setNumWarnings(unsigned NumWarnings) {
590 this->NumWarnings = NumWarnings;
593 /// \brief Return an ID for a diagnostic with the specified format string and
596 /// If this is the first request for this diagnostic, it is registered and
597 /// created, otherwise the existing ID is returned.
599 /// \param FormatString A fixed diagnostic format string that will be hashed
600 /// and mapped to a unique DiagID.
601 template <unsigned N>
602 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
603 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
604 StringRef(FormatString, N - 1));
607 /// \brief Converts a diagnostic argument (as an intptr_t) into the string
608 /// that represents it.
609 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
610 StringRef Modifier, StringRef Argument,
611 ArrayRef<ArgumentValue> PrevArgs,
612 SmallVectorImpl<char> &Output,
613 ArrayRef<intptr_t> QualTypeVals) const {
614 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
615 ArgToStringCookie, QualTypeVals);
618 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
620 ArgToStringCookie = Cookie;
623 /// \brief Note that the prior diagnostic was emitted by some other
624 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
625 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
626 LastDiagLevel = Other.LastDiagLevel;
629 /// \brief Reset the state of the diagnostic object to its initial
633 //===--------------------------------------------------------------------===//
634 // DiagnosticsEngine classification and reporting interfaces.
637 /// \brief Determine whether the diagnostic is known to be ignored.
639 /// This can be used to opportunistically avoid expensive checks when it's
640 /// known for certain that the diagnostic has been suppressed at the
641 /// specified location \p Loc.
643 /// \param Loc The source location we are interested in finding out the
644 /// diagnostic state. Can be null in order to query the latest state.
645 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
646 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
647 diag::Severity::Ignored;
650 /// \brief Based on the way the client configured the DiagnosticsEngine
651 /// object, classify the specified diagnostic ID into a Level, consumable by
652 /// the DiagnosticConsumer.
654 /// To preserve invariant assumptions, this function should not be used to
655 /// influence parse or semantic analysis actions. Instead consider using
658 /// \param Loc The source location we are interested in finding out the
659 /// diagnostic state. Can be null in order to query the latest state.
660 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
661 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
664 /// \brief Issue the message to the client.
666 /// This actually returns an instance of DiagnosticBuilder which emits the
667 /// diagnostics (through @c ProcessDiag) when it is destroyed.
669 /// \param DiagID A member of the @c diag::kind enum.
670 /// \param Loc Represents the source location associated with the diagnostic,
671 /// which can be an invalid location if no position information is available.
672 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
673 inline DiagnosticBuilder Report(unsigned DiagID);
675 void Report(const StoredDiagnostic &storedDiag);
677 /// \brief Determine whethere there is already a diagnostic in flight.
678 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
680 /// \brief Set the "delayed" diagnostic that will be emitted once
681 /// the current diagnostic completes.
683 /// If a diagnostic is already in-flight but the front end must
684 /// report a problem (e.g., with an inconsistent file system
685 /// state), this routine sets a "delayed" diagnostic that will be
686 /// emitted after the current diagnostic completes. This should
687 /// only be used for fatal errors detected at inconvenient
688 /// times. If emitting a delayed diagnostic causes a second delayed
689 /// diagnostic to be introduced, that second delayed diagnostic
692 /// \param DiagID The ID of the diagnostic being delayed.
694 /// \param Arg1 A string argument that will be provided to the
695 /// diagnostic. A copy of this string will be stored in the
696 /// DiagnosticsEngine object itself.
698 /// \param Arg2 A string argument that will be provided to the
699 /// diagnostic. A copy of this string will be stored in the
700 /// DiagnosticsEngine object itself.
701 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
702 StringRef Arg2 = "");
704 /// \brief Clear out the current diagnostic.
705 void Clear() { CurDiagID = ~0U; }
707 /// \brief Return the value associated with this diagnostic flag.
708 StringRef getFlagValue() const { return FlagValue; }
711 /// \brief Report the delayed diagnostic.
712 void ReportDelayed();
714 // This is private state used by DiagnosticBuilder. We put it here instead of
715 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
716 // object. This implementation choice means that we can only have one
717 // diagnostic "in flight" at a time, but this seems to be a reasonable
718 // tradeoff to keep these objects small. Assertions verify that only one
719 // diagnostic is in flight at a time.
720 friend class DiagnosticIDs;
721 friend class DiagnosticBuilder;
722 friend class Diagnostic;
723 friend class PartialDiagnostic;
724 friend class DiagnosticErrorTrap;
726 /// \brief The location of the current diagnostic that is in flight.
727 SourceLocation CurDiagLoc;
729 /// \brief The ID of the current diagnostic that is in flight.
731 /// This is set to ~0U when there is no diagnostic in flight.
735 /// \brief The maximum number of arguments we can hold.
737 /// We currently only support up to 10 arguments (%0-%9). A single
738 /// diagnostic with more than that almost certainly has to be simplified
743 /// \brief The number of entries in Arguments.
744 signed char NumDiagArgs;
746 /// \brief Specifies whether an argument is in DiagArgumentsStr or
747 /// in DiagArguments.
749 /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
751 unsigned char DiagArgumentsKind[MaxArguments];
753 /// \brief Holds the values of each string argument for the current
756 /// This is only used when the corresponding ArgumentKind is ak_std_string.
757 std::string DiagArgumentsStr[MaxArguments];
759 /// \brief The values for the various substitution positions.
761 /// This is used when the argument is not an std::string. The specific
762 /// value is mangled into an intptr_t and the interpretation depends on
763 /// exactly what sort of argument kind it is.
764 intptr_t DiagArgumentsVal[MaxArguments];
766 /// \brief The list of ranges added to this diagnostic.
767 SmallVector<CharSourceRange, 8> DiagRanges;
769 /// \brief If valid, provides a hint with some code to insert, remove,
770 /// or modify at a particular position.
771 SmallVector<FixItHint, 8> DiagFixItHints;
773 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
774 bool isPragma = L.isValid();
775 DiagnosticMapping Mapping =
776 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
778 // If this is a pragma mapping, then set the diagnostic mapping flags so
779 // that we override command line options.
781 Mapping.setNoWarningAsError(true);
782 Mapping.setNoErrorAsFatal(true);
788 /// \brief Used to report a diagnostic that is finally fully formed.
790 /// \returns true if the diagnostic was emitted, false if it was suppressed.
792 return Diags->ProcessDiag(*this);
795 /// @name Diagnostic Emission
798 // Sema requires access to the following functions because the current design
799 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
800 // access us directly to ensure we minimize the emitted code for the common
801 // Sema::Diag() patterns.
804 /// \brief Emit the current diagnostic and clear the diagnostic state.
806 /// \param Force Emit the diagnostic regardless of suppression settings.
807 bool EmitCurrentDiagnostic(bool Force = false);
809 unsigned getCurrentDiagID() const { return CurDiagID; }
811 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
815 friend class ASTReader;
816 friend class ASTWriter;
819 /// \brief RAII class that determines when any errors have occurred
820 /// between the time the instance was created and the time it was
822 class DiagnosticErrorTrap {
823 DiagnosticsEngine &Diag;
825 unsigned NumUnrecoverableErrors;
828 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
829 : Diag(Diag) { reset(); }
831 /// \brief Determine whether any errors have occurred since this
832 /// object instance was created.
833 bool hasErrorOccurred() const {
834 return Diag.TrapNumErrorsOccurred > NumErrors;
837 /// \brief Determine whether any unrecoverable errors have occurred since this
838 /// object instance was created.
839 bool hasUnrecoverableErrorOccurred() const {
840 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
843 /// \brief Set to initial state of "no errors occurred".
845 NumErrors = Diag.TrapNumErrorsOccurred;
846 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
850 //===----------------------------------------------------------------------===//
852 //===----------------------------------------------------------------------===//
854 /// \brief A little helper class used to produce diagnostics.
856 /// This is constructed by the DiagnosticsEngine::Report method, and
857 /// allows insertion of extra information (arguments and source ranges) into
858 /// the currently "in flight" diagnostic. When the temporary for the builder
859 /// is destroyed, the diagnostic is issued.
861 /// Note that many of these will be created as temporary objects (many call
862 /// sites), so we want them to be small and we never want their address taken.
863 /// This ensures that compilers with somewhat reasonable optimizers will promote
864 /// the common fields to registers, eliminating increments of the NumArgs field,
866 class DiagnosticBuilder {
867 mutable DiagnosticsEngine *DiagObj;
868 mutable unsigned NumArgs;
870 /// \brief Status variable indicating if this diagnostic is still active.
872 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
873 // but LLVM is not currently smart enough to eliminate the null check that
874 // Emit() would end up with if we used that as our status variable.
875 mutable bool IsActive;
877 /// \brief Flag indicating that this diagnostic is being emitted via a
878 /// call to ForceEmit.
879 mutable bool IsForceEmit;
881 void operator=(const DiagnosticBuilder &) = delete;
882 friend class DiagnosticsEngine;
885 : DiagObj(nullptr), NumArgs(0), IsActive(false), IsForceEmit(false) {}
887 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
888 : DiagObj(diagObj), NumArgs(0), IsActive(true), IsForceEmit(false) {
889 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
890 diagObj->DiagRanges.clear();
891 diagObj->DiagFixItHints.clear();
894 friend class PartialDiagnostic;
898 DiagObj->NumDiagArgs = NumArgs;
901 /// \brief Clear out the current diagnostic.
908 /// \brief Determine whether this diagnostic is still active.
909 bool isActive() const { return IsActive; }
911 /// \brief Force the diagnostic builder to emit the diagnostic now.
913 /// Once this function has been called, the DiagnosticBuilder object
914 /// should not be used again before it is destroyed.
916 /// \returns true if a diagnostic was emitted, false if the
917 /// diagnostic was suppressed.
919 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
920 // (or by a subclass, as in SemaDiagnosticBuilder).
921 if (!isActive()) return false;
923 // When emitting diagnostics, we set the final argument count into
924 // the DiagnosticsEngine object.
927 // Process the diagnostic.
928 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
930 // This diagnostic is dead.
937 /// Copy constructor. When copied, this "takes" the diagnostic info from the
938 /// input and neuters it.
939 DiagnosticBuilder(const DiagnosticBuilder &D) {
941 IsActive = D.IsActive;
942 IsForceEmit = D.IsForceEmit;
947 /// \brief Retrieve an empty diagnostic builder.
948 static DiagnosticBuilder getEmpty() {
949 return DiagnosticBuilder();
952 /// \brief Emits the diagnostic.
953 ~DiagnosticBuilder() {
957 /// \brief Forces the diagnostic to be emitted.
958 const DiagnosticBuilder &setForceEmit() const {
963 /// \brief Conversion of DiagnosticBuilder to bool always returns \c true.
965 /// This allows is to be used in boolean error contexts (where \c true is
966 /// used to indicate that an error has occurred), like:
968 /// return Diag(...);
970 operator bool() const { return true; }
972 void AddString(StringRef S) const {
973 assert(isActive() && "Clients must not add to cleared diagnostic!");
974 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
975 "Too many arguments to diagnostic!");
976 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
977 DiagObj->DiagArgumentsStr[NumArgs++] = S;
980 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
981 assert(isActive() && "Clients must not add to cleared diagnostic!");
982 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
983 "Too many arguments to diagnostic!");
984 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
985 DiagObj->DiagArgumentsVal[NumArgs++] = V;
988 void AddSourceRange(const CharSourceRange &R) const {
989 assert(isActive() && "Clients must not add to cleared diagnostic!");
990 DiagObj->DiagRanges.push_back(R);
993 void AddFixItHint(const FixItHint &Hint) const {
994 assert(isActive() && "Clients must not add to cleared diagnostic!");
996 DiagObj->DiagFixItHints.push_back(Hint);
999 void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
1002 struct AddFlagValue {
1003 explicit AddFlagValue(StringRef V) : Val(V) {}
1007 /// \brief Register a value for the flag in the current diagnostic. This
1008 /// value will be shown as the suffix "=value" after the flag name. It is
1009 /// useful in cases where the diagnostic flag accepts values (e.g.,
1010 /// -Rpass or -Wframe-larger-than).
1011 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1012 const AddFlagValue V) {
1013 DB.addFlagValue(V.Val);
1017 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1023 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1025 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1026 DiagnosticsEngine::ak_c_string);
1030 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
1031 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1035 // We use enable_if here to prevent that this overload is selected for
1036 // pointers or other arguments that are implicitly convertible to bool.
1037 template <typename T>
1039 typename std::enable_if<std::is_same<T, bool>::value,
1040 const DiagnosticBuilder &>::type
1041 operator<<(const DiagnosticBuilder &DB, T I) {
1042 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1046 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1048 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1052 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1054 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1058 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1059 const IdentifierInfo *II) {
1060 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1061 DiagnosticsEngine::ak_identifierinfo);
1065 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
1066 // so that we only match those arguments that are (statically) DeclContexts;
1067 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
1069 template<typename T>
1071 typename std::enable_if<std::is_same<T, DeclContext>::value,
1072 const DiagnosticBuilder &>::type
1073 operator<<(const DiagnosticBuilder &DB, T *DC) {
1074 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1075 DiagnosticsEngine::ak_declcontext);
1079 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1080 const SourceRange &R) {
1081 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1085 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1086 ArrayRef<SourceRange> Ranges) {
1087 for (const SourceRange &R: Ranges)
1088 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1092 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1093 const CharSourceRange &R) {
1094 DB.AddSourceRange(R);
1098 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1099 const FixItHint &Hint) {
1100 DB.AddFixItHint(Hint);
1104 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1105 ArrayRef<FixItHint> Hints) {
1106 for (const FixItHint &Hint : Hints)
1107 DB.AddFixItHint(Hint);
1111 /// A nullability kind paired with a bit indicating whether it used a
1112 /// context-sensitive keyword.
1113 typedef std::pair<NullabilityKind, bool> DiagNullabilityKind;
1115 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1116 DiagNullabilityKind nullability);
1118 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1120 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
1124 return DiagnosticBuilder(this);
1127 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1128 return Report(SourceLocation(), DiagID);
1131 //===----------------------------------------------------------------------===//
1133 //===----------------------------------------------------------------------===//
1135 /// A little helper class (which is basically a smart pointer that forwards
1136 /// info from DiagnosticsEngine) that allows clients to enquire about the
1137 /// currently in-flight diagnostic.
1139 const DiagnosticsEngine *DiagObj;
1140 StringRef StoredDiagMessage;
1142 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1143 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1144 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1146 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1147 unsigned getID() const { return DiagObj->CurDiagID; }
1148 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1149 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1150 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1152 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1154 /// \brief Return the kind of the specified index.
1156 /// Based on the kind of argument, the accessors below can be used to get
1159 /// \pre Idx < getNumArgs()
1160 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1161 assert(Idx < getNumArgs() && "Argument index out of range!");
1162 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1165 /// \brief Return the provided argument string specified by \p Idx.
1166 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1167 const std::string &getArgStdStr(unsigned Idx) const {
1168 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1169 "invalid argument accessor!");
1170 return DiagObj->DiagArgumentsStr[Idx];
1173 /// \brief Return the specified C string argument.
1174 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1175 const char *getArgCStr(unsigned Idx) const {
1176 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1177 "invalid argument accessor!");
1178 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1181 /// \brief Return the specified signed integer argument.
1182 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1183 int getArgSInt(unsigned Idx) const {
1184 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1185 "invalid argument accessor!");
1186 return (int)DiagObj->DiagArgumentsVal[Idx];
1189 /// \brief Return the specified unsigned integer argument.
1190 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1191 unsigned getArgUInt(unsigned Idx) const {
1192 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1193 "invalid argument accessor!");
1194 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1197 /// \brief Return the specified IdentifierInfo argument.
1198 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1199 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1200 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1201 "invalid argument accessor!");
1202 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1205 /// \brief Return the specified non-string argument in an opaque form.
1206 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1207 intptr_t getRawArg(unsigned Idx) const {
1208 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1209 "invalid argument accessor!");
1210 return DiagObj->DiagArgumentsVal[Idx];
1213 /// \brief Return the number of source ranges associated with this diagnostic.
1214 unsigned getNumRanges() const {
1215 return DiagObj->DiagRanges.size();
1218 /// \pre Idx < getNumRanges()
1219 const CharSourceRange &getRange(unsigned Idx) const {
1220 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1221 return DiagObj->DiagRanges[Idx];
1224 /// \brief Return an array reference for this diagnostic's ranges.
1225 ArrayRef<CharSourceRange> getRanges() const {
1226 return DiagObj->DiagRanges;
1229 unsigned getNumFixItHints() const {
1230 return DiagObj->DiagFixItHints.size();
1233 const FixItHint &getFixItHint(unsigned Idx) const {
1234 assert(Idx < getNumFixItHints() && "Invalid index!");
1235 return DiagObj->DiagFixItHints[Idx];
1238 ArrayRef<FixItHint> getFixItHints() const {
1239 return DiagObj->DiagFixItHints;
1242 /// \brief Format this diagnostic into a string, substituting the
1243 /// formal arguments into the %0 slots.
1245 /// The result is appended onto the \p OutStr array.
1246 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1248 /// \brief Format the given format-string into the output buffer using the
1249 /// arguments stored in this diagnostic.
1250 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1251 SmallVectorImpl<char> &OutStr) const;
1255 * \brief Represents a diagnostic in a form that can be retained until its
1256 * corresponding source manager is destroyed.
1258 class StoredDiagnostic {
1260 DiagnosticsEngine::Level Level;
1262 std::string Message;
1263 std::vector<CharSourceRange> Ranges;
1264 std::vector<FixItHint> FixIts;
1268 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1269 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1271 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1272 StringRef Message, FullSourceLoc Loc,
1273 ArrayRef<CharSourceRange> Ranges,
1274 ArrayRef<FixItHint> Fixits);
1275 ~StoredDiagnostic();
1277 /// \brief Evaluates true when this object stores a diagnostic.
1278 explicit operator bool() const { return Message.size() > 0; }
1280 unsigned getID() const { return ID; }
1281 DiagnosticsEngine::Level getLevel() const { return Level; }
1282 const FullSourceLoc &getLocation() const { return Loc; }
1283 StringRef getMessage() const { return Message; }
1285 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1287 typedef std::vector<CharSourceRange>::const_iterator range_iterator;
1288 range_iterator range_begin() const { return Ranges.begin(); }
1289 range_iterator range_end() const { return Ranges.end(); }
1290 unsigned range_size() const { return Ranges.size(); }
1292 ArrayRef<CharSourceRange> getRanges() const {
1293 return llvm::makeArrayRef(Ranges);
1297 typedef std::vector<FixItHint>::const_iterator fixit_iterator;
1298 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1299 fixit_iterator fixit_end() const { return FixIts.end(); }
1300 unsigned fixit_size() const { return FixIts.size(); }
1302 ArrayRef<FixItHint> getFixIts() const {
1303 return llvm::makeArrayRef(FixIts);
1307 /// \brief Abstract interface, implemented by clients of the front-end, which
1308 /// formats and prints fully processed diagnostics.
1309 class DiagnosticConsumer {
1311 unsigned NumWarnings; ///< Number of warnings reported
1312 unsigned NumErrors; ///< Number of errors reported
1315 DiagnosticConsumer() : NumWarnings(0), NumErrors(0) { }
1317 unsigned getNumErrors() const { return NumErrors; }
1318 unsigned getNumWarnings() const { return NumWarnings; }
1319 virtual void clear() { NumWarnings = NumErrors = 0; }
1321 virtual ~DiagnosticConsumer();
1323 /// \brief Callback to inform the diagnostic client that processing
1324 /// of a source file is beginning.
1326 /// Note that diagnostics may be emitted outside the processing of a source
1327 /// file, for example during the parsing of command line options. However,
1328 /// diagnostics with source range information are required to only be emitted
1329 /// in between BeginSourceFile() and EndSourceFile().
1331 /// \param LangOpts The language options for the source file being processed.
1332 /// \param PP The preprocessor object being used for the source; this is
1333 /// optional, e.g., it may not be present when processing AST source files.
1334 virtual void BeginSourceFile(const LangOptions &LangOpts,
1335 const Preprocessor *PP = nullptr) {}
1337 /// \brief Callback to inform the diagnostic client that processing
1338 /// of a source file has ended.
1340 /// The diagnostic client should assume that any objects made available via
1341 /// BeginSourceFile() are inaccessible.
1342 virtual void EndSourceFile() {}
1344 /// \brief Callback to inform the diagnostic client that processing of all
1345 /// source files has ended.
1346 virtual void finish() {}
1348 /// \brief Indicates whether the diagnostics handled by this
1349 /// DiagnosticConsumer should be included in the number of diagnostics
1350 /// reported by DiagnosticsEngine.
1352 /// The default implementation returns true.
1353 virtual bool IncludeInDiagnosticCounts() const;
1355 /// \brief Handle this diagnostic, reporting it to the user or
1356 /// capturing it to a log as needed.
1358 /// The default implementation just keeps track of the total number of
1359 /// warnings and errors.
1360 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1361 const Diagnostic &Info);
1364 /// \brief A diagnostic client that ignores all diagnostics.
1365 class IgnoringDiagConsumer : public DiagnosticConsumer {
1366 virtual void anchor();
1367 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1368 const Diagnostic &Info) override {
1373 /// \brief Diagnostic consumer that forwards diagnostics along to an
1374 /// existing, already-initialized diagnostic consumer.
1376 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1377 DiagnosticConsumer &Target;
1380 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1382 ~ForwardingDiagnosticConsumer() override;
1384 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1385 const Diagnostic &Info) override;
1386 void clear() override;
1388 bool IncludeInDiagnosticCounts() const override;
1391 // Struct used for sending info about how a type should be printed.
1392 struct TemplateDiffTypes {
1395 unsigned PrintTree : 1;
1396 unsigned PrintFromType : 1;
1397 unsigned ElideType : 1;
1398 unsigned ShowColors : 1;
1399 // The printer sets this variable to true if the template diff was used.
1400 unsigned TemplateDiffUsed : 1;
1403 /// Special character that the diagnostic printer will use to toggle the bold
1404 /// attribute. The character itself will be not be printed.
1405 const char ToggleHighlight = 127;
1408 /// ProcessWarningOptions - Initialize the diagnostic client and process the
1409 /// warning options specified on the command line.
1410 void ProcessWarningOptions(DiagnosticsEngine &Diags,
1411 const DiagnosticOptions &Opts,
1412 bool ReportDiags = true);
1414 } // end namespace clang