]> git.lizzy.rs Git - rust.git/blob - src/libcore/panic.rs
Auto merge of #66821 - eddyb:global-trait-caching, r=nikomatsakis
[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     /// Returns the source location of the caller of this function. If that function's caller is
181     /// annotated then its call location will be returned, and so on up the stack to the first call
182     /// within a non-tracked function body.
183     ///
184     /// # Examples
185     ///
186     /// ```
187     /// #![feature(track_caller)]
188     /// use core::panic::Location;
189     ///
190     /// /// Returns the [`Location`] at which it is called.
191     /// #[track_caller]
192     /// fn get_caller_location() -> &'static Location<'static> {
193     ///     Location::caller()
194     /// }
195     ///
196     /// /// Returns a [`Location`] from within this function's definition.
197     /// fn get_just_one_location() -> &'static Location<'static> {
198     ///     get_caller_location()
199     /// }
200     ///
201     /// let fixed_location = get_just_one_location();
202     /// assert_eq!(fixed_location.file(), file!());
203     /// assert_eq!(fixed_location.line(), 15);
204     /// assert_eq!(fixed_location.column(), 5);
205     ///
206     /// // running the same untracked function in a different location gives us the same result
207     /// let second_fixed_location = get_just_one_location();
208     /// assert_eq!(fixed_location.file(), second_fixed_location.file());
209     /// assert_eq!(fixed_location.line(), second_fixed_location.line());
210     /// assert_eq!(fixed_location.column(), second_fixed_location.column());
211     ///
212     /// let this_location = get_caller_location();
213     /// assert_eq!(this_location.file(), file!());
214     /// assert_eq!(this_location.line(), 29);
215     /// assert_eq!(this_location.column(), 21);
216     ///
217     /// // running the tracked function in a different location produces a different value
218     /// let another_location = get_caller_location();
219     /// assert_eq!(this_location.file(), another_location.file());
220     /// assert_ne!(this_location.line(), another_location.line());
221     /// assert_ne!(this_location.column(), another_location.column());
222     /// ```
223     #[cfg(not(bootstrap))]
224     #[unstable(feature = "track_caller",
225                reason = "uses #[track_caller] which is not yet stable",
226                issue = "47809")]
227     #[track_caller]
228     pub const fn caller() -> &'static Location<'static> {
229         crate::intrinsics::caller_location()
230     }
231 }
232
233 impl<'a> Location<'a> {
234     #![unstable(feature = "panic_internals",
235                 reason = "internal details of the implementation of the `panic!` \
236                           and related macros",
237                 issue = "0")]
238     #[doc(hidden)]
239     pub const fn internal_constructor(file: &'a str, line: u32, col: u32) -> Self {
240         Location { file, line, col }
241     }
242
243     /// Returns the name of the source file from which the panic originated.
244     ///
245     /// # Examples
246     ///
247     /// ```should_panic
248     /// use std::panic;
249     ///
250     /// panic::set_hook(Box::new(|panic_info| {
251     ///     if let Some(location) = panic_info.location() {
252     ///         println!("panic occurred in file '{}'", location.file());
253     ///     } else {
254     ///         println!("panic occurred but can't get location information...");
255     ///     }
256     /// }));
257     ///
258     /// panic!("Normal panic");
259     /// ```
260     #[stable(feature = "panic_hooks", since = "1.10.0")]
261     pub fn file(&self) -> &str {
262         self.file
263     }
264
265     /// Returns the line number from which the panic originated.
266     ///
267     /// # Examples
268     ///
269     /// ```should_panic
270     /// use std::panic;
271     ///
272     /// panic::set_hook(Box::new(|panic_info| {
273     ///     if let Some(location) = panic_info.location() {
274     ///         println!("panic occurred at line {}", location.line());
275     ///     } else {
276     ///         println!("panic occurred but can't get location information...");
277     ///     }
278     /// }));
279     ///
280     /// panic!("Normal panic");
281     /// ```
282     #[stable(feature = "panic_hooks", since = "1.10.0")]
283     pub fn line(&self) -> u32 {
284         self.line
285     }
286
287     /// Returns the column from which the panic originated.
288     ///
289     /// # Examples
290     ///
291     /// ```should_panic
292     /// use std::panic;
293     ///
294     /// panic::set_hook(Box::new(|panic_info| {
295     ///     if let Some(location) = panic_info.location() {
296     ///         println!("panic occurred at column {}", location.column());
297     ///     } else {
298     ///         println!("panic occurred but can't get location information...");
299     ///     }
300     /// }));
301     ///
302     /// panic!("Normal panic");
303     /// ```
304     #[stable(feature = "panic_col", since = "1.25.0")]
305     pub fn column(&self) -> u32 {
306         self.col
307     }
308 }
309
310 #[stable(feature = "panic_hook_display", since = "1.26.0")]
311 impl fmt::Display for Location<'_> {
312     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
313         write!(formatter, "{}:{}:{}", self.file, self.line, self.col)
314     }
315 }
316
317 /// An internal trait used by libstd to pass data from libstd to `panic_unwind`
318 /// and other panic runtimes. Not intended to be stabilized any time soon, do
319 /// not use.
320 #[unstable(feature = "std_internals", issue = "0")]
321 #[doc(hidden)]
322 pub unsafe trait BoxMeUp {
323     /// Take full ownership of the contents.
324     /// The return type is actually `Box<dyn Any + Send>`, but we cannot use `Box` in libcore.
325     ///
326     /// After this method got called, only some dummy default value is left in `self`.
327     /// Calling this method twice, or calling `get` after calling this method, is an error.
328     ///
329     /// The argument is borrowed because the panic runtime (`__rust_start_panic`) only
330     /// gets a borrowed `dyn BoxMeUp`.
331     fn take_box(&mut self) -> *mut (dyn Any + Send);
332
333     /// Just borrow the contents.
334     fn get(&mut self) -> &(dyn Any + Send);
335 }