1 //===--- Diagnostic.h - C Language Family Diagnostic Handling ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Defines the Diagnostic-related interfaces.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
16 #define LLVM_CLANG_BASIC_DIAGNOSTIC_H
18 #include "clang/Basic/DiagnosticIDs.h"
19 #include "clang/Basic/DiagnosticOptions.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Basic/Specifiers.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/IntrusiveRefCntPtr.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
34 #include <type_traits>
41 class DiagnosticBuilder;
42 class DiagnosticConsumer;
46 class StoredDiagnostic;
50 enum TokenKind : unsigned short;
52 } // end namespace tok
54 /// \brief Annotates a diagnostic with some code that should be
55 /// inserted, removed, or replaced to fix the problem.
57 /// This kind of hint should be used when we are certain that the
58 /// introduction, removal, or modification of a particular (small!)
59 /// amount of code will correct a compilation error. The compiler
60 /// should also provide full recovery from such errors, such that
61 /// suppressing the diagnostic output can still result in successful
65 /// \brief Code that should be replaced to correct the error. Empty for an
67 CharSourceRange RemoveRange;
69 /// \brief Code in the specific range that should be inserted in the insertion
71 CharSourceRange InsertFromRange;
73 /// \brief The actual code to insert at the insertion location, as a
75 std::string CodeToInsert;
77 bool BeforePreviousInsertions;
79 /// \brief Empty code modification hint, indicating that no code
80 /// modification is known.
81 FixItHint() : BeforePreviousInsertions(false) { }
84 return !RemoveRange.isValid();
87 /// \brief Create a code modification hint that inserts the given
88 /// code string at a specific location.
89 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
91 bool BeforePreviousInsertions = false) {
94 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
95 Hint.CodeToInsert = Code;
96 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
100 /// \brief Create a code modification hint that inserts the given
101 /// code from \p FromRange at a specific location.
102 static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
103 CharSourceRange FromRange,
104 bool BeforePreviousInsertions = false) {
107 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
108 Hint.InsertFromRange = FromRange;
109 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
113 /// \brief Create a code modification hint that removes the given
115 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
117 Hint.RemoveRange = RemoveRange;
120 static FixItHint CreateRemoval(SourceRange RemoveRange) {
121 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
124 /// \brief Create a code modification hint that replaces the given
125 /// source range with the given code string.
126 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
129 Hint.RemoveRange = RemoveRange;
130 Hint.CodeToInsert = Code;
134 static FixItHint CreateReplacement(SourceRange RemoveRange,
136 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
140 /// \brief Concrete class used by the front-end to report problems and issues.
142 /// This massages the diagnostics (e.g. handling things like "report warnings
143 /// as errors" and passes them off to the DiagnosticConsumer for reporting to
144 /// the user. DiagnosticsEngine is tied to one translation unit and one
146 class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
148 /// \brief The level of the diagnostic, after it has been through mapping.
150 Ignored = DiagnosticIDs::Ignored,
151 Note = DiagnosticIDs::Note,
152 Remark = DiagnosticIDs::Remark,
153 Warning = DiagnosticIDs::Warning,
154 Error = DiagnosticIDs::Error,
155 Fatal = DiagnosticIDs::Fatal
159 ak_std_string, ///< std::string
160 ak_c_string, ///< const char *
162 ak_uint, ///< unsigned
163 ak_tokenkind, ///< enum TokenKind : unsigned
164 ak_identifierinfo, ///< IdentifierInfo
165 ak_qualtype, ///< QualType
166 ak_declarationname, ///< DeclarationName
167 ak_nameddecl, ///< NamedDecl *
168 ak_nestednamespec, ///< NestedNameSpecifier *
169 ak_declcontext, ///< DeclContext *
170 ak_qualtype_pair, ///< pair<QualType, QualType>
174 /// \brief Represents on argument value, which is a union discriminated
175 /// by ArgumentKind, with a value.
176 typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
179 unsigned char AllExtensionsSilenced; // Used by __extension__
180 bool IgnoreAllWarnings; // Ignore all warnings: -w
181 bool WarningsAsErrors; // Treat warnings like errors.
182 bool EnableAllWarnings; // Enable all warnings.
183 bool ErrorsAsFatal; // Treat errors like fatal errors.
184 bool FatalsAsError; // Treat fatal errors like errors.
185 bool SuppressSystemWarnings; // Suppress warnings in system headers.
186 bool SuppressAllDiagnostics; // Suppress all diagnostics.
187 bool ElideType; // Elide common types of templates.
188 bool PrintTemplateTree; // Print a tree when comparing templates.
189 bool ShowColors; // Color printing is enabled.
190 OverloadsShown ShowOverloads; // Which overload candidates to show.
191 unsigned ErrorLimit; // Cap of # errors emitted, 0 -> no limit.
192 unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
194 unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation
195 // backtrace stack, 0 -> no limit.
196 diag::Severity ExtBehavior; // Map extensions to warnings or errors?
197 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
198 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
199 DiagnosticConsumer *Client;
200 std::unique_ptr<DiagnosticConsumer> Owner;
201 SourceManager *SourceMgr;
203 /// \brief Mapping information for diagnostics.
205 /// Mapping info is packed into four bits per diagnostic. The low three
206 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
207 /// The high bit is set when the mapping was established as a user mapping.
208 /// If the high bit is clear, then the low bits are set to the default
209 /// value, and should be mapped with -pedantic, -Werror, etc.
211 /// A new DiagState is created and kept around when diagnostic pragmas modify
212 /// the state so that we know what is the diagnostic state at any given
215 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
218 typedef llvm::DenseMap<unsigned, DiagnosticMapping>::iterator iterator;
219 typedef llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator
222 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
223 DiagMap[Diag] = Info;
226 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
228 const_iterator begin() const { return DiagMap.begin(); }
229 const_iterator end() const { return DiagMap.end(); }
232 /// \brief Keeps and automatically disposes all DiagStates that we create.
233 std::list<DiagState> DiagStates;
235 /// \brief Represents a point in source where the diagnostic state was
236 /// modified because of a pragma.
238 /// 'Loc' can be null if the point represents the diagnostic state
239 /// modifications done through the command-line.
240 struct DiagStatePoint {
243 DiagStatePoint(DiagState *State, FullSourceLoc Loc)
244 : State(State), Loc(Loc) { }
246 bool operator<(const DiagStatePoint &RHS) const {
247 // If Loc is invalid it means it came from <command-line>, in which case
248 // we regard it as coming before any valid source location.
249 if (RHS.Loc.isInvalid())
253 return Loc.isBeforeInTranslationUnitThan(RHS.Loc);
257 /// \brief A sorted vector of all DiagStatePoints representing changes in
258 /// diagnostic state due to diagnostic pragmas.
260 /// The vector is always sorted according to the SourceLocation of the
262 typedef std::vector<DiagStatePoint> DiagStatePointsTy;
263 mutable DiagStatePointsTy DiagStatePoints;
265 /// \brief Keeps the DiagState that was active during each diagnostic 'push'
266 /// so we can get back at it when we 'pop'.
267 std::vector<DiagState *> DiagStateOnPushStack;
269 DiagState *GetCurDiagState() const {
270 assert(!DiagStatePoints.empty());
271 return DiagStatePoints.back().State;
274 void PushDiagStatePoint(DiagState *State, SourceLocation L) {
275 FullSourceLoc Loc(L, getSourceManager());
276 // Make sure that DiagStatePoints is always sorted according to Loc.
277 assert(Loc.isValid() && "Adding invalid loc point");
278 assert(!DiagStatePoints.empty() &&
279 (DiagStatePoints.back().Loc.isInvalid() ||
280 DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) &&
281 "Previous point loc comes after or is the same as new one");
282 DiagStatePoints.push_back(DiagStatePoint(State, Loc));
285 /// \brief Finds the DiagStatePoint that contains the diagnostic state of
286 /// the given source location.
287 DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const;
289 /// \brief Sticky flag set to \c true when an error is emitted.
292 /// \brief Sticky flag set to \c true when an "uncompilable error" occurs.
293 /// I.e. an error that was not upgraded from a warning by -Werror.
294 bool UncompilableErrorOccurred;
296 /// \brief Sticky flag set to \c true when a fatal error is emitted.
297 bool FatalErrorOccurred;
299 /// \brief Indicates that an unrecoverable error has occurred.
300 bool UnrecoverableErrorOccurred;
302 /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred
303 /// during a parsing section, e.g. during parsing a function.
304 unsigned TrapNumErrorsOccurred;
305 unsigned TrapNumUnrecoverableErrorsOccurred;
307 /// \brief The level of the last diagnostic emitted.
309 /// This is used to emit continuation diagnostics with the same level as the
310 /// diagnostic that they follow.
311 DiagnosticIDs::Level LastDiagLevel;
313 unsigned NumWarnings; ///< Number of warnings reported
314 unsigned NumErrors; ///< Number of errors reported
316 /// \brief A function pointer that converts an opaque diagnostic
317 /// argument to a strings.
319 /// This takes the modifiers and argument that was present in the diagnostic.
321 /// The PrevArgs array indicates the previous arguments formatted for this
322 /// diagnostic. Implementations of this function can use this information to
323 /// avoid redundancy across arguments.
325 /// This is a hack to avoid a layering violation between libbasic and libsema.
326 typedef void (*ArgToStringFnTy)(
327 ArgumentKind Kind, intptr_t Val,
328 StringRef Modifier, StringRef Argument,
329 ArrayRef<ArgumentValue> PrevArgs,
330 SmallVectorImpl<char> &Output,
332 ArrayRef<intptr_t> QualTypeVals);
333 void *ArgToStringCookie;
334 ArgToStringFnTy ArgToStringFn;
336 /// \brief ID of the "delayed" diagnostic, which is a (typically
337 /// fatal) diagnostic that had to be delayed because it was found
338 /// while emitting another diagnostic.
339 unsigned DelayedDiagID;
341 /// \brief First string argument for the delayed diagnostic.
342 std::string DelayedDiagArg1;
344 /// \brief Second string argument for the delayed diagnostic.
345 std::string DelayedDiagArg2;
347 /// \brief Optional flag value.
349 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
350 /// -Rpass=<value>. The content of this string is emitted after the flag name
352 std::string FlagValue;
355 explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
356 DiagnosticOptions *DiagOpts,
357 DiagnosticConsumer *client = nullptr,
358 bool ShouldOwnClient = true);
359 DiagnosticsEngine(const DiagnosticsEngine &) = delete;
360 DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
361 ~DiagnosticsEngine();
363 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
367 /// \brief Retrieve the diagnostic options.
368 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
370 typedef llvm::iterator_range<DiagState::const_iterator> diag_mapping_range;
372 /// \brief Get the current set of diagnostic mappings.
373 diag_mapping_range getDiagnosticMappings() const {
374 const DiagState &DS = *GetCurDiagState();
375 return diag_mapping_range(DS.begin(), DS.end());
378 DiagnosticConsumer *getClient() { return Client; }
379 const DiagnosticConsumer *getClient() const { return Client; }
381 /// \brief Determine whether this \c DiagnosticsEngine object own its client.
382 bool ownsClient() const { return Owner != nullptr; }
384 /// \brief Return the current diagnostic client along with ownership of that
386 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
388 bool hasSourceManager() const { return SourceMgr != nullptr; }
389 SourceManager &getSourceManager() const {
390 assert(SourceMgr && "SourceManager not set!");
393 void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
395 //===--------------------------------------------------------------------===//
396 // DiagnosticsEngine characterization methods, used by a client to customize
397 // how diagnostics are emitted.
400 /// \brief Copies the current DiagMappings and pushes the new copy
401 /// onto the top of the stack.
402 void pushMappings(SourceLocation Loc);
404 /// \brief Pops the current DiagMappings off the top of the stack,
405 /// causing the new top of the stack to be the active mappings.
407 /// \returns \c true if the pop happens, \c false if there is only one
408 /// DiagMapping on the stack.
409 bool popMappings(SourceLocation Loc);
411 /// \brief Set the diagnostic client associated with this diagnostic object.
413 /// \param ShouldOwnClient true if the diagnostic object should take
414 /// ownership of \c client.
415 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
417 /// \brief Specify a limit for the number of errors we should
418 /// emit before giving up.
420 /// Zero disables the limit.
421 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
423 /// \brief Specify the maximum number of template instantiation
424 /// notes to emit along with a given diagnostic.
425 void setTemplateBacktraceLimit(unsigned Limit) {
426 TemplateBacktraceLimit = Limit;
429 /// \brief Retrieve the maximum number of template instantiation
430 /// notes to emit along with a given diagnostic.
431 unsigned getTemplateBacktraceLimit() const {
432 return TemplateBacktraceLimit;
435 /// \brief Specify the maximum number of constexpr evaluation
436 /// notes to emit along with a given diagnostic.
437 void setConstexprBacktraceLimit(unsigned Limit) {
438 ConstexprBacktraceLimit = Limit;
441 /// \brief Retrieve the maximum number of constexpr evaluation
442 /// notes to emit along with a given diagnostic.
443 unsigned getConstexprBacktraceLimit() const {
444 return ConstexprBacktraceLimit;
447 /// \brief When set to true, any unmapped warnings are ignored.
449 /// If this and WarningsAsErrors are both set, then this one wins.
450 void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
451 bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
453 /// \brief When set to true, any unmapped ignored warnings are no longer
456 /// If this and IgnoreAllWarnings are both set, then that one wins.
457 void setEnableAllWarnings(bool Val) { EnableAllWarnings = Val; }
458 bool getEnableAllWarnings() const { return EnableAllWarnings; }
460 /// \brief When set to true, any warnings reported are issued as errors.
461 void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
462 bool getWarningsAsErrors() const { return WarningsAsErrors; }
464 /// \brief When set to true, any error reported is made a fatal error.
465 void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
466 bool getErrorsAsFatal() const { return ErrorsAsFatal; }
468 /// \brief When set to true, any fatal error reported is made an error.
470 /// This setting takes precedence over the setErrorsAsFatal setting above.
471 void setFatalsAsError(bool Val) { FatalsAsError = Val; }
472 bool getFatalsAsError() const { return FatalsAsError; }
474 /// \brief When set to true mask warnings that come from system headers.
475 void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
476 bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
478 /// \brief Suppress all diagnostics, to silence the front end when we
479 /// know that we don't want any more diagnostics to be passed along to the
481 void setSuppressAllDiagnostics(bool Val = true) {
482 SuppressAllDiagnostics = Val;
484 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
486 /// \brief Set type eliding, to skip outputting same types occurring in
488 void setElideType(bool Val = true) { ElideType = Val; }
489 bool getElideType() { return ElideType; }
491 /// \brief Set tree printing, to outputting the template difference in a
493 void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
494 bool getPrintTemplateTree() { return PrintTemplateTree; }
496 /// \brief Set color printing, so the type diffing will inject color markers
498 void setShowColors(bool Val = false) { ShowColors = Val; }
499 bool getShowColors() { return ShowColors; }
501 /// \brief Specify which overload candidates to show when overload resolution
504 /// By default, we show all candidates.
505 void setShowOverloads(OverloadsShown Val) {
508 OverloadsShown getShowOverloads() const { return ShowOverloads; }
510 /// \brief Pretend that the last diagnostic issued was ignored, so any
511 /// subsequent notes will be suppressed.
513 /// This can be used by clients who suppress diagnostics themselves.
514 void setLastDiagnosticIgnored() {
515 if (LastDiagLevel == DiagnosticIDs::Fatal)
516 FatalErrorOccurred = true;
517 LastDiagLevel = DiagnosticIDs::Ignored;
520 /// \brief Determine whether the previous diagnostic was ignored. This can
521 /// be used by clients that want to determine whether notes attached to a
522 /// diagnostic will be suppressed.
523 bool isLastDiagnosticIgnored() const {
524 return LastDiagLevel == DiagnosticIDs::Ignored;
527 /// \brief Controls whether otherwise-unmapped extension diagnostics are
528 /// mapped onto ignore/warning/error.
530 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
531 void setExtensionHandlingBehavior(diag::Severity H) { ExtBehavior = H; }
532 diag::Severity getExtensionHandlingBehavior() const { return ExtBehavior; }
534 /// \brief Counter bumped when an __extension__ block is/ encountered.
536 /// When non-zero, all extension diagnostics are entirely silenced, no
537 /// matter how they are mapped.
538 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
539 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
540 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
542 /// \brief This allows the client to specify that certain warnings are
545 /// Notes can never be mapped, errors can only be mapped to fatal, and
546 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
548 /// \param Loc The source location that this change of diagnostic state should
549 /// take affect. It can be null if we are setting the latest state.
550 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
552 /// \brief Change an entire diagnostic group (e.g. "unknown-pragmas") to
553 /// have the specified mapping.
555 /// \returns true (and ignores the request) if "Group" was unknown, false
558 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
559 /// state of the -Wfoo group and vice versa.
561 /// \param Loc The source location that this change of diagnostic state should
562 /// take affect. It can be null if we are setting the state from command-line.
563 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
565 SourceLocation Loc = SourceLocation());
567 /// \brief Set the warning-as-error flag for the given diagnostic group.
569 /// This function always only operates on the current diagnostic state.
571 /// \returns True if the given group is unknown, false otherwise.
572 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
574 /// \brief Set the error-as-fatal flag for the given diagnostic group.
576 /// This function always only operates on the current diagnostic state.
578 /// \returns True if the given group is unknown, false otherwise.
579 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
581 /// \brief Add the specified mapping to all diagnostics of the specified
584 /// Mainly to be used by -Wno-everything to disable all warnings but allow
585 /// subsequent -W options to enable specific warnings.
586 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
587 SourceLocation Loc = SourceLocation());
589 bool hasErrorOccurred() const { return ErrorOccurred; }
591 /// \brief Errors that actually prevent compilation, not those that are
592 /// upgraded from a warning by -Werror.
593 bool hasUncompilableErrorOccurred() const {
594 return UncompilableErrorOccurred;
596 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
598 /// \brief Determine whether any kind of unrecoverable error has occurred.
599 bool hasUnrecoverableErrorOccurred() const {
600 return FatalErrorOccurred || UnrecoverableErrorOccurred;
603 unsigned getNumWarnings() const { return NumWarnings; }
605 void setNumWarnings(unsigned NumWarnings) {
606 this->NumWarnings = NumWarnings;
609 /// \brief Return an ID for a diagnostic with the specified format string and
612 /// If this is the first request for this diagnostic, it is registered and
613 /// created, otherwise the existing ID is returned.
615 /// \param FormatString A fixed diagnostic format string that will be hashed
616 /// and mapped to a unique DiagID.
617 template <unsigned N>
618 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
619 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
620 StringRef(FormatString, N - 1));
623 /// \brief Converts a diagnostic argument (as an intptr_t) into the string
624 /// that represents it.
625 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
626 StringRef Modifier, StringRef Argument,
627 ArrayRef<ArgumentValue> PrevArgs,
628 SmallVectorImpl<char> &Output,
629 ArrayRef<intptr_t> QualTypeVals) const {
630 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
631 ArgToStringCookie, QualTypeVals);
634 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
636 ArgToStringCookie = Cookie;
639 /// \brief Note that the prior diagnostic was emitted by some other
640 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
641 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
642 LastDiagLevel = Other.LastDiagLevel;
645 /// \brief Reset the state of the diagnostic object to its initial
649 //===--------------------------------------------------------------------===//
650 // DiagnosticsEngine classification and reporting interfaces.
653 /// \brief Determine whether the diagnostic is known to be ignored.
655 /// This can be used to opportunistically avoid expensive checks when it's
656 /// known for certain that the diagnostic has been suppressed at the
657 /// specified location \p Loc.
659 /// \param Loc The source location we are interested in finding out the
660 /// diagnostic state. Can be null in order to query the latest state.
661 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
662 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
663 diag::Severity::Ignored;
666 /// \brief Based on the way the client configured the DiagnosticsEngine
667 /// object, classify the specified diagnostic ID into a Level, consumable by
668 /// the DiagnosticConsumer.
670 /// To preserve invariant assumptions, this function should not be used to
671 /// influence parse or semantic analysis actions. Instead consider using
674 /// \param Loc The source location we are interested in finding out the
675 /// diagnostic state. Can be null in order to query the latest state.
676 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
677 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
680 /// \brief Issue the message to the client.
682 /// This actually returns an instance of DiagnosticBuilder which emits the
683 /// diagnostics (through @c ProcessDiag) when it is destroyed.
685 /// \param DiagID A member of the @c diag::kind enum.
686 /// \param Loc Represents the source location associated with the diagnostic,
687 /// which can be an invalid location if no position information is available.
688 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
689 inline DiagnosticBuilder Report(unsigned DiagID);
691 void Report(const StoredDiagnostic &storedDiag);
693 /// \brief Determine whethere there is already a diagnostic in flight.
694 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
696 /// \brief Set the "delayed" diagnostic that will be emitted once
697 /// the current diagnostic completes.
699 /// If a diagnostic is already in-flight but the front end must
700 /// report a problem (e.g., with an inconsistent file system
701 /// state), this routine sets a "delayed" diagnostic that will be
702 /// emitted after the current diagnostic completes. This should
703 /// only be used for fatal errors detected at inconvenient
704 /// times. If emitting a delayed diagnostic causes a second delayed
705 /// diagnostic to be introduced, that second delayed diagnostic
708 /// \param DiagID The ID of the diagnostic being delayed.
710 /// \param Arg1 A string argument that will be provided to the
711 /// diagnostic. A copy of this string will be stored in the
712 /// DiagnosticsEngine object itself.
714 /// \param Arg2 A string argument that will be provided to the
715 /// diagnostic. A copy of this string will be stored in the
716 /// DiagnosticsEngine object itself.
717 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
718 StringRef Arg2 = "");
720 /// \brief Clear out the current diagnostic.
721 void Clear() { CurDiagID = ~0U; }
723 /// \brief Return the value associated with this diagnostic flag.
724 StringRef getFlagValue() const { return FlagValue; }
727 /// \brief Report the delayed diagnostic.
728 void ReportDelayed();
730 // This is private state used by DiagnosticBuilder. We put it here instead of
731 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
732 // object. This implementation choice means that we can only have one
733 // diagnostic "in flight" at a time, but this seems to be a reasonable
734 // tradeoff to keep these objects small. Assertions verify that only one
735 // diagnostic is in flight at a time.
736 friend class DiagnosticIDs;
737 friend class DiagnosticBuilder;
738 friend class Diagnostic;
739 friend class PartialDiagnostic;
740 friend class DiagnosticErrorTrap;
742 /// \brief The location of the current diagnostic that is in flight.
743 SourceLocation CurDiagLoc;
745 /// \brief The ID of the current diagnostic that is in flight.
747 /// This is set to ~0U when there is no diagnostic in flight.
751 /// \brief The maximum number of arguments we can hold.
753 /// We currently only support up to 10 arguments (%0-%9). A single
754 /// diagnostic with more than that almost certainly has to be simplified
759 /// \brief The number of entries in Arguments.
760 signed char NumDiagArgs;
762 /// \brief Specifies whether an argument is in DiagArgumentsStr or
763 /// in DiagArguments.
765 /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
767 unsigned char DiagArgumentsKind[MaxArguments];
769 /// \brief Holds the values of each string argument for the current
772 /// This is only used when the corresponding ArgumentKind is ak_std_string.
773 std::string DiagArgumentsStr[MaxArguments];
775 /// \brief The values for the various substitution positions.
777 /// This is used when the argument is not an std::string. The specific
778 /// value is mangled into an intptr_t and the interpretation depends on
779 /// exactly what sort of argument kind it is.
780 intptr_t DiagArgumentsVal[MaxArguments];
782 /// \brief The list of ranges added to this diagnostic.
783 SmallVector<CharSourceRange, 8> DiagRanges;
785 /// \brief If valid, provides a hint with some code to insert, remove,
786 /// or modify at a particular position.
787 SmallVector<FixItHint, 8> DiagFixItHints;
789 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
790 bool isPragma = L.isValid();
791 DiagnosticMapping Mapping =
792 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
794 // If this is a pragma mapping, then set the diagnostic mapping flags so
795 // that we override command line options.
797 Mapping.setNoWarningAsError(true);
798 Mapping.setNoErrorAsFatal(true);
804 /// \brief Used to report a diagnostic that is finally fully formed.
806 /// \returns true if the diagnostic was emitted, false if it was suppressed.
808 return Diags->ProcessDiag(*this);
811 /// @name Diagnostic Emission
814 // Sema requires access to the following functions because the current design
815 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
816 // access us directly to ensure we minimize the emitted code for the common
817 // Sema::Diag() patterns.
820 /// \brief Emit the current diagnostic and clear the diagnostic state.
822 /// \param Force Emit the diagnostic regardless of suppression settings.
823 bool EmitCurrentDiagnostic(bool Force = false);
825 unsigned getCurrentDiagID() const { return CurDiagID; }
827 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
831 friend class ASTReader;
832 friend class ASTWriter;
835 /// \brief RAII class that determines when any errors have occurred
836 /// between the time the instance was created and the time it was
838 class DiagnosticErrorTrap {
839 DiagnosticsEngine &Diag;
841 unsigned NumUnrecoverableErrors;
844 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
845 : Diag(Diag) { reset(); }
847 /// \brief Determine whether any errors have occurred since this
848 /// object instance was created.
849 bool hasErrorOccurred() const {
850 return Diag.TrapNumErrorsOccurred > NumErrors;
853 /// \brief Determine whether any unrecoverable errors have occurred since this
854 /// object instance was created.
855 bool hasUnrecoverableErrorOccurred() const {
856 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
859 /// \brief Set to initial state of "no errors occurred".
861 NumErrors = Diag.TrapNumErrorsOccurred;
862 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
866 //===----------------------------------------------------------------------===//
868 //===----------------------------------------------------------------------===//
870 /// \brief A little helper class used to produce diagnostics.
872 /// This is constructed by the DiagnosticsEngine::Report method, and
873 /// allows insertion of extra information (arguments and source ranges) into
874 /// the currently "in flight" diagnostic. When the temporary for the builder
875 /// is destroyed, the diagnostic is issued.
877 /// Note that many of these will be created as temporary objects (many call
878 /// sites), so we want them to be small and we never want their address taken.
879 /// This ensures that compilers with somewhat reasonable optimizers will promote
880 /// the common fields to registers, eliminating increments of the NumArgs field,
882 class DiagnosticBuilder {
883 mutable DiagnosticsEngine *DiagObj = nullptr;
884 mutable unsigned NumArgs = 0;
886 /// \brief Status variable indicating if this diagnostic is still active.
888 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
889 // but LLVM is not currently smart enough to eliminate the null check that
890 // Emit() would end up with if we used that as our status variable.
891 mutable bool IsActive = false;
893 /// \brief Flag indicating that this diagnostic is being emitted via a
894 /// call to ForceEmit.
895 mutable bool IsForceEmit = false;
897 friend class DiagnosticsEngine;
899 DiagnosticBuilder() = default;
901 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
902 : DiagObj(diagObj), IsActive(true) {
903 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
904 diagObj->DiagRanges.clear();
905 diagObj->DiagFixItHints.clear();
908 friend class PartialDiagnostic;
912 DiagObj->NumDiagArgs = NumArgs;
915 /// \brief Clear out the current diagnostic.
922 /// \brief Determine whether this diagnostic is still active.
923 bool isActive() const { return IsActive; }
925 /// \brief Force the diagnostic builder to emit the diagnostic now.
927 /// Once this function has been called, the DiagnosticBuilder object
928 /// should not be used again before it is destroyed.
930 /// \returns true if a diagnostic was emitted, false if the
931 /// diagnostic was suppressed.
933 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
934 // (or by a subclass, as in SemaDiagnosticBuilder).
935 if (!isActive()) return false;
937 // When emitting diagnostics, we set the final argument count into
938 // the DiagnosticsEngine object.
941 // Process the diagnostic.
942 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
944 // This diagnostic is dead.
951 /// Copy constructor. When copied, this "takes" the diagnostic info from the
952 /// input and neuters it.
953 DiagnosticBuilder(const DiagnosticBuilder &D) {
955 IsActive = D.IsActive;
956 IsForceEmit = D.IsForceEmit;
961 DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
963 /// \brief Emits the diagnostic.
964 ~DiagnosticBuilder() {
968 /// \brief Retrieve an empty diagnostic builder.
969 static DiagnosticBuilder getEmpty() {
970 return DiagnosticBuilder();
973 /// \brief Forces the diagnostic to be emitted.
974 const DiagnosticBuilder &setForceEmit() const {
979 /// \brief Conversion of DiagnosticBuilder to bool always returns \c true.
981 /// This allows is to be used in boolean error contexts (where \c true is
982 /// used to indicate that an error has occurred), like:
984 /// return Diag(...);
986 operator bool() const { return true; }
988 void AddString(StringRef S) const {
989 assert(isActive() && "Clients must not add to cleared diagnostic!");
990 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
991 "Too many arguments to diagnostic!");
992 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
993 DiagObj->DiagArgumentsStr[NumArgs++] = S;
996 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
997 assert(isActive() && "Clients must not add to cleared diagnostic!");
998 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
999 "Too many arguments to diagnostic!");
1000 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
1001 DiagObj->DiagArgumentsVal[NumArgs++] = V;
1004 void AddSourceRange(const CharSourceRange &R) const {
1005 assert(isActive() && "Clients must not add to cleared diagnostic!");
1006 DiagObj->DiagRanges.push_back(R);
1009 void AddFixItHint(const FixItHint &Hint) const {
1010 assert(isActive() && "Clients must not add to cleared diagnostic!");
1012 DiagObj->DiagFixItHints.push_back(Hint);
1015 void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
1018 struct AddFlagValue {
1019 explicit AddFlagValue(StringRef V) : Val(V) {}
1023 /// \brief Register a value for the flag in the current diagnostic. This
1024 /// value will be shown as the suffix "=value" after the flag name. It is
1025 /// useful in cases where the diagnostic flag accepts values (e.g.,
1026 /// -Rpass or -Wframe-larger-than).
1027 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1028 const AddFlagValue V) {
1029 DB.addFlagValue(V.Val);
1033 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1039 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1041 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1042 DiagnosticsEngine::ak_c_string);
1046 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
1047 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1051 // We use enable_if here to prevent that this overload is selected for
1052 // pointers or other arguments that are implicitly convertible to bool.
1053 template <typename T>
1055 typename std::enable_if<std::is_same<T, bool>::value,
1056 const DiagnosticBuilder &>::type
1057 operator<<(const DiagnosticBuilder &DB, T I) {
1058 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1062 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1064 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1068 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1070 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1074 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1075 const IdentifierInfo *II) {
1076 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1077 DiagnosticsEngine::ak_identifierinfo);
1081 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
1082 // so that we only match those arguments that are (statically) DeclContexts;
1083 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
1085 template <typename T>
1086 inline typename std::enable_if<
1087 std::is_same<typename std::remove_const<T>::type, DeclContext>::value,
1088 const DiagnosticBuilder &>::type
1089 operator<<(const DiagnosticBuilder &DB, T *DC) {
1090 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1091 DiagnosticsEngine::ak_declcontext);
1095 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1097 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1101 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1102 ArrayRef<SourceRange> Ranges) {
1103 for (SourceRange R : Ranges)
1104 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1108 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1109 const CharSourceRange &R) {
1110 DB.AddSourceRange(R);
1114 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1115 const FixItHint &Hint) {
1116 DB.AddFixItHint(Hint);
1120 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1121 ArrayRef<FixItHint> Hints) {
1122 for (const FixItHint &Hint : Hints)
1123 DB.AddFixItHint(Hint);
1127 /// A nullability kind paired with a bit indicating whether it used a
1128 /// context-sensitive keyword.
1129 typedef std::pair<NullabilityKind, bool> DiagNullabilityKind;
1131 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1132 DiagNullabilityKind nullability);
1134 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1136 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
1140 return DiagnosticBuilder(this);
1143 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1144 return Report(SourceLocation(), DiagID);
1147 //===----------------------------------------------------------------------===//
1149 //===----------------------------------------------------------------------===//
1151 /// A little helper class (which is basically a smart pointer that forwards
1152 /// info from DiagnosticsEngine) that allows clients to enquire about the
1153 /// currently in-flight diagnostic.
1155 const DiagnosticsEngine *DiagObj;
1156 StringRef StoredDiagMessage;
1159 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1160 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1161 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1163 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1164 unsigned getID() const { return DiagObj->CurDiagID; }
1165 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1166 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1167 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1169 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1171 /// \brief Return the kind of the specified index.
1173 /// Based on the kind of argument, the accessors below can be used to get
1176 /// \pre Idx < getNumArgs()
1177 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1178 assert(Idx < getNumArgs() && "Argument index out of range!");
1179 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1182 /// \brief Return the provided argument string specified by \p Idx.
1183 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1184 const std::string &getArgStdStr(unsigned Idx) const {
1185 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1186 "invalid argument accessor!");
1187 return DiagObj->DiagArgumentsStr[Idx];
1190 /// \brief Return the specified C string argument.
1191 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1192 const char *getArgCStr(unsigned Idx) const {
1193 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1194 "invalid argument accessor!");
1195 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1198 /// \brief Return the specified signed integer argument.
1199 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1200 int getArgSInt(unsigned Idx) const {
1201 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1202 "invalid argument accessor!");
1203 return (int)DiagObj->DiagArgumentsVal[Idx];
1206 /// \brief Return the specified unsigned integer argument.
1207 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1208 unsigned getArgUInt(unsigned Idx) const {
1209 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1210 "invalid argument accessor!");
1211 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1214 /// \brief Return the specified IdentifierInfo argument.
1215 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1216 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1217 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1218 "invalid argument accessor!");
1219 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1222 /// \brief Return the specified non-string argument in an opaque form.
1223 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1224 intptr_t getRawArg(unsigned Idx) const {
1225 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1226 "invalid argument accessor!");
1227 return DiagObj->DiagArgumentsVal[Idx];
1230 /// \brief Return the number of source ranges associated with this diagnostic.
1231 unsigned getNumRanges() const {
1232 return DiagObj->DiagRanges.size();
1235 /// \pre Idx < getNumRanges()
1236 const CharSourceRange &getRange(unsigned Idx) const {
1237 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1238 return DiagObj->DiagRanges[Idx];
1241 /// \brief Return an array reference for this diagnostic's ranges.
1242 ArrayRef<CharSourceRange> getRanges() const {
1243 return DiagObj->DiagRanges;
1246 unsigned getNumFixItHints() const {
1247 return DiagObj->DiagFixItHints.size();
1250 const FixItHint &getFixItHint(unsigned Idx) const {
1251 assert(Idx < getNumFixItHints() && "Invalid index!");
1252 return DiagObj->DiagFixItHints[Idx];
1255 ArrayRef<FixItHint> getFixItHints() const {
1256 return DiagObj->DiagFixItHints;
1259 /// \brief Format this diagnostic into a string, substituting the
1260 /// formal arguments into the %0 slots.
1262 /// The result is appended onto the \p OutStr array.
1263 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1265 /// \brief Format the given format-string into the output buffer using the
1266 /// arguments stored in this diagnostic.
1267 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1268 SmallVectorImpl<char> &OutStr) const;
1272 * \brief Represents a diagnostic in a form that can be retained until its
1273 * corresponding source manager is destroyed.
1275 class StoredDiagnostic {
1277 DiagnosticsEngine::Level Level;
1279 std::string Message;
1280 std::vector<CharSourceRange> Ranges;
1281 std::vector<FixItHint> FixIts;
1284 StoredDiagnostic() = default;
1285 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1286 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1288 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1289 StringRef Message, FullSourceLoc Loc,
1290 ArrayRef<CharSourceRange> Ranges,
1291 ArrayRef<FixItHint> Fixits);
1293 /// \brief Evaluates true when this object stores a diagnostic.
1294 explicit operator bool() const { return !Message.empty(); }
1296 unsigned getID() const { return ID; }
1297 DiagnosticsEngine::Level getLevel() const { return Level; }
1298 const FullSourceLoc &getLocation() const { return Loc; }
1299 StringRef getMessage() const { return Message; }
1301 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1303 typedef std::vector<CharSourceRange>::const_iterator range_iterator;
1304 range_iterator range_begin() const { return Ranges.begin(); }
1305 range_iterator range_end() const { return Ranges.end(); }
1306 unsigned range_size() const { return Ranges.size(); }
1308 ArrayRef<CharSourceRange> getRanges() const {
1309 return llvm::makeArrayRef(Ranges);
1312 typedef std::vector<FixItHint>::const_iterator fixit_iterator;
1313 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1314 fixit_iterator fixit_end() const { return FixIts.end(); }
1315 unsigned fixit_size() const { return FixIts.size(); }
1317 ArrayRef<FixItHint> getFixIts() const {
1318 return llvm::makeArrayRef(FixIts);
1322 /// \brief Abstract interface, implemented by clients of the front-end, which
1323 /// formats and prints fully processed diagnostics.
1324 class DiagnosticConsumer {
1326 unsigned NumWarnings = 0; ///< Number of warnings reported
1327 unsigned NumErrors = 0; ///< Number of errors reported
1330 DiagnosticConsumer() = default;
1332 virtual ~DiagnosticConsumer();
1334 unsigned getNumErrors() const { return NumErrors; }
1335 unsigned getNumWarnings() const { return NumWarnings; }
1336 virtual void clear() { NumWarnings = NumErrors = 0; }
1338 /// \brief Callback to inform the diagnostic client that processing
1339 /// of a source file is beginning.
1341 /// Note that diagnostics may be emitted outside the processing of a source
1342 /// file, for example during the parsing of command line options. However,
1343 /// diagnostics with source range information are required to only be emitted
1344 /// in between BeginSourceFile() and EndSourceFile().
1346 /// \param LangOpts The language options for the source file being processed.
1347 /// \param PP The preprocessor object being used for the source; this is
1348 /// optional, e.g., it may not be present when processing AST source files.
1349 virtual void BeginSourceFile(const LangOptions &LangOpts,
1350 const Preprocessor *PP = nullptr) {}
1352 /// \brief Callback to inform the diagnostic client that processing
1353 /// of a source file has ended.
1355 /// The diagnostic client should assume that any objects made available via
1356 /// BeginSourceFile() are inaccessible.
1357 virtual void EndSourceFile() {}
1359 /// \brief Callback to inform the diagnostic client that processing of all
1360 /// source files has ended.
1361 virtual void finish() {}
1363 /// \brief Indicates whether the diagnostics handled by this
1364 /// DiagnosticConsumer should be included in the number of diagnostics
1365 /// reported by DiagnosticsEngine.
1367 /// The default implementation returns true.
1368 virtual bool IncludeInDiagnosticCounts() const;
1370 /// \brief Handle this diagnostic, reporting it to the user or
1371 /// capturing it to a log as needed.
1373 /// The default implementation just keeps track of the total number of
1374 /// warnings and errors.
1375 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1376 const Diagnostic &Info);
1379 /// \brief A diagnostic client that ignores all diagnostics.
1380 class IgnoringDiagConsumer : public DiagnosticConsumer {
1381 virtual void anchor();
1383 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1384 const Diagnostic &Info) override {
1389 /// \brief Diagnostic consumer that forwards diagnostics along to an
1390 /// existing, already-initialized diagnostic consumer.
1392 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1393 DiagnosticConsumer &Target;
1396 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1398 ~ForwardingDiagnosticConsumer() override;
1400 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1401 const Diagnostic &Info) override;
1402 void clear() override;
1404 bool IncludeInDiagnosticCounts() const override;
1407 // Struct used for sending info about how a type should be printed.
1408 struct TemplateDiffTypes {
1411 unsigned PrintTree : 1;
1412 unsigned PrintFromType : 1;
1413 unsigned ElideType : 1;
1414 unsigned ShowColors : 1;
1415 // The printer sets this variable to true if the template diff was used.
1416 unsigned TemplateDiffUsed : 1;
1419 /// Special character that the diagnostic printer will use to toggle the bold
1420 /// attribute. The character itself will be not be printed.
1421 const char ToggleHighlight = 127;
1424 /// ProcessWarningOptions - Initialize the diagnostic client and process the
1425 /// warning options specified on the command line.
1426 void ProcessWarningOptions(DiagnosticsEngine &Diags,
1427 const DiagnosticOptions &Opts,
1428 bool ReportDiags = true);
1430 } // end namespace clang
1432 #endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H