core/panic/panic_info.rs
1use crate::fmt::{self, Display};
2use crate::panic::Location;
3
4/// A struct providing information about a panic.
5///
6/// A `PanicInfo` structure is passed to the panic handler defined by `#[panic_handler]`.
7///
8/// For the type used by the panic hook mechanism in `std`, see [`std::panic::PanicHookInfo`].
9///
10/// [`std::panic::PanicHookInfo`]: ../../std/panic/struct.PanicHookInfo.html
11#[lang = "panic_info"]
12#[stable(feature = "panic_hooks", since = "1.10.0")]
13#[derive(Debug)]
14#[cfg_attr(feature = "ferrocene_subset", expect(dead_code))]
15pub struct PanicInfo<'a> {
16 message: &'a fmt::Arguments<'a>,
17 location: &'a Location<'a>,
18 can_unwind: bool,
19 force_no_backtrace: bool,
20}
21
22/// A message that was given to the `panic!()` macro.
23///
24/// The [`Display`] implementation of this type will format the message with the arguments
25/// that were given to the `panic!()` macro.
26///
27/// See [`PanicInfo::message`].
28#[stable(feature = "panic_info_message", since = "1.81.0")]
29pub struct PanicMessage<'a> {
30 message: &'a fmt::Arguments<'a>,
31}
32
33impl<'a> PanicInfo<'a> {
34 #[inline]
35 pub(crate) fn new(
36 message: &'a fmt::Arguments<'a>,
37 location: &'a Location<'a>,
38 can_unwind: bool,
39 force_no_backtrace: bool,
40 ) -> Self {
41 PanicInfo { location, message, can_unwind, force_no_backtrace }
42 }
43
44 /// The message that was given to the `panic!` macro.
45 ///
46 /// # Example
47 ///
48 /// The type returned by this method implements `Display`, so it can
49 /// be passed directly to [`write!()`] and similar macros.
50 ///
51 /// [`write!()`]: core::write
52 ///
53 /// ```ignore (no_std)
54 /// #[panic_handler]
55 /// fn panic_handler(panic_info: &PanicInfo<'_>) -> ! {
56 /// write!(DEBUG_OUTPUT, "panicked: {}", panic_info.message());
57 /// loop {}
58 /// }
59 /// ```
60 #[must_use]
61 #[stable(feature = "panic_info_message", since = "1.81.0")]
62 pub fn message(&self) -> PanicMessage<'_> {
63 PanicMessage { message: self.message }
64 }
65
66 /// Returns information about the location from which the panic originated,
67 /// if available.
68 ///
69 /// This method will currently always return [`Some`], but this may change
70 /// in future versions.
71 ///
72 /// # Examples
73 ///
74 /// ```should_panic
75 /// use std::panic;
76 ///
77 /// panic::set_hook(Box::new(|panic_info| {
78 /// if let Some(location) = panic_info.location() {
79 /// println!("panic occurred in file '{}' at line {}",
80 /// location.file(),
81 /// location.line(),
82 /// );
83 /// } else {
84 /// println!("panic occurred but can't get location information...");
85 /// }
86 /// }));
87 ///
88 /// panic!("Normal panic");
89 /// ```
90 #[must_use]
91 #[stable(feature = "panic_hooks", since = "1.10.0")]
92 pub fn location(&self) -> Option<&Location<'_>> {
93 // NOTE: If this is changed to sometimes return None,
94 // deal with that case in std::panicking::default_hook and core::panicking::panic_fmt.
95 Some(&self.location)
96 }
97
98 /// Returns the payload associated with the panic.
99 ///
100 /// On this type, `core::panic::PanicInfo`, this method never returns anything useful.
101 /// It only exists because of compatibility with [`std::panic::PanicHookInfo`],
102 /// which used to be the same type.
103 ///
104 /// See [`std::panic::PanicHookInfo::payload`].
105 ///
106 /// [`std::panic::PanicHookInfo`]: ../../std/panic/struct.PanicHookInfo.html
107 /// [`std::panic::PanicHookInfo::payload`]: ../../std/panic/struct.PanicHookInfo.html#method.payload
108 #[deprecated(since = "1.81.0", note = "this never returns anything useful")]
109 #[stable(feature = "panic_hooks", since = "1.10.0")]
110 #[allow(deprecated, deprecated_in_future)]
111 #[cfg(not(feature = "ferrocene_subset"))]
112 pub fn payload(&self) -> &(dyn crate::any::Any + Send) {
113 struct NoPayload;
114 &NoPayload
115 }
116
117 /// Returns whether the panic handler is allowed to unwind the stack from
118 /// the point where the panic occurred.
119 ///
120 /// This is true for most kinds of panics with the exception of panics
121 /// caused by trying to unwind out of a `Drop` implementation or a function
122 /// whose ABI does not support unwinding.
123 ///
124 /// It is safe for a panic handler to unwind even when this function returns
125 /// false, however this will simply cause the panic handler to be called
126 /// again.
127 #[must_use]
128 #[unstable(feature = "panic_can_unwind", issue = "92988")]
129 #[cfg(not(feature = "ferrocene_subset"))]
130 pub fn can_unwind(&self) -> bool {
131 self.can_unwind
132 }
133
134 #[unstable(
135 feature = "panic_internals",
136 reason = "internal details of the implementation of the `panic!` and related macros",
137 issue = "none"
138 )]
139 #[doc(hidden)]
140 #[inline]
141 #[cfg(not(feature = "ferrocene_subset"))]
142 pub fn force_no_backtrace(&self) -> bool {
143 self.force_no_backtrace
144 }
145}
146
147#[stable(feature = "panic_hook_display", since = "1.26.0")]
148impl Display for PanicInfo<'_> {
149 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
150 formatter.write_str("panicked at ")?;
151 self.location.fmt(formatter)?;
152 formatter.write_str(":\n")?;
153 formatter.write_fmt(*self.message)?;
154 Ok(())
155 }
156}
157
158impl<'a> PanicMessage<'a> {
159 /// Gets the formatted message, if it has no arguments to be formatted at runtime.
160 ///
161 /// This can be used to avoid allocations in some cases.
162 ///
163 /// # Guarantees
164 ///
165 /// For `panic!("just a literal")`, this function is guaranteed to
166 /// return `Some("just a literal")`.
167 ///
168 /// For most cases with placeholders, this function will return `None`.
169 ///
170 /// See [`fmt::Arguments::as_str`] for details.
171 #[stable(feature = "panic_info_message", since = "1.81.0")]
172 #[rustc_const_stable(feature = "const_arguments_as_str", since = "1.84.0")]
173 #[must_use]
174 #[inline]
175 pub const fn as_str(&self) -> Option<&'static str> {
176 self.message.as_str()
177 }
178}
179
180#[stable(feature = "panic_info_message", since = "1.81.0")]
181impl Display for PanicMessage<'_> {
182 #[inline]
183 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
184 formatter.write_fmt(*self.message)
185 }
186}
187
188#[stable(feature = "panic_info_message", since = "1.81.0")]
189impl fmt::Debug for PanicMessage<'_> {
190 #[inline]
191 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
192 formatter.write_fmt(*self.message)
193 }
194}