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