]> git.lizzy.rs Git - rust.git/blob - src/libcore/panic.rs
Auto merge of #57118 - Zoxc:query-stats, r=wesleywiser
[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 any::Any;
8 use 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: 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(message: Option<&'a fmt::Arguments<'a>>,
49                                 location: Location<'a>)
50                                 -> Self {
51         struct NoPayload;
52         PanicInfo { payload: &NoPayload, location, message }
53     }
54
55     #[doc(hidden)]
56     #[inline]
57     pub fn set_payload(&mut self, info: &'a (dyn Any + Send)) {
58         self.payload = info;
59     }
60
61     /// Returns the payload associated with the panic.
62     ///
63     /// This will commonly, but not always, be a `&'static str` or [`String`].
64     ///
65     /// [`String`]: ../../std/string/struct.String.html
66     ///
67     /// # Examples
68     ///
69     /// ```should_panic
70     /// use std::panic;
71     ///
72     /// panic::set_hook(Box::new(|panic_info| {
73     ///     println!("panic occurred: {:?}", panic_info.payload().downcast_ref::<&str>().unwrap());
74     /// }));
75     ///
76     /// panic!("Normal panic");
77     /// ```
78     #[stable(feature = "panic_hooks", since = "1.10.0")]
79     pub fn payload(&self) -> &(dyn Any + Send) {
80         self.payload
81     }
82
83     /// If the `panic!` macro from the `core` crate (not from `std`)
84     /// was used with a formatting string and some additional arguments,
85     /// returns that message ready to be used for example with [`fmt::write`]
86     ///
87     /// [`fmt::write`]: ../fmt/fn.write.html
88     #[unstable(feature = "panic_info_message", issue = "44489")]
89     pub fn message(&self) -> Option<&fmt::Arguments> {
90         self.message
91     }
92
93     /// Returns information about the location from which the panic originated,
94     /// if available.
95     ///
96     /// This method will currently always return [`Some`], but this may change
97     /// in future versions.
98     ///
99     /// [`Some`]: ../../std/option/enum.Option.html#variant.Some
100     ///
101     /// # Examples
102     ///
103     /// ```should_panic
104     /// use std::panic;
105     ///
106     /// panic::set_hook(Box::new(|panic_info| {
107     ///     if let Some(location) = panic_info.location() {
108     ///         println!("panic occurred in file '{}' at line {}", location.file(),
109     ///             location.line());
110     ///     } else {
111     ///         println!("panic occurred but can't get location information...");
112     ///     }
113     /// }));
114     ///
115     /// panic!("Normal panic");
116     /// ```
117     #[stable(feature = "panic_hooks", since = "1.10.0")]
118     pub fn location(&self) -> Option<&Location> {
119         // NOTE: If this is changed to sometimes return None,
120         // deal with that case in std::panicking::default_hook and std::panicking::begin_panic_fmt.
121         Some(&self.location)
122     }
123 }
124
125 #[stable(feature = "panic_hook_display", since = "1.26.0")]
126 impl fmt::Display for PanicInfo<'_> {
127     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
128         formatter.write_str("panicked at ")?;
129         if let Some(message) = self.message {
130             write!(formatter, "'{}', ", message)?
131         } else if let Some(payload) = self.payload.downcast_ref::<&'static str>() {
132             write!(formatter, "'{}', ", payload)?
133         }
134         // NOTE: we cannot use downcast_ref::<String>() here
135         // since String is not available in libcore!
136         // The payload is a String when `std::panic!` is called with multiple arguments,
137         // but in that case the message is also available.
138
139         self.location.fmt(formatter)
140     }
141 }
142
143 /// A struct containing information about the location of a panic.
144 ///
145 /// This structure is created by the [`location`] method of [`PanicInfo`].
146 ///
147 /// [`location`]: ../../std/panic/struct.PanicInfo.html#method.location
148 /// [`PanicInfo`]: ../../std/panic/struct.PanicInfo.html
149 ///
150 /// # Examples
151 ///
152 /// ```should_panic
153 /// use std::panic;
154 ///
155 /// panic::set_hook(Box::new(|panic_info| {
156 ///     if let Some(location) = panic_info.location() {
157 ///         println!("panic occurred in file '{}' at line {}", location.file(), location.line());
158 ///     } else {
159 ///         println!("panic occurred but can't get location information...");
160 ///     }
161 /// }));
162 ///
163 /// panic!("Normal panic");
164 /// ```
165 #[derive(Debug)]
166 #[stable(feature = "panic_hooks", since = "1.10.0")]
167 pub struct Location<'a> {
168     file: &'a str,
169     line: u32,
170     col: u32,
171 }
172
173 impl<'a> Location<'a> {
174     #![unstable(feature = "panic_internals",
175                 reason = "internal details of the implementation of the `panic!` \
176                           and related macros",
177                 issue = "0")]
178     #[doc(hidden)]
179     pub fn internal_constructor(file: &'a str, line: u32, col: u32) -> Self {
180         Location { file, line, col }
181     }
182
183     /// Returns the name of the source file from which the panic originated.
184     ///
185     /// # Examples
186     ///
187     /// ```should_panic
188     /// use std::panic;
189     ///
190     /// panic::set_hook(Box::new(|panic_info| {
191     ///     if let Some(location) = panic_info.location() {
192     ///         println!("panic occurred in file '{}'", location.file());
193     ///     } else {
194     ///         println!("panic occurred but can't get location information...");
195     ///     }
196     /// }));
197     ///
198     /// panic!("Normal panic");
199     /// ```
200     #[stable(feature = "panic_hooks", since = "1.10.0")]
201     pub fn file(&self) -> &str {
202         self.file
203     }
204
205     /// Returns the line number from which the panic originated.
206     ///
207     /// # Examples
208     ///
209     /// ```should_panic
210     /// use std::panic;
211     ///
212     /// panic::set_hook(Box::new(|panic_info| {
213     ///     if let Some(location) = panic_info.location() {
214     ///         println!("panic occurred at line {}", location.line());
215     ///     } else {
216     ///         println!("panic occurred but can't get location information...");
217     ///     }
218     /// }));
219     ///
220     /// panic!("Normal panic");
221     /// ```
222     #[stable(feature = "panic_hooks", since = "1.10.0")]
223     pub fn line(&self) -> u32 {
224         self.line
225     }
226
227     /// Returns the column from which the panic originated.
228     ///
229     /// # Examples
230     ///
231     /// ```should_panic
232     /// use std::panic;
233     ///
234     /// panic::set_hook(Box::new(|panic_info| {
235     ///     if let Some(location) = panic_info.location() {
236     ///         println!("panic occurred at column {}", location.column());
237     ///     } else {
238     ///         println!("panic occurred but can't get location information...");
239     ///     }
240     /// }));
241     ///
242     /// panic!("Normal panic");
243     /// ```
244     #[stable(feature = "panic_col", since = "1.25.0")]
245     pub fn column(&self) -> u32 {
246         self.col
247     }
248 }
249
250 #[stable(feature = "panic_hook_display", since = "1.26.0")]
251 impl fmt::Display for Location<'_> {
252     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
253         write!(formatter, "{}:{}:{}", self.file, self.line, self.col)
254     }
255 }
256
257 /// An internal trait used by libstd to pass data from libstd to `panic_unwind`
258 /// and other panic runtimes. Not intended to be stabilized any time soon, do
259 /// not use.
260 #[unstable(feature = "std_internals", issue = "0")]
261 #[doc(hidden)]
262 pub unsafe trait BoxMeUp {
263     fn box_me_up(&mut self) -> *mut (dyn Any + Send);
264     fn get(&mut self) -> &(dyn Any + Send);
265 }