rust-lang / rust-lang/rust

`#![feature(generic_const_exprs)]` does not compile stable code related to lifetimes

Open
#124,531 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-const-generics C-bug F-generic_const_exprs P-low S-has-mcve T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Concretely, consider the following code which compiles perfectly fine under both stable and nightly rust

use std::marker::PhantomData;

const CONSTANT_M: usize = 4;

struct Foo<T, const GENERIC_M: usize> {
    content: PhantomData<[T; GENERIC_M]>
}

struct Foobar<'a, T>
    where T: 'a
{
    data: &'a T
}

fn create_foo<'a, F>(_: F) -> &'a Foo<i32, CONSTANT_M>
    where F: FnMut(i64) -> ()
{
    Box::leak(Box::new(Foo { content: PhantomData }))
}

fn create_foobar() -> Foobar<'static, Foo<i32, CONSTANT_M>> {
    let create = |_: i64| ();
    Foobar { data: create_foo::<'static, _>(|y| create(y)) }
}

Playground

This makes complete sense, since the lifetime parameters on the function create_foo() clearly specify that F must be valid in the body of the function, but not necessarily for the whole lifetime 'a. Note also that the code uses const generics, but only the subset that has been stabilized.

However, just adding #![feature(generic_const_exprs)] without changing anything else gives a compiler error

closure may outlive the current function, but it borrows `create`, which is owned by the current function

within create_foobar(). This should not be the case, as the closure stored in the variable create does not have to outlive the current function, or even live for 'static.
Playground

I am using rustc 1.77.0-nightly.

Edit Significantly simplified example code.

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 two linked Playground examples with and without #![feature(generic_const_exprs)] and compare the diagnostics. Trace the lifetime and closure handling involved in create_foo and create_foobar; done means the example remains accepted when the feature is enabled, without incorrectly requiring the closure to outlive the current function.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.