]> git.lizzy.rs Git - rust.git/blob - library/core/src/panicking.rs
Rollup merge of #103432 - jsha:box-is-not-notable, r=GuillaumeGomez
[rust.git] / library / core / src / panicking.rs
1 //! Panic support for libcore
2 //!
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:
7 //!
8 //! ```
9 //! fn panic_impl(pi: &core::panic::PanicInfo<'_>) -> !
10 //! # { loop {} }
11 //! ```
12 //!
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.
17 //!
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.
21
22 #![allow(dead_code, missing_docs)]
23 #![unstable(
24     feature = "core_panic",
25     reason = "internal details of the implementation of the `panic!` and related macros",
26     issue = "none"
27 )]
28
29 use crate::fmt;
30 use crate::panic::{Location, PanicInfo};
31
32 // First we define the two main entry points that all panics go through.
33 // In the end both are just convenience wrappers around `panic_impl`.
34
35 /// The entry point for panicking with a formatted message.
36 ///
37 /// This is designed to reduce the amount of code required at the call
38 /// site as much as possible (so that `panic!()` has as low an impact
39 /// on (e.g.) the inlining of other functions as possible), by moving
40 /// the actual formatting into this shared place.
41 #[cold]
42 // If panic_immediate_abort, inline the abort call,
43 // otherwise avoid inlining because of it is cold path.
44 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
45 #[cfg_attr(feature = "panic_immediate_abort", inline)]
46 #[track_caller]
47 #[lang = "panic_fmt"] // needed for const-evaluated panics
48 #[rustc_do_not_const_check] // hooked by const-eval
49 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
50 pub const fn panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
51     if cfg!(feature = "panic_immediate_abort") {
52         super::intrinsics::abort()
53     }
54
55     // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
56     // that gets resolved to the `#[panic_handler]` function.
57     extern "Rust" {
58         #[lang = "panic_impl"]
59         fn panic_impl(pi: &PanicInfo<'_>) -> !;
60     }
61
62     let pi = PanicInfo::internal_constructor(Some(&fmt), Location::caller(), true);
63
64     // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
65     unsafe { panic_impl(&pi) }
66 }
67
68 /// Like panic_fmt, but without unwinding and track_caller to reduce the impact on codesize.
69 /// Also just works on `str`, as a `fmt::Arguments` needs more space to be passed.
70 #[cold]
71 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
72 #[cfg_attr(feature = "panic_immediate_abort", inline)]
73 #[cfg_attr(not(bootstrap), rustc_nounwind)]
74 #[cfg_attr(bootstrap, rustc_allocator_nounwind)]
75 pub fn panic_str_nounwind(msg: &'static str) -> ! {
76     if cfg!(feature = "panic_immediate_abort") {
77         super::intrinsics::abort()
78     }
79
80     // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
81     // that gets resolved to the `#[panic_handler]` function.
82     extern "Rust" {
83         #[lang = "panic_impl"]
84         fn panic_impl(pi: &PanicInfo<'_>) -> !;
85     }
86
87     // PanicInfo with the `can_unwind` flag set to false forces an abort.
88     let pieces = [msg];
89     let fmt = fmt::Arguments::new_v1(&pieces, &[]);
90     let pi = PanicInfo::internal_constructor(Some(&fmt), Location::caller(), false);
91
92     // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
93     unsafe { panic_impl(&pi) }
94 }
95
96 // Next we define a bunch of higher-level wrappers that all bottom out in the two core functions
97 // above.
98
99 /// The underlying implementation of libcore's `panic!` macro when no formatting is used.
100 #[cold]
101 // never inline unless panic_immediate_abort to avoid code
102 // bloat at the call sites as much as possible
103 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
104 #[cfg_attr(feature = "panic_immediate_abort", inline)]
105 #[track_caller]
106 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
107 #[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators
108 pub const fn panic(expr: &'static str) -> ! {
109     // Use Arguments::new_v1 instead of format_args!("{expr}") to potentially
110     // reduce size overhead. The format_args! macro uses str's Display trait to
111     // write expr, which calls Formatter::pad, which must accommodate string
112     // truncation and padding (even though none is used here). Using
113     // Arguments::new_v1 may allow the compiler to omit Formatter::pad from the
114     // output binary, saving up to a few kilobytes.
115     panic_fmt(fmt::Arguments::new_v1(&[expr], &[]));
116 }
117
118 #[inline]
119 #[track_caller]
120 #[rustc_diagnostic_item = "panic_str"]
121 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
122 pub const fn panic_str(expr: &str) -> ! {
123     panic_display(&expr);
124 }
125
126 #[inline]
127 #[track_caller]
128 #[rustc_diagnostic_item = "unreachable_display"] // needed for `non-fmt-panics` lint
129 pub fn unreachable_display<T: fmt::Display>(x: &T) -> ! {
130     panic_fmt(format_args!("internal error: entered unreachable code: {}", *x));
131 }
132
133 #[inline]
134 #[track_caller]
135 #[lang = "panic_display"] // needed for const-evaluated panics
136 #[rustc_do_not_const_check] // hooked by const-eval
137 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
138 pub const fn panic_display<T: fmt::Display>(x: &T) -> ! {
139     panic_fmt(format_args!("{}", *x));
140 }
141
142 #[cold]
143 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
144 #[track_caller]
145 #[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access
146 fn panic_bounds_check(index: usize, len: usize) -> ! {
147     if cfg!(feature = "panic_immediate_abort") {
148         super::intrinsics::abort()
149     }
150
151     panic!("index out of bounds: the len is {len} but the index is {index}")
152 }
153
154 /// Panic because we cannot unwind out of a function.
155 ///
156 /// This function is called directly by the codegen backend, and must not have
157 /// any extra arguments (including those synthesized by track_caller).
158 #[cold]
159 #[inline(never)]
160 #[lang = "panic_no_unwind"] // needed by codegen for panic in nounwind function
161 #[cfg_attr(not(bootstrap), rustc_nounwind)]
162 #[cfg_attr(bootstrap, rustc_allocator_nounwind)]
163 fn panic_no_unwind() -> ! {
164     panic_str_nounwind("panic in a function that cannot unwind")
165 }
166
167 /// This function is used instead of panic_fmt in const eval.
168 #[lang = "const_panic_fmt"]
169 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
170 pub const fn const_panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
171     if let Some(msg) = fmt.as_str() {
172         panic_str(msg);
173     } else {
174         // SAFETY: This is only evaluated at compile time, which reliably
175         // handles this UB (in case this branch turns out to be reachable
176         // somehow).
177         unsafe { crate::hint::unreachable_unchecked() };
178     }
179 }
180
181 #[derive(Debug)]
182 #[doc(hidden)]
183 pub enum AssertKind {
184     Eq,
185     Ne,
186     Match,
187 }
188
189 /// Internal function for `assert_eq!` and `assert_ne!` macros
190 #[cold]
191 #[track_caller]
192 #[doc(hidden)]
193 pub fn assert_failed<T, U>(
194     kind: AssertKind,
195     left: &T,
196     right: &U,
197     args: Option<fmt::Arguments<'_>>,
198 ) -> !
199 where
200     T: fmt::Debug + ?Sized,
201     U: fmt::Debug + ?Sized,
202 {
203     assert_failed_inner(kind, &left, &right, args)
204 }
205
206 /// Internal function for `assert_match!`
207 #[cold]
208 #[track_caller]
209 #[doc(hidden)]
210 pub fn assert_matches_failed<T: fmt::Debug + ?Sized>(
211     left: &T,
212     right: &str,
213     args: Option<fmt::Arguments<'_>>,
214 ) -> ! {
215     // The pattern is a string so it can be displayed directly.
216     struct Pattern<'a>(&'a str);
217     impl fmt::Debug for Pattern<'_> {
218         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219             f.write_str(self.0)
220         }
221     }
222     assert_failed_inner(AssertKind::Match, &left, &Pattern(right), args);
223 }
224
225 /// Non-generic version of the above functions, to avoid code bloat.
226 #[track_caller]
227 fn assert_failed_inner(
228     kind: AssertKind,
229     left: &dyn fmt::Debug,
230     right: &dyn fmt::Debug,
231     args: Option<fmt::Arguments<'_>>,
232 ) -> ! {
233     let op = match kind {
234         AssertKind::Eq => "==",
235         AssertKind::Ne => "!=",
236         AssertKind::Match => "matches",
237     };
238
239     match args {
240         Some(args) => panic!(
241             r#"assertion failed: `(left {} right)`
242   left: `{:?}`,
243  right: `{:?}`: {}"#,
244             op, left, right, args
245         ),
246         None => panic!(
247             r#"assertion failed: `(left {} right)`
248   left: `{:?}`,
249  right: `{:?}`"#,
250             op, left, right,
251         ),
252     }
253 }