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

diagnostic refers to the wrong object's lifetime #126565

Open
spookyvision opened this issue Jun 16, 2024 · 0 comments
Open

diagnostic refers to the wrong object's lifetime #126565

spookyvision opened this issue Jun 16, 2024 · 0 comments
Labels
A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@spookyvision
Copy link
Contributor

Code

use std::{any::Any, cell::RefCell, rc::Rc};

fn doit(it: &dyn Any) {
    if let Some(s) = it.downcast_ref::<&str>() {
        println!("{s}");
    }
}
fn main() {
    // this works fine:
    let s = Rc::new(RefCell::new("hello, inner!"));
    let inner: &str = &s.borrow();
    doit(&inner as &dyn Any);
    // the commented line at the bottom doesn't compile:
    // `s` dropped here while still borrowed
    //
    // but it seems the real issue is not the lifetime of `s` but the
    // intermediate `Ref` created by `borrow()` that gets dropped too early.
    //
    //doit(&s.borrow() as &dyn Any);
}

Current output

error[E0597]: `s` does not live long enough
(...)
`s` dropped here while still borrowed

Desired output

casting Ref<'_, &'static str> to &dyn Any requires that `s` is borrowed for 'static

Rationale and extra context

the lifetime of s isn't the problem - it's the implicit temporary Ref object that does not live long enough

Other cases

No response

Rust Version

rustc 1.79.0 (129f3b996 2024-06-10)
binary: rustc
commit-hash: 129f3b9964af4d4a709d1383930ade12dfe7c081
commit-date: 2024-06-10
host: aarch64-apple-darwin
release: 1.79.0
LLVM version: 18.1.7

Anything else?

thanks to @Dirbaio for both figuring out the actual problem and suggesting the improved diagnostic!

@spookyvision spookyvision added A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Jun 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-diagnostics Area: Messages for errors, warnings, and lints T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

No branches or pull requests

1 participant