Skip to content

generic_const_exprs doesn't evaluate size_of::<T>() if T has a generic #144021

Open
@SuperSamus

Description

@SuperSamus

Code

I tried this code:

#![feature(generic_const_exprs)]

#[repr(transparent)]
struct FixedI8<const FRAC: i32>(i8);

impl<const FRAC: i32> FixedI8<FRAC> {
    fn from_be_bytes(bytes: [u8; 1]) -> Self {
        todo!()
    }
}

trait Fixed
where
    Self: Sized,
{
    fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self;
}

impl<const FRAC: i32> Fixed for FixedI8<FRAC> {
    fn from_be_bytes(bits: [u8; size_of::<Self>()]) -> Self {
        Self::from_be_bytes(bits)
    }
}

And this code:

#![feature(generic_const_exprs)]

use std::marker::PhantomData;

#[repr(transparent)]
struct FixedI8<T> {
    field: i8,
    _a: PhantomData<T>,
}

impl<T> FixedI8<T> {
    fn from_be_bytes(bytes: [u8; 1]) -> Self {
        todo!()
    }
}

trait Fixed
where
    Self: Sized,
{
    fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self;
}

impl<T> Fixed for FixedI8<T> {
    fn from_be_bytes(bits: [u8; size_of::<Self>()]) -> Self {
        Self::from_be_bytes(bits)
    }
}

I expected to see this happen: the code compiles, just like before the regression, or how it still compiles if the type has no generic:

#![feature(generic_const_exprs)]

#[repr(transparent)]
struct FixedI8(i8);

impl FixedI8 {
    fn from_be_bytes(bytes: [u8; 1]) -> Self {
        todo!()
    }
}

trait Fixed
where
    Self: Sized,
{
    fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self;
}

impl Fixed for FixedI8 {
    fn from_be_bytes(bits: [u8; size_of::<Self>()]) -> Self {
        Self::from_be_bytes(bits)
    }
}

Instead, this happened:

error[E0308]: mismatched types
  --> src/lib.rs:26:29
   |
26 |         Self::from_be_bytes(bits)
   |                             ^^^^ expected `1`, found `size_of::<Self>()`
   |
   = note: expected constant `1`
              found constant `size_of::<Self>()`

Version with regression

The PR that caused the regression is #140553.

A real crate affected by the regression is the alpha version of fixed (issue on that repo).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-genericsArea: const generics (parameters and arguments)C-bugCategory: This is a bug.F-generic_const_exprs`#![feature(generic_const_exprs)]`T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions