Skip to content
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

impl-trait return type is bounded by all input type parameters, even when unnecessary #42940

Open
Arnavion opened this issue Jun 27, 2017 · 31 comments
Labels
A-impl-trait Area: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch. A-lifetimes Area: Lifetimes / regions C-bug Category: This is a bug. F-precise_capturing `#![feature(precise_capturing)]` T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. WG-async Working group: Async & await

Comments

@Arnavion
Copy link

Arnavion commented Jun 27, 2017

rustc 1.20.0-nightly (f590a44ce 2017-06-27)
binary: rustc
commit-hash: f590a44ce61888c78b9044817d8b798db5cd2ffd
commit-date: 2017-06-27
host: x86_64-pc-windows-msvc
release: 1.20.0-nightly
LLVM version: 4.0
#![feature(conservative_impl_trait)]

trait Future {
}

impl<F> Future for Box<F> where F: Future + ?Sized {
}

struct SomeFuture<'a>(&'a Client);
impl<'a> Future for SomeFuture<'a> {
}

struct Client;
impl Client {
	fn post<'a, B>(&'a self, _body: &B) -> impl Future + 'a /* (1) */ {
		SomeFuture(self)
	}
}

fn login<'a>(client: &'a Client, username: &str) -> impl Future + 'a {
	client.post(&[username])
}

fn main() {
	let client = Client;
	let _f = {
		let username = "foo".to_string();
		login(&client, &username)
	};
}

Since SomeFuture borrows 'a Client, I'd expect impl Future + 'a to be the correct return type, but it gives this error:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src\main.rs:21:16
   |
21 |    client.post(&[username])
   |                  ^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the function body at 20:1...
  --> src\main.rs:20:1
   |
20 | / fn login<'a>(client: &'a Client, username: &str) -> impl Future + 'a {
21 | |  client.post(&[username])
22 | | }
   | |_^
note: ...so that expression is assignable (expected &str, found &str)
  --> src\main.rs:21:16
   |
21 |    client.post(&[username])
   |                  ^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the function body at 20:1...
  --> src\main.rs:20:1
   |
20 | / fn login<'a>(client: &'a Client, username: &str) -> impl Future + 'a {
21 | |  client.post(&[username])
22 | | }
   | |_^
note: ...so that the type `impl Future` will meet its required lifetime bounds
  --> src\main.rs:20:53
   |
20 | fn login<'a>(client: &'a Client, username: &str) -> impl Future + 'a {
   |                                                     ^^^^^^^^^^^^^^^^

error: aborting due to previous error(s)
  • Changing _body to have an explicit lifetime like _body: &'b B where 'b is independent of 'a or where 'a: 'b does not change the error. This and the original error make it seem that returning an impl trait is somehow causing the _body parameter to get the 'a lifetime, even though it's clearly unused, let alone used in a way that it would require the 'a lifetime.

  • Changing (1) from impl Future + 'a to SomeFuture<'a> fixes it.

  • Changing (1) from impl Future + 'a to Box<Future + 'a> and returning Box::new(SomeFuture(self)) fixes it.

@Mark-Simulacrum Mark-Simulacrum added the A-impl-trait Area: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch. label Jun 28, 2017
@Mark-Simulacrum Mark-Simulacrum added the C-bug Category: This is a bug. label Jul 28, 2017
@Arnavion
Copy link
Author

Arnavion commented Oct 10, 2017

From some experimentation, it seems to be because fn foo<T>(_: T) -> impl Bar compiles to something like fn foo<T>(_: T) -> impl Bar + 't, where 't is the lifetime of T. (I don't think this relationship can be expressed in regular Rust code, though Ralith on IRC suggested one could consider the anonymous type to contain PhantomData<T>)

Thus in the original code fn post<'a, B>(&'a self, _body: &B) -> impl Future + 'a effectively forces the return type to be bounded by B's lifetime in addition to 'a. This is why changing _body: &B to _body: B does not change anything, nor does annotating the parameter as _body: &'b B for an unconstrained 'b


In light of that, here's a smaller repro:

#![feature(conservative_impl_trait)]

trait Tr { }

struct S;
impl Tr for S { }

