core/
panic.rs

1//! Panic support in the standard library.
2
3#![stable(feature = "core_panic_info", since = "1.41.0")]
4
5mod location;
6mod panic_info;
7#[cfg(not(feature = "ferrocene_subset"))]
8mod unwind_safe;
9
10#[stable(feature = "panic_hooks", since = "1.10.0")]
11pub use self::location::Location;
12#[stable(feature = "panic_hooks", since = "1.10.0")]
13pub use self::panic_info::PanicInfo;
14#[stable(feature = "panic_info_message", since = "1.81.0")]
15pub use self::panic_info::PanicMessage;
16#[stable(feature = "catch_unwind", since = "1.9.0")]
17#[cfg(not(feature = "ferrocene_subset"))]
18pub use self::unwind_safe::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe};
19#[cfg(not(feature = "ferrocene_subset"))]
20use crate::any::Any;
21
22// Ferrocene addition: avoid depending in fmt
23#[doc(hidden)]
24#[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
25#[allow_internal_unstable(panic_internals, const_format_args)]
26#[rustc_diagnostic_item = "core_panic_2015_macro"]
27#[rustc_macro_transparency = "semitransparent"]
28#[cfg(feature = "ferrocene_certified_runtime")]
29pub macro panic_2015($($t:tt)*) {{ $crate::panicking::panic("explicit panic") }}
30
31#[doc(hidden)]
32#[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
33#[allow_internal_unstable(panic_internals, const_format_args)]
34#[rustc_diagnostic_item = "core_panic_2015_macro"]
35#[rustc_macro_transparency = "semitransparent"]
36#[cfg(not(feature = "ferrocene_certified_runtime"))]
37pub macro panic_2015 {
38    () => (
39        $crate::panicking::panic("explicit panic")
40    ),
41    ($msg:literal $(,)?) => (
42        $crate::panicking::panic($msg)
43    ),
44    // Use `panic_str_2015` instead of `panic_display::<&str>` for non_fmt_panic lint.
45    ($msg:expr $(,)?) => ({
46        $crate::panicking::panic_str_2015($msg);
47    }),
48    // Special-case the single-argument case for const_panic.
49    ("{}", $arg:expr $(,)?) => ({
50        $crate::panicking::panic_display(&$arg);
51    }),
52    ($fmt:expr, $($arg:tt)+) => ({
53        // Semicolon to prevent temporaries inside the formatting machinery from
54        // being considered alive in the caller after the panic_fmt call.
55        $crate::panicking::panic_fmt($crate::const_format_args!($fmt, $($arg)+));
56    }),
57}
58
59// Ferrocene addition: avoid depending in fmt
60#[doc(hidden)]
61#[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
62#[allow_internal_unstable(panic_internals, const_format_args)]
63#[rustc_diagnostic_item = "core_panic_2021_macro"]
64#[rustc_macro_transparency = "semitransparent"]
65#[cfg(feature = "ferrocene_certified_runtime")]
66pub macro panic_2021($($t:tt)*) {{ $crate::panicking::panic("explicit panic") }}
67
68#[doc(hidden)]
69#[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")]
70#[allow_internal_unstable(panic_internals, const_format_args)]
71#[rustc_diagnostic_item = "core_panic_2021_macro"]
72#[rustc_macro_transparency = "semitransparent"]
73#[cfg(not(feature = "ferrocene_certified_runtime"))]
74pub macro panic_2021 {
75    () => (
76        $crate::panicking::panic("explicit panic")
77    ),
78    // Special-case the single-argument case for const_panic.
79    ("{}", $arg:expr $(,)?) => ({
80        $crate::panicking::panic_display(&$arg);
81    }),
82    ($($t:tt)+) => ({
83        // Semicolon to prevent temporaries inside the formatting machinery from
84        // being considered alive in the caller after the panic_fmt call.
85        $crate::panicking::panic_fmt($crate::const_format_args!($($t)+));
86    }),
87}
88
89// Ferrocene addition: avoid depending in fmt
90#[doc(hidden)]
91#[unstable(feature = "edition_panic", issue = "none", reason = "use unreachable!() instead")]
92#[allow_internal_unstable(panic_internals)]
93#[rustc_diagnostic_item = "unreachable_2015_macro"]
94#[rustc_macro_transparency = "semitransparent"]
95#[cfg(feature = "ferrocene_certified_runtime")]
96pub macro unreachable_2015 {
97    ($($t:tt)*) => (
98        $crate::panicking::panic("internal error: entered unreachable code")
99    ),
100}
101
102#[doc(hidden)]
103#[unstable(feature = "edition_panic", issue = "none", reason = "use unreachable!() instead")]
104#[allow_internal_unstable(panic_internals)]
105#[rustc_diagnostic_item = "unreachable_2015_macro"]
106#[rustc_macro_transparency = "semitransparent"]
107#[cfg(not(feature = "ferrocene_certified_runtime"))]
108pub macro unreachable_2015 {
109    () => (
110        $crate::panicking::panic("internal error: entered unreachable code")
111    ),
112    // Use of `unreachable_display` for non_fmt_panic lint.
113    // NOTE: the message ("internal error ...") is embedded directly in unreachable_display
114    ($msg:expr $(,)?) => ({
115        $crate::panicking::unreachable_display(&$msg);
116    }),
117    ($fmt:expr, $($arg:tt)*) => (
118        $crate::panic!($crate::concat!("internal error: entered unreachable code: ", $fmt), $($arg)*)
119    ),
120}
121
122// Ferrocene addition: avoid depending in fmt
123#[doc(hidden)]
124#[unstable(feature = "edition_panic", issue = "none", reason = "use unreachable!() instead")]
125#[allow_internal_unstable(panic_internals)]
126#[rustc_macro_transparency = "semitransparent"]
127#[cfg(feature = "ferrocene_certified_runtime")]
128pub macro unreachable_2021 {
129    ($($t:tt)*) => (
130        $crate::panicking::panic("internal error: entered unreachable code")
131    ),
132}
133
134#[doc(hidden)]
135#[unstable(feature = "edition_panic", issue = "none", reason = "use unreachable!() instead")]
136#[allow_internal_unstable(panic_internals)]
137#[rustc_macro_transparency = "semitransparent"]
138#[cfg(not(feature = "ferrocene_certified_runtime"))]
139pub macro unreachable_2021 {
140    () => (
141        $crate::panicking::panic("internal error: entered unreachable code")
142    ),
143    ($($t:tt)+) => (
144        $crate::panic!("internal error: entered unreachable code: {}", $crate::format_args!($($t)+))
145    ),
146}
147
148/// Invokes a closure, aborting if the closure unwinds.
149///
150/// When compiled with aborting panics, this function is effectively a no-op.
151/// With unwinding panics, an unwind results in another call into the panic
152/// hook followed by a process abort.
153///
154/// # Notes
155///
156/// Instead of using this function, code should attempt to support unwinding.
157/// Implementing [`Drop`] allows you to restore invariants uniformly in both
158/// return and unwind paths.
159///
160/// If an unwind can lead to logical issues but not soundness issues, you
161/// should allow the unwind. Opting out of [`UnwindSafe`] indicates to your
162/// consumers that they need to consider correctness in the face of unwinds.
163///
164/// If an unwind would be unsound, then this function should be used in order
165/// to prevent unwinds. However, note that `extern "C" fn` will automatically
166/// convert unwinds to aborts, so using this function isn't necessary for FFI.
167#[unstable(feature = "abort_unwind", issue = "130338")]
168#[rustc_nounwind]
169#[cfg(not(feature = "ferrocene_subset"))]
170pub fn abort_unwind<F: FnOnce() -> R, R>(f: F) -> R {
171    f()
172}
173
174/// An internal trait used by std to pass data from std to `panic_unwind` and
175/// other panic runtimes. Not intended to be stabilized any time soon, do not
176/// use.
177#[unstable(feature = "std_internals", issue = "none")]
178#[doc(hidden)]
179#[cfg(not(feature = "ferrocene_subset"))]
180pub unsafe trait PanicPayload: crate::fmt::Display {
181    /// Take full ownership of the contents.
182    /// The return type is actually `Box<dyn Any + Send>`, but we cannot use `Box` in core.
183    ///
184    /// After this method got called, only some dummy default value is left in `self`.
185    /// Calling this method twice, or calling `get` after calling this method, is an error.
186    ///
187    /// The argument is borrowed because the panic runtime (`__rust_start_panic`) only
188    /// gets a borrowed `dyn PanicPayload`.
189    fn take_box(&mut self) -> *mut (dyn Any + Send);
190
191    /// Just borrow the contents.
192    fn get(&mut self) -> &(dyn Any + Send);
193
194    /// Tries to borrow the contents as `&str`, if possible without doing any allocations.
195    fn as_str(&mut self) -> Option<&str> {
196        None
197    }
198}
199
200/// Helper macro for panicking in a `const fn`.
201/// Invoke as:
202/// ```rust,ignore (just an example)
203/// core::macros::const_panic!("boring message", "flavored message {a} {b:?}", a: u32 = foo.len(), b: Something = bar);
204/// ```
205/// where the first message will be printed in const-eval,
206/// and the second message will be printed at runtime.
207// All uses of this macro are FIXME(const-hack).
208#[unstable(feature = "panic_internals", issue = "none")]
209#[doc(hidden)]
210pub macro const_panic {
211    ($const_msg:literal, $runtime_msg:literal, $($arg:ident : $ty:ty = $val:expr),* $(,)?) => {{
212        // Wrap call to `const_eval_select` in a function so that we can
213        // add the `rustc_allow_const_fn_unstable`. This is okay to do
214        // because both variants will panic, just with different messages.
215        #[rustc_allow_const_fn_unstable(const_eval_select)]
216        #[inline(always)] // inline the wrapper
217        #[track_caller]
218        // Ferrocene addition: otherwise "unused variable" errors
219        #[cfg_attr(feature = "ferrocene_certified_runtime", expect(unused_variables))]
220        const fn do_panic($($arg: $ty),*) -> ! {
221            $crate::intrinsics::const_eval_select!(
222                @capture { $($arg: $ty = $arg),* } -> !:
223                #[noinline]
224                if const #[track_caller] #[inline] { // Inline this, to prevent codegen
225                    $crate::panic!($const_msg)
226                } else #[track_caller] { // Do not inline this, it makes perf worse
227                    $crate::panic!($runtime_msg)
228                }
229            )
230        }
231
232        do_panic($($val),*)
233    }},
234    // We support leaving away the `val` expressions for *all* arguments
235    // (but not for *some* arguments, that's too tricky).
236    ($const_msg:literal, $runtime_msg:literal, $($arg:ident : $ty:ty),* $(,)?) => {
237        $crate::panic::const_panic!(
238            $const_msg,
239            $runtime_msg,
240            $($arg: $ty = $arg),*
241        )
242    },
243}
244
245/// A version of `assert` that prints a non-formatting message in const contexts.
246///
247/// See [`const_panic!`].
248#[unstable(feature = "panic_internals", issue = "none")]
249#[doc(hidden)]
250pub macro const_assert {
251    ($condition: expr, $const_msg:literal, $runtime_msg:literal, $($arg:tt)*) => {{
252        if !$crate::intrinsics::likely($condition) {
253            $crate::panic::const_panic!($const_msg, $runtime_msg, $($arg)*)
254        }
255    }}
256}