core/panic/location.rs
1use crate::cmp::Ordering;
2use crate::ffi::CStr;
3use crate::fmt;
4use crate::hash::{Hash, Hasher};
5use crate::marker::PhantomData;
6use crate::ptr::NonNull;
7
8/// A struct containing information about the location of a panic.
9///
10/// This structure is created by [`PanicHookInfo::location()`] and [`PanicInfo::location()`].
11///
12/// [`PanicInfo::location()`]: crate::panic::PanicInfo::location
13/// [`PanicHookInfo::location()`]: ../../std/panic/struct.PanicHookInfo.html#method.location
14///
15/// # Examples
16///
17/// ```should_panic
18/// use std::panic;
19///
20/// panic::set_hook(Box::new(|panic_info| {
21/// if let Some(location) = panic_info.location() {
22/// println!("panic occurred in file '{}' at line {}", location.file(), location.line());
23/// } else {
24/// println!("panic occurred but can't get location information...");
25/// }
26/// }));
27///
28/// panic!("Normal panic");
29/// ```
30///
31/// # Comparisons
32///
33/// Comparisons for equality and ordering are made in file, line, then column priority.
34/// Files are compared as strings, not `Path`, which could be unexpected.
35/// See [`Location::file`]'s documentation for more discussion.
36#[lang = "panic_location"]
37#[stable(feature = "panic_hooks", since = "1.10.0")]
38#[derive(Copy, Clone)]
39#[ferrocene::prevalidated]
40pub struct Location<'a> {
41 // A raw pointer is used rather than a reference because the pointer is valid for one more byte
42 // than the length stored in this pointer; the additional byte is the NUL-terminator used by
43 // `Location::file_as_c_str`.
44 filename: NonNull<str>,
45 line: u32,
46 col: u32,
47 _filename: PhantomData<&'a str>,
48}
49
50#[stable(feature = "panic_hooks", since = "1.10.0")]
51#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
52const impl PartialEq for Location<'_> {
53 fn eq(&self, other: &Self) -> bool {
54 // Compare col / line first as they're cheaper to compare and more likely to differ,
55 // while not impacting the result.
56 self.col == other.col && self.line == other.line && self.file() == other.file()
57 }
58}
59
60#[stable(feature = "panic_hooks", since = "1.10.0")]
61#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
62const impl Eq for Location<'_> {}
63
64#[stable(feature = "panic_hooks", since = "1.10.0")]
65#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
66const impl Ord for Location<'_> {
67 fn cmp(&self, other: &Self) -> Ordering {
68 self.file()
69 .cmp(other.file())
70 .then_with(const || self.line.cmp(&other.line))
71 .then_with(const || self.col.cmp(&other.col))
72 }
73}
74
75#[stable(feature = "panic_hooks", since = "1.10.0")]
76#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
77const impl PartialOrd for Location<'_> {
78 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
79 Some(self.cmp(other))
80 }
81}
82
83#[stable(feature = "panic_hooks", since = "1.10.0")]
84impl Hash for Location<'_> {
85 fn hash<H: Hasher>(&self, state: &mut H) {
86 self.file().hash(state);
87 self.line.hash(state);
88 self.col.hash(state);
89 }
90}
91
92#[stable(feature = "panic_hooks", since = "1.10.0")]
93impl fmt::Debug for Location<'_> {
94 #[ferrocene::prevalidated]
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 f.debug_struct("Location")
97 .field("file", &self.file())
98 .field("line", &self.line)
99 .field("column", &self.col)
100 .finish()
101 }
102}
103
104impl<'a> Location<'a> {
105 /// Returns the source location of the caller of this function. If that function's caller is
106 /// annotated then its call location will be returned, and so on up the stack to the first call
107 /// within a non-tracked function body.
108 ///
109 /// # Examples
110 ///
111 /// ```standalone_crate
112 /// use std::panic::Location;
113 ///
114 /// /// ```
115 /// /// |1 |11 |21 |31 |41
116 /// /// +-|---------|---------|---------|---------|--------
117 /// /// 15 | #[track_caller]
118 /// /// 16 | fn new_location() -> &'static Location<'static> {
119 /// /// 17 | Location::caller()
120 /// /// | ------------------| the value of this expression depends on the caller,
121 /// /// | | since the function is marked #[track_caller]
122 /// /// 18 | }
123 /// /// ```
124 /// #[track_caller]
125 /// fn new_location() -> &'static Location<'static> {
126 /// Location::caller()
127 /// }
128 ///
129 /// /// ```
130 /// /// |1 |5 |11 |21 |31 |41 |51
131 /// /// +-|---|-----|---------|---------|---------|---------|---
132 /// /// 29 | fn constant_location() -> &'static Location<'static> {
133 /// /// 30 | new_location()
134 /// /// | ^ any invocation of constant_location() points here,
135 /// /// | no matter the location it is called from
136 /// /// 31 | }
137 /// /// ```
138 /// fn constant_location() -> &'static Location<'static> {
139 /// new_location()
140 /// }
141 ///
142 /// fn main() {
143 /// // |1 |5 |11 |21 |31 |41 |51
144 /// // +-|---|-----|---------|---------|---------|---------|---
145 /// // 29 | fn constant_location() -> &'static Location<'static> {
146 /// // 30 | new_location()
147 /// // | ^ `let constant` points here
148 /// // 31 | }
149 /// let constant = constant_location();
150 /// assert_eq!(constant.file(), file!());
151 /// assert_eq!((constant.line(), constant.column()), (30, 5));
152 ///
153 /// let constant_2 = constant_location();
154 /// assert_eq!(
155 /// (constant.file(), constant.line(), constant.column()),
156 /// (constant_2.file(), constant_2.line(), constant_2.column())
157 /// );
158 ///
159 /// // |1 |11 |16 |21 |31
160 /// // +-|---------|----|----|---------|------
161 /// // 55 | let here = new_location();
162 /// // | ^ `let here` points here, as `new_location()` is the callsite
163 /// // 56 | assert_eq!(here.file(), file!());
164 /// let here = new_location();
165 /// assert_eq!(here.file(), file!());
166 /// assert_eq!((here.line(), here.column()), (55, 16));
167 ///
168 /// // |1 |11 |21 ||32 |41 |51
169 /// // +-|---------|---------|---------||--------|---------|------
170 /// // 64 | let yet_another_location = new_location();
171 /// // | ^ `let yet_another_location` points here
172 /// // 65 | assert_eq!(here.file(), yet_another_location.file());
173 /// let yet_another_location = new_location();
174 /// assert_eq!(here.file(), yet_another_location.file());
175 /// assert_ne!(
176 /// (here.line(), here.column()),
177 /// (yet_another_location.line(), yet_another_location.column())
178 /// );
179 /// }
180 /// ```
181 #[must_use]
182 #[stable(feature = "track_caller", since = "1.46.0")]
183 #[rustc_const_stable(feature = "const_caller_location", since = "1.79.0")]
184 #[track_caller]
185 #[inline]
186 #[ferrocene::prevalidated]
187 pub const fn caller() -> &'static Location<'static> {
188 crate::intrinsics::caller_location()
189 }
190
191 /// Returns the name of the source file from which the panic originated.
192 ///
193 /// # `&str`, not `&Path`
194 ///
195 /// The returned name refers to a source path on the compiling system, but it isn't valid to
196 /// represent this directly as a `&Path`. The compiled code may run on a different system with
197 /// a different `Path` implementation than the system providing the contents and this library
198 /// does not currently have a different "host path" type.
199 ///
200 /// The most surprising behavior occurs when "the same" file is reachable via multiple paths in
201 /// the module system (usually using the `#[path = "..."]` attribute or similar), which can
202 /// cause what appears to be identical code to return differing values from this function.
203 ///
204 /// # Cross-compilation
205 ///
206 /// This value is not suitable for passing to `Path::new` or similar constructors when the host
207 /// platform and target platform differ.
208 ///
209 /// # Examples
210 ///
211 /// ```should_panic
212 /// use std::panic;
213 ///
214 /// panic::set_hook(Box::new(|panic_info| {
215 /// if let Some(location) = panic_info.location() {
216 /// println!("panic occurred in file '{}'", location.file());
217 /// } else {
218 /// println!("panic occurred but can't get location information...");
219 /// }
220 /// }));
221 ///
222 /// panic!("Normal panic");
223 /// ```
224 #[must_use]
225 #[stable(feature = "panic_hooks", since = "1.10.0")]
226 #[rustc_const_stable(feature = "const_location_fields", since = "1.79.0")]
227 #[ferrocene::prevalidated]
228 pub const fn file(&self) -> &'a str {
229 // SAFETY: The filename is valid.
230 unsafe { self.filename.as_ref() }
231 }
232
233 /// Returns the name of the source file as a nul-terminated `CStr`.
234 ///
235 /// This is useful for interop with APIs that expect C/C++ `__FILE__` or
236 /// `std::source_location::file_name`, both of which return a nul-terminated `const char*`.
237 #[must_use]
238 #[inline]
239 #[stable(feature = "file_with_nul", since = "1.92.0")]
240 #[rustc_const_stable(feature = "file_with_nul", since = "1.92.0")]
241 pub const fn file_as_c_str(&self) -> &'a CStr {
242 let filename = self.filename.as_ptr();
243
244 // SAFETY: The filename is valid for `filename_len+1` bytes, so this addition can't
245 // overflow.
246 let cstr_len = unsafe { crate::mem::size_of_val_raw(filename).unchecked_add(1) };
247
248 // SAFETY: The filename is valid for `filename_len+1` bytes.
249 let slice = unsafe { crate::slice::from_raw_parts(filename.cast(), cstr_len) };
250
251 // SAFETY: The filename is guaranteed to have a trailing nul byte and no interior nul bytes.
252 unsafe { CStr::from_bytes_with_nul_unchecked(slice) }
253 }
254
255 /// Returns the line number from which the panic originated.
256 ///
257 /// # Examples
258 ///
259 /// ```should_panic
260 /// use std::panic;
261 ///
262 /// panic::set_hook(Box::new(|panic_info| {
263 /// if let Some(location) = panic_info.location() {
264 /// println!("panic occurred at line {}", location.line());
265 /// } else {
266 /// println!("panic occurred but can't get location information...");
267 /// }
268 /// }));
269 ///
270 /// panic!("Normal panic");
271 /// ```
272 #[must_use]
273 #[stable(feature = "panic_hooks", since = "1.10.0")]
274 #[rustc_const_stable(feature = "const_location_fields", since = "1.79.0")]
275 #[inline]
276 #[ferrocene::prevalidated]
277 pub const fn line(&self) -> u32 {
278 self.line
279 }
280
281 /// Returns the column from which the panic originated.
282 ///
283 /// # Examples
284 ///
285 /// ```should_panic
286 /// use std::panic;
287 ///
288 /// panic::set_hook(Box::new(|panic_info| {
289 /// if let Some(location) = panic_info.location() {
290 /// println!("panic occurred at column {}", location.column());
291 /// } else {
292 /// println!("panic occurred but can't get location information...");
293 /// }
294 /// }));
295 ///
296 /// panic!("Normal panic");
297 /// ```
298 #[must_use]
299 #[stable(feature = "panic_col", since = "1.25.0")]
300 #[rustc_const_stable(feature = "const_location_fields", since = "1.79.0")]
301 #[inline]
302 #[ferrocene::prevalidated]
303 pub const fn column(&self) -> u32 {
304 self.col
305 }
306}
307
308#[stable(feature = "panic_hook_display", since = "1.26.0")]
309impl fmt::Display for Location<'_> {
310 #[inline]
311 #[ferrocene::prevalidated]
312 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
313 write!(formatter, "{}:{}:{}", self.file(), self.line, self.col)
314 }
315}
316
317#[stable(feature = "panic_hooks", since = "1.10.0")]
318unsafe impl Send for Location<'_> {}
319#[stable(feature = "panic_hooks", since = "1.10.0")]
320unsafe impl Sync for Location<'_> {}