rust-lang / rust-lang/rust

unnecessary closure constraint propagation V2

Open
#154,267 3 comments 0 reactions 1 assignee View on GitHub

@LorrensP-2158466 is already working on this.

Since Mar 23, 2026.

A-borrow-checker A-closures A-higher-ranked A-lifetimes C-bug T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code (credit to @lcnr):

struct Arg<'a: 'c, 'b: 'c, 'c, T> {
    field: *mut (&'a (), &'b (), &'c (), T),
}

impl<'a, 'b, 'c, T> Arg<'a, 'b, 'c, T> {
    fn constrain(self)
    where
        T: 'a,
    {
    }
}

fn takes_closure<'a, 'b, T>(_: impl for<'c> FnOnce(Arg<'a, 'b, 'c, T>)) {}

fn error<'a, 'b, T: 'a>() {
    takes_closure::<'a, 'b, T>(|arg| arg.constrain());
}

fn main() {}

This should compile fine, but instead this error is reported:

error[E0309]: the parameter type `T` may not live long enough
  --> src/lib.rs:19:38
   |
18 | fn error<'a, 'b, T: 'a>() {
   |              -- the parameter type `T` must be valid for the lifetime `'b` as defined here...
19 |     takes_closure::<'a, 'b, T>(|arg| arg.constrain());
   |                                      ^^^^^^^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds
   |
help: consider adding an explicit lifetime bound
   |
18 | fn error<'a, 'b, T: 'a + 'b>() {
   |                        ++++

For more information about this error, try `rustc --explain E0309`.

So what's happening here is that during the type test T: 'a we have to propagate some requirements so we can prove the type test. This happens here:
https://github.com/rust-lang/rust/blob/13e2abaac846b2680ae93e1b3bd9fe7fe1b9a7fe/compiler/rustc_borrowck/src/region_infer/mod.rs#L712-L736

We loop over lower_bound_universal_regions of 'a, these are ['a, 'c].

Then for each of these regions we loop over their non_local_upper_bounds and propagate T: 'ub. Nothing special happens with 'abut it does with 'c. Its non_local_upper_bounds are ['a, 'b] and we thus propagate T: 'a and T: 'b, propagating T: 'b is incorrect and results in the above error.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.