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

"does not live long enough" when returning Option<impl trait> #55535

Open
Riateche opened this issue Oct 31, 2018 · 3 comments
Open

"does not live long enough" when returning Option<impl trait> #55535

Riateche opened this issue Oct 31, 2018 · 3 comments
Labels
A-impl-trait Area: impl Trait. Universally / existentially quantified anonymous types with static dispatch. A-lifetimes Area: lifetime related

Comments

@Riateche
Copy link

This doesn't compile:

use std::cell::RefCell;

struct B;
struct A {
    b: B,
}

impl A {
    fn b(&self) -> Option<impl Iterator<Item = &B>> {
        Some(::std::iter::once(&self.b))
    }
}

fn func(a: RefCell<A>) {
    let lock = a.borrow_mut();
    if let Some(_b) = lock.b() {}
}

However, it compiles when impl trait is replaced with the concrete type:

fn b(&self) -> Option<::std::iter::Once<&B>> {

It also compiles with impl trait if Option is removed:

impl A {
    fn b(&self) -> impl Iterator<Item = &B> {
        ::std::iter::once(&self.b)
    }
}

fn func(a: RefCell<A>) {
    let lock = a.borrow_mut();
    let _b = lock.b();
}
@cramertj cramertj added A-impl-trait Area: impl Trait. Universally / existentially quantified anonymous types with static dispatch. A-lifetimes Area: lifetime related labels Oct 31, 2018
@pnkfelix
Copy link
Member

pnkfelix commented Nov 2, 2018

cc #46413 because I think this may be a result of our temporary lifetime rules (and perhaps some interaction between them and other features like variance)

here is the message we currently emit from the 2018 edition for the given code:

error[E0597]: `lock` does not live long enough
  --> src/lib.rs:16:23
   |
16 |     if let Some(_b) = lock.b() {}
   |                       ^^^^----
   |                       |
   |                       borrowed value does not live long enough
   |                       a temporary with access to the borrow is created here ...
17 | }
   | -
   | |
   | `lock` dropped here while still borrowed
   | ... and the borrow might be used here, when that temporary is dropped and \
         runs the destructor for type `std::option::Option<impl std::iter::Iterator>`
   |
   = note: The temporary is part of an expression at the end of a block. \
     Consider adding semicolon after the expression so its temporaries are \
     dropped sooner, before the local variables declared by the block are dropped.

Following the advice provided (by adding a semicolon after the if let expression) does allow the code to compile, for better or for worse.

@matthew-mcallister
Copy link
Contributor

I seem to have found another similar case where this happens. If an impl Iterator borrowing a temporary is used in the final expression of a block, it causes the same compiler error. Switching to a return statement solves the error.

struct Array {
    inner: [u32; 3],
}

impl Array {
    fn iter(&self) -> impl Iterator<Item = &u32> {
        self.inner.iter()
    }

    fn compare(&self) -> bool {
        let foo2 = Array { inner: [1, 2, 3u32] };
        self.iter().zip(foo2.iter()).all(|(&x, &y)| x > y)
        // Switching to a return statement fixes it:
        //return self.iter().zip(foo2.iter()).all(|(&x, &y)| x > y);
    }
}

The error message actually does show how to fix the problem, though it's still fairly silly.

Output:

error[E0597]: `foo2` does not live long enough
  --> src/lib.rs:12:25
   |
12 |         self.iter().zip(foo2.iter()).all(|(&x, &y)| x > y)
   |         ----------------^^^^--------
   |         |               |
   |         |               borrowed value does not live long enough
   |         a temporary with access to the borrow is created here ...
...
15 |     }
   |     -
   |     |
   |     `foo2` dropped here while still borrowed
   |     ... and the borrow might be used here, when that temporary is dropped and runs the
destructor for type `std::iter::Zip<impl std::iter::Iterator, impl std::iter::Iterator>`
   |
   = note: The temporary is part of an expression at the end of a block. Consider forcing this
temporary to be dropped sooner, before the block's local variables are dropped. For example,
you could save the expression's value in a new local variable `x` and then make `x` be the
expression at the end of the block.

@danielhenrymantilla
Copy link
Contributor

danielhenrymantilla commented Sep 22, 2021

Yeah, this has to do with the drop glue (or potential drop glue in the case of RPIT (-> impl Trait)) of temporaries that belong to an end-of-block expression whose value thus "slides" onto the outer scope.

In that case, that drop glue runs at "the end of statement" w.r.t. the outer scope, not the inner one, which means that that drop glue runs after all the locals of that scope have been themselves dropped. So, if that -> impl 'local + … did happen to have drop glue that accessed the 'local-bound referee, then it could cause a use-after-free, hence the conservative error.

Doing let it = <expr with temporaries>; it (and, more surprisingly, return <expr with temporaries>;) changes the location of the "end of statement" where those temporaries shall be dropped.

Here is a curious playground showcasing this behavior:

use ::core::cell::Cell as Mut;

fn on_drop<'f, F: 'f>(f: F) -> impl 'f + Sized
// Feel free to replace the RPIT with:
//                          -> ::scopeguard::ScopeGuard<(), F>
where
    F: FnOnce(()),
{
    ::scopeguard::guard((), f)
}

fn explicit_return(b: &Mut<bool>) {
    let _local = on_drop(|()| b.set(true));
    return drop(&on_drop(|()| b.set(false)));
}

fn implicit_return(b: &Mut<bool>) {
    let _local = on_drop(|()| b.set(true));
    drop(&on_drop(|()| b.set(false)))
}

fn test(f: impl FnOnce(&Mut<bool>)) -> bool {
    let mut temporary_is_dropped_before_local = <_>::default(); /* or whatever */
    f(Mut::from_mut(&mut temporary_is_dropped_before_local));
    temporary_is_dropped_before_local
}

fn main() {
    assert_eq!(test(explicit_return), true);
    assert_eq!(test(implicit_return), false);
}

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: lifetime related
Projects
None yet
Development

No branches or pull requests

5 participants