Skip to main content

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