fn foo<T>(_t: T) -> impl Tr {
    S
}

struct S2;

fn main() {
    let _bar = {
        let s2 = S2;
        foo(&s2)
    };
}

which complains that s2 is dropped while still borrowed because the compiler thinks it needs to live as long as _bar.

@Arnavion Arnavion changed the title impl trait with lifetime bound seems to apply the bound to other unbounded lifetimes impl-trait return type is bounded by all input type parameters, even when unnecessary Oct 10, 2017
@cramertj
Copy link
Member

cramertj commented Jan 5, 2018

This is an intentional restriction. See RFC 1951 for the reasoning.

@Arnavion
Copy link
Author

Arnavion commented Jan 5, 2018

Sure. So can there be a way that I can convince the compiler that Client::post's and foo's results don't depend on all the inputs? Maybe it can be made to not override explicit lifetimes like it does in the Client::post example? (I recognize this won't help for the foo example since there is no way to ascribe a lifetime to T.)

The reasoning in the RFC is that eventually there will be syntax that provides control over which lifetime are and are not part of the returned existential ("Assumption 1"). But for the OP example where there already is an explicit lifetime and bound so it could be made to work today.

@cramertj
Copy link
Member

cramertj commented Jan 5, 2018

Oh, I understand what you're saying now. Yes, if the return type contains an explicit lifetime bound, the compiler should be able to understand that the returned type outlives that lifetime bound. Currently, it cannot do that if there are type parameters involved. This should be fixed. Thanks for the report!

@Arnavion
Copy link
Author

Arnavion commented Aug 6, 2018

This is fixed by existential_type

The fact that existential types intentionally don't have the "generic lifetime inheriting" behavior that impl trait has is documented here.


Updated 2023-10-09 for current syntax:

@alexreg
Copy link
Contributor

alexreg commented Nov 19, 2018

@cramertj @pnkfelix This should probably be closed for the same reason as #53450, if I'm not mistaken?

@cramertj
Copy link
Member

No, this is still a bug. The fact that existential type provides a workaround does not mean that the code here shouldn't work-- if you say that your return type outlives some lifetime, then it shouldn't also be bound by the lifetime of a type that cannot be contained in the return type.

e.g. this doesn't compile today and shouldn't:

trait X {}
impl<T> X for T {}
fn foo<'a, T>(x: &'a u8, t: T) -> impl X + 'a {
    (x, t)
}

You have to explicitly add T: 'a in order for the return type to satisfy the impl X + 'a bound. If T didn't already outlive 'a, it couldn't appear in the return type.

@alexreg
Copy link
Contributor

alexreg commented Nov 19, 2018

@cramertj Okay, so this is an issue with a lifetime inference, right? (Not actual bounds checking.) Would you mind writing up mentoring instructions so someone can tackle this? (Maybe even me.)

@alexreg
Copy link
Contributor

alexreg commented Nov 24, 2018

@nikomatsakis Can we do something about this soon you think? :-) Seems kind of urgent to me, though perhaps this affects me more than most users.

@aidanhs
Copy link
Member

aidanhs commented Dec 23, 2018

Just to check, this is the same issue right?

use std::path::Path;

trait RR {}
impl RR for () {}

fn foo<'a>(path: &'a Path) -> impl RR + 'static {
    bar(path)
}
fn bar<P: AsRef<Path>>(path: P) -> impl RR + 'static {
    ()
}

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=0a65678ab18f34888291c9c514ec2834

gives

error: cannot infer an appropriate lifetime
 --> src/lib.rs:7:9
  |
6 | fn foo<'a>(path: &'a Path) -> impl RR + 'static {
  |                               ----------------- this return type evaluates to the `'static` lifetime...
7 |     bar(path)
  |         ^^^^ ...but this borrow...
  |
note: ...can't outlive the lifetime 'a as defined on the function body at 6:8
 --> src/lib.rs:6:8
  |
6 | fn foo<'a>(path: &'a Path) -> impl RR + 'static {
  |        ^^
help: you can add a constraint to the return type to make it last less than `'static` and match the lifetime 'a as defined on the function body at 6:8
  |
