]> git.lizzy.rs Git - rust.git/blob - src/libcore/panic.rs
Rollup merge of #73169 - Amanieu:asm-warnings, r=petrochenkov
[rust.git] / src / libcore / panic.rs
1 //! Panic support in the standard library.
2
3 #![stable(feature = "core_panic_info", since = "1.41.0")]
4
5 use crate::any::Any;
6 use crate::fmt;
7
8 /// A struct providing information about a panic.
9 ///
10 /// `PanicInfo` structure is passed to a panic hook set by the [`set_hook`]
11 /// function.
12 ///
13 /// [`set_hook`]: ../../std/panic/fn.set_hook.html
14 ///
15 /// # Examples
16 ///
17 /// ```should_panic
18 /// use std::panic;
19 ///
20 /// panic::set_hook(Box::new(|panic_info| {
21 ///     if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
22 ///         println!("panic occurred: {:?}", s);
23 ///     } else {
24 ///         println!("panic occurred");
25 ///     }
26 /// }));
27 ///
28 /// panic!("Normal panic");
29 /// ```
30 #[lang = "panic_info"]
31 #[stable(feature = "panic_hooks", since = "1.10.0")]
32 #[derive(Debug)]
33 pub struct PanicInfo<'a> {
34     payload: &'a (dyn Any + Send),
35     message: Option<&'a fmt::Arguments<'a>>,
36     location: &'a Location<'a>,
37 }
38
39 impl<'a> PanicInfo<'a> {
40     #[unstable(
41         feature = "panic_internals",
42         reason = "internal details of the implementation of the `panic!` \
43                          and related macros",
44         issue = "none"
45     )]
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 { location, message, payload: &NoPayload }
54     }
55
56     #[unstable(
57         feature = "panic_internals",
58         reason = "internal details of the implementation of the `panic!` \
59                          and related macros",
60         issue = "none"
61     )]
62     #[doc(hidden)]
63     #[inline]
64     pub fn set_payload(&mut self, info: &'a (dyn Any + Send)) {
65         self.payload = info;
66     }
67
68     /// Returns the payload associated with the panic.
69     ///
70     /// This will commonly, but not always, be a `&'static str` or [`String`].
71     ///
72     /// [`String`]: ../../std/string/struct.String.html
73     ///
74     /// # Examples
75     ///
76     /// ```should_panic
77     /// use std::panic;
78     ///
79     /// panic::set_hook(Box::new(|panic_info| {
80     ///     if let Some(s) = panic_info.payload().downcast_ref::<&str>() {
81     ///         println!("panic occurred: {:?}", s);
82     ///     } else {
83     ///         println!("panic occurred");
84     ///     }
85     /// }));
86     ///
87     /// panic!("Normal panic");
88     /// ```
89     #[stable(feature = "panic_hooks", since = "1.10.0")]
90     pub fn payload(&self) -> &(dyn Any + Send) {
91         self.payload
92     }
93
94     /// If the `panic!` macro from the `core` crate (not from `std`)
95     /// was used with a formatting string and some additional arguments,
96     /// returns that message ready to be used for example with [`fmt::write`]
97     ///
98     /// [`fmt::write`]: ../fmt/fn.write.html
99     #[unstable(feature = "panic_info_message", issue = "66745")]
100     pub fn message(&self) -> Option<&fmt::Arguments<'_>> {
101         self.message
102     }
103
104     /// Returns information about the location from which the panic originated,
105     /// if available.
106     ///
107     /// This method will currently always return [`Some`], but this may change
108     /// in future versions.
109     ///
110     /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
111     ///
112     /// # Examples
113     ///
114     /// ```should_panic
115     /// use std::panic;
116     ///
117     /// panic::set_hook(Box::new(|panic_info| {
118     ///     if let Some(location) = panic_info.location() {
119     ///         println!("panic occurred in file '{}' at line {}",
120     ///             location.file(),
121     ///             location.line(),
122     ///         );
123     ///     } else {
124     ///         println!("panic occurred but can't get location information...");
125     ///     }
126     /// }));
127     ///
128     /// panic!("Normal panic");
129     /// ```
130     #[stable(feature = "panic_hooks", since = "1.10.0")]
131     pub fn location(&self) -> Option<&Location<'_>> {
132         // NOTE: If this is changed to sometimes return None,
133         // deal with that case in std::panicking::default_hook and std::panicking::begin_panic_fmt.
134         Some(&self.location)
135     }
136 }
137
138 #[stable(feature = "panic_hook_display", since = "1.26.0")]
139 impl fmt::Display for PanicInfo<'_> {
140     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
141         formatter.write_str("panicked at ")?;
142         if let Some(message) = self.message {
143             write!(formatter, "'{}', ", message)?
144         } else if let Some(payload) = self.payload.downcast_ref::<&'static str>() {
145             write!(formatter, "'{}', ", payload)?
146         }
147         // NOTE: we cannot use downcast_ref::<String>() here
148         // since String is not available in libcore!
149         // The payload is a String when `std::panic!` is called with multiple arguments,
150         // but in that case the message is also available.
151
152         self.location.fmt(formatter)
153     }
154 }
155
156 /// A struct containing information about the location of a panic.
157 ///
158 /// This structure is created by the [`location`] method of [`PanicInfo`].
159 ///
160 /// [`location`]: ../../std/panic/struct.PanicInfo.html#method.location
161 /// [`PanicInfo`]: ../../std/panic/struct.PanicInfo.html
162 ///
163 /// # Examples
164 ///
165 /// ```should_panic
166 /// use std::panic;
167 ///
168 /// panic::set_hook(Box::new(|panic_info| {
169 ///     if let Some(location) = panic_info.location() {
170 ///         println!("panic occurred in file '{}' at line {}", location.file(), location.line());
171 ///     } else {
172 ///         println!("panic occurred but can't get location information...");
173 ///     }
174 /// }));
175 ///
176 /// panic!("Normal panic");
177 /// ```
178 #[lang = "panic_location"]
179 #[derive(Debug)]
180 #[stable(feature = "panic_hooks", since = "1.10.0")]
181 pub struct Location<'a> {
182     file: &'a str,
183     line: u32,
184     col: u32,
185 }
186
187 impl<'a> Location<'a> {
188     /// Returns the source location of the caller of this function. If that function's caller is
189     /// annotated then its call location will be returned, and so on up the stack to the first call
190     /// within a non-tracked function body.
191     ///
192     /// # Examples
193     ///
194     /// ```
195     /// #![feature(track_caller)]
196     /// use core::panic::Location;
197     ///
198     /// /// Returns the [`Location`] at which it is called.
199     /// #[track_caller]
200     /// fn get_caller_location() -> &'static Location<'static> {
201     ///     Location::caller()
202     /// }
203     ///
204     /// /// Returns a [`Location`] from within this function's definition.
205     /// fn get_just_one_location() -> &'static Location<'static> {
206     ///     get_caller_location()
207     /// }
208     ///
209     /// let fixed_location = get_just_one_location();
210     /// assert_eq!(fixed_location.file(), file!());
211     /// assert_eq!(fixed_location.line(), 15);
212     /// assert_eq!(fixed_location.column(), 5);
213     ///
214     /// // running the same untracked function in a different location gives us the same result
215     /// let second_fixed_location = get_just_one_location();
216     /// assert_eq!(fixed_location.file(), second_fixed_location.file());
217     /// assert_eq!(fixed_location.line(), second_fixed_location.line());
218     /// assert_eq!(fixed_location.column(), second_fixed_location.column());
219     ///
220     /// let this_location = get_caller_location();
221     /// assert_eq!(this_location.file(), file!());
222     /// assert_eq!(this_location.line(), 29);
223     /// assert_eq!(this_location.column(), 21);
224     ///
225     /// // running the tracked function in a different location produces a different value
226     /// let another_location = get_caller_location();
227     /// assert_eq!(this_location.file(), another_location.file());
228     /// assert_ne!(this_location.line(), another_location.line());
229     /// assert_ne!(this_location.column(), another_location.column());
230     /// ```
231     // FIXME: When stabilizing this method, please also update the documentation
232     // of `intrinsics::caller_location`.
233     #[unstable(
234         feature = "track_caller",
235         reason = "uses #[track_caller] which is not yet stable",
236         issue = "47809"
237     )]
238     #[track_caller]
239     pub const fn caller() -> &'static Location<'static> {
240         crate::intrinsics::caller_location()
241     }
242 }
243
244 impl<'a> Location<'a> {
245     #![unstable(
246         feature = "panic_internals",
247         reason = "internal details of the implementation of the `panic!` \
248                           and related macros",
249         issue = "none"
250     )]
251     #[doc(hidden)]
252     pub const fn internal_constructor(file: &'a str, line: u32, col: u32) -> Self {
253         Location { file, line, col }
254     }
255
256     /// Returns the name of the source file from which the panic originated.
257     ///
258     /// # Examples
259     ///
260     /// ```should_panic
261     /// use std::panic;
262     ///
263     /// panic::set_hook(Box::new(|panic_info| {
264     ///     if let Some(location) = panic_info.location() {
265     ///         println!("panic occurred in file '{}'", location.file());
266     ///     } else {
267     ///         println!("panic occurred but can't get location information...");
268     ///     }
269     /// }));
270     ///
271     /// panic!("Normal panic");
272     /// ```
273     #[stable(feature = "panic_hooks", since = "1.10.0")]
274     pub fn file(&self) -> &str {
275         self.file
276     }
277
278     /// Returns the line number from which the panic originated.
279     ///
280     /// # Examples
281     ///
282     /// ```should_panic
283     /// use std::panic;
284     ///
285     /// panic::set_hook(Box::new(|panic_info| {
286     ///     if let Some(location) = panic_info.location() {
287     ///         println!("panic occurred at line {}", location.line());
288     ///     } else {
289     ///         println!("panic occurred but can't get location information...");
290     ///     }
291     /// }));
292     ///
293     /// panic!("Normal panic");
294     /// ```
295     #[stable(feature = "panic_hooks", since = "1.10.0")]
296     pub fn line(&self) -> u32 {
297         self.line
298     }
299
300     /// Returns the column from which the panic originated.
301     ///
302     /// # Examples
303     ///
304     /// ```should_panic
305     /// use std::panic;
306     ///
307     /// panic::set_hook(Box::new(|panic_info| {
308     ///     if let Some(location) = panic_info.location() {
309     ///         println!("panic occurred at column {}", location.column());
310     ///     } else {
311     ///         println!("panic occurred but can't get location information...");
312     ///     }
313     /// }));
314     ///
315     /// panic!("Normal panic");
316     /// ```
317     #[stable(feature = "panic_col", since = "1.25.0")]
318     pub fn column(&self) -> u32 {
319         self.col
320     }
321 }
322
323 #[stable(feature = "panic_hook_display", since = "1.26.0")]
324 impl fmt::Display for Location<'_> {
325     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
326         write!(formatter, "{}:{}:{}", self.file, self.line, self.col)
327     }
328 }
329
330 /// An internal trait used by libstd to pass data from libstd to `panic_unwind`
331 /// and other panic runtimes. Not intended to be stabilized any time soon, do
332 /// not use.
333 #[unstable(feature = "std_internals", issue = "none")]
334 #[doc(hidden)]
335 pub unsafe trait BoxMeUp {
336     /// Take full ownership of the contents.
337     /// The return type is actually `Box<dyn Any + Send>`, but we cannot use `Box` in libcore.
338     ///
339     /// After this method got called, only some dummy default value is left in `self`.
340     /// Calling this method twice, or calling `get` after calling this method, is an error.
341     ///
342     /// The argument is borrowed because the panic runtime (`__rust_start_panic`) only
343     /// gets a borrowed `dyn BoxMeUp`.
344     fn take_box(&mut self) -> *mut (dyn Any + Send);
345
346     /// Just borrow the contents.
347     fn get(&mut self) -> &(dyn Any + Send);
348 }