rust-lang / rust-lang/rust

Lifetime extension in consts/statics sometimes makes *less* code compile

Open
#143,129 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-const-eval A-constant-promotion A-lifetimes A-temporary-lifetime-extension C-bug T-compiler T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

@traviscross found this fun example:

const C1: &[u8] = { let x: &'static mut [u8] = &mut []; x }; //~ OK
const C2: &[u8] = { &mut [] }; //~ ERROR

C1 compiles because empty arrays get promoted even behind mutable references.

C2 does not compile because that borrow is in lifetime extension position, and then the const-checks reject it due to being a non-transient mutable borrow. If we didn't do lifetime extension here, then the code would work, since then const-checks would consider the borrow to be transient, and finally promotion would make the rest work.

Not sure if this is worth fixing, but it's definitely odd. If we did want to fix it, we would have to either

  • ensure that const-checks accept non-transient borrows that will later get promoted (duplicating the same logic... ugh)
  • or run promotion before const-checks (which seems to be the opposite of what @oli-obk has planned)

@rust-lang/wg-const-eval

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

Reproduce the C1 and C2 examples and read the linked Rust Reference lifetime-extension section first. Then trace how lifetime extension, const-checks, and promotion process these borrows; a complete resolution would establish whether this behavior should change and make the intended result consistent.

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
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.