6 | fn foo<'a>(path: &'a Path) -> impl RR + 'static + 'a {
  |                               ^^^^^^^^^^^^^^^^^^^^^^

(I also think the suggestion is misleading - won't adding a 'a after 'static' be a no-op since it will choose the longer of the two?)

@cramertj
Copy link
Member

cramertj commented Dec 26, 2018

@aidanhs Yes to both (well, the answer to the second question is a bit more complicated, but "it won't work" is correct ;) ).

@Marwes
Copy link
Contributor

Marwes commented Jan 9, 2019

Also encountered this issue with the following (minimised) code. Also found a workaround by specifying a dummy trait and moving the (static) lifetime there.

Errors

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=56e0e8506c1b32ee44d471d5cb6ed215

trait Parser2 {
    type Input;
    type PartialState;
}

struct Test<I>(::std::marker::PhantomData<fn(I)>);

impl<I> Parser2 for Test<I> {
    type Input = I;
    type PartialState = ();
}

fn line<'a, I>() -> impl Parser2<Input = I, PartialState = impl Send + 'static> {
    Test(::std::marker::PhantomData)
}

fn status<'a, I>() -> impl Parser2<Input = I, PartialState = impl Send + 'static> {
    line()
}

fn main() {
}

Works

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=74f4abad271f12df1d79a133007ee07f

trait Parser2 {
    type Input;
    type PartialState;
}

struct Test<I>(::std::marker::PhantomData<fn(I)>);

impl<I> Parser2 for Test<I> {
    type Input = I;
    type PartialState = ();
}

trait Static: Send + 'static {}
impl<T> Static for T where T: Send + 'static {}

fn line<'a, I>() -> impl Parser2<Input = I, PartialState = impl Static> {
    Test(::std::marker::PhantomData)
}

fn status<'a, I>() -> impl Parser2<Input = I, PartialState = impl Static> {
    line()
}

@alexreg
Copy link
Contributor

alexreg commented Jan 9, 2019

@nikomatsakis Would be curious to get your thoughts on this along with the other not-too-dissimilar covariant lifetimes issue.

@nikomatsakis
Copy link
Contributor

I've often found it pretty useful to model impl Trait in terms of associated types. If we include the effects of the default keyword, in fact, we get a very close modeling (without the inference), except for "auto trait propagation". I think this modeling is relevant here.

the model

Basically an impl Trait instance like

fn post<'a, B>(&'a self, _body: &B) -> impl Future + 'a { .. }

can be modeled as if there were a "one-off" trait with a single impl:

trait Post<'a, B> {
    //     ^^^^ these are the "captured" parameters, per RFC 1951
    type Output: Future + 'a;
}

impl<'a, B> Post for () {
    default type Output = /* the hidden type that compiler infers */;
}

and the function were then declared like so:

fn post<'a, B>(&'a self, _body: &B) -> <() as Post>::Output { .. }

Why does this matter?

Look at the next function, login:

fn login<'a>(client: &'a Client, username: &str) -> impl Future + 'a { .. }

