num-derive icon indicating copy to clipboard operation
num-derive copied to clipboard

Ignore zero-width fields like `PhantomData`

Open raklaptudirm opened this issue 1 year ago • 2 comments

Currently, the concept of "newtypes" only refers to structs with a single field. This prevents the derives for working when the structure might have zero-width types like PhantomData for complier hints.

// This should work.
#[derive(FromPrimitive)]
struct A<B>(u16, PhantomData<B>);

This behavior can be seen in #[repr(transparent)], where the annotation will work as long as there is only one non-zero-width type.

raklaptudirm avatar Jan 16 '25 08:01 raklaptudirm

AFAIK, we don't have any type information like size available in a proc macro, nor even path resolution to know that we're looking at core or std::marker::PhantomData in particular.

Maybe we could use an explicit "ignore" attribute though, akin to #[derivative(Hash="ignore")] or #[serde(skip)].

PS: Note that the nomicon description is incomplete -- the reference mentions that the other ZST fields must also have alignment 1 for #[repr(transparent)]. Alignment doesn't really matter for newtype derives though.

cuviper avatar Jan 17 '25 18:01 cuviper

A similar resolution was suggested in https://github.com/JelteF/derive_more/issues/437 so I am in favor of this approach.

raklaptudirm avatar Jan 18 '25 11:01 raklaptudirm