rust-lang / rust-lang/rust

rustc overflow with size_of::<Self> constraint

Open
#126,637 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-trait-system C-bug F-generic_const_exprs P-low T-compiler
Dominant language
Rust
Stars
119k
Forks
16.2k
PR merge metrics
PR metrics pending

Description

I want to do things with a type level representation of my type's size, i.e. U<{core::mem::size_of::<Self>()}> in the below code. This requires a [(); core::mem::size_of::<Self>()]: bound everywhere, which breaks the compiler.

This is especially annoying because IMO [(); core::mem::size_of::<T>()]: should come for free for all T

#![feature(associated_type_defaults)]
#![feature(generic_const_exprs)]

struct U<const N: usize>;

trait Foo: Sized where [(); core::mem::size_of::<Self>()]:
{
    type MyU = U<{core::mem::size_of::<Self>()}>;
}

impl<T: Sized> Foo for T 
where 
  [(); core::mem::size_of::<Self>()]:,
  Self::MyU:
{}

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=8352f18917259811c1e72a8fd153c684

This simplified version also breaks

#![feature(generic_const_exprs)]

struct U<const N: usize>;

trait Foo: Sized where [(); core::mem::size_of::<Self>()]:
{
    type MyU;
}

impl<T: Sized> Foo for T 
where 
  [(); core::mem::size_of::<Self>()]:,
  Self::MyU:
{}

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=a224e122810fcfbb34c69b56a067ce82

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 reproducing both linked Rust Playground examples on nightly and recording the overflow diagnostics. Then trace the compiler's handling of the [(); core::mem::size_of::<Self>()]: bounds and generic const expressions; done means these examples no longer overflow while preserving the intended validity checks.

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.