this function winds up inferring that the hidden type X is <() as Post<'0, B>>::Output for some fresh inference variable '0, and hence we must infer that X: Future and X: 'a. Since the Output is declared as default in the impl, we can't fully normalize it, and must instead rely on the declared bounds (type Output: Future + 'a, where the 'a here will be the variable '0).

The bug report here seems correct: we should be able to prove that X: 'a by adding the requirement that '0: 'a and not requiring B: 'a. And if you try to write out the model I wrote above, you'll find that the compiler does so (at least I expect you will).

How does this work for associated types?

The compiler handles similar problems already for associated types. The rules were outlined in RFC 1214, along with some of the challenges. I think we should probably be able to apply the compiler's existing heuristics to this problem, but it might take a bit of work.

The relevant function is here:

fn projection_must_outlive(
&mut self,
origin: infer::SubregionOrigin<'tcx>,
region: ty::Region<'tcx>,
projection_ty: ty::ProjectionTy<'tcx>,
) {

In particular, I believe this heuristic is the one that will help:

// If we found a unique bound `'b` from the trait, and we
// found nothing else from the environment, then the best
// action is to require that `'b: 'r`, so do that.
//
// This is best no matter what rule we use:
//
// - OutlivesProjectionEnv: these would translate to the requirement that `'b:'r`
// - OutlivesProjectionTraitDef: these would translate to the requirement that `'b:'r`
// - OutlivesProjectionComponent: this would require `'b:'r`
// in addition to other conditions
if !trait_bounds.is_empty()
&& trait_bounds[1..]
.iter()
.chain(approx_env_bounds.iter().map(|b| &b.1))
.all(|b| *b == trait_bounds[0])

@chpio
Copy link
Contributor

chpio commented Jun 20, 2019

this stackoverflow question seems related + a funny error message from the compiler about the lifetime, that could be changed?!

@acceleratesage
Copy link

acceleratesage commented Oct 14, 2021

I also encountered this issue recently and would love to see it fixed, as it makes working with async harder.

@pnkfelix
Copy link
Member

pnkfelix commented Mar 7, 2022

tagging with wg-async with hopes that it will be enqueued as a polish issue for a volunteer from that group to work on.

@rustbot label: +wg-async

@traviscross
Copy link
Contributor

traviscross commented Sep 16, 2023

The important thing to understand about this issue is that it doesn't have anything to do with the lifetime bounds. The lifetime bounds work exactly as you would expect that they would. Consider this minimized version of the issue:

fn capture<'o, T>(_t: T) -> impl Send + 'o {}
fn outlives<'o, T: 'o>(_t: T) {}

fn test<'o>(x: ()) -> impl Send + 'o {
    outlives::<'o, _>(capture::<'o, &'_ ()>(&x)); // OK.
    capture::<'o, &'_ ()>(&x)
//                        ^^
// ERROR: Borrowed value does not live long enough.
}

Playground link

The line labeled "OK" compiles fine. This shows that the opaque type returned by capture does in fact outlive 'o.

However, Rust won't let a value of this type escape up the stack (without type erasure) because there's no way to give the captured lifetime a name that's valid outside of the function.

A full analysis of this subtle issue is available here.

bors added a commit to rust-lang-ci/rust that referenced this issue Oct 7, 2023
Consider alias bounds when computing liveness in NLL

# Background

Right now, liveness analysis in NLL is a bit simplistic. It simply walks through all of the regions of a type and marks them as being live at points. This is problematic in the case of aliases, since it requires that we mark **all** of the regions in their args[^1] as live, leading to bugs like rust-lang#42940.

In reality, we may be able to deduce that fewer regions are allowed to be present in the projected type (or "hidden type" for opaques) via item bounds or where clauses, and therefore ideally, we should be able to soundly require fewer regions to be live in the alias.

For example:
```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn capture<'o>(_: &'o mut ()) -> impl Sized + Captures<'o> + 'static {}

fn test_two_mut(mut x: ()) {
    let _f1 = capture(&mut x);
    let _f2 = capture(&mut x);
    //~^ ERROR cannot borrow `x` as mutable more than once at a time
}
```

In the example above, we should be able to deduce from the `'static` bound on `capture`'s opaque that even though `'o` is a captured region, it *can never* show up in the opaque's hidden type, and can soundly be ignored for liveness purposes.

# The Fix

We apply a simple version of RFC 1214's `OutlivesProjectionEnv` and `OutlivesProjectionTraitDef` rules to NLL's `make_all_regions_live` computation.

Specifically, when we encounter an alias type, we:
1. Look for a unique outlives bound in the param-env or item bounds for that alias. If there is more than one unique region, bail, unless any of the outlives bound's regions is `'static`, and in that case, prefer `'static`. If we find such a unique region, we can mark that outlives region as live and skip walking through the args of the opaque.
2. Otherwise, walk through the alias's args recursively, as we do today.

## Additionally: Opaque Hidden Types

A similar bug comes about when walking through the hidden type of an opaque to validate it doesn't capture lifetimes that aren't part of that opaque. For example:

```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn a() -> impl Sized + 'static {
    b(&vec![])
}

fn b<'o>(_: &'o Vec<i32>) -> impl Sized + Captures<'o> + 'static {}
```

The hidden type of `a::{opaque}` is inferred to be `b::<'?1>::{opaque}`, where `'?1` is a region local to the body of `a`. However, the `'static` bound on `b`'s opaque should allow us to deduce that the hidden type will never mention that region `'?1`, and we can ignore it (and replace it with `ReErased` in `b`'s opaque's hidden type). Similarly to liveness, we don't currently do anything other than recurse through aliases for their lifetime components.

