diagnostic refers to the wrong object's lifetime
Open
Nobody has claimed this yet.
A-borrow-checker
A-diagnostics
A-lifetimes
D-confusing
D-terse
T-compiler
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
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!
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by compiling the provided Rust reproducer with rustc 1.79.0 and compare the current E0597 diagnostic with the desired message. Trace the compiler diagnostic path for the cast involving Ref<'_, &'static str> and the implicit temporary created by borrow(). Done means the diagnostic identifies the temporary Ref object's lifetime rather than incorrectly referring to s.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100