1 //===--- Diagnostic.h - C Language Family Diagnostic Handling ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Defines the Diagnostic-related interfaces.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
16 #define LLVM_CLANG_BASIC_DIAGNOSTIC_H
18 #include "clang/Basic/DiagnosticIDs.h"
19 #include "clang/Basic/DiagnosticOptions.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Basic/Specifiers.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/IntrusiveRefCntPtr.h"
25 #include "llvm/ADT/iterator_range.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/StringRef.h"
35 #include <type_traits>
42 class DiagnosticBuilder;
43 class DiagnosticConsumer;
47 class StoredDiagnostic;
51 enum TokenKind : unsigned short;
53 } // end namespace tok
55 /// \brief Annotates a diagnostic with some code that should be
56 /// inserted, removed, or replaced to fix the problem.
58 /// This kind of hint should be used when we are certain that the
59 /// introduction, removal, or modification of a particular (small!)
60 /// amount of code will correct a compilation error. The compiler
61 /// should also provide full recovery from such errors, such that
62 /// suppressing the diagnostic output can still result in successful
66 /// \brief Code that should be replaced to correct the error. Empty for an
68 CharSourceRange RemoveRange;
70 /// \brief Code in the specific range that should be inserted in the insertion
72 CharSourceRange InsertFromRange;
74 /// \brief The actual code to insert at the insertion location, as a
76 std::string CodeToInsert;
78 bool BeforePreviousInsertions;
80 /// \brief Empty code modification hint, indicating that no code
81 /// modification is known.
82 FixItHint() : BeforePreviousInsertions(false) { }
85 return !RemoveRange.isValid();
88 /// \brief Create a code modification hint that inserts the given
89 /// code string at a specific location.
90 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
92 bool BeforePreviousInsertions = false) {
95 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
96 Hint.CodeToInsert = Code;
97 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
101 /// \brief Create a code modification hint that inserts the given
102 /// code from \p FromRange at a specific location.
103 static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
104 CharSourceRange FromRange,
105 bool BeforePreviousInsertions = false) {
108 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
109 Hint.InsertFromRange = FromRange;
110 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
114 /// \brief Create a code modification hint that removes the given
116 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
118 Hint.RemoveRange = RemoveRange;
121 static FixItHint CreateRemoval(SourceRange RemoveRange) {
122 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
125 /// \brief Create a code modification hint that replaces the given
126 /// source range with the given code string.
127 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
130 Hint.RemoveRange = RemoveRange;
131 Hint.CodeToInsert = Code;
135 static FixItHint CreateReplacement(SourceRange RemoveRange,
137 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
141 /// \brief Concrete class used by the front-end to report problems and issues.
143 /// This massages the diagnostics (e.g. handling things like "report warnings
144 /// as errors" and passes them off to the DiagnosticConsumer for reporting to
145 /// the user. DiagnosticsEngine is tied to one translation unit and one
147 class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
149 /// \brief The level of the diagnostic, after it has been through mapping.
151 Ignored = DiagnosticIDs::Ignored,
152 Note = DiagnosticIDs::Note,
153 Remark = DiagnosticIDs::Remark,
154 Warning = DiagnosticIDs::Warning,
155 Error = DiagnosticIDs::Error,
156 Fatal = DiagnosticIDs::Fatal
160 ak_std_string, ///< std::string
161 ak_c_string, ///< const char *
163 ak_uint, ///< unsigned
164 ak_tokenkind, ///< enum TokenKind : unsigned
165 ak_identifierinfo, ///< IdentifierInfo
166 ak_qualtype, ///< QualType
167 ak_declarationname, ///< DeclarationName
168 ak_nameddecl, ///< NamedDecl *
169 ak_nestednamespec, ///< NestedNameSpecifier *
170 ak_declcontext, ///< DeclContext *
171 ak_qualtype_pair, ///< pair<QualType, QualType>
175 /// \brief Represents on argument value, which is a union discriminated
176 /// by ArgumentKind, with a value.
177 typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
180 unsigned char AllExtensionsSilenced; // Used by __extension__
181 bool SuppressAfterFatalError; // Suppress diagnostics after a fatal error?
182 bool SuppressAllDiagnostics; // Suppress all diagnostics.
183 bool ElideType; // Elide common types of templates.
184 bool PrintTemplateTree; // Print a tree when comparing templates.
185 bool ShowColors; // Color printing is enabled.
186 OverloadsShown ShowOverloads; // Which overload candidates to show.
187 unsigned ErrorLimit; // Cap of # errors emitted, 0 -> no limit.
188 unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
190 unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation
191 // backtrace stack, 0 -> no limit.
192 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
193 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
194 DiagnosticConsumer *Client;
195 std::unique_ptr<DiagnosticConsumer> Owner;
196 SourceManager *SourceMgr;
198 /// \brief Mapping information for diagnostics.
200 /// Mapping info is packed into four bits per diagnostic. The low three
201 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
202 /// The high bit is set when the mapping was established as a user mapping.
203 /// If the high bit is clear, then the low bits are set to the default
204 /// value, and should be mapped with -pedantic, -Werror, etc.
206 /// A new DiagState is created and kept around when diagnostic pragmas modify
207 /// the state so that we know what is the diagnostic state at any given
210 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
213 // "Global" configuration state that can actually vary between modules.
214 unsigned IgnoreAllWarnings : 1; // Ignore all warnings: -w
215 unsigned EnableAllWarnings : 1; // Enable all warnings.
216 unsigned WarningsAsErrors : 1; // Treat warnings like errors.
217 unsigned ErrorsAsFatal : 1; // Treat errors like fatal errors.
218 unsigned SuppressSystemWarnings : 1; // Suppress warnings in system headers.
219 diag::Severity ExtBehavior; // Map extensions to warnings or errors?
222 : IgnoreAllWarnings(false), EnableAllWarnings(false),
223 WarningsAsErrors(false), ErrorsAsFatal(false),
224 SuppressSystemWarnings(false), ExtBehavior(diag::Severity::Ignored) {}
226 typedef llvm::DenseMap<unsigned, DiagnosticMapping>::iterator iterator;
227 typedef llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator
230 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
231 DiagMap[Diag] = Info;
233 DiagnosticMapping lookupMapping(diag::kind Diag) const {
234 return DiagMap.lookup(Diag);
237 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
239 const_iterator begin() const { return DiagMap.begin(); }
240 const_iterator end() const { return DiagMap.end(); }
243 /// \brief Keeps and automatically disposes all DiagStates that we create.
244 std::list<DiagState> DiagStates;
246 /// A mapping from files to the diagnostic states for those files. Lazily
247 /// built on demand for files in which the diagnostic state has not changed.
250 /// Add an initial diagnostic state.
251 void appendFirst(DiagState *State);
252 /// Add a new latest state point.
253 void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
254 /// Look up the diagnostic state at a given source location.
255 DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
256 /// Determine whether this map is empty.
257 bool empty() const { return Files.empty(); }
258 /// Clear out this map.
261 FirstDiagState = CurDiagState = nullptr;
262 CurDiagStateLoc = SourceLocation();
265 /// Grab the most-recently-added state point.
266 DiagState *getCurDiagState() const { return CurDiagState; }
267 /// Get the location at which a diagnostic state was last added.
268 SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
271 /// \brief Represents a point in source where the diagnostic state was
272 /// modified because of a pragma.
274 /// 'Loc' can be null if the point represents the diagnostic state
275 /// modifications done through the command-line.
276 struct DiagStatePoint {
279 DiagStatePoint(DiagState *State, unsigned Offset)
280 : State(State), Offset(Offset) { }
283 /// Description of the diagnostic states and state transitions for a
284 /// particular FileID.
286 /// The diagnostic state for the parent file. This is strictly redundant,
287 /// as looking up the DecomposedIncludedLoc for the FileID in the Files
288 /// map would give us this, but we cache it here for performance.
289 File *Parent = nullptr;
290 /// The offset of this file within its parent.
291 unsigned ParentOffset = 0;
292 /// Whether this file has any local (not imported from an AST file)
293 /// diagnostic state transitions.
294 bool HasLocalTransitions = false;
295 /// The points within the file where the state changes. There will always
296 /// be at least one of these (the state on entry to the file).
297 llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
299 DiagState *lookup(unsigned Offset) const;
302 /// The diagnostic states for each file.
303 mutable std::map<FileID, File> Files;
305 /// The initial diagnostic state.
306 DiagState *FirstDiagState;
307 /// The current diagnostic state.
308 DiagState *CurDiagState;
309 /// The location at which the current diagnostic state was established.
310 SourceLocation CurDiagStateLoc;
312 /// Get the diagnostic state information for a file.
313 File *getFile(SourceManager &SrcMgr, FileID ID) const;
315 friend class ASTReader;
316 friend class ASTWriter;
319 DiagStateMap DiagStatesByLoc;
321 /// \brief Keeps the DiagState that was active during each diagnostic 'push'
322 /// so we can get back at it when we 'pop'.
323 std::vector<DiagState *> DiagStateOnPushStack;
325 DiagState *GetCurDiagState() const {
326 return DiagStatesByLoc.getCurDiagState();
329 void PushDiagStatePoint(DiagState *State, SourceLocation L);
331 /// \brief Finds the DiagStatePoint that contains the diagnostic state of
332 /// the given source location.
333 DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
334 return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
335 : DiagStatesByLoc.getCurDiagState();
338 /// \brief Sticky flag set to \c true when an error is emitted.
341 /// \brief Sticky flag set to \c true when an "uncompilable error" occurs.
342 /// I.e. an error that was not upgraded from a warning by -Werror.
343 bool UncompilableErrorOccurred;
345 /// \brief Sticky flag set to \c true when a fatal error is emitted.
346 bool FatalErrorOccurred;
348 /// \brief Indicates that an unrecoverable error has occurred.
349 bool UnrecoverableErrorOccurred;
351 /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred
352 /// during a parsing section, e.g. during parsing a function.
353 unsigned TrapNumErrorsOccurred;
354 unsigned TrapNumUnrecoverableErrorsOccurred;
356 /// \brief The level of the last diagnostic emitted.
358 /// This is used to emit continuation diagnostics with the same level as the
359 /// diagnostic that they follow.
360 DiagnosticIDs::Level LastDiagLevel;
362 unsigned NumWarnings; ///< Number of warnings reported
363 unsigned NumErrors; ///< Number of errors reported
365 /// \brief A function pointer that converts an opaque diagnostic
366 /// argument to a strings.
368 /// This takes the modifiers and argument that was present in the diagnostic.
370 /// The PrevArgs array indicates the previous arguments formatted for this
371 /// diagnostic. Implementations of this function can use this information to
372 /// avoid redundancy across arguments.
374 /// This is a hack to avoid a layering violation between libbasic and libsema.
375 typedef void (*ArgToStringFnTy)(
376 ArgumentKind Kind, intptr_t Val,
377 StringRef Modifier, StringRef Argument,
378 ArrayRef<ArgumentValue> PrevArgs,
379 SmallVectorImpl<char> &Output,
381 ArrayRef<intptr_t> QualTypeVals);
382 void *ArgToStringCookie;
383 ArgToStringFnTy ArgToStringFn;
385 /// \brief ID of the "delayed" diagnostic, which is a (typically
386 /// fatal) diagnostic that had to be delayed because it was found
387 /// while emitting another diagnostic.
388 unsigned DelayedDiagID;
390 /// \brief First string argument for the delayed diagnostic.
391 std::string DelayedDiagArg1;
393 /// \brief Second string argument for the delayed diagnostic.
394 std::string DelayedDiagArg2;
396 /// \brief Optional flag value.
398 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
399 /// -Rpass=<value>. The content of this string is emitted after the flag name
401 std::string FlagValue;
404 explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
405 DiagnosticOptions *DiagOpts,
406 DiagnosticConsumer *client = nullptr,
407 bool ShouldOwnClient = true);
408 DiagnosticsEngine(const DiagnosticsEngine &) = delete;
409 DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
410 ~DiagnosticsEngine();
412 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
416 /// \brief Retrieve the diagnostic options.
417 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
419 typedef llvm::iterator_range<DiagState::const_iterator> diag_mapping_range;
421 /// \brief Get the current set of diagnostic mappings.
422 diag_mapping_range getDiagnosticMappings() const {
423 const DiagState &DS = *GetCurDiagState();
424 return diag_mapping_range(DS.begin(), DS.end());
427 DiagnosticConsumer *getClient() { return Client; }
428 const DiagnosticConsumer *getClient() const { return Client; }
430 /// \brief Determine whether this \c DiagnosticsEngine object own its client.
431 bool ownsClient() const { return Owner != nullptr; }
433 /// \brief Return the current diagnostic client along with ownership of that
435 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
437 bool hasSourceManager() const { return SourceMgr != nullptr; }
438 SourceManager &getSourceManager() const {
439 assert(SourceMgr && "SourceManager not set!");
442 void setSourceManager(SourceManager *SrcMgr) {
443 assert(DiagStatesByLoc.empty() &&
444 "Leftover diag state from a different SourceManager.");
448 //===--------------------------------------------------------------------===//
449 // DiagnosticsEngine characterization methods, used by a client to customize
450 // how diagnostics are emitted.
453 /// \brief Copies the current DiagMappings and pushes the new copy
454 /// onto the top of the stack.
455 void pushMappings(SourceLocation Loc);
457 /// \brief Pops the current DiagMappings off the top of the stack,
458 /// causing the new top of the stack to be the active mappings.
460 /// \returns \c true if the pop happens, \c false if there is only one
461 /// DiagMapping on the stack.
462 bool popMappings(SourceLocation Loc);
464 /// \brief Set the diagnostic client associated with this diagnostic object.
466 /// \param ShouldOwnClient true if the diagnostic object should take
467 /// ownership of \c client.
468 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
470 /// \brief Specify a limit for the number of errors we should
471 /// emit before giving up.
473 /// Zero disables the limit.
474 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
476 /// \brief Specify the maximum number of template instantiation
477 /// notes to emit along with a given diagnostic.
478 void setTemplateBacktraceLimit(unsigned Limit) {
479 TemplateBacktraceLimit = Limit;
482 /// \brief Retrieve the maximum number of template instantiation
483 /// notes to emit along with a given diagnostic.
484 unsigned getTemplateBacktraceLimit() const {
485 return TemplateBacktraceLimit;
488 /// \brief Specify the maximum number of constexpr evaluation
489 /// notes to emit along with a given diagnostic.
490 void setConstexprBacktraceLimit(unsigned Limit) {
491 ConstexprBacktraceLimit = Limit;
494 /// \brief Retrieve the maximum number of constexpr evaluation
495 /// notes to emit along with a given diagnostic.
496 unsigned getConstexprBacktraceLimit() const {
497 return ConstexprBacktraceLimit;
500 /// \brief When set to true, any unmapped warnings are ignored.
502 /// If this and WarningsAsErrors are both set, then this one wins.
503 void setIgnoreAllWarnings(bool Val) {
504 GetCurDiagState()->IgnoreAllWarnings = Val;
506 bool getIgnoreAllWarnings() const {
507 return GetCurDiagState()->IgnoreAllWarnings;
510 /// \brief When set to true, any unmapped ignored warnings are no longer
513 /// If this and IgnoreAllWarnings are both set, then that one wins.
514 void setEnableAllWarnings(bool Val) {
515 GetCurDiagState()->EnableAllWarnings = Val;
517 bool getEnableAllWarnings() const {
518 return GetCurDiagState()->EnableAllWarnings;
521 /// \brief When set to true, any warnings reported are issued as errors.
522 void setWarningsAsErrors(bool Val) {
523 GetCurDiagState()->WarningsAsErrors = Val;
525 bool getWarningsAsErrors() const {
526 return GetCurDiagState()->WarningsAsErrors;
529 /// \brief When set to true, any error reported is made a fatal error.
530 void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
531 bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
533 /// \brief When set to true (the default), suppress further diagnostics after
535 void setSuppressAfterFatalError(bool Val) { SuppressAfterFatalError = Val; }
537 /// \brief When set to true mask warnings that come from system headers.
538 void setSuppressSystemWarnings(bool Val) {
539 GetCurDiagState()->SuppressSystemWarnings = Val;
541 bool getSuppressSystemWarnings() const {
542 return GetCurDiagState()->SuppressSystemWarnings;
545 /// \brief Suppress all diagnostics, to silence the front end when we
546 /// know that we don't want any more diagnostics to be passed along to the
548 void setSuppressAllDiagnostics(bool Val = true) {
549 SuppressAllDiagnostics = Val;
551 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
553 /// \brief Set type eliding, to skip outputting same types occurring in
555 void setElideType(bool Val = true) { ElideType = Val; }
556 bool getElideType() { return ElideType; }
558 /// \brief Set tree printing, to outputting the template difference in a
560 void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
561 bool getPrintTemplateTree() { return PrintTemplateTree; }
563 /// \brief Set color printing, so the type diffing will inject color markers
565 void setShowColors(bool Val = false) { ShowColors = Val; }
566 bool getShowColors() { return ShowColors; }
568 /// \brief Specify which overload candidates to show when overload resolution
571 /// By default, we show all candidates.
572 void setShowOverloads(OverloadsShown Val) {
575 OverloadsShown getShowOverloads() const { return ShowOverloads; }
577 /// \brief Pretend that the last diagnostic issued was ignored, so any
578 /// subsequent notes will be suppressed.
580 /// This can be used by clients who suppress diagnostics themselves.
581 void setLastDiagnosticIgnored() {
582 if (LastDiagLevel == DiagnosticIDs::Fatal)
583 FatalErrorOccurred = true;
584 LastDiagLevel = DiagnosticIDs::Ignored;
587 /// \brief Determine whether the previous diagnostic was ignored. This can
588 /// be used by clients that want to determine whether notes attached to a
589 /// diagnostic will be suppressed.
590 bool isLastDiagnosticIgnored() const {
591 return LastDiagLevel == DiagnosticIDs::Ignored;
594 /// \brief Controls whether otherwise-unmapped extension diagnostics are
595 /// mapped onto ignore/warning/error.
597 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
598 void setExtensionHandlingBehavior(diag::Severity H) {
599 GetCurDiagState()->ExtBehavior = H;
601 diag::Severity getExtensionHandlingBehavior() const {
602 return GetCurDiagState()->ExtBehavior;
605 /// \brief Counter bumped when an __extension__ block is/ encountered.
607 /// When non-zero, all extension diagnostics are entirely silenced, no
608 /// matter how they are mapped.
609 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
610 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
611 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
613 /// \brief This allows the client to specify that certain warnings are
616 /// Notes can never be mapped, errors can only be mapped to fatal, and
617 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
619 /// \param Loc The source location that this change of diagnostic state should
620 /// take affect. It can be null if we are setting the latest state.
621 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
623 /// \brief Change an entire diagnostic group (e.g. "unknown-pragmas") to
624 /// have the specified mapping.
626 /// \returns true (and ignores the request) if "Group" was unknown, false
629 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
630 /// state of the -Wfoo group and vice versa.
632 /// \param Loc The source location that this change of diagnostic state should
633 /// take affect. It can be null if we are setting the state from command-line.
634 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
636 SourceLocation Loc = SourceLocation());
638 /// \brief Set the warning-as-error flag for the given diagnostic group.
640 /// This function always only operates on the current diagnostic state.
642 /// \returns True if the given group is unknown, false otherwise.
643 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
645 /// \brief Set the error-as-fatal flag for the given diagnostic group.
647 /// This function always only operates on the current diagnostic state.
649 /// \returns True if the given group is unknown, false otherwise.
650 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
652 /// \brief Add the specified mapping to all diagnostics of the specified
655 /// Mainly to be used by -Wno-everything to disable all warnings but allow
656 /// subsequent -W options to enable specific warnings.
657 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
658 SourceLocation Loc = SourceLocation());
660 bool hasErrorOccurred() const { return ErrorOccurred; }
662 /// \brief Errors that actually prevent compilation, not those that are
663 /// upgraded from a warning by -Werror.
664 bool hasUncompilableErrorOccurred() const {
665 return UncompilableErrorOccurred;
667 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
669 /// \brief Determine whether any kind of unrecoverable error has occurred.
670 bool hasUnrecoverableErrorOccurred() const {
671 return FatalErrorOccurred || UnrecoverableErrorOccurred;
674 unsigned getNumWarnings() const { return NumWarnings; }
676 void setNumWarnings(unsigned NumWarnings) {
677 this->NumWarnings = NumWarnings;
680 /// \brief Return an ID for a diagnostic with the specified format string and
683 /// If this is the first request for this diagnostic, it is registered and
684 /// created, otherwise the existing ID is returned.
686 /// \param FormatString A fixed diagnostic format string that will be hashed
687 /// and mapped to a unique DiagID.
688 template <unsigned N>
689 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
690 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
691 StringRef(FormatString, N - 1));
694 /// \brief Converts a diagnostic argument (as an intptr_t) into the string
695 /// that represents it.
696 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
697 StringRef Modifier, StringRef Argument,
698 ArrayRef<ArgumentValue> PrevArgs,
699 SmallVectorImpl<char> &Output,
700 ArrayRef<intptr_t> QualTypeVals) const {
701 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
702 ArgToStringCookie, QualTypeVals);
705 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
707 ArgToStringCookie = Cookie;
710 /// \brief Note that the prior diagnostic was emitted by some other
711 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
712 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
713 LastDiagLevel = Other.LastDiagLevel;
716 /// \brief Reset the state of the diagnostic object to its initial
720 //===--------------------------------------------------------------------===//
721 // DiagnosticsEngine classification and reporting interfaces.
724 /// \brief Determine whether the diagnostic is known to be ignored.
726 /// This can be used to opportunistically avoid expensive checks when it's
727 /// known for certain that the diagnostic has been suppressed at the
728 /// specified location \p Loc.
730 /// \param Loc The source location we are interested in finding out the
731 /// diagnostic state. Can be null in order to query the latest state.
732 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
733 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
734 diag::Severity::Ignored;
737 /// \brief Based on the way the client configured the DiagnosticsEngine
738 /// object, classify the specified diagnostic ID into a Level, consumable by
739 /// the DiagnosticConsumer.
741 /// To preserve invariant assumptions, this function should not be used to
742 /// influence parse or semantic analysis actions. Instead consider using
745 /// \param Loc The source location we are interested in finding out the
746 /// diagnostic state. Can be null in order to query the latest state.
747 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
748 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
751 /// \brief Issue the message to the client.
753 /// This actually returns an instance of DiagnosticBuilder which emits the
754 /// diagnostics (through @c ProcessDiag) when it is destroyed.
756 /// \param DiagID A member of the @c diag::kind enum.
757 /// \param Loc Represents the source location associated with the diagnostic,
758 /// which can be an invalid location if no position information is available.
759 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
760 inline DiagnosticBuilder Report(unsigned DiagID);
762 void Report(const StoredDiagnostic &storedDiag);
764 /// \brief Determine whethere there is already a diagnostic in flight.
765 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
767 /// \brief Set the "delayed" diagnostic that will be emitted once
768 /// the current diagnostic completes.
770 /// If a diagnostic is already in-flight but the front end must
771 /// report a problem (e.g., with an inconsistent file system
772 /// state), this routine sets a "delayed" diagnostic that will be
773 /// emitted after the current diagnostic completes. This should
774 /// only be used for fatal errors detected at inconvenient
775 /// times. If emitting a delayed diagnostic causes a second delayed
776 /// diagnostic to be introduced, that second delayed diagnostic
779 /// \param DiagID The ID of the diagnostic being delayed.
781 /// \param Arg1 A string argument that will be provided to the
782 /// diagnostic. A copy of this string will be stored in the
783 /// DiagnosticsEngine object itself.
785 /// \param Arg2 A string argument that will be provided to the
786 /// diagnostic. A copy of this string will be stored in the
787 /// DiagnosticsEngine object itself.
788 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
789 StringRef Arg2 = "");
791 /// \brief Clear out the current diagnostic.
792 void Clear() { CurDiagID = ~0U; }
794 /// \brief Return the value associated with this diagnostic flag.
795 StringRef getFlagValue() const { return FlagValue; }
798 /// \brief Report the delayed diagnostic.
799 void ReportDelayed();
801 // This is private state used by DiagnosticBuilder. We put it here instead of
802 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
803 // object. This implementation choice means that we can only have one
804 // diagnostic "in flight" at a time, but this seems to be a reasonable
805 // tradeoff to keep these objects small. Assertions verify that only one
806 // diagnostic is in flight at a time.
807 friend class DiagnosticIDs;
808 friend class DiagnosticBuilder;
809 friend class Diagnostic;
810 friend class PartialDiagnostic;
811 friend class DiagnosticErrorTrap;
813 /// \brief The location of the current diagnostic that is in flight.
814 SourceLocation CurDiagLoc;
816 /// \brief The ID of the current diagnostic that is in flight.
818 /// This is set to ~0U when there is no diagnostic in flight.
822 /// \brief The maximum number of arguments we can hold.
824 /// We currently only support up to 10 arguments (%0-%9). A single
825 /// diagnostic with more than that almost certainly has to be simplified
830 /// \brief The number of entries in Arguments.
831 signed char NumDiagArgs;
833 /// \brief Specifies whether an argument is in DiagArgumentsStr or
834 /// in DiagArguments.
836 /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
838 unsigned char DiagArgumentsKind[MaxArguments];
840 /// \brief Holds the values of each string argument for the current
843 /// This is only used when the corresponding ArgumentKind is ak_std_string.
844 std::string DiagArgumentsStr[MaxArguments];
846 /// \brief The values for the various substitution positions.
848 /// This is used when the argument is not an std::string. The specific
849 /// value is mangled into an intptr_t and the interpretation depends on
850 /// exactly what sort of argument kind it is.
851 intptr_t DiagArgumentsVal[MaxArguments];
853 /// \brief The list of ranges added to this diagnostic.
854 SmallVector<CharSourceRange, 8> DiagRanges;
856 /// \brief If valid, provides a hint with some code to insert, remove,
857 /// or modify at a particular position.
858 SmallVector<FixItHint, 8> DiagFixItHints;
860 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
861 bool isPragma = L.isValid();
862 DiagnosticMapping Mapping =
863 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
865 // If this is a pragma mapping, then set the diagnostic mapping flags so
866 // that we override command line options.
868 Mapping.setNoWarningAsError(true);
869 Mapping.setNoErrorAsFatal(true);
875 /// \brief Used to report a diagnostic that is finally fully formed.
877 /// \returns true if the diagnostic was emitted, false if it was suppressed.
879 return Diags->ProcessDiag(*this);
882 /// @name Diagnostic Emission
885 // Sema requires access to the following functions because the current design
886 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
887 // access us directly to ensure we minimize the emitted code for the common
888 // Sema::Diag() patterns.
891 /// \brief Emit the current diagnostic and clear the diagnostic state.
893 /// \param Force Emit the diagnostic regardless of suppression settings.
894 bool EmitCurrentDiagnostic(bool Force = false);
896 unsigned getCurrentDiagID() const { return CurDiagID; }
898 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
902 friend class ASTReader;
903 friend class ASTWriter;
906 /// \brief RAII class that determines when any errors have occurred
907 /// between the time the instance was created and the time it was
909 class DiagnosticErrorTrap {
910 DiagnosticsEngine &Diag;
912 unsigned NumUnrecoverableErrors;
915 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
916 : Diag(Diag) { reset(); }
918 /// \brief Determine whether any errors have occurred since this
919 /// object instance was created.
920 bool hasErrorOccurred() const {
921 return Diag.TrapNumErrorsOccurred > NumErrors;
924 /// \brief Determine whether any unrecoverable errors have occurred since this
925 /// object instance was created.
926 bool hasUnrecoverableErrorOccurred() const {
927 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
930 /// \brief Set to initial state of "no errors occurred".
932 NumErrors = Diag.TrapNumErrorsOccurred;
933 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
937 //===----------------------------------------------------------------------===//
939 //===----------------------------------------------------------------------===//
941 /// \brief A little helper class used to produce diagnostics.
943 /// This is constructed by the DiagnosticsEngine::Report method, and
944 /// allows insertion of extra information (arguments and source ranges) into
945 /// the currently "in flight" diagnostic. When the temporary for the builder
946 /// is destroyed, the diagnostic is issued.
948 /// Note that many of these will be created as temporary objects (many call
949 /// sites), so we want them to be small and we never want their address taken.
950 /// This ensures that compilers with somewhat reasonable optimizers will promote
951 /// the common fields to registers, eliminating increments of the NumArgs field,
953 class DiagnosticBuilder {
954 mutable DiagnosticsEngine *DiagObj = nullptr;
955 mutable unsigned NumArgs = 0;
957 /// \brief Status variable indicating if this diagnostic is still active.
959 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
960 // but LLVM is not currently smart enough to eliminate the null check that
961 // Emit() would end up with if we used that as our status variable.
962 mutable bool IsActive = false;
964 /// \brief Flag indicating that this diagnostic is being emitted via a
965 /// call to ForceEmit.
966 mutable bool IsForceEmit = false;
968 friend class DiagnosticsEngine;
970 DiagnosticBuilder() = default;
972 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
973 : DiagObj(diagObj), IsActive(true) {
974 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
975 diagObj->DiagRanges.clear();
976 diagObj->DiagFixItHints.clear();
979 friend class PartialDiagnostic;
983 DiagObj->NumDiagArgs = NumArgs;
986 /// \brief Clear out the current diagnostic.
993 /// \brief Determine whether this diagnostic is still active.
994 bool isActive() const { return IsActive; }
996 /// \brief Force the diagnostic builder to emit the diagnostic now.
998 /// Once this function has been called, the DiagnosticBuilder object
999 /// should not be used again before it is destroyed.
1001 /// \returns true if a diagnostic was emitted, false if the
1002 /// diagnostic was suppressed.
1004 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1005 // (or by a subclass, as in SemaDiagnosticBuilder).
1006 if (!isActive()) return false;
1008 // When emitting diagnostics, we set the final argument count into
1009 // the DiagnosticsEngine object.
1012 // Process the diagnostic.
1013 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
1015 // This diagnostic is dead.
1022 /// Copy constructor. When copied, this "takes" the diagnostic info from the
1023 /// input and neuters it.
1024 DiagnosticBuilder(const DiagnosticBuilder &D) {
1025 DiagObj = D.DiagObj;
1026 IsActive = D.IsActive;
1027 IsForceEmit = D.IsForceEmit;
1029 NumArgs = D.NumArgs;
1032 DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1034 /// \brief Emits the diagnostic.
1035 ~DiagnosticBuilder() {
1039 /// \brief Retrieve an empty diagnostic builder.
1040 static DiagnosticBuilder getEmpty() {
1041 return DiagnosticBuilder();
1044 /// \brief Forces the diagnostic to be emitted.
1045 const DiagnosticBuilder &setForceEmit() const {
1050 /// \brief Conversion of DiagnosticBuilder to bool always returns \c true.
1052 /// This allows is to be used in boolean error contexts (where \c true is
1053 /// used to indicate that an error has occurred), like:
1055 /// return Diag(...);
1057 operator bool() const { return true; }
1059 void AddString(StringRef S) const {
1060 assert(isActive() && "Clients must not add to cleared diagnostic!");
1061 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1062 "Too many arguments to diagnostic!");
1063 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
1064 DiagObj->DiagArgumentsStr[NumArgs++] = S;
1067 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1068 assert(isActive() && "Clients must not add to cleared diagnostic!");
1069 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1070 "Too many arguments to diagnostic!");
1071 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
1072 DiagObj->DiagArgumentsVal[NumArgs++] = V;
1075 void AddSourceRange(const CharSourceRange &R) const {
1076 assert(isActive() && "Clients must not add to cleared diagnostic!");
1077 DiagObj->DiagRanges.push_back(R);
1080 void AddFixItHint(const FixItHint &Hint) const {
1081 assert(isActive() && "Clients must not add to cleared diagnostic!");
1083 DiagObj->DiagFixItHints.push_back(Hint);
1086 void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
1089 struct AddFlagValue {
1090 explicit AddFlagValue(StringRef V) : Val(V) {}
1094 /// \brief Register a value for the flag in the current diagnostic. This
1095 /// value will be shown as the suffix "=value" after the flag name. It is
1096 /// useful in cases where the diagnostic flag accepts values (e.g.,
1097 /// -Rpass or -Wframe-larger-than).
1098 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1099 const AddFlagValue V) {
1100 DB.addFlagValue(V.Val);
1104 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1110 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1112 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1113 DiagnosticsEngine::ak_c_string);
1117 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
1118 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1122 // We use enable_if here to prevent that this overload is selected for
1123 // pointers or other arguments that are implicitly convertible to bool.
1124 template <typename T>
1126 typename std::enable_if<std::is_same<T, bool>::value,
1127 const DiagnosticBuilder &>::type
1128 operator<<(const DiagnosticBuilder &DB, T I) {
1129 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1133 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1135 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1139 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1141 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1145 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1146 const IdentifierInfo *II) {
1147 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1148 DiagnosticsEngine::ak_identifierinfo);
1152 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
1153 // so that we only match those arguments that are (statically) DeclContexts;
1154 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
1156 template <typename T>
1157 inline typename std::enable_if<
1158 std::is_same<typename std::remove_const<T>::type, DeclContext>::value,
1159 const DiagnosticBuilder &>::type
1160 operator<<(const DiagnosticBuilder &DB, T *DC) {
1161 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1162 DiagnosticsEngine::ak_declcontext);
1166 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1168 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1172 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1173 ArrayRef<SourceRange> Ranges) {
1174 for (SourceRange R : Ranges)
1175 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1179 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1180 const CharSourceRange &R) {
1181 DB.AddSourceRange(R);
1185 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1186 const FixItHint &Hint) {
1187 DB.AddFixItHint(Hint);
1191 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1192 ArrayRef<FixItHint> Hints) {
1193 for (const FixItHint &Hint : Hints)
1194 DB.AddFixItHint(Hint);
1198 /// A nullability kind paired with a bit indicating whether it used a
1199 /// context-sensitive keyword.
1200 typedef std::pair<NullabilityKind, bool> DiagNullabilityKind;
1202 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1203 DiagNullabilityKind nullability);
1205 inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1207 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
1211 return DiagnosticBuilder(this);
1214 inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1215 return Report(SourceLocation(), DiagID);
1218 //===----------------------------------------------------------------------===//
1220 //===----------------------------------------------------------------------===//
1222 /// A little helper class (which is basically a smart pointer that forwards
1223 /// info from DiagnosticsEngine) that allows clients to enquire about the
1224 /// currently in-flight diagnostic.
1226 const DiagnosticsEngine *DiagObj;
1227 StringRef StoredDiagMessage;
1230 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1231 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1232 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1234 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1235 unsigned getID() const { return DiagObj->CurDiagID; }
1236 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1237 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1238 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1240 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1242 /// \brief Return the kind of the specified index.
1244 /// Based on the kind of argument, the accessors below can be used to get
1247 /// \pre Idx < getNumArgs()
1248 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1249 assert(Idx < getNumArgs() && "Argument index out of range!");
1250 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1253 /// \brief Return the provided argument string specified by \p Idx.
1254 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1255 const std::string &getArgStdStr(unsigned Idx) const {
1256 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1257 "invalid argument accessor!");
1258 return DiagObj->DiagArgumentsStr[Idx];
1261 /// \brief Return the specified C string argument.
1262 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1263 const char *getArgCStr(unsigned Idx) const {
1264 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1265 "invalid argument accessor!");
1266 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1269 /// \brief Return the specified signed integer argument.
1270 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1271 int getArgSInt(unsigned Idx) const {
1272 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1273 "invalid argument accessor!");
1274 return (int)DiagObj->DiagArgumentsVal[Idx];
1277 /// \brief Return the specified unsigned integer argument.
1278 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1279 unsigned getArgUInt(unsigned Idx) const {
1280 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1281 "invalid argument accessor!");
1282 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1285 /// \brief Return the specified IdentifierInfo argument.
1286 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1287 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1288 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1289 "invalid argument accessor!");
1290 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1293 /// \brief Return the specified non-string argument in an opaque form.
1294 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1295 intptr_t getRawArg(unsigned Idx) const {
1296 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1297 "invalid argument accessor!");
1298 return DiagObj->DiagArgumentsVal[Idx];
1301 /// \brief Return the number of source ranges associated with this diagnostic.
1302 unsigned getNumRanges() const {
1303 return DiagObj->DiagRanges.size();
1306 /// \pre Idx < getNumRanges()
1307 const CharSourceRange &getRange(unsigned Idx) const {
1308 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1309 return DiagObj->DiagRanges[Idx];
1312 /// \brief Return an array reference for this diagnostic's ranges.
1313 ArrayRef<CharSourceRange> getRanges() const {
1314 return DiagObj->DiagRanges;
1317 unsigned getNumFixItHints() const {
1318 return DiagObj->DiagFixItHints.size();
1321 const FixItHint &getFixItHint(unsigned Idx) const {
1322 assert(Idx < getNumFixItHints() && "Invalid index!");
1323 return DiagObj->DiagFixItHints[Idx];
1326 ArrayRef<FixItHint> getFixItHints() const {
1327 return DiagObj->DiagFixItHints;
1330 /// \brief Format this diagnostic into a string, substituting the
1331 /// formal arguments into the %0 slots.
1333 /// The result is appended onto the \p OutStr array.
1334 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1336 /// \brief Format the given format-string into the output buffer using the
1337 /// arguments stored in this diagnostic.
1338 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1339 SmallVectorImpl<char> &OutStr) const;
1343 * \brief Represents a diagnostic in a form that can be retained until its
1344 * corresponding source manager is destroyed.
1346 class StoredDiagnostic {
1348 DiagnosticsEngine::Level Level;
1350 std::string Message;
1351 std::vector<CharSourceRange> Ranges;
1352 std::vector<FixItHint> FixIts;
1355 StoredDiagnostic() = default;
1356 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1357 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1359 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1360 StringRef Message, FullSourceLoc Loc,
1361 ArrayRef<CharSourceRange> Ranges,
1362 ArrayRef<FixItHint> Fixits);
1364 /// \brief Evaluates true when this object stores a diagnostic.
1365 explicit operator bool() const { return !Message.empty(); }
1367 unsigned getID() const { return ID; }
1368 DiagnosticsEngine::Level getLevel() const { return Level; }
1369 const FullSourceLoc &getLocation() const { return Loc; }
1370 StringRef getMessage() const { return Message; }
1372 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1374 typedef std::vector<CharSourceRange>::const_iterator range_iterator;
1375 range_iterator range_begin() const { return Ranges.begin(); }
1376 range_iterator range_end() const { return Ranges.end(); }
1377 unsigned range_size() const { return Ranges.size(); }
1379 ArrayRef<CharSourceRange> getRanges() const {
1380 return llvm::makeArrayRef(Ranges);
1383 typedef std::vector<FixItHint>::const_iterator fixit_iterator;
1384 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1385 fixit_iterator fixit_end() const { return FixIts.end(); }
1386 unsigned fixit_size() const { return FixIts.size(); }
1388 ArrayRef<FixItHint> getFixIts() const {
1389 return llvm::makeArrayRef(FixIts);
1393 /// \brief Abstract interface, implemented by clients of the front-end, which
1394 /// formats and prints fully processed diagnostics.
1395 class DiagnosticConsumer {
1397 unsigned NumWarnings = 0; ///< Number of warnings reported
1398 unsigned NumErrors = 0; ///< Number of errors reported
1401 DiagnosticConsumer() = default;
1403 virtual ~DiagnosticConsumer();
1405 unsigned getNumErrors() const { return NumErrors; }
1406 unsigned getNumWarnings() const { return NumWarnings; }
1407 virtual void clear() { NumWarnings = NumErrors = 0; }
1409 /// \brief Callback to inform the diagnostic client that processing
1410 /// of a source file is beginning.
1412 /// Note that diagnostics may be emitted outside the processing of a source
1413 /// file, for example during the parsing of command line options. However,
1414 /// diagnostics with source range information are required to only be emitted
1415 /// in between BeginSourceFile() and EndSourceFile().
1417 /// \param LangOpts The language options for the source file being processed.
1418 /// \param PP The preprocessor object being used for the source; this is
1419 /// optional, e.g., it may not be present when processing AST source files.
1420 virtual void BeginSourceFile(const LangOptions &LangOpts,
1421 const Preprocessor *PP = nullptr) {}
1423 /// \brief Callback to inform the diagnostic client that processing
1424 /// of a source file has ended.
1426 /// The diagnostic client should assume that any objects made available via
1427 /// BeginSourceFile() are inaccessible.
1428 virtual void EndSourceFile() {}
1430 /// \brief Callback to inform the diagnostic client that processing of all
1431 /// source files has ended.
1432 virtual void finish() {}
1434 /// \brief Indicates whether the diagnostics handled by this
1435 /// DiagnosticConsumer should be included in the number of diagnostics
1436 /// reported by DiagnosticsEngine.
1438 /// The default implementation returns true.
1439 virtual bool IncludeInDiagnosticCounts() const;
1441 /// \brief Handle this diagnostic, reporting it to the user or
1442 /// capturing it to a log as needed.
1444 /// The default implementation just keeps track of the total number of
1445 /// warnings and errors.
1446 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1447 const Diagnostic &Info);
1450 /// \brief A diagnostic client that ignores all diagnostics.
1451 class IgnoringDiagConsumer : public DiagnosticConsumer {
1452 virtual void anchor();
1454 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1455 const Diagnostic &Info) override {
1460 /// \brief Diagnostic consumer that forwards diagnostics along to an
1461 /// existing, already-initialized diagnostic consumer.
1463 class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1464 DiagnosticConsumer &Target;
1467 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1469 ~ForwardingDiagnosticConsumer() override;
1471 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1472 const Diagnostic &Info) override;
1473 void clear() override;
1475 bool IncludeInDiagnosticCounts() const override;
1478 // Struct used for sending info about how a type should be printed.
1479 struct TemplateDiffTypes {
1482 unsigned PrintTree : 1;
1483 unsigned PrintFromType : 1;
1484 unsigned ElideType : 1;
1485 unsigned ShowColors : 1;
1486 // The printer sets this variable to true if the template diff was used.
1487 unsigned TemplateDiffUsed : 1;
1490 /// Special character that the diagnostic printer will use to toggle the bold
1491 /// attribute. The character itself will be not be printed.
1492 const char ToggleHighlight = 127;
1495 /// ProcessWarningOptions - Initialize the diagnostic client and process the
1496 /// warning options specified on the command line.
1497 void ProcessWarningOptions(DiagnosticsEngine &Diags,
1498 const DiagnosticOptions &Opts,
1499 bool ReportDiags = true);
1501 } // end namespace clang
1503 #endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H