diff --git a/library/core/src/panic/location.rs b/library/core/src/panic/location.rs index 6ef7d5a22a30f..cafdcfa2c2e02 100644 --- a/library/core/src/panic/location.rs +++ b/library/core/src/panic/location.rs @@ -183,7 +183,7 @@ impl<'a> Location<'a> { #[must_use] #[stable(feature = "panic_hooks", since = "1.10.0")] #[rustc_const_stable(feature = "const_location_fields", since = "1.79.0")] - pub const fn file(&self) -> &str { + pub const fn file(&self) -> &'a str { // SAFETY: The filename is valid. unsafe { self.filename.as_ref() } } @@ -195,7 +195,7 @@ impl<'a> Location<'a> { #[must_use] #[unstable(feature = "file_with_nul", issue = "141727")] #[inline] - pub const fn file_with_nul(&self) -> &CStr { + pub const fn file_with_nul(&self) -> &'a CStr { let filename = self.filename.as_ptr(); // SAFETY: The filename is valid for `filename_len+1` bytes, so this addition can't diff --git a/library/coretests/tests/panic/location.rs b/library/coretests/tests/panic/location.rs index 910001bcc1c58..a7db05a15c68f 100644 --- a/library/coretests/tests/panic/location.rs +++ b/library/coretests/tests/panic/location.rs @@ -47,11 +47,19 @@ fn location_const_column() { assert_eq!(COLUMN, 40); } +#[test] +fn location_file_lifetime<'x>() { + // Verify that the returned `&str`s lifetime is derived from the generic + // lifetime 'a, not the lifetime of `&self`, when calling `Location::file`. + // Test failure is indicated by a compile failure, not a runtime panic. + let _: for<'a> fn(&'a Location<'x>) -> &'x str = Location::file; +} + #[test] fn location_debug() { let f = format!("{:?}", Location::caller()); assert!(f.contains(&format!("{:?}", file!()))); - assert!(f.contains("52")); + assert!(f.contains("60")); assert!(f.contains("29")); }