This PR ends up using the same region visitor as liveness for opaque type region captures.

## Limitations

This approach has some limitations. Specifically, since liveness doesn't use the same type-test logic as outlives bounds do, we can't really try several options when we're faced with a choice.

If we encounter two unique outlives regions in the param-env or bounds, we simply fall back to walking the opaque via its args. I expect this to be mostly mitigated by the special treatment of `'static`, and can be fixed in a forwards-compatible by a more sophisticated analysis in the future.

## Read more

Context: rust-lang#42940 (comment)
More context: rust-lang#115822 (comment)

Fixes rust-lang#42940

[^1]: except for bivariant region args in opaques, which will become less relevant when we move onto edition 2024 capture semantics for opaques.
@Rua
Copy link
Contributor

Rua commented Oct 9, 2023

How can I tell Rust that no, the return type does not, in fact, capture any input lifetimes, and is entirely static?

@Arnavion
Copy link
Author

Arnavion commented Oct 9, 2023

How can I tell Rust that no, the return type does not, in fact, capture any input lifetimes, and is entirely static?

#42940 (comment)

@Rua
Copy link
Contributor

Rua commented Oct 10, 2023

How can I tell Rust that no, the return type does not, in fact, capture any input lifetimes, and is entirely static?

#42940 (comment)

Sadly that doesn't work when I try it, it says the feature is unstable.

@Arnavion
Copy link
Author

If it was possible to use TAIT in stable this issue wouldn't still be open.

@davidzeng0
Copy link
Contributor

davidzeng0 commented Oct 21, 2023

video.webm

Wild that removing mut gets rid of the error
Same behavior on nightly

Maybe someone can look into this, I'm relatively new to rust and I don't think mut should have any affect on lifetime checks. Probably a compiler bug

Edit: on second thought maybe the pointer cast is causing it, not entirely sure

Either way, it should work as all lifetimes are bounded to the impl trait, yet it doesn't

bors added a commit to rust-lang-ci/rust that referenced this issue Oct 29, 2023
…his-time-sound, r=aliemjay

Consider alias bounds when computing liveness in NLL (but this time sound hopefully)

This is a revival of rust-lang#116040, except removing the changes to opaque lifetime captures check to make sure that we're not triggering any unsoundness due to the lack of general existential regions and the currently-existing `ReErased` hack we use instead.

r? `@aliemjay` -- I appreciate you pointing out the unsoundenss in the previous iteration of this PR, and I'd like to hear that you're happy with this iteration of this PR before this goes back into FCP :>

Fixes rust-lang#116794 as well

---

