1 //! Panic support for libcore
3 //! The core library cannot define panicking, but it does *declare* panicking. This
4 //! means that the functions inside of libcore are allowed to panic, but to be
5 //! useful an upstream crate must define panicking for libcore to use. The current
6 //! interface for panicking is:
9 //! fn panic_impl(pi: &core::panic::PanicInfo<'_>) -> !
13 //! This definition allows for panicking with any general message, but it does not
14 //! allow for failing with a `Box<Any>` value. (`PanicInfo` just contains a `&(dyn Any + Send)`,
15 //! for which we fill in a dummy value in `PanicInfo::internal_constructor`.)
16 //! The reason for this is that libcore is not allowed to allocate.
18 //! This module contains a few other panicking functions, but these are just the
19 //! necessary lang items for the compiler. All panics are funneled through this
20 //! one function. The actual symbol is declared through the `#[panic_handler]` attribute.
22 #![allow(dead_code, missing_docs)]
24 feature = "core_panic",
25 reason = "internal details of the implementation of the `panic!` and related macros",
30 use crate::panic::{Location, PanicInfo};
32 /// The underlying implementation of libcore's `panic!` macro when no formatting is used.
34 // never inline unless panic_immediate_abort to avoid code
35 // bloat at the call sites as much as possible
36 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
37 #[cfg_attr(feature = "panic_immediate_abort", inline)]
39 #[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators
40 pub const fn panic(expr: &'static str) -> ! {
41 // Use Arguments::new_v1 instead of format_args!("{}", expr) to potentially
42 // reduce size overhead. The format_args! macro uses str's Display trait to
43 // write expr, which calls Formatter::pad, which must accommodate string
44 // truncation and padding (even though none is used here). Using
45 // Arguments::new_v1 may allow the compiler to omit Formatter::pad from the
46 // output binary, saving up to a few kilobytes.
47 panic_fmt(fmt::Arguments::new_v1(&[expr], &[]));
52 #[lang = "panic_str"] // needed for `non-fmt-panics` lint
53 pub const fn panic_str(expr: &str) -> ! {
59 #[lang = "panic_display"] // needed for const-evaluated panics
60 #[rustc_do_not_const_check] // hooked by const-eval
61 pub const fn panic_display<T: fmt::Display>(x: &T) -> ! {
62 panic_fmt(format_args!("{}", *x));
66 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
68 #[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access
69 fn panic_bounds_check(index: usize, len: usize) -> ! {
70 if cfg!(feature = "panic_immediate_abort") {
71 super::intrinsics::abort()
74 panic!("index out of bounds: the len is {} but the index is {}", len, index)
77 /// The entry point for panicking with a formatted message.
79 /// This is designed to reduce the amount of code required at the call
80 /// site as much as possible (so that `panic!()` has as low an impact
81 /// on (e.g.) the inlining of other functions as possible), by moving
82 /// the actual formatting into this shared place.
84 // If panic_immediate_abort, inline the abort call,
85 // otherwise avoid inlining because of it is cold path.
86 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
87 #[cfg_attr(feature = "panic_immediate_abort", inline)]
89 #[lang = "panic_fmt"] // needed for const-evaluated panics
90 #[rustc_do_not_const_check] // hooked by const-eval
91 pub const fn panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
92 if cfg!(feature = "panic_immediate_abort") {
93 super::intrinsics::abort()
96 // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
97 // that gets resolved to the `#[panic_handler]` function.
99 #[lang = "panic_impl"]
100 fn panic_impl(pi: &PanicInfo<'_>) -> !;
103 let pi = PanicInfo::internal_constructor(Some(&fmt), Location::caller());
105 // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
106 unsafe { panic_impl(&pi) }
109 /// This function is used instead of panic_fmt in const eval.
110 #[lang = "const_panic_fmt"]
111 pub const fn const_panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
112 if let Some(msg) = fmt.as_str() {
115 // SAFETY: This is only evaluated at compile time, which reliably
116 // handles this UB (in case this branch turns out to be reachable
118 unsafe { crate::hint::unreachable_unchecked() };
124 pub enum AssertKind {
130 /// Internal function for `assert_eq!` and `assert_ne!` macros
134 pub fn assert_failed<T, U>(
138 args: Option<fmt::Arguments<'_>>,
141 T: fmt::Debug + ?Sized,
142 U: fmt::Debug + ?Sized,
144 assert_failed_inner(kind, &left, &right, args)
147 /// Internal function for `assert_match!`
151 pub fn assert_matches_failed<T: fmt::Debug + ?Sized>(
154 args: Option<fmt::Arguments<'_>>,
156 // Use the Display implementation to display the pattern.
157 struct Pattern<'a>(&'a str);
158 impl fmt::Debug for Pattern<'_> {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 fmt::Display::fmt(self.0, f)
163 assert_failed_inner(AssertKind::Match, &left, &Pattern(right), args);
166 /// Non-generic version of the above functions, to avoid code bloat.
168 fn assert_failed_inner(
170 left: &dyn fmt::Debug,
171 right: &dyn fmt::Debug,
172 args: Option<fmt::Arguments<'_>>,
174 let op = match kind {
175 AssertKind::Eq => "==",
176 AssertKind::Ne => "!=",
177 AssertKind::Match => "matches",
181 Some(args) => panic!(
182 r#"assertion failed: `(left {} right)`
185 op, left, right, args
188 r#"assertion failed: `(left {} right)`