rust: macros: Add derive Display for enums
Subsystems (4)
v2 cover rust: macros: Add derive Display for enums
This patch series adds a derive macro for implementing kernel::fmt::Display on enums using the syn crate, and then applies it to the Chipset enum in the nova-core driver.
Maurice Hieronymus (2):
rust: macros: Add derive Display for enums
gpu: nova-core: Use derive Display for Chipset enum
drivers/gpu/nova-core/gpu.rs | 17 ++---------- rust/macros/display.rs | 52 ++++++++++++++++++++++++++++++++++++ rust/macros/lib.rs | 42 +++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 15 deletions(-) create mode 100644 rust/macros/display.rs
---
v1: https://lore.kernel.org/all/[email protected]/
Changes since v1:
- Instead of using the name() method with lowercase strings, implement a proper derive macro using syn as suggested by the reviewer
- The derive macro outputs the exact variant name as written (case-preserved)
- Supports all enum variant types: unit, tuple, and struct variants
base-commit: f8f9c1f4d0c7a64600e2ca312dec824a0bc2f1da
Signature · 1 line
2.51.2
PATCH v2 1/2 rust: macros: Add derive Display for enums
Add a derive macro that implements kernel::fmt::Display for enums. The macro outputs the exact variant name as written, preserving case.
This supports all enum variant types: unit, tuple, and struct variants. For variants with data, only the variant name is displayed.
--- rust/macros/display.rs | 52 ++++++++++++++++++++++++++++++++++++++++++ rust/macros/lib.rs | 42 ++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 rust/macros/display.rs
rust/macros/display.rs new file +52 -0
@@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Derive macro for `Display` on enums. +//! +//! This module provides a derive macro that implements `kernel::fmt::Display` +//! for enums, outputting the exact variant name as written. + +use proc_macro::TokenStream ; + +pub (crate )fn derive_display (input:TokenStream ) ->TokenStream { +let input: syn::DeriveInput = syn::parse (input).expect ("failed to parse input" ); + +let data =match &input.data { + syn::Data ::Enum (data) => data, + syn::Data ::Struct (_) => { +panic! ("derive(Display) only supports enums, not structs" ); + } + syn::Data ::Union (_) => { +panic! ("derive(Display) only supports enums, not unions" ); + } + }; + +// Generate match arms for each variant. +let match_arms = data.variants.iter ().map (|variant| { +let variant_ident = &variant.ident; +let variant_name = variant_ident.to_string (); + +// Handle different variant types: unit, tuple, and struct. +let pattern =match &variant.fields { + syn::Fields ::Unit => quote::quote! {Self ::#variant_ident }, + syn::Fields ::Unnamed (_) => quote::quote! {Self ::#variant_ident (..) }, + syn::Fields ::Named (_) => quote::quote! {Self ::#variant_ident { .. } }, + }; + + quote::quote! { + #pattern => f.write_str (#variant_name) + } + }); + +let name = &input.ident; +let expanded = quote::quote! { +impl ::kernel::fmt::Display for #name { +fn fmt (&self, f: &mut ::kernel::fmt::Formatter <'_>) -> ::kernel::fmt::Result { +match self { + #(#match_arms),* + } + } + } + }; + + expanded.into () +}
rust/macros/lib.rs +42 -0
51 lines not on this page · raw message
Signature · 1 line
2.51.2
Benno Lossin
reviewerQuoted 5 lines · Maurice Hieronymus
Add a derive macro that implements
kernel::fmt::Displayfor enums. The macro outputs the exact variant name as written, preserving case.This supports all enum variant types: unit, tuple, and struct variants. For variants with data, only the variant name is displayed.
I don't think we should be adding this. Display is designed for user-facing output and so it should always be carefully designed and no automation should exist for it.
The use-case in the second patch is also much better served by either a manual match on the enum:
impl fmt::Display for Chipset {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Chipset::Variant => write!(f, "Variant"),
// ...
}
}
}Or by adding the respective code in the declarative macro already used to define it.
Cheers,
Benno
Quoted 6 lines
Signed-off-by Maurice Hieronymus <[email protected]>--- rust/macros/display.rs | 52 ++++++++++++++++++++++++++++++++++++++++++ rust/macros/lib.rs | 42 ++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 rust/macros/display.rs
Danilo Krummrich
maintainerQuoted 10 lines · Benno Lossin
Quoted 5 lines · Maurice Hieronymus
Add a derive macro that implements
kernel::fmt::Displayfor enums. The macro outputs the exact variant name as written, preserving case.This supports all enum variant types: unit, tuple, and struct variants. For variants with data, only the variant name is displayed.
I don't think we should be adding this. Display is designed for user-facing output and so it should always be carefully designed and no automation should exist for it.
In general I agree, but simple stringification of an enum variant for a Display implementation is a very common use-case and it seems pretty unfortunate to have to fall back to either do the below (especially if there are a lot of enum variants) or having to go the declarative path of doing something as in [1].
Especially in combination with things like FromPrimitive and ToPrimitive it gets us rid of the cases where we need such declarative macro mess.
Eventually, drivers will most likely implement their own proc macro for this or repeat the declarative macro pattern over and over again.
Maybe we should just pick a more specific name for such a derive macro than macros::Display.
Maybe something along the lines of macros::EnumVariantDisplay? We could also have an optional argument indicating whether it should be converted to lower / upper case.
Benno Lossin
reviewerQuoted 17 lines · Danilo Krummrich
Quoted 10 lines · Benno Lossin
Quoted 5 lines · Maurice Hieronymus
Add a derive macro that implements
kernel::fmt::Displayfor enums. The macro outputs the exact variant name as written, preserving case.This supports all enum variant types: unit, tuple, and struct variants. For variants with data, only the variant name is displayed.
I don't think we should be adding this. Display is designed for user-facing output and so it should always be carefully designed and no automation should exist for it.
In general I agree, but simple stringification of an enum variant for a Display implementation is a very common use-case and it seems pretty unfortunate to have to fall back to either do the below (especially if there are a lot of enum variants) or having to go the declarative path of doing something as in [1].
Quoted 5 lines
Especially in combination with things like FromPrimitive and ToPrimitive it gets us rid of the cases where we need such declarative macro mess.
Eventually, drivers will most likely implement their own proc macro for this or repeat the declarative macro pattern over and over again.
When the definition already uses declarative macros, adding the Display impl there is the correct way to do it IMO. If it is just a normal definition, then a match is annoying when you have many variants.
Quoted 6 lines
Maybe we should just pick a more specific name for such a derive macro than
macros::Display.Maybe something along the lines of
macros::EnumVariantDisplay? We could also have an optional argument indicating whether it should be converted to lower / upper case.
I'm still skeptical about having a derive macro for Display. What about adding & deriving the following trait instead:
pub trait EnumVariantName {
fn variant_name(&self) -> &'static str;
}To print this, you of course need to call the function, but it is much more self-descriptive than printing the Chipset directly.
Cheers,
Benno
Danilo Krummrich
maintainerQuoted 6 lines · Benno Lossin
I'm still skeptical about having a derive macro for
Display. What about adding & deriving the following trait instead:pub trait EnumVariantName { fn variant_name(&self) -> &'static str; }
With a derive macro for this trait, that sounds absolutely reasonable -- a corresponding Display implementation becomes trivial with this.
Quoted 11 lines · Danilo Krummrich
Quoted 6 lines · Benno Lossin
I'm still skeptical about having a derive macro for
Display. What about adding & deriving the following trait instead:pub trait EnumVariantName {
fnvariant_name(&self)-> &'static str;
}With a derive macro for this trait, that sounds absolutely reasonable -- a
corresponding Display implementation becomes trivial with this.
Sounds good to me too. I will change my implementation and send a V3 shortly.
Gary Guo
reviewerQuoted 23 lines · On Mon, 05 Jan 2026 11:29:04 +0100 "Danilo Krummrich" <[email protected]> wrote:
Quoted 10 lines · Benno Lossin
Quoted 5 lines · Maurice Hieronymus
Add a derive macro that implements
kernel::fmt::Displayfor enums. The macro outputs the exact variant name as written, preserving case.This supports all enum variant types: unit, tuple, and struct variants. For variants with data, only the variant name is displayed.
I don't think we should be adding this. Display is designed for user-facing output and so it should always be carefully designed and no automation should exist for it.
In general I agree, but simple stringification of an enum variant for a Display implementation is a very common use-case and it seems pretty unfortunate to have to fall back to either do the below (especially if there are a lot of enum variants) or having to go the declarative path of doing something as in [1].
Especially in combination with things like FromPrimitive and ToPrimitive it gets us rid of the cases where we need such declarative macro mess.
Eventually, drivers will most likely implement their own proc macro for this or repeat the declarative macro pattern over and over again.
Quoted 6 lines
Maybe we should just pick a more specific name for such a derive macro than
macros::Display.Maybe something along the lines of
macros::EnumVariantDisplay? We could also have an optional argument indicating whether it should be converted to lower / upper case.
I think the proposal is reasonable.
Being able to print enum name is very common and this is why crates like strum exist.
Perhaps if we want to make user having a thought about what names to expose to users, we can have the case conversion argument be mandatory, so they are forced to make a choice rather than blindly stuck #[derive(Display)] onto their enum.
Best,
Gary
Quoted 46 lines · Gary Guo
Quoted 37 lines · On Mon, 05 Jan 2026 11:29:04 +0100 "Danilo Krummrich" <[email protected]> wrote:
Quoted 6 lines · Benno Lossin
Quoted 5 lines · Maurice Hieronymus
Add a derive macro that implements
kernel::fmt::Displayfor enums.
The macro outputs the exact variant name as written, preserving case.Quoted 8 lines
Quoted 3 lines
This supports all enum variant types: unit, tuple, and struct variants.
For variants with data, only the variant name is displayed.I don't think we should be adding this. Display is designed for user-facing output and so it should always be carefully designed and no
automation should exist for it.In general I agree, but simple stringification of an enum variant for a Display
implementation is a very common use-case and it seems pretty unfortunate to have
to fall back to either do the below (especially if there are a lot of enum
variants) or having to go the declarative path of doing something as in [1].Especially in combination with things like FromPrimitive and ToPrimitive it gets
us rid of the cases where we need such declarative macro mess.Eventually, drivers will most likely implement their own proc macro for this or
repeat the declarative macro pattern over and over again.Maybe we should just pick a more specific name for such a derive macro than
macros::Display.Quoted 5 lines
Maybe something along the lines of
macros::EnumVariantDisplay? We could also
have an optional argument indicating whether it should be converted to lower /
upper case.
Quoted 5 lines
I think the proposal is reasonable.
Being able to print enum name is very common and this is why crates likestrumexist.
Before I start implementing, I want to reach common ground.
In my opinion a derive macro which implements Display would be perfectly fine, as long as the name suggests what it does. So for example #[derive(DisplayEnumVariant)]. This would communicate the intent clearly to the user.
Benno, would you be okay with that? If not, Gary and Danilo, are you fine with the proposed trait implementation (e.g. the variant_name function)?
Quoted 6 lines
Perhaps if we want to make user having a thought about what names to expose to users, we can have the case conversion argument be mandatory, so
they are forced to make a choice rather than blindly stuck#[derive(Display)]onto their enum.
Are there any common use-cases where one wants to change the case of the enum variants? If not, I would not implement an argument and rather name the macro accordingly, so the intent is clear.
Thanks,
Maurice
Quoted 2 lines
Best,
Gary
Danilo Krummrich
maintainerQuoted 10 lines · Maurice Hieronymus
Before I start implementing, I want to reach common ground.
In my opinion a derive macro which implements Display would be perfectly fine, as long as the name suggests what it does. So for example #[derive(DisplayEnumVariant)]. This would communicate the intent clearly to the user.
Benno, would you be okay with that? If not, Gary and Danilo, are you fine with the proposed trait implementation (e.g. the
variant_namefunction)?
Actually, it might even be reasonable to have both. In the Nova driver we have the case that we want to print the enum variant exactly as it is defined in the code and a lowercase version of the enum variant.
Quoted 3 lines
Are there any common use-cases where one wants to change the case of the enum variants? If not, I would not implement an argument and rather name the macro accordingly, so the intent is clear.
As mentioned above, we do have a case in Nova where we also want a lowercase representation to construct a firmware path with.
Quoted 25 lines · Danilo Krummrich
Quoted 11 lines · Maurice Hieronymus
Before I start implementing, I want to reach common ground.
In my opinion a derive macro which implements Display would be perfectly fine, as long as the name suggests what it does. So for example #[derive(DisplayEnumVariant)]. This would communicate the intent clearly to the user.
Benno, would you be okay with that? If not, Gary and Danilo, are you
fine with the proposed trait implementation (e.g. thevariant_namefunction)?Actually, it might even be reasonable to have both. In the Nova driver we have
the case that we want to print the enum variant exactly as it is defined in the
code and a lowercase version of the enum variant.Quoted 5 lines
Are there any common use-cases where one wants to change the case of
the enum variants? If not, I would not implement an argument and rather
name the macro accordingly, so the intent is clear.
Quoted 3 lines
As mentioned above, we do have a case in Nova where we also want a lowercase
representation to construct a firmware path with.
So there would be the need to have two derive macros:
1. #[derive(DisplayEnumVariant)]
Implements Display for all enum variants as they are (original case).
2. #[derive(ImplementVariantName(Case::Lowercase))] Implements the mentioned trait. Case could be an Enum where one could choose between Case::Lowercase and Case::Original.
Something along those lines?
Benno Lossin
reviewerQuoted 10 lines · Maurice Hieronymus
Quoted 9 lines · Danilo Krummrich
Quoted 8 lines · Maurice Hieronymus
Before I start implementing, I want to reach common ground.
In my opinion a derive macro which implements Display would be perfectly fine, as long as the name suggests what it does. So for example #[derive(DisplayEnumVariant)]. This would communicate the intent clearly to the user.
Benno, would you be okay with that? If not, Gary and Danilo, are
I'd prefer if we stay a bit more cautious about directly deriving Display. The trait with the variant name sounds like a very sensible idea.
We can talk about this in the team in our weekly meeting, they might change my mind :)
Quoted 20 lines
Quoted 16 lines
Quoted 3 lines
you
fine with the proposed trait implementation (e.g. thevariant_namefunction)?Actually, it might even be reasonable to have both. In the Nova driver we have
the case that we want to print the enum variant exactly as it is defined in the
code and a lowercase version of the enum variant.Quoted 5 lines
Are there any common use-cases where one wants to change the case of
the enum variants? If not, I would not implement an argument and rather
name the macro accordingly, so the intent is clear.Quoted 3 lines
As mentioned above, we do have a case in Nova where we also want a lowercase
representation to construct a firmware path with.
Quoted 8 lines
So there would be the need to have two derive macros:
1. #[derive(DisplayEnumVariant)]
Implements Display for all enum variants as they are (original case).2. #[derive(ImplementVariantName(Case::Lowercase))] Implements the mentioned trait. Case could be an Enum where one could choose between
Case::LowercaseandCase::Original.
You'll need to use a helper attribute, something like:
#[derive(VariantName)]
#[variant_name(case = "lowercase")]Cheers,
Benno
PATCH v2 2/2 gpu: nova-core: Use derive Display for Chipset enum
In reply to Maurice HieronymusUse the derive macro for implementing fmt::Display on the Chipset enum instead of relying on the compiler-generated Display output. This ensures stable display strings that won't change unexpectedly.
--- drivers/gpu/nova-core/gpu.rs | 17 ++--------------- 1 file changed, 2 insertions(+), 15 deletions(-)
drivers/gpu/nova-core/gpu.rs +2 -15
@@ -4,6 +4,7 @@ device, devres::Devres, fmt, + macros, pci, prelude::*, sync::Arc, //
@@ -26,7 +27,7 @@ macro_rules! define_chipset { ({ $($variant:ident = $value:expr),* $(,)* }) => {/// Enum representation of the GPU chipset. -#[derive(fmt:: Debug , Copy , Clone , PartialOrd , Ord , PartialEq , Eq )] +#[derive(macros:: Display , fmt:: Debug , Copy , Clone , PartialOrd , Ord , PartialEq , Eq )] pub(crate) enum Chipset { $($variant = $value),*, }
@@ -107,20 +108,6 @@ pub(crate) fn arch(&self) -> Architecture { } } -// TODO -// -// The resulting strings are used to generate firmware paths, hence the -// generated strings have to be stable. -// -// Hence, replace with something like strum_macros derive(Display). -// -// For now, redirect to fmt::Debug for convenience. -impl fmt::Display for Chipset { -fn fmt (&self, f: &mut fmt::Formatter <'_>) -> fmt::Result { -write! (f,"{self:?}" ) - } -} -/// Enum representation of the GPU generation. /// /// TODO: remove the `Default` trait implementation, and the `#[default]`
Signature · 1 line
2.51.2