rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
97.21k stars 12.56k forks source link

Error on bounds for unused lifetime #130014

Open Coder-256 opened 3 weeks ago

Coder-256 commented 3 weeks ago

The following fails to build:

struct Foo<'a, 'b: 'a, 'c: 'a>(&'a mut &'a (), &'b (), &'c ());
fn with_foo<'b>(_f: impl FnOnce(Foo<'_, 'b, '_>)) {}

struct Bar;
impl Bar {
    fn baz<'a>(&'a self, _foo: Foo<'a, '_, '_>) {}

    fn call_baz<'b>(&'b self) {
        with_foo::<'b>(|foo| self.baz(foo))
    }
}
error[E0521]: borrowed data escapes outside of method
 --> src/lib.rs:9:30
  |
8 |     fn call_baz<'b>(&'b self) {
  |                 --  -------- `self` is a reference that is only valid in the method body
  |                 |
  |                 lifetime `'b` defined here
9 |         with_foo::<'b>(|foo| self.baz(foo))
  |                              ^^^^^^^^^^^^^
  |                              |
  |                              `self` escapes the method body here
  |                              argument requires that `'b` must outlive `'static`

For more information about this error, try `rustc --explain E0521`.
error: could not compile `playground` (lib) due to 1 previous error

However, it works if the bounds on 'c argument on the declaration of Foo are changed to either 'c: 'b, or simply an unbounded lifetime 'c. This seems unexpected because 'c: 'b is a stricter bound than 'c: 'a (and 'c is a weaker bound than 'c: 'a). It's even stranger because the 'c lifetime is unused in this example.

This seems to be either a bug, unexpected limitation, or as another user suggested, an NLL regression. I created a post on URLO that has some further discussion.

Meta

rustc --version --verbose:

rustc 1.81.0 (eeb90cda1 2024-09-04)
binary: rustc
commit-hash: eeb90cda1969383f56a2637cbd3037bdf598841c
commit-date: 2024-09-04
host: x86_64-unknown-linux-gnu
release: 1.81.0
LLVM version: 18.1.7
workingjubilee commented 3 weeks ago

it can't really be a regression if there's no prior release that compiles it, but perhaps there i... ah, rust 1.38.0! good to know???

workingjubilee commented 3 weeks ago

= warning: this represents potential undefined behavior in your code and this warning will become a hard error in the future

workingjubilee commented 3 weeks ago

QuineDot's example:

I can't immediately conjure an argument why it shouldn't typecheck either other than "seems hard :(" so I'll leave that to those officially designated for judging "hm, that type feature seems hard :("