(mostly copied from rust-lang#116040 and reworked slightly)

# Background

Right now, liveness analysis in NLL is a bit simplistic. It simply walks through all of the regions of a type and marks them as being live at points. This is problematic in the case of aliases, since it requires that we mark **all** of the regions in their args[^1] as live, leading to bugs like rust-lang#42940.

In reality, we may be able to deduce that fewer regions are allowed to be present in the projected type (or "hidden type" for opaques) via item bounds or where clauses, and therefore ideally, we should be able to soundly require fewer regions to be live in the alias.

For example:
```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn capture<'o>(_: &'o mut ()) -> impl Sized + Captures<'o> + 'static {}

fn test_two_mut(mut x: ()) {
    let _f1 = capture(&mut x);
    let _f2 = capture(&mut x);
    //~^ ERROR cannot borrow `x` as mutable more than once at a time
}
```

In the example above, we should be able to deduce from the `'static` bound on `capture`'s opaque that even though `'o` is a captured region, it *can never* show up in the opaque's hidden type, and can soundly be ignored for liveness purposes.

# The Fix

We apply a simple version of RFC 1214's `OutlivesProjectionEnv` and `OutlivesProjectionTraitDef` rules to NLL's `make_all_regions_live` computation.

Specifically, when we encounter an alias type, we:
1. Look for a unique outlives bound in the param-env or item bounds for that alias. If there is more than one unique region, bail, unless any of the outlives bound's regions is `'static`, and in that case, prefer `'static`. If we find such a unique region, we can mark that outlives region as live and skip walking through the args of the opaque.
2. Otherwise, walk through the alias's args recursively, as we do today.

## Limitation: Multiple choices

This approach has some limitations. Firstly, since liveness doesn't use the same type-test logic as outlives bounds do, we can't really try several options when we're faced with a choice.

If we encounter two unique outlives regions in the param-env or bounds, we simply fall back to walking the opaque via its args. I expect this to be mostly mitigated by the special treatment of `'static`, and can be fixed in a forwards-compatible by a more sophisticated analysis in the future.

## Limitation: Opaque hidden types

Secondly, we do not employ any of these rules when considering whether the regions captured by a hidden type are valid. That causes this code (cc rust-lang#42940) to fail:

```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn a() -> impl Sized + 'static {
    b(&vec![])
}

fn b<'o>(_: &'o Vec<i32>) -> impl Sized + Captures<'o> + 'static {}
```

We need to have existential regions to avoid [unsoundness](rust-lang#116040 (comment)) when an opaque captures a region which is not represented in its own substs but which outlives a region that does.

## Read more

Context: rust-lang#115822 (comment) (for the liveness case)
More context: rust-lang#42940 (comment) (for the opaque capture case, which this does not fix)

[^1]: except for bivariant region args in opaques, which will become less relevant when we move onto edition 2024 capture semantics for opaques.
github-actions bot pushed a commit to rust-lang/miri that referenced this issue Nov 2, 2023
…sound, r=aliemjay

Consider alias bounds when computing liveness in NLL (but this time sound hopefully)

This is a revival of #116040, except removing the changes to opaque lifetime captures check to make sure that we're not triggering any unsoundness due to the lack of general existential regions and the currently-existing `ReErased` hack we use instead.

r? `@aliemjay` -- I appreciate you pointing out the unsoundenss in the previous iteration of this PR, and I'd like to hear that you're happy with this iteration of this PR before this goes back into FCP :>

Fixes #116794 as well

---

(mostly copied from #116040 and reworked slightly)

# Background

Right now, liveness analysis in NLL is a bit simplistic. It simply walks through all of the regions of a type and marks them as being live at points. This is problematic in the case of aliases, since it requires that we mark **all** of the regions in their args[^1] as live, leading to bugs like #42940.

In reality, we may be able to deduce that fewer regions are allowed to be present in the projected type (or "hidden type" for opaques) via item bounds or where clauses, and therefore ideally, we should be able to soundly require fewer regions to be live in the alias.

For example:
```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn capture<'o>(_: &'o mut ()) -> impl Sized + Captures<'o> + 'static {}

fn test_two_mut(mut x: ()) {
    let _f1 = capture(&mut x);
    let _f2 = capture(&mut x);
    //~^ ERROR cannot borrow `x` as mutable more than once at a time
}
```

In the example above, we should be able to deduce from the `'static` bound on `capture`'s opaque that even though `'o` is a captured region, it *can never* show up in the opaque's hidden type, and can soundly be ignored for liveness purposes.

# The Fix

We apply a simple version of RFC 1214's `OutlivesProjectionEnv` and `OutlivesProjectionTraitDef` rules to NLL's `make_all_regions_live` computation.

Specifically, when we encounter an alias type, we:
1. Look for a unique outlives bound in the param-env or item bounds for that alias. If there is more than one unique region, bail, unless any of the outlives bound's regions is `'static`, and in that case, prefer `'static`. If we find such a unique region, we can mark that outlives region as live and skip walking through the args of the opaque.
2. Otherwise, walk through the alias's args recursively, as we do today.

## Limitation: Multiple choices

This approach has some limitations. Firstly, since liveness doesn't use the same type-test logic as outlives bounds do, we can't really try several options when we're faced with a choice.

If we encounter two unique outlives regions in the param-env or bounds, we simply fall back to walking the opaque via its args. I expect this to be mostly mitigated by the special treatment of `'static`, and can be fixed in a forwards-compatible by a more sophisticated analysis in the future.

## Limitation: Opaque hidden types

Secondly, we do not employ any of these rules when considering whether the regions captured by a hidden type are valid. That causes this code (cc #42940) to fail:

```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn a() -> impl Sized + 'static {
    b(&vec![])
}

fn b<'o>(_: &'o Vec<i32>) -> impl Sized + Captures<'o> + 'static {}
```

We need to have existential regions to avoid [unsoundness](rust-lang/rust#116040 (comment)) when an opaque captures a region which is not represented in its own substs but which outlives a region that does.

## Read more

Context: rust-lang/rust#115822 (comment) (for the liveness case)
More context: rust-lang/rust#42940 (comment) (for the opaque capture case, which this does not fix)

[^1]: except for bivariant region args in opaques, which will become less relevant when we move onto edition 2024 capture semantics for opaques.
lnicola pushed a commit to lnicola/rust-analyzer that referenced this issue Apr 7, 2024
…sound, r=aliemjay

Consider alias bounds when computing liveness in NLL (but this time sound hopefully)

This is a revival of #116040, except removing the changes to opaque lifetime captures check to make sure that we're not triggering any unsoundness due to the lack of general existential regions and the currently-existing `ReErased` hack we use instead.

r? `@aliemjay` -- I appreciate you pointing out the unsoundenss in the previous iteration of this PR, and I'd like to hear that you're happy with this iteration of this PR before this goes back into FCP :>

Fixes #116794 as well

---

(mostly copied from #116040 and reworked slightly)

# Background

Right now, liveness analysis in NLL is a bit simplistic. It simply walks through all of the regions of a type and marks them as being live at points. This is problematic in the case of aliases, since it requires that we mark **all** of the regions in their args[^1] as live, leading to bugs like #42940.

In reality, we may be able to deduce that fewer regions are allowed to be present in the projected type (or "hidden type" for opaques) via item bounds or where clauses, and therefore ideally, we should be able to soundly require fewer regions to be live in the alias.

For example:
```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn capture<'o>(_: &'o mut ()) -> impl Sized + Captures<'o> + 'static {}

fn test_two_mut(mut x: ()) {
    let _f1 = capture(&mut x);
    let _f2 = capture(&mut x);
    //~^ ERROR cannot borrow `x` as mutable more than once at a time
}
```

In the example above, we should be able to deduce from the `'static` bound on `capture`'s opaque that even though `'o` is a captured region, it *can never* show up in the opaque's hidden type, and can soundly be ignored for liveness purposes.

# The Fix

We apply a simple version of RFC 1214's `OutlivesProjectionEnv` and `OutlivesProjectionTraitDef` rules to NLL's `make_all_regions_live` computation.

Specifically, when we encounter an alias type, we:
1. Look for a unique outlives bound in the param-env or item bounds for that alias. If there is more than one unique region, bail, unless any of the outlives bound's regions is `'static`, and in that case, prefer `'static`. If we find such a unique region, we can mark that outlives region as live and skip walking through the args of the opaque.
2. Otherwise, walk through the alias's args recursively, as we do today.

## Limitation: Multiple choices

This approach has some limitations. Firstly, since liveness doesn't use the same type-test logic as outlives bounds do, we can't really try several options when we're faced with a choice.

If we encounter two unique outlives regions in the param-env or bounds, we simply fall back to walking the opaque via its args. I expect this to be mostly mitigated by the special treatment of `'static`, and can be fixed in a forwards-compatible by a more sophisticated analysis in the future.

## Limitation: Opaque hidden types

Secondly, we do not employ any of these rules when considering whether the regions captured by a hidden type are valid. That causes this code (cc #42940) to fail:

```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn a() -> impl Sized + 'static {
    b(&vec![])
}

fn b<'o>(_: &'o Vec<i32>) -> impl Sized + Captures<'o> + 'static {}
```

We need to have existential regions to avoid [unsoundness](rust-lang/rust#116040 (comment)) when an opaque captures a region which is not represented in its own substs but which outlives a region that does.

## Read more

Context: rust-lang/rust#115822 (comment) (for the liveness case)
More context: rust-lang/rust#42940 (comment) (for the opaque capture case, which this does not fix)

[^1]: except for bivariant region args in opaques, which will become less relevant when we move onto edition 2024 capture semantics for opaques.
RalfJung pushed a commit to RalfJung/rust-analyzer that referenced this issue Apr 27, 2024
…sound, r=aliemjay

Consider alias bounds when computing liveness in NLL (but this time sound hopefully)

This is a revival of #116040, except removing the changes to opaque lifetime captures check to make sure that we're not triggering any unsoundness due to the lack of general existential regions and the currently-existing `ReErased` hack we use instead.

r? `@aliemjay` -- I appreciate you pointing out the unsoundenss in the previous iteration of this PR, and I'd like to hear that you're happy with this iteration of this PR before this goes back into FCP :>

Fixes #116794 as well

---

(mostly copied from #116040 and reworked slightly)

# Background

Right now, liveness analysis in NLL is a bit simplistic. It simply walks through all of the regions of a type and marks them as being live at points. This is problematic in the case of aliases, since it requires that we mark **all** of the regions in their args[^1] as live, leading to bugs like #42940.

In reality, we may be able to deduce that fewer regions are allowed to be present in the projected type (or "hidden type" for opaques) via item bounds or where clauses, and therefore ideally, we should be able to soundly require fewer regions to be live in the alias.

For example:
```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn capture<'o>(_: &'o mut ()) -> impl Sized + Captures<'o> + 'static {}

fn test_two_mut(mut x: ()) {
    let _f1 = capture(&mut x);
    let _f2 = capture(&mut x);
    //~^ ERROR cannot borrow `x` as mutable more than once at a time
}
```

In the example above, we should be able to deduce from the `'static` bound on `capture`'s opaque that even though `'o` is a captured region, it *can never* show up in the opaque's hidden type, and can soundly be ignored for liveness purposes.

# The Fix

We apply a simple version of RFC 1214's `OutlivesProjectionEnv` and `OutlivesProjectionTraitDef` rules to NLL's `make_all_regions_live` computation.

Specifically, when we encounter an alias type, we:
1. Look for a unique outlives bound in the param-env or item bounds for that alias. If there is more than one unique region, bail, unless any of the outlives bound's regions is `'static`, and in that case, prefer `'static`. If we find such a unique region, we can mark that outlives region as live and skip walking through the args of the opaque.
2. Otherwise, walk through the alias's args recursively, as we do today.

## Limitation: Multiple choices

This approach has some limitations. Firstly, since liveness doesn't use the same type-test logic as outlives bounds do, we can't really try several options when we're faced with a choice.

If we encounter two unique outlives regions in the param-env or bounds, we simply fall back to walking the opaque via its args. I expect this to be mostly mitigated by the special treatment of `'static`, and can be fixed in a forwards-compatible by a more sophisticated analysis in the future.

## Limitation: Opaque hidden types

Secondly, we do not employ any of these rules when considering whether the regions captured by a hidden type are valid. That causes this code (cc #42940) to fail:

```rust
trait Captures<'a> {}
impl<T> Captures<'_> for T {}

fn a() -> impl Sized + 'static {
    b(&vec![])
}

fn b<'o>(_: &'o Vec<i32>) -> impl Sized + Captures<'o> + 'static {}
```

We need to have existential regions to avoid [unsoundness](rust-lang/rust#116040 (comment)) when an opaque captures a region which is not represented in its own substs but which outlives a region that does.

## Read more

Context: rust-lang/rust#115822 (comment) (for the liveness case)
More context: rust-lang/rust#42940 (comment) (for the opaque capture case, which this does not fix)

[^1]: except for bivariant region args in opaques, which will become less relevant when we move onto edition 2024 capture semantics for opaques.
@traviscross traviscross added the F-precise_capturing `#![feature(precise_capturing)]` label May 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-impl-trait Area: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch. A-lifetimes Area: Lifetimes / regions C-bug Category: This is a bug. F-precise_capturing `#![feature(precise_capturing)]` T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. WG-async Working group: Async & await
Projects
None yet
Development

Successfully merging a pull request may close this issue.