]> git.lizzy.rs Git - rust.git/blob - src/libcore/panic.rs
Rollup merge of #66847 - dtolnay:_fmt, r=joshtriplett
[rust.git] / src / libcore / panic.rs
1 //! Panic support in the standard library.
2
3 #![unstable(feature = "core_panic_info",
4             reason = "newly available in libcore",
5             issue = "44489")]
6
7 use crate::any::Any;
8 use crate::fmt;
9
10 /// A struct providing information about a panic.
11 ///
12 /// `PanicInfo` structure is passed to a panic hook set by the [`set_hook`]
13 /// function.
14 ///
15 /// [`set_hook`]: ../../std/panic/fn.set_hook.html
16 ///
17 /// # Examples
18 ///
19 /// ```should_panic
20 /// use std::panic;
21 ///
22 /// panic::set_hook(Box::new(|panic_info| {
23 ///     if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
24 ///         println!("panic occurred: {:?}", s);
25 ///     } else {
26 ///         println!("panic occurred");
27 ///     }
28 /// }));
29 ///
30 /// panic!("Normal panic");
31 /// ```
32 #[lang = "panic_info"]
33 #[stable(feature = "panic_hooks", since = "1.10.0")]
34 #[derive(Debug)]
35 pub struct PanicInfo<'a> {
36     payload: &'a (dyn Any + Send),
37     message: Option<&'a fmt::Arguments<'a>>,
38     location: &'a Location<'a>,
39 }
40
41 impl<'a> PanicInfo<'a> {
42     #![unstable(feature = "panic_internals",
43                 reason = "internal details of the implementation of the `panic!` \
44                           and related macros",
45                 issue = "0")]
46     #[doc(hidden)]
47     #[inline]
48     pub fn internal_constructor(
49         message: Option<&'a fmt::Arguments<'a>>,
50         location: &'a Location<'a>,
51     ) -> Self {
52         struct NoPayload;
53         PanicInfo {
54             location,
55             message,
56             payload: &NoPayload,
57         }
58     }
59
60     #[doc(hidden)]
61     #[inline]
62     pub fn set_payload(&mut self, info: &'a (dyn Any + Send)) {
63         self.payload = info;
64     }
65
66     /// Returns the payload associated with the panic.
67     ///
68     /// This will commonly, but not always, be a `&'static str` or [`String`].
69     ///
70     /// [`String`]: ../../std/string/struct.String.html
71     ///
72     /// # Examples
73     ///
74     /// ```should_panic
75     /// use std::panic;
76     ///
77     /// panic::set_hook(Box::new(|panic_info| {
78     ///     println!("panic occurred: {:?}", panic_info.payload().downcast_ref::<&str>().unwrap());
79     /// }));
80     ///
81     /// panic!("Normal panic");
82     /// ```
83     #[stable(feature = "panic_hooks", since = "1.10.0")]
84     pub fn payload(&self) -> &(dyn Any + Send) {
85         self.payload
86     }
87
88     /// If the `panic!` macro from the `core` crate (not from `std`)
89     /// was used with a formatting string and some additional arguments,
90     /// returns that message ready to be used for example with [`fmt::write`]
91     ///
92     /// [`fmt::write`]: ../fmt/fn.write.html
93     #[unstable(feature = "panic_info_message", issue = "44489")]
94     pub fn message(&self) -> Option<&fmt::Arguments<'_>> {
95         self.message
96     }
97
98     /// Returns information about the location from which the panic originated,
99     /// if available.
100     ///
101     /// This method will currently always return [`Some`], but this may change
102     /// in future versions.
103     ///
104     /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
105     ///
106     /// # Examples
107     ///
108     /// ```should_panic
109     /// use std::panic;
110     ///
111     /// panic::set_hook(Box::new(|panic_info| {
112     ///     if let Some(location) = panic_info.location() {
113     ///         println!("panic occurred in file '{}' at line {}", location.file(),
114     ///             location.line());
115     ///     } else {
116     ///         println!("panic occurred but can't get location information...");
117     ///     }
118     /// }));
119     ///
120     /// panic!("Normal panic");
121     /// ```
122     #[stable(feature = "panic_hooks", since = "1.10.0")]
123     pub fn location(&self) -> Option<&Location<'_>> {
124         // NOTE: If this is changed to sometimes return None,
125         // deal with that case in std::panicking::default_hook and std::panicking::begin_panic_fmt.
126         Some(&self.location)
127     }
128 }
129
130 #[stable(feature = "panic_hook_display", since = "1.26.0")]
131 impl fmt::Display for PanicInfo<'_> {
132     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
133         formatter.write_str("panicked at ")?;
134         if let Some(message) = self.message {
135             write!(formatter, "'{}', ", message)?
136         } else if let Some(payload) = self.payload.downcast_ref::<&'static str>() {
137             write!(formatter, "'{}', ", payload)?
138         }
139         // NOTE: we cannot use downcast_ref::<String>() here
140         // since String is not available in libcore!
141         // The payload is a String when `std::panic!` is called with multiple arguments,
142         // but in that case the message is also available.
143
144         self.location.fmt(formatter)
145     }
146 }
147
148 /// A struct containing information about the location of a panic.
149 ///
150 /// This structure is created by the [`location`] method of [`PanicInfo`].
151 ///
152 /// [`location`]: ../../std/panic/struct.PanicInfo.html#method.location
153 /// [`PanicInfo`]: ../../std/panic/struct.PanicInfo.html
154 ///
155 /// # Examples
156 ///
157 /// ```should_panic
158 /// use std::panic;
159 ///
160 /// panic::set_hook(Box::new(|panic_info| {
161 ///     if let Some(location) = panic_info.location() {
162 ///         println!("panic occurred in file '{}' at line {}", location.file(), location.line());
163 ///     } else {
164 ///         println!("panic occurred but can't get location information...");
165 ///     }
166 /// }));
167 ///
168 /// panic!("Normal panic");
169 /// ```
170 #[lang = "panic_location"]
171 #[derive(Debug)]
172 #[stable(feature = "panic_hooks", since = "1.10.0")]
173 pub struct Location<'a> {
174     file: &'a str,
175     line: u32,
176     col: u32,
177 }
178
179 impl<'a> Location<'a> {
180     #![unstable(feature = "panic_internals",
181                 reason = "internal details of the implementation of the `panic!` \
182                           and related macros",
183                 issue = "0")]
184     #[doc(hidden)]
185     pub const fn internal_constructor(file: &'a str, line: u32, col: u32) -> Self {
186         Location { file, line, col }
187     }
188
189     /// Returns the name of the source file from which the panic originated.
190     ///
191     /// # Examples
192     ///
193     /// ```should_panic
194     /// use std::panic;
195     ///
196     /// panic::set_hook(Box::new(|panic_info| {
197     ///     if let Some(location) = panic_info.location() {
198     ///         println!("panic occurred in file '{}'", location.file());
199     ///     } else {
200     ///         println!("panic occurred but can't get location information...");
201     ///     }
202     /// }));
203     ///
204     /// panic!("Normal panic");
205     /// ```
206     #[stable(feature = "panic_hooks", since = "1.10.0")]
207     pub fn file(&self) -> &str {
208         self.file
209     }
210
211     /// Returns the line number from which the panic originated.
212     ///
213     /// # Examples
214     ///
215     /// ```should_panic
216     /// use std::panic;
217     ///
218     /// panic::set_hook(Box::new(|panic_info| {
219     ///     if let Some(location) = panic_info.location() {
220     ///         println!("panic occurred at line {}", location.line());
221     ///     } else {
222     ///         println!("panic occurred but can't get location information...");
223     ///     }
224     /// }));
225     ///
226     /// panic!("Normal panic");
227     /// ```
228     #[stable(feature = "panic_hooks", since = "1.10.0")]
229     pub fn line(&self) -> u32 {
230         self.line
231     }
232
233     /// Returns the column from which the panic originated.
234     ///
235     /// # Examples
236     ///
237     /// ```should_panic
238     /// use std::panic;
239     ///
240     /// panic::set_hook(Box::new(|panic_info| {
241     ///     if let Some(location) = panic_info.location() {
242     ///         println!("panic occurred at column {}", location.column());
243     ///     } else {
244     ///         println!("panic occurred but can't get location information...");
245     ///     }
246     /// }));
247     ///
248     /// panic!("Normal panic");
249     /// ```
250     #[stable(feature = "panic_col", since = "1.25.0")]
251     pub fn column(&self) -> u32 {
252         self.col
253     }
254 }
255
256 #[stable(feature = "panic_hook_display", since = "1.26.0")]
257 impl fmt::Display for Location<'_> {
258     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
259         write!(formatter, "{}:{}:{}", self.file, self.line, self.col)
260     }
261 }
262
263 /// An internal trait used by libstd to pass data from libstd to `panic_unwind`
264 /// and other panic runtimes. Not intended to be stabilized any time soon, do
265 /// not use.
266 #[unstable(feature = "std_internals", issue = "0")]
267 #[doc(hidden)]
268 pub unsafe trait BoxMeUp {
269     /// Take full ownership of the contents.
270     /// The return type is actually `Box<dyn Any + Send>`, but we cannot use `Box` in libcore.
271     ///
272     /// After this method got called, only some dummy default value is left in `self`.
273     /// Calling this method twice, or calling `get` after calling this method, is an error.
274     ///
275     /// The argument is borrowed because the panic runtime (`__rust_start_panic`) only
276     /// gets a borrowed `dyn BoxMeUp`.
277     fn take_box(&mut self) -> *mut (dyn Any + Send);
278
279     /// Just borrow the contents.
280     fn get(&mut self) -> &(dyn Any + Send);
281 }