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