rust-lang / rust-lang/rust

`impl Trait` and bounds on associated types can produce values that mention invalid lifetimes

Open
#151,861 24 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-associated-items A-borrow-checker A-impl-trait C-bug I-types-nominated T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

View all comments

This was discovered by @danielhenrymantilla.

It seems that a value of type impl Trait<'a> + 'static can be used even if the lifetime 'a has already expired. This then can be used to produce a value of type &'a Thing, where 'a has already expired. For example:

fn foo<'r>(r: &'r str) -> impl 'static + Into<&'r str> {
    struct Wrapper(::core::ptr::NonNull<str>);
    
    impl<'r> Into<&'r str> for Wrapper {
        fn into(self) -> &'r str {
            unsafe {
                // Safety: `Wrapper` becomes an `impl use<'r> + Into<&'r str>`
                // so it cannot yield something with anything else than this `'r`
                // lifetime (or a covariant shrinkage thereof).
                self.0.as_ref()
            }
        }
    }
    
    Wrapper(r.into())
}

fn main() {
    let a = foo(&String::from("huh"));
    let _unrelated = String::from("UB!");
    dbg!(a.into());
}

The above code has one unsafe block, and causes use-after-free. It's unclear if this use of unsafe is correct or not, so I don't know if this is a soundness issue in rust's borrow checker.

As far as I can tell, this cannot cause UB without unsafe code. But still, it seems worrying.

Meta

Reproducible on the playground with version 1.95.0-nightly (2026-01-29 842bd5be253e17831e31)

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.

Research direction

Start by running the playground reproducer with nightly 1.95.0 (2026-01-29) and examine how impl Trait, associated-type bounds, and expired lifetimes are handled. Establish whether the behavior is a borrow-checker soundness issue and whether the unsafe conversion is permitted; done means the issue has a confirmed classification and a clearly defined compiler change or explanation.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.