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 FatalsAsError; // Treat fatal errors like errors.
177 bool SuppressSystemWarnings; // Suppress warnings in system headers.
178 bool SuppressAllDiagnostics; // Suppress all diagnostics.
179 bool ElideType; // Elide common types of templates.
180 bool PrintTemplateTree; // Print a tree when comparing templates.
181 bool ShowColors; // Color printing is enabled.
182 OverloadsShown ShowOverloads; // Which overload candidates to show.
183 unsigned ErrorLimit; // Cap of # errors emitted, 0 -> no limit.
184 unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
186 unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation
187 // backtrace stack, 0 -> no limit.
188 diag::Severity ExtBehavior; // Map extensions to warnings or errors?
189 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
190 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
191 DiagnosticConsumer *Client;
192 std::unique_ptr<DiagnosticConsumer> Owner;
193 SourceManager *SourceMgr;
195 /// \brief Mapping information for diagnostics.
197 /// Mapping info is packed into four bits per diagnostic. The low three
198 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
199 /// The high bit is set when the mapping was established as a user mapping.
200 /// If the high bit is clear, then the low bits are set to the default
201 /// value, and should be mapped with -pedantic, -Werror, etc.
203 /// A new DiagState is created and kept around when diagnostic pragmas modify
204 /// the state so that we know what is the diagnostic state at any given
207 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
210 typedef llvm::DenseMap<unsigned, DiagnosticMapping>::iterator iterator;
211 typedef llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator
214 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
215 DiagMap[Diag] = Info;
218 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
220 const_iterator begin() const { return DiagMap.begin(); }
221 const_iterator end() const { return DiagMap.end(); }
224 /// \brief Keeps and automatically disposes all DiagStates that we create.
225 std::list<DiagState> DiagStates;
227 /// \brief Represents a point in source where the diagnostic state was
228 /// modified because of a pragma.
230 /// 'Loc' can be null if the point represents the diagnostic state
231 /// modifications done through the command-line.
232 struct DiagStatePoint {
235 DiagStatePoint(DiagState *State, FullSourceLoc Loc)
236 : State(State), Loc(Loc) { }
238 bool operator<(const DiagStatePoint &RHS) const {
239 // If Loc is invalid it means it came from <command-line>, in which case
240 // we regard it as coming before any valid source location.
241 if (RHS.Loc.isInvalid())
245 return Loc.isBeforeInTranslationUnitThan(RHS.Loc);
249 /// \brief A sorted vector of all DiagStatePoints representing changes in
250 /// diagnostic state due to diagnostic pragmas.
252 /// The vector is always sorted according to the SourceLocation of the
254 typedef std::vector<DiagStatePoint> DiagStatePointsTy;
255 mutable DiagStatePointsTy DiagStatePoints;
257 /// \brief Keeps the DiagState that was active during each diagnostic 'push'
258 /// so we can get back at it when we 'pop'.
259 std::vector<DiagState *> DiagStateOnPushStack;
261 DiagState *GetCurDiagState() const {
262 assert(!DiagStatePoints.empty());
263 return DiagStatePoints.back().State;
266 void PushDiagStatePoint(DiagState *State, SourceLocation L) {
267 FullSourceLoc Loc(L, getSourceManager());
268 // Make sure that DiagStatePoints is always sorted according to Loc.
269 assert(Loc.isValid() && "Adding invalid loc point");
270 assert(!DiagStatePoints.empty() &&
271 (DiagStatePoints.back().Loc.isInvalid() ||
272 DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) &&
273 "Previous point loc comes after or is the same as new one");
274 DiagStatePoints.push_back(DiagStatePoint(State, Loc));
277 /// \brief Finds the DiagStatePoint that contains the diagnostic state of
278 /// the given source location.
279 DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const;
281 /// \brief Sticky flag set to \c true when an error is emitted.
284 /// \brief Sticky flag set to \c true when an "uncompilable error" occurs.
285 /// I.e. an error that was not upgraded from a warning by -Werror.
286 bool UncompilableErrorOccurred;
288 /// \brief Sticky flag set to \c true when a fatal error is emitted.
289 bool FatalErrorOccurred;
291 /// \brief Indicates that an unrecoverable error has occurred.
292 bool UnrecoverableErrorOccurred;
294 /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred
295 /// during a parsing section, e.g. during parsing a function.
296 unsigned TrapNumErrorsOccurred;
297 unsigned TrapNumUnrecoverableErrorsOccurred;
299 /// \brief The level of the last diagnostic emitted.
301 /// This is used to emit continuation diagnostics with the same level as the
302 /// diagnostic that they follow.
303 DiagnosticIDs::Level LastDiagLevel;
305 unsigned NumWarnings; ///< Number of warnings reported
306 unsigned NumErrors; ///< Number of errors reported
308 /// \brief A function pointer that converts an opaque diagnostic
309 /// argument to a strings.
311 /// This takes the modifiers and argument that was present in the diagnostic.
313 /// The PrevArgs array indicates the previous arguments formatted for this
314 /// diagnostic. Implementations of this function can use this information to
315 /// avoid redundancy across arguments.
317 /// This is a hack to avoid a layering violation between libbasic and libsema.
318 typedef void (*ArgToStringFnTy)(
319 ArgumentKind Kind, intptr_t Val,
320 StringRef Modifier, StringRef Argument,
321 ArrayRef<ArgumentValue> PrevArgs,
322 SmallVectorImpl<char> &Output,
324 ArrayRef<intptr_t> QualTypeVals);
325 void *ArgToStringCookie;
326 ArgToStringFnTy ArgToStringFn;
328 /// \brief ID of the "delayed" diagnostic, which is a (typically
329 /// fatal) diagnostic that had to be delayed because it was found
330 /// while emitting another diagnostic.
331 unsigned DelayedDiagID;
333 /// \brief First string argument for the delayed diagnostic.
334 std::string DelayedDiagArg1;
336 /// \brief Second string argument for the delayed diagnostic.
337 std::string DelayedDiagArg2;
339 /// \brief Optional flag value.
341 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
342 /// -Rpass=<value>. The content of this string is emitted after the flag name
344 std::string FlagValue;
347 explicit DiagnosticsEngine(
348 const IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
349 DiagnosticOptions *DiagOpts,
350 DiagnosticConsumer *client = nullptr,
351 bool ShouldOwnClient = true);
352 ~DiagnosticsEngine();
354 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
358 /// \brief Retrieve the diagnostic options.
359 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
361 typedef llvm::iterator_range<DiagState::const_iterator> diag_mapping_range;
363 /// \brief Get the current set of diagnostic mappings.
364 diag_mapping_range getDiagnosticMappings() const {
365 const DiagState &DS = *GetCurDiagState();
366 return diag_mapping_range(DS.begin(), DS.end());
369 DiagnosticConsumer *getClient() { return Client; }
370 const DiagnosticConsumer *getClient() const { return Client; }
372 /// \brief Determine whether this \c DiagnosticsEngine object own its client.
373 bool ownsClient() const { return Owner != nullptr; }
375 /// \brief Return the current diagnostic client along with ownership of that
377 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
379 bool hasSourceManager() const { return SourceMgr != nullptr; }
380 SourceManager &getSourceManager() const {
381 assert(SourceMgr && "SourceManager not set!");
384 void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
386 //===--------------------------------------------------------------------===//
387 // DiagnosticsEngine characterization methods, used by a client to customize
388 // how diagnostics are emitted.
391 /// \brief Copies the current DiagMappings and pushes the new copy
392 /// onto the top of the stack.
393 void pushMappings(SourceLocation Loc);
395 /// \brief Pops the current DiagMappings off the top of the stack,
396 /// causing the new top of the stack to be the active mappings.
398 /// \returns \c true if the pop happens, \c false if there is only one
399 /// DiagMapping on the stack.
400 bool popMappings(SourceLocation Loc);
402 /// \brief Set the diagnostic client associated with this diagnostic object.
404 /// \param ShouldOwnClient true if the diagnostic object should take
405 /// ownership of \c client.
406 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
408 /// \brief Specify a limit for the number of errors we should
409 /// emit before giving up.
411 /// Zero disables the limit.
412 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
414 /// \brief Specify the maximum number of template instantiation
415 /// notes to emit along with a given diagnostic.
416 void setTemplateBacktraceLimit(unsigned Limit) {
417 TemplateBacktraceLimit = Limit;
420 /// \brief Retrieve the maximum number of template instantiation
421 /// notes to emit along with a given diagnostic.
422 unsigned getTemplateBacktraceLimit() const {
423 return TemplateBacktraceLimit;
426 /// \brief Specify the maximum number of constexpr evaluation
427 /// notes to emit along with a given diagnostic.
428 void setConstexprBacktraceLimit(unsigned Limit) {
429 ConstexprBacktraceLimit = Limit;
432 /// \brief Retrieve the maximum number of constexpr evaluation
433 /// notes to emit along with a given diagnostic.
434 unsigned getConstexprBacktraceLimit() const {
435 return ConstexprBacktraceLimit;
438 /// \brief When set to true, any unmapped warnings are ignored.
440 /// If this and WarningsAsErrors are both set, then this one wins.
441 void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
442 bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
444 /// \brief When set to true, any unmapped ignored warnings are no longer
447 /// If this and IgnoreAllWarnings are both set, then that one wins.
448 void setEnableAllWarnings(bool Val) { EnableAllWarnings = Val; }
449 bool getEnableAllWarnings() const { return EnableAllWarnings; }
451 /// \brief When set to true, any warnings reported are issued as errors.
452 void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
453 bool getWarningsAsErrors() const { return WarningsAsErrors; }
455 /// \brief When set to true, any error reported is made a fatal error.
456 void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
457 bool getErrorsAsFatal() const { return ErrorsAsFatal; }
459 /// \brief When set to true, any fatal error reported is made an error.
461 /// This setting takes precedence over the setErrorsAsFatal setting above.
462 void setFatalsAsError(bool Val) { FatalsAsError = Val; }
463 bool getFatalsAsError() const { return FatalsAsError; }
465 /// \brief When set to true mask warnings that come from system headers.
466 void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
467 bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
469 /// \brief Suppress all diagnostics, to silence the front end when we
470 /// know that we don't want any more diagnostics to be passed along to the
472 void setSuppressAllDiagnostics(bool Val = true) {
473 SuppressAllDiagnostics = Val;
475 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
477 /// \brief Set type eliding, to skip outputting same types occurring in
479 void setElideType(bool Val = true) { ElideType = Val; }
480 bool getElideType() { return ElideType; }
482 /// \brief Set tree printing, to outputting the template difference in a
484 void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
485 bool getPrintTemplateTree() { return PrintTemplateTree; }
487 /// \brief Set color printing, so the type diffing will inject color markers
489 void setShowColors(bool Val = false) { ShowColors = Val; }
490 bool getShowColors() { return ShowColors; }
492 /// \brief Specify which overload candidates to show when overload resolution
495 /// By default, we show all candidates.
496 void setShowOverloads(OverloadsShown Val) {
499 OverloadsShown getShowOverloads() const { return ShowOverloads; }
501 /// \brief Pretend that the last diagnostic issued was ignored, so any
502 /// subsequent notes will be suppressed.
504 /// This can be used by clients who suppress diagnostics themselves.
505 void setLastDiagnosticIgnored() {
506 if (LastDiagLevel == DiagnosticIDs::Fatal)
507 FatalErrorOccurred = true;
508 LastDiagLevel = DiagnosticIDs::Ignored;
511 /// \brief Determine whether the previous diagnostic was ignored. This can
512 /// be used by clients that want to determine whether notes attached to a
513 /// diagnostic will be suppressed.
514 bool isLastDiagnosticIgnored() const {
515 return LastDiagLevel == DiagnosticIDs::Ignored;
518 /// \brief Controls whether otherwise-unmapped extension diagnostics are
519 /// mapped onto ignore/warning/error.
521 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
522 void setExtensionHandlingBehavior(diag::Severity H) { ExtBehavior = H; }
523 diag::Severity getExtensionHandlingBehavior() const { return ExtBehavior; }
525 /// \brief Counter bumped when an __extension__ block is/ encountered.
527 /// When non-zero, all extension diagnostics are entirely silenced, no
528 /// matter how they are mapped.
529 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
530 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
531 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
533 /// \brief This allows the client to specify that certain warnings are
536 /// Notes can never be mapped, errors can only be mapped to fatal, and
537 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
539 /// \param Loc The source location that this change of diagnostic state should
540 /// take affect. It can be null if we are setting the latest state.
541 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
543 /// \brief Change an entire diagnostic group (e.g. "unknown-pragmas") to
544 /// have the specified mapping.
546 /// \returns true (and ignores the request) if "Group" was unknown, false
549 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
550 /// state of the -Wfoo group and vice versa.
552 /// \param Loc The source location that this change of diagnostic state should
553 /// take affect. It can be null if we are setting the state from command-line.
554 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
556 SourceLocation Loc = SourceLocation());
558 /// \brief Set the warning-as-error 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 setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
565 /// \brief Set the error-as-fatal flag for the given diagnostic group.
567 /// This function always only operates on the current diagnostic state.
569 /// \returns True if the given group is unknown, false otherwise.
570 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
572 /// \brief Add the specified mapping to all diagnostics of the specified
575 /// Mainly to be used by -Wno-everything to disable all warnings but allow
576 /// subsequent -W options to enable specific warnings.
577 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
578 SourceLocation Loc = SourceLocation());
580 bool hasErrorOccurred() const { return ErrorOccurred; }
582 /// \brief Errors that actually prevent compilation, not those that are
583 /// upgraded from a warning by -Werror.
584 bool hasUncompilableErrorOccurred() const {
585 return UncompilableErrorOccurred;
587 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
589 /// \brief Determine whether any kind of unrecoverable error has occurred.
590 bool hasUnrecoverableErrorOccurred() const {
591 return FatalErrorOccurred || UnrecoverableErrorOccurred;
594 unsigned getNumWarnings() const { return NumWarnings; }
596 void setNumWarnings(unsigned NumWarnings) {
597 this->NumWarnings = NumWarnings;
600 /// \brief Return an ID for a diagnostic with the specified format string and
603 /// If this is the first request for this diagnostic, it is registered and
604 /// created, otherwise the existing ID is returned.
606 /// \param FormatString A fixed diagnostic format string that will be hashed
607 /// and mapped to a unique DiagID.
608 template <unsigned N>
609 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
610 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
611 StringRef(FormatString, N - 1));
614 /// \brief Converts a diagnostic argument (as an intptr_t) into the string
615 /// that represents it.
616 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
617 StringRef Modifier, StringRef Argument,
618 ArrayRef<ArgumentValue> PrevArgs,
619 SmallVectorImpl<char> &Output,
620 ArrayRef<intptr_t> QualTypeVals) const {
621 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
622 ArgToStringCookie, QualTypeVals);
625 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
627 ArgToStringCookie = Cookie;
630 /// \brief Note that the prior diagnostic was emitted by some other
631 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
632 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
633 LastDiagLevel = Other.LastDiagLevel;
636 /// \brief Reset the state of the diagnostic object to its initial
640 //===--------------------------------------------------------------------===//
641 // DiagnosticsEngine classification and reporting interfaces.
644 /// \brief Determine whether the diagnostic is known to be ignored.
646 /// This can be used to opportunistically avoid expensive checks when it's
647 /// known for certain that the diagnostic has been suppressed at the
648 /// specified location \p Loc.
650 /// \param Loc The source location we are interested in finding out the
651 /// diagnostic state. Can be null in order to query the latest state.
652 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
653 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
654 diag::Severity::Ignored;
657 /// \brief Based on the way the client configured the DiagnosticsEngine
658 /// object, classify the specified diagnostic ID into a Level, consumable by
659 /// the DiagnosticConsumer.
661 /// To preserve invariant assumptions, this function should not be used to
662 /// influence parse or semantic analysis actions. Instead consider using
665 /// \param Loc The source location we are interested in finding out the
666 /// diagnostic state. Can be null in order to query the latest state.
667 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
668 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
671 /// \brief Issue the message to the client.
673 /// This actually returns an instance of DiagnosticBuilder which emits the
674 /// diagnostics (through @c ProcessDiag) when it is destroyed.
676 /// \param DiagID A member of the @c diag::kind enum.
677 /// \param Loc Represents the source location associated with the diagnostic,
678 /// which can be an invalid location if no position information is available.
679 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
680 inline DiagnosticBuilder Report(unsigned DiagID);
682 void Report(const StoredDiagnostic &storedDiag);
684 /// \brief Determine whethere there is already a diagnostic in flight.
685 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
687 /// \brief Set the "delayed" diagnostic that will be emitted once
688 /// the current diagnostic completes.
690 /// If a diagnostic is already in-flight but the front end must
691 /// report a problem (e.g., with an inconsistent file system
692 /// state), this routine sets a "delayed" diagnostic that will be
693 /// emitted after the current diagnostic completes. This should
694 /// only be used for fatal errors detected at inconvenient
695 /// times. If emitting a delayed diagnostic causes a second delayed
696 /// diagnostic to be introduced, that second delayed diagnostic
699 /// \param DiagID The ID of the diagnostic being delayed.
701 /// \param Arg1 A string argument that will be provided to the
702 /// diagnostic. A copy of this string will be stored in the
703 /// DiagnosticsEngine object itself.
705 /// \param Arg2 A string argument that will be provided to the
706 /// diagnostic. A copy of this string will be stored in the
707 /// DiagnosticsEngine object itself.
708 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
709 StringRef Arg2 = "");
711 /// \brief Clear out the current diagnostic.
712 void Clear() { CurDiagID = ~0U; }
714 /// \brief Return the value associated with this diagnostic flag.
715 StringRef getFlagValue() const { return FlagValue; }
718 /// \brief Report the delayed diagnostic.
719 void ReportDelayed();
721 // This is private state used by DiagnosticBuilder. We put it here instead of
722 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
723 // object. This implementation choice means that we can only have one
724 // diagnostic "in flight" at a time, but this seems to be a reasonable
725 // tradeoff to keep these objects small. Assertions verify that only one
726 // diagnostic is in flight at a time.
727 friend class DiagnosticIDs;
728 friend class DiagnosticBuilder;
729 friend class Diagnostic;
730 friend class PartialDiagnostic;
731 friend class DiagnosticErrorTrap;
733 /// \brief The location of the current diagnostic that is in flight.
734 SourceLocation CurDiagLoc;
736 /// \brief The ID of the current diagnostic that is in flight.
738 /// This is set to ~0U when there is no diagnostic in flight.
742 /// \brief The maximum number of arguments we can hold.
744 /// We currently only support up to 10 arguments (%0-%9). A single
745 /// diagnostic with more than that almost certainly has to be simplified
750 /// \brief The number of entries in Arguments.
751 signed char NumDiagArgs;
753 /// \brief Specifies whether an argument is in DiagArgumentsStr or
754 /// in DiagArguments.
756 /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
758 unsigned char DiagArgumentsKind[MaxArguments];
760 /// \brief Holds the values of each string argument for the current
763 /// This is only used when the corresponding ArgumentKind is ak_std_string.
764 std::string DiagArgumentsStr[MaxArguments];
766 /// \brief The values for the various substitution positions.
768 /// This is used when the argument is not an std::string. The specific
769 /// value is mangled into an intptr_t and the interpretation depends on
770 /// exactly what sort of argument kind it is.
771 intptr_t DiagArgumentsVal[MaxArguments];
773 /// \brief The list of ranges added to this diagnostic.
774 SmallVector<CharSourceRange, 8> DiagRanges;
776 /// \brief If valid, provides a hint with some code to insert, remove,
777 /// or modify at a particular position.
778 SmallVector<FixItHint, 8> DiagFixItHints;
780 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
781 bool isPragma = L.isValid();
782 DiagnosticMapping Mapping =
783 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
785 // If this is a pragma mapping, then set the diagnostic mapping flags so
786 // that we override command line options.
788 Mapping.setNoWarningAsError(true);
789 Mapping.setNoErrorAsFatal(true);
795 /// \brief Used to report a diagnostic that is finally fully formed.
797 /// \returns true if the diagnostic was emitted, false if it was suppressed.
799 return Diags->ProcessDiag(*this);
802 /// @name Diagnostic Emission
805 // Sema requires access to the following functions because the current design
806 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
807 // access us directly to ensure we minimize the emitted code for the common
808 // Sema::Diag() patterns.
811 /// \brief Emit the current diagnostic and clear the diagnostic state.
813 /// \param Force Emit the diagnostic regardless of suppression settings.
814 bool EmitCurrentDiagnostic(bool Force = false);
816 unsigned getCurrentDiagID() const { return CurDiagID; }
818 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
822 friend class ASTReader;
823 friend class ASTWriter;
826 /// \brief RAII class that determines when any errors have occurred
827 /// between the time the instance was created and the time it was
829 class DiagnosticErrorTrap {
830 DiagnosticsEngine &Diag;
832 unsigned NumUnrecoverableErrors;
835 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
836 : Diag(Diag) { reset(); }
838 /// \brief Determine whether any errors have occurred since this
839 /// object instance was created.
840 bool hasErrorOccurred() const {
841 return Diag.TrapNumErrorsOccurred > NumErrors;
844 /// \brief Determine whether any unrecoverable errors have occurred since this
845 /// object instance was created.
846 bool hasUnrecoverableErrorOccurred() const {
847 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
850 /// \brief Set to initial state of "no errors occurred".
852 NumErrors = Diag.TrapNumErrorsOccurred;
853 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
857 //===----------------------------------------------------------------------===//
859 //===----------------------------------------------------------------------===//
861 /// \brief A little helper class used to produce diagnostics.
863 /// This is constructed by the DiagnosticsEngine::Report method, and
864 /// allows insertion of extra information (arguments and source ranges) into
865 /// the currently "in flight" diagnostic. When the temporary for the builder
866 /// is destroyed, the diagnostic is issued.
868 /// Note that many of these will be created as temporary objects (many call
869 /// sites), so we want them to be small and we never want their address taken.
870 /// This ensures that compilers with somewhat reasonable optimizers will promote
871 /// the common fields to registers, eliminating increments of the NumArgs field,
873 class DiagnosticBuilder {
874 mutable DiagnosticsEngine *DiagObj = nullptr;
875 mutable unsigned NumArgs = 0;
877 /// \brief Status variable indicating if this diagnostic is still active.
879 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
880 // but LLVM is not currently smart enough to eliminate the null check that
881 // Emit() would end up with if we used that as our status variable.
882 mutable bool IsActive = false;
884 /// \brief Flag indicating that this diagnostic is being emitted via a
885 /// call to ForceEmit.
886 mutable bool IsForceEmit = false;
888 void operator=(const DiagnosticBuilder &) = delete;
889 friend class DiagnosticsEngine;
891 DiagnosticBuilder() = default;
893 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
894 : DiagObj(diagObj), IsActive(true) {
895 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
896 diagObj->DiagRanges.clear();
897 diagObj->DiagFixItHints.clear();
900 friend class PartialDiagnostic;
904 DiagObj->NumDiagArgs = NumArgs;
907 /// \brief Clear out the current diagnostic.
914 /// \brief Determine whether this diagnostic is still active.
915 bool isActive() const { return IsActive; }
917 /// \brief Force the diagnostic builder to emit the diagnostic now.
919 /// Once this function has been called, the DiagnosticBuilder object
920 /// should not be used again before it is destroyed.
922 /// \returns true if a diagnostic was emitted, false if the
923 /// diagnostic was suppressed.
925 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
926 // (or by a subclass, as in SemaDiagnosticBuilder).
927 if (!isActive()) return false;
929 // When emitting diagnostics, we set the final argument count into
930 // the DiagnosticsEngine object.
933 // Process the diagnostic.
934 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
936 // This diagnostic is dead.
943 /// Copy constructor. When copied, this "takes" the diagnostic info from the
944 /// input and neuters it.
945 DiagnosticBuilder(const DiagnosticBuilder &D) {
947 IsActive = D.IsActive;
948 IsForceEmit = D.IsForceEmit;
953 /// \brief Retrieve an empty diagnostic builder.
954 static DiagnosticBuilder getEmpty() {
955 return DiagnosticBuilder();
958 /// \brief Emits the diagnostic.
959 ~DiagnosticBuilder() {
963 /// \brief Forces the diagnostic to be emitted.
964 const DiagnosticBuilder &setForceEmit() const {
969 /// \brief Conversion of DiagnosticBuilder to bool always returns \c true.
971 /// This allows is to be used in boolean error contexts (where \c true is
972 /// used to indicate that an error has occurred), like:
974 /// return Diag(...);
976 operator bool() const { return true; }
978 void AddString(StringRef S) const {
979 assert(isActive() && "Clients must not add to cleared diagnostic!");
980 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
981 "Too many arguments to diagnostic!");
982 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
983 DiagObj->DiagArgumentsStr[NumArgs++] = S;
986 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
987 assert(isActive() && "Clients must not add to cleared diagnostic!");
988 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
989 "Too many arguments to diagnostic!");
990 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
991 DiagObj->DiagArgumentsVal[NumArgs++] = V;
994 void AddSourceRange(const CharSourceRange &R) const {
995 assert(isActive() && "Clients must not add to cleared diagnostic!");
996 DiagObj->DiagRanges.push_back(R);
999 void AddFixItHint(const FixItHint &Hint) const {
1000 assert(isActive() && "Clients must not add to cleared diagnostic!");
1002 DiagObj->DiagFixItHints.push_back(Hint);
1005 void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
1008 struct AddFlagValue {
1009 explicit AddFlagValue(StringRef V) : Val(V) {}
1013 /// \brief Register a value for the flag in the current diagnostic. This
1014 /// value will be shown as the suffix "=value" after the flag name. It is
1015 /// useful in cases where the diagnostic flag accepts values (e.g.,
1016 /// -Rpass or -Wframe-larger-than).
1017 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1018 const AddFlagValue V) {
1019 DB.addFlagValue(V.Val);
1023 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1029 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1031 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1032 DiagnosticsEngine::ak_c_string);
1036 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
1037 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1041 // We use enable_if here to prevent that this overload is selected for
1042 // pointers or other arguments that are implicitly convertible to bool.
1043 template <typename T>
1045 typename std::enable_if<std::is_same<T, bool>::value,
1046 const DiagnosticBuilder &>::type
1047 operator<<(const DiagnosticBuilder &DB, T I) {
1048 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1052 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1054 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1058 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1060 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1064 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1065 const IdentifierInfo *II) {
1066 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1067 DiagnosticsEngine::ak_identifierinfo);
1071 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
1072 // so that we only match those arguments that are (statically) DeclContexts;
1073 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
1075 template <typename T>
1076 inline typename std::enable_if<
1077 std::is_same<typename std::remove_const<T>::type, DeclContext>::value,
1078 const DiagnosticBuilder &>::type
1079 operator<<(const DiagnosticBuilder &DB, T *DC) {
1080 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1081 DiagnosticsEngine::ak_declcontext);
1085 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1087 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1091 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1092 ArrayRef<SourceRange> Ranges) {
1093 for (SourceRange R : Ranges)
1094 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1098 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1099 const CharSourceRange &R) {
1100 DB.AddSourceRange(R);
1104 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1105 const FixItHint &Hint) {
1106 DB.AddFixItHint(Hint);
1110 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1111 ArrayRef<FixItHint> Hints) {
1112 for (const FixItHint &Hint : Hints)
1113 DB.AddFixItHint(Hint);
1117 /// A nullability kind paired with a bit indicating whether it used a
1118 /// context-sensitive keyword.
1119 typedef std::pair<NullabilityKind, bool> DiagNullabilityKind;
1121 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1122 DiagNullabilityKind nullability);
1124 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1126 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
1130 return DiagnosticBuilder(this);
1133 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1134 return Report(SourceLocation(), DiagID);
1137 //===----------------------------------------------------------------------===//
1139 //===----------------------------------------------------------------------===//
1141 /// A little helper class (which is basically a smart pointer that forwards
1142 /// info from DiagnosticsEngine) that allows clients to enquire about the
1143 /// currently in-flight diagnostic.
1145 const DiagnosticsEngine *DiagObj;
1146 StringRef StoredDiagMessage;
1148 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1149 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1150 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1152 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1153 unsigned getID() const { return DiagObj->CurDiagID; }
1154 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1155 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1156 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1158 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1160 /// \brief Return the kind of the specified index.
1162 /// Based on the kind of argument, the accessors below can be used to get
1165 /// \pre Idx < getNumArgs()
1166 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1167 assert(Idx < getNumArgs() && "Argument index out of range!");
1168 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1171 /// \brief Return the provided argument string specified by \p Idx.
1172 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1173 const std::string &getArgStdStr(unsigned Idx) const {
1174 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1175 "invalid argument accessor!");
1176 return DiagObj->DiagArgumentsStr[Idx];
1179 /// \brief Return the specified C string argument.
1180 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1181 const char *getArgCStr(unsigned Idx) const {
1182 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1183 "invalid argument accessor!");
1184 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1187 /// \brief Return the specified signed integer argument.
1188 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1189 int getArgSInt(unsigned Idx) const {
1190 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1191 "invalid argument accessor!");
1192 return (int)DiagObj->DiagArgumentsVal[Idx];
1195 /// \brief Return the specified unsigned integer argument.
1196 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1197 unsigned getArgUInt(unsigned Idx) const {
1198 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1199 "invalid argument accessor!");
1200 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1203 /// \brief Return the specified IdentifierInfo argument.
1204 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1205 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1206 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1207 "invalid argument accessor!");
1208 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1211 /// \brief Return the specified non-string argument in an opaque form.
1212 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1213 intptr_t getRawArg(unsigned Idx) const {
1214 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1215 "invalid argument accessor!");
1216 return DiagObj->DiagArgumentsVal[Idx];
1219 /// \brief Return the number of source ranges associated with this diagnostic.
1220 unsigned getNumRanges() const {
1221 return DiagObj->DiagRanges.size();
1224 /// \pre Idx < getNumRanges()
1225 const CharSourceRange &getRange(unsigned Idx) const {
1226 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1227 return DiagObj->DiagRanges[Idx];
1230 /// \brief Return an array reference for this diagnostic's ranges.
1231 ArrayRef<CharSourceRange> getRanges() const {
1232 return DiagObj->DiagRanges;
1235 unsigned getNumFixItHints() const {
1236 return DiagObj->DiagFixItHints.size();
1239 const FixItHint &getFixItHint(unsigned Idx) const {
1240 assert(Idx < getNumFixItHints() && "Invalid index!");
1241 return DiagObj->DiagFixItHints[Idx];
1244 ArrayRef<FixItHint> getFixItHints() const {
1245 return DiagObj->DiagFixItHints;
1248 /// \brief Format this diagnostic into a string, substituting the
1249 /// formal arguments into the %0 slots.
1251 /// The result is appended onto the \p OutStr array.
1252 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1254 /// \brief Format the given format-string into the output buffer using the
1255 /// arguments stored in this diagnostic.
1256 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1257 SmallVectorImpl<char> &OutStr) const;
1261 * \brief Represents a diagnostic in a form that can be retained until its
1262 * corresponding source manager is destroyed.
1264 class StoredDiagnostic {
1266 DiagnosticsEngine::Level Level;
1268 std::string Message;
1269 std::vector<CharSourceRange> Ranges;
1270 std::vector<FixItHint> FixIts;
1273 StoredDiagnostic() = default;
1274 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1275 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1277 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1278 StringRef Message, FullSourceLoc Loc,
1279 ArrayRef<CharSourceRange> Ranges,
1280 ArrayRef<FixItHint> Fixits);
1282 /// \brief Evaluates true when this object stores a diagnostic.
1283 explicit operator bool() const { return Message.size() > 0; }
1285 unsigned getID() const { return ID; }
1286 DiagnosticsEngine::Level getLevel() const { return Level; }
1287 const FullSourceLoc &getLocation() const { return Loc; }
1288 StringRef getMessage() const { return Message; }
1290 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1292 typedef std::vector<CharSourceRange>::const_iterator range_iterator;
1293 range_iterator range_begin() const { return Ranges.begin(); }
1294 range_iterator range_end() const { return Ranges.end(); }
1295 unsigned range_size() const { return Ranges.size(); }
1297 ArrayRef<CharSourceRange> getRanges() const {
1298 return llvm::makeArrayRef(Ranges);
1302 typedef std::vector<FixItHint>::const_iterator fixit_iterator;
1303 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1304 fixit_iterator fixit_end() const { return FixIts.end(); }
1305 unsigned fixit_size() const { return FixIts.size(); }
1307 ArrayRef<FixItHint> getFixIts() const {
1308 return llvm::makeArrayRef(FixIts);
1312 /// \brief Abstract interface, implemented by clients of the front-end, which
1313 /// formats and prints fully processed diagnostics.
1314 class DiagnosticConsumer {
1316 unsigned NumWarnings; ///< Number of warnings reported
1317 unsigned NumErrors; ///< Number of errors reported
1320 DiagnosticConsumer() : NumWarnings(0), NumErrors(0) { }
1322 unsigned getNumErrors() const { return NumErrors; }
1323 unsigned getNumWarnings() const { return NumWarnings; }
1324 virtual void clear() { NumWarnings = NumErrors = 0; }
1326 virtual ~DiagnosticConsumer();
1328 /// \brief Callback to inform the diagnostic client that processing
1329 /// of a source file is beginning.
1331 /// Note that diagnostics may be emitted outside the processing of a source
1332 /// file, for example during the parsing of command line options. However,
1333 /// diagnostics with source range information are required to only be emitted
1334 /// in between BeginSourceFile() and EndSourceFile().
1336 /// \param LangOpts The language options for the source file being processed.
1337 /// \param PP The preprocessor object being used for the source; this is
1338 /// optional, e.g., it may not be present when processing AST source files.
1339 virtual void BeginSourceFile(const LangOptions &LangOpts,
1340 const Preprocessor *PP = nullptr) {}
1342 /// \brief Callback to inform the diagnostic client that processing
1343 /// of a source file has ended.
1345 /// The diagnostic client should assume that any objects made available via
1346 /// BeginSourceFile() are inaccessible.
1347 virtual void EndSourceFile() {}
1349 /// \brief Callback to inform the diagnostic client that processing of all
1350 /// source files has ended.
1351 virtual void finish() {}
1353 /// \brief Indicates whether the diagnostics handled by this
1354 /// DiagnosticConsumer should be included in the number of diagnostics
1355 /// reported by DiagnosticsEngine.
1357 /// The default implementation returns true.
1358 virtual bool IncludeInDiagnosticCounts() const;
1360 /// \brief Handle this diagnostic, reporting it to the user or
1361 /// capturing it to a log as needed.
1363 /// The default implementation just keeps track of the total number of
1364 /// warnings and errors.
1365 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1366 const Diagnostic &Info);
1369 /// \brief A diagnostic client that ignores all diagnostics.
1370 class IgnoringDiagConsumer : public DiagnosticConsumer {
1371 virtual void anchor();
1372 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1373 const Diagnostic &Info) override {
1378 /// \brief Diagnostic consumer that forwards diagnostics along to an
1379 /// existing, already-initialized diagnostic consumer.
1381 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1382 DiagnosticConsumer &Target;
1385 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1387 ~ForwardingDiagnosticConsumer() override;
1389 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1390 const Diagnostic &Info) override;
1391 void clear() override;
1393 bool IncludeInDiagnosticCounts() const override;
1396 // Struct used for sending info about how a type should be printed.
1397 struct TemplateDiffTypes {
1400 unsigned PrintTree : 1;
1401 unsigned PrintFromType : 1;
1402 unsigned ElideType : 1;
1403 unsigned ShowColors : 1;
1404 // The printer sets this variable to true if the template diff was used.
1405 unsigned TemplateDiffUsed : 1;
1408 /// Special character that the diagnostic printer will use to toggle the bold
1409 /// attribute. The character itself will be not be printed.
1410 const char ToggleHighlight = 127;
1413 /// ProcessWarningOptions - Initialize the diagnostic client and process the
1414 /// warning options specified on the command line.
1415 void ProcessWarningOptions(DiagnosticsEngine &Diags,
1416 const DiagnosticOptions &Opts,
1417 bool ReportDiags = true);
1419 } // end namespace clang