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