Skip to content

Fix overly restrictive lifetime in core::panic::Location::file return type #132087

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions library/core/src/panic/location.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() }
}
Expand All @@ -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
Expand Down
10 changes: 9 additions & 1 deletion library/coretests/tests/panic/location.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
}

Expand Down
Loading