]> git.proxmox.com Git - rustc.git/blob - library/core/src/panicking.rs
New upstream version 1.52.0+dfsg1
[rustc.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(fmt::Arguments::new_v1(&[expr], &[]));
51 }
52
53 #[inline]
54 #[track_caller]
55 #[lang = "panic_str"] // needed for const-evaluated panics
56 pub fn panic_str(expr: &str) -> ! {
57 panic_fmt(format_args!("{}", expr));
58 }
59
60 #[cold]
61 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
62 #[track_caller]
63 #[lang = "panic_bounds_check"] // needed by codegen for panic on OOB array/slice access
64 fn panic_bounds_check(index: usize, len: usize) -> ! {
65 if cfg!(feature = "panic_immediate_abort") {
66 super::intrinsics::abort()
67 }
68
69 panic!("index out of bounds: the len is {} but the index is {}", len, index)
70 }
71
72 /// The underlying implementation of libcore's `panic!` macro when formatting is used.
73 #[cold]
74 #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never))]
75 #[cfg_attr(feature = "panic_immediate_abort", inline)]
76 #[track_caller]
77 pub fn panic_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 let pi = PanicInfo::internal_constructor(Some(&fmt), Location::caller());
90
91 // SAFETY: `panic_impl` is defined in safe Rust code and thus is safe to call.
92 unsafe { panic_impl(&pi) }
93 }
94
95 #[derive(Debug)]
96 #[doc(hidden)]
97 pub enum AssertKind {
98 Eq,
99 Ne,
100 }
101
102 /// Internal function for `assert_eq!` and `assert_ne!` macros
103 #[cold]
104 #[track_caller]
105 #[doc(hidden)]
106 pub fn assert_failed<T, U>(
107 kind: AssertKind,
108 left: &T,
109 right: &U,
110 args: Option<fmt::Arguments<'_>>,
111 ) -> !
112 where
113 T: fmt::Debug + ?Sized,
114 U: fmt::Debug + ?Sized,
115 {
116 #[track_caller]
117 fn inner(
118 kind: AssertKind,
119 left: &dyn fmt::Debug,
120 right: &dyn fmt::Debug,
121 args: Option<fmt::Arguments<'_>>,
122 ) -> ! {
123 let op = match kind {
124 AssertKind::Eq => "==",
125 AssertKind::Ne => "!=",
126 };
127
128 match args {
129 Some(args) => panic!(
130 r#"assertion failed: `(left {} right)`
131 left: `{:?}`,
132 right: `{:?}`: {}"#,
133 op, left, right, args
134 ),
135 None => panic!(
136 r#"assertion failed: `(left {} right)`
137 left: `{:?}`,
138 right: `{:?}`"#,
139 op, left, right,
140 ),
141 }
142 }
143 inner(kind, &left, &right, args)
144 }