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