]> git.lizzy.rs Git - rust.git/blob - library/core/src/panicking.rs
Auto merge of #106474 - erikdesjardins:noalias, r=bjorn3
[rust.git] / library / core / src / panicking.rs
1 //! Panic support for core
2 //!
3 //! The core library cannot define panicking, but it does *declare* panicking. This
4 //! means that the functions inside of core are allowed to panic, but to be
5 //! useful an upstream crate must define panicking for core 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 core 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 // If panic_immediate_abort, inline the abort call,
42 // otherwise avoid inlining because of it is cold path.
43 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
44 #[cfg_attr(feature = "panic_immediate_abort", inline)]
45 #[track_caller]
46 #[lang = "panic_fmt"] // needed for const-evaluated panics
47 #[rustc_do_not_const_check] // hooked by const-eval
48 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
49 pub const fn panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
50     if cfg!(feature = "panic_immediate_abort") {
51         super::intrinsics::abort()
52     }
53
54     // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
55     // that gets resolved to the `#[panic_handler]` function.
56     extern "Rust" {
57         #[lang = "panic_impl"]
58         fn panic_impl(pi: &PanicInfo<'_>) -> !;
59     }
60
61     let pi = PanicInfo::internal_constructor(Some(&fmt), Location::caller(), true);
62
63     // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
64     unsafe { panic_impl(&pi) }
65 }
66
67 /// Like `panic_fmt`, but for non-unwinding panics.
68 ///
69 /// Has to be a separate function so that it can carry the `rustc_nounwind` attribute.
70 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
71 #[cfg_attr(feature = "panic_immediate_abort", inline)]
72 #[track_caller]
73 // This attribute has the key side-effect that if the panic handler ignores `can_unwind`
74 // and unwinds anyway, we will hit the "unwinding out of nounwind function" guard,
75 // which causes a "panic in a function that cannot unwind".
76 #[rustc_nounwind]
77 pub fn panic_nounwind_fmt(fmt: fmt::Arguments<'_>) -> ! {
78     if cfg!(feature = "panic_immediate_abort") {
79         super::intrinsics::abort()
80     }
81
82     // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
83     // that gets resolved to the `#[panic_handler]` function.
84     extern "Rust" {
85         #[lang = "panic_impl"]
86         fn panic_impl(pi: &PanicInfo<'_>) -> !;
87     }
88
89     // PanicInfo with the `can_unwind` flag set to false forces an abort.
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 core's `panic!` macro when no formatting is used.
100 // never inline unless panic_immediate_abort to avoid code
101 // bloat at the call sites as much as possible
102 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
103 #[cfg_attr(feature = "panic_immediate_abort", inline)]
104 #[track_caller]
105 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
106 #[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators
107 pub const fn panic(expr: &'static str) -> ! {
108     // Use Arguments::new_v1 instead of format_args!("{expr}") to potentially
109     // reduce size overhead. The format_args! macro uses str's Display trait to
110     // write expr, which calls Formatter::pad, which must accommodate string
111     // truncation and padding (even though none is used here). Using
112     // Arguments::new_v1 may allow the compiler to omit Formatter::pad from the
113     // output binary, saving up to a few kilobytes.
114     panic_fmt(fmt::Arguments::new_v1(&[expr], &[]));
115 }
116
117 /// Like `panic`, but without unwinding and track_caller to reduce the impact on codesize.
118 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
119 #[cfg_attr(feature = "panic_immediate_abort", inline)]
120 #[cfg_attr(not(bootstrap), lang = "panic_nounwind")] // needed by codegen for non-unwinding panics
121 #[rustc_nounwind]
122 pub fn panic_nounwind(expr: &'static str) -> ! {
123     panic_nounwind_fmt(fmt::Arguments::new_v1(&[expr], &[]));
124 }
125
126 #[inline]
127 #[track_caller]
128 #[rustc_diagnostic_item = "panic_str"]
129 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
130 pub const fn panic_str(expr: &str) -> ! {
131     panic_display(&expr);
132 }
133
134 #[inline]
135 #[track_caller]
136 #[rustc_diagnostic_item = "unreachable_display"] // needed for `non-fmt-panics` lint
137 pub fn unreachable_display<T: fmt::Display>(x: &T) -> ! {
138     panic_fmt(format_args!("internal error: entered unreachable code: {}", *x));
139 }
140
141 #[inline]
142 #[track_caller]
143 #[lang = "panic_display"] // needed for const-evaluated panics
144 #[rustc_do_not_const_check] // hooked by const-eval
145 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
146 pub const fn panic_display<T: fmt::Display>(x: &T) -> ! {
147     panic_fmt(format_args!("{}", *x));
148 }
149
150 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
151 #[cfg_attr(feature = "panic_immediate_abort", inline)]
152 #[track_caller]
153 #[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access
154 fn panic_bounds_check(index: usize, len: usize) -> ! {
155     if cfg!(feature = "panic_immediate_abort") {
156         super::intrinsics::abort()
157     }
158
159     panic!("index out of bounds: the len is {len} but the index is {index}")
160 }
161
162 /// Panic because we cannot unwind out of a function.
163 ///
164 /// This function is called directly by the codegen backend, and must not have
165 /// any extra arguments (including those synthesized by track_caller).
166 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
167 #[cfg_attr(feature = "panic_immediate_abort", inline)]
168 #[cfg_attr(bootstrap, lang = "panic_no_unwind")] // needed by codegen for panic in nounwind function
169 #[cfg_attr(not(bootstrap), lang = "panic_cannot_unwind")] // needed by codegen for panic in nounwind function
170 #[rustc_nounwind]
171 fn panic_cannot_unwind() -> ! {
172     panic_nounwind("panic in a function that cannot unwind")
173 }
174
175 /// This function is used instead of panic_fmt in const eval.
176 #[lang = "const_panic_fmt"]
177 #[rustc_const_unstable(feature = "core_panic", issue = "none")]
178 pub const fn const_panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
179     if let Some(msg) = fmt.as_str() {
180         panic_str(msg);
181     } else {
182         // SAFETY: This is only evaluated at compile time, which reliably
183         // handles this UB (in case this branch turns out to be reachable
184         // somehow).
185         unsafe { crate::hint::unreachable_unchecked() };
186     }
187 }
188
189 #[derive(Debug)]
190 #[doc(hidden)]
191 pub enum AssertKind {
192     Eq,
193     Ne,
194     Match,
195 }
196
197 /// Internal function for `assert_eq!` and `assert_ne!` macros
198 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
199 #[cfg_attr(feature = "panic_immediate_abort", inline)]
200 #[track_caller]
201 #[doc(hidden)]
202 pub fn assert_failed<T, U>(
203     kind: AssertKind,
204     left: &T,
205     right: &U,
206     args: Option<fmt::Arguments<'_>>,
207 ) -> !
208 where
209     T: fmt::Debug + ?Sized,
210     U: fmt::Debug + ?Sized,
211 {
212     assert_failed_inner(kind, &left, &right, args)
213 }
214
215 /// Internal function for `assert_match!`
216 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
217 #[cfg_attr(feature = "panic_immediate_abort", inline)]
218 #[track_caller]
219 #[doc(hidden)]
220 pub fn assert_matches_failed<T: fmt::Debug + ?Sized>(
221     left: &T,
222     right: &str,
223     args: Option<fmt::Arguments<'_>>,
224 ) -> ! {
225     // The pattern is a string so it can be displayed directly.
226     struct Pattern<'a>(&'a str);
227     impl fmt::Debug for Pattern<'_> {
228         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229             f.write_str(self.0)
230         }
231     }
232     assert_failed_inner(AssertKind::Match, &left, &Pattern(right), args);
233 }
234
235 /// Non-generic version of the above functions, to avoid code bloat.
236 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)]
237 #[cfg_attr(feature = "panic_immediate_abort", inline)]
238 #[track_caller]
239 fn assert_failed_inner(
240     kind: AssertKind,
241     left: &dyn fmt::Debug,
242     right: &dyn fmt::Debug,
243     args: Option<fmt::Arguments<'_>>,
244 ) -> ! {
245     let op = match kind {
246         AssertKind::Eq => "==",
247         AssertKind::Ne => "!=",
248         AssertKind::Match => "matches",
249     };
250
251     match args {
252         Some(args) => panic!(
253             r#"assertion failed: `(left {} right)`
254   left: `{:?}`,
255  right: `{:?}`: {}"#,
256             op, left, right, args
257         ),
258         None => panic!(
259             r#"assertion failed: `(left {} right)`
260   left: `{:?}`,
261  right: `{:?}`"#,
262             op, left, right,
263         ),
264     }
265 }