]> git.lizzy.rs Git - rust.git/blob - library/core/src/panicking.rs
Make Arguments constructors unsafe
[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 #[track_caller]
38 #[lang = "panic"] // needed by codegen for panic on overflow and other `Assert` MIR terminators
39 pub fn panic(expr: &'static str) -> ! {
40     if cfg!(feature = "panic_immediate_abort") {
41         super::intrinsics::abort()
42     }
43
44     // Use Arguments::new_v1 instead of format_args!("{}", expr) to potentially
45     // reduce size overhead. The format_args! macro uses str's Display trait to
46     // write expr, which calls Formatter::pad, which must accommodate string
47     // truncation and padding (even though none is used here). Using
48     // Arguments::new_v1 may allow the compiler to omit Formatter::pad from the
49     // output binary, saving up to a few kilobytes.
50     panic_fmt(
51         #[cfg(bootstrap)]
52         fmt::Arguments::new_v1(&[expr], &[]),
53         #[cfg(not(bootstrap))]
54         // SAFETY: Arguments::new_v1 is safe with exactly one str and zero args
55         unsafe {
56             fmt::Arguments::new_v1(&[expr], &[])
57         },
58     );
59 }
60
61 #[inline]
62 #[track_caller]
63 #[lang = "panic_str"] // needed for const-evaluated panics
64 pub fn panic_str(expr: &str) -> ! {
65     panic_fmt(format_args!("{}", expr));
66 }
67
68 #[cold]
69 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
70 #[track_caller]
71 #[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access
72 fn panic_bounds_check(index: usize, len: usize) -> ! {
73     if cfg!(feature = "panic_immediate_abort") {
74         super::intrinsics::abort()
75     }
76
77     panic!("index out of bounds: the len is {} but the index is {}", len, index)
78 }
79
80 /// The underlying implementation of libcore's `panic!` macro when formatting is used.
81 #[cold]
82 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
83 #[cfg_attr(feature = "panic_immediate_abort", inline)]
84 #[track_caller]
85 #[cfg_attr(not(bootstrap), lang = "panic_fmt")] // needed for const-evaluated panics
86 pub fn panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
87     if cfg!(feature = "panic_immediate_abort") {
88         super::intrinsics::abort()
89     }
90
91     // NOTE This function never crosses the FFI boundary; it's a Rust-to-Rust call
92     // that gets resolved to the `#[panic_handler]` function.
93     extern "Rust" {
94         #[lang = "panic_impl"]
95         fn panic_impl(pi: &PanicInfo<'_>) -> !;
96     }
97
98     let pi = PanicInfo::internal_constructor(Some(&fmt), Location::caller());
99
100     // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
101     unsafe { panic_impl(&pi) }
102 }
103
104 /// This function is used instead of panic_fmt in const eval.
105 #[cfg(not(bootstrap))]
106 #[lang = "const_panic_fmt"]
107 pub const fn const_panic_fmt(fmt: fmt::Arguments<'_>) -> ! {
108     if let Some(msg) = fmt.as_str() {
109         panic_str(msg);
110     } else {
111         // SAFETY: This is only evaluated at compile time, which reliably
112         // handles this UB (in case this branch turns out to be reachable
113         // somehow).
114         unsafe { crate::hint::unreachable_unchecked() };
115     }
116 }
117
118 #[derive(Debug)]
119 #[doc(hidden)]
120 pub enum AssertKind {
121     Eq,
122     Ne,
123     Match,
124 }
125
126 /// Internal function for `assert_eq!` and `assert_ne!` macros
127 #[cold]
128 #[track_caller]
129 #[doc(hidden)]
130 pub fn assert_failed<T, U>(
131     kind: AssertKind,
132     left: &T,
133     right: &U,
134     args: Option<fmt::Arguments<'_>>,
135 ) -> !
136 where
137     T: fmt::Debug + ?Sized,
138     U: fmt::Debug + ?Sized,
139 {
140     assert_failed_inner(kind, &left, &right, args)
141 }
142
143 /// Internal function for `assert_match!`
144 #[cold]
145 #[track_caller]
146 #[doc(hidden)]
147 pub fn assert_matches_failed<T: fmt::Debug + ?Sized>(
148     left: &T,
149     right: &str,
150     args: Option<fmt::Arguments<'_>>,
151 ) -> ! {
152     // Use the Display implementation to display the pattern.
153     struct Pattern<'a>(&'a str);
154     impl fmt::Debug for Pattern<'_> {
155         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156             fmt::Display::fmt(self.0, f)
157         }
158     }
159     assert_failed_inner(AssertKind::Match, &left, &Pattern(right), args);
160 }
161
162 /// Non-generic version of the above functions, to avoid code bloat.
163 #[track_caller]
164 fn assert_failed_inner(
165     kind: AssertKind,
166     left: &dyn fmt::Debug,
167     right: &dyn fmt::Debug,
168     args: Option<fmt::Arguments<'_>>,
169 ) -> ! {
170     let op = match kind {
171         AssertKind::Eq => "==",
172         AssertKind::Ne => "!=",
173         AssertKind::Match => "matches",
174     };
175
176     match args {
177         Some(args) => panic!(
178             r#"assertion failed: `(left {} right)`
179   left: `{:?}`,
180  right: `{:?}`: {}"#,
181             op, left, right, args
182         ),
183         None => panic!(
184             r#"assertion failed: `(left {} right)`
185   left: `{:?}`,
186  right: `{:?}`"#,
187             op, left, right,
188         ),
189     }
190 }