]> git.lizzy.rs Git - rust.git/blob - library/core/src/panicking.rs
Rollup merge of #91207 - richkadel:rk-bump-coverage-version, r=tmandry
[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 #[lang = "panic_str"] // needed for `non-fmt-panics` lint
54 pub const fn panic_str(expr: &str) -> ! {
55     panic_display(&expr);
56 }
57
58 #[inline]
59 #[track_caller]
60 #[lang = "panic_display"] // needed for const-evaluated panics
61 #[rustc_do_not_const_check] // hooked by const-eval
62 pub const fn panic_display<T: fmt::Display>(x: &T) -> ! {
63     panic_fmt(format_args!("{}", *x));
64 }
65
66 #[cold]
67 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
68 #[track_caller]
69 #[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access
70 fn panic_bounds_check(index: usize, len: usize) -> ! {
71     if cfg!(feature = "panic_immediate_abort") {
72         super::intrinsics::abort()
73     }
74
75     panic!("index out of bounds: the len is {} but the index is {}", len, index)
76 }
77
78 /// The entry point for panicking with a formatted message.
79 ///
80 /// This is designed to reduce the amount of code required at the call
81 /// site as much as possible (so that `panic!()` has as low an impact
82 /// on (e.g.) the inlining of other functions as possible), by moving
83 /// the actual formatting into this shared place.
84 #[cold]
85 // If panic_immediate_abort, inline the abort call,
86 // otherwise avoid inlining because of it is cold path.
87 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
88 #[cfg_attr(feature = "panic_immediate_abort", inline)]
89 #[track_caller]
90 #[lang = "panic_fmt"] // needed for const-evaluated panics
91 #[rustc_do_not_const_check] // hooked by const-eval
92 pub const fn panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
93     if cfg!(feature = "panic_immediate_abort") {
94         super::intrinsics::abort()
95     }
96
97     // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
98     // that gets resolved to the `#[panic_handler]` function.
99     extern "Rust" {
100         #[lang = "panic_impl"]
101         fn panic_impl(pi: &PanicInfo<'_>) -> !;
102     }
103
104     let pi = PanicInfo::internal_constructor(Some(&fmt), Location::caller());
105
106     // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
107     unsafe { panic_impl(&pi) }
108 }
109
110 /// This function is used instead of panic_fmt in const eval.
111 #[lang = "const_panic_fmt"]
112 pub const fn const_panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
113     if let Some(msg) = fmt.as_str() {
114         panic_str(msg);
115     } else {
116         // SAFETY: This is only evaluated at compile time, which reliably
117         // handles this UB (in case this branch turns out to be reachable
118         // somehow).
119         unsafe { crate::hint::unreachable_unchecked() };
120     }
121 }
122
123 #[derive(Debug)]
124 #[doc(hidden)]
125 pub enum AssertKind {
126     Eq,
127     Ne,
128     Match,
129 }
130
131 /// Internal function for `assert_eq!` and `assert_ne!` macros
132 #[cold]
133 #[track_caller]
134 #[doc(hidden)]
135 pub fn assert_failed<T, U>(
136     kind: AssertKind,
137     left: &T,
138     right: &U,
139     args: Option<fmt::Arguments<'_>>,
140 ) -> !
141 where
142     T: fmt::Debug + ?Sized,
143     U: fmt::Debug + ?Sized,
144 {
145     assert_failed_inner(kind, &left, &right, args)
146 }
147
148 /// Internal function for `assert_match!`
149 #[cold]
150 #[track_caller]
151 #[doc(hidden)]
152 pub fn assert_matches_failed<T: fmt::Debug + ?Sized>(
153     left: &T,
154     right: &str,
155     args: Option<fmt::Arguments<'_>>,
156 ) -> ! {
157     // Use the Display implementation to display the pattern.
158     struct Pattern<'a>(&'a str);
159     impl fmt::Debug for Pattern<'_> {
160         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161             fmt::Display::fmt(self.0, f)
162         }
163     }
164     assert_failed_inner(AssertKind::Match, &left, &Pattern(right), args);
165 }
166
167 /// Non-generic version of the above functions, to avoid code bloat.
168 #[track_caller]
169 fn assert_failed_inner(
170     kind: AssertKind,
171     left: &dyn fmt::Debug,
172     right: &dyn fmt::Debug,
173     args: Option<fmt::Arguments<'_>>,
174 ) -> ! {
175     let op = match kind {
176         AssertKind::Eq => "==",
177         AssertKind::Ne => "!=",
178         AssertKind::Match => "matches",
179     };
180
181     match args {
182         Some(args) => panic!(
183             r#"assertion failed: `(left {} right)`
184   left: `{:?}`,
185  right: `{:?}`: {}"#,
186             op, left, right, args
187         ),
188         None => panic!(
189             r#"assertion failed: `(left {} right)`
190   left: `{:?}`,
191  right: `{:?}`"#,
192             op, left, right,
193         ),
194     }
195 }