c2rust icon indicating copy to clipboard operation
c2rust copied to clipboard

Translate enums as newtype structs with associated constants?

Open Rua opened this issue 3 weeks ago • 1 comments

Currently, enums are translated as simple type aliases, with their variants translated as separate const values. This translation loses the connection between the variants and the enum they belong to. So I wonder if it would be nicer to translate them as newtype structs with associated constants?

So the following C code

enum MyEnum {
    Variant1,
    Variant2,
    Variant3,
};

would become

#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct MyEnum(pub ::core::ffi::c_uint);

impl MyEnum {
    pub const Variant1: Self = Self(0);
    pub const Variant2: Self = Self(1);
    pub const Variant3: Self = Self(2);
}

This matches how, for example, ash translates C enums (example). This way, the information that was present in the C type system is not lost, which is a benefit for later refactoring. The user can refactor it into the original system relatively easily if they want.

Rua avatar Dec 07 '25 17:12 Rua

I agree this would be a nicer translation. We would also need to add casts in places where an enum is implicitly coerced to an int or other enum, which does happen in C a bunch.

kkysen avatar Dec 07 '25 19:12 kkysen