Skip to content

Overly restrictive lifetime in std::panic::Location::file #131770

@ijchen

Description

@ijchen

The problem

The signature of std::panic::Location::file is currently:

pub struct Location<'a> {
    file: &'a str,
    // ...
}

impl<'a> Location<'a> {
    pub const fn file(&self) -> &str
}

which, with lifetimes expanded, is:

pub const fn file<'b>(self: &'b Location<'a>) -> &'b str

This makes the following impossible:

let location: Location<'static> = unimplemented!();

let file: &'static str = location.file();
//        ------------   ^^^^^^^^ borrowed value does not live long enough
//        |
//        type annotation requires that `location` is borrowed for `'static`

The solution

As far as I can tell, this should be a trivial fix - literally just adding the 'a lifetime to the return type:

impl<'a> Location<'a> {
    pub const fn file(&self) -> &'a str
}

Unfortunately, I also believe this is technically a breaking change (playground):

fn uh_oh<'x>() {
    let _: for<'a> fn(&'a Location<'x>) -> &'a str = Location::<'x>::file;
}
error: lifetime may not live long enough
  --> src/lib.rs:22:12
   |
21 | fn uh_oh<'x>() {
   |          -- lifetime `'x` defined here
22 |     let _: for<'a> fn(&'a Location<'x>) -> &'a str = Location::<'x>::file;
   |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'x` must outlive `'static`

Looking for mentor

I would love to get more experience contributing to rust, so if someone would be willing to guide me through the process, I'd love to implement the fix myself, and go through the whole merge + review process to get more comfortable contributing.

I imagine the first step would be to consult the library or library API team on the path forward considering potential breakage ("crater run"? deprecate and make a file2?), then implementation, review, and merge - but I'm new to this, and would appreciate a mentor to guide me through the process 😄

Metadata

Metadata

Assignees

Labels

A-lifetimesArea: Lifetimes / regionsA-panicArea: Panicking machineryT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions