Skip to content

DeriveDisplay macro for enum #1726

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Jul 10, 2023
Merged
12 changes: 3 additions & 9 deletions sea-orm-macros/src/derives/active_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ impl ActiveEnum {
} else if meta.path.is_ident("num_value") {
is_int = true;
num_value = Some(meta.value()?.parse::<LitInt>()?);
} else if meta.path.is_ident("display_value") {
Some(meta.value()?.parse::<LitStr>()?);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this is not needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the code for DeriveActiveEnum will panic if there is some unrecognised attributes, I added this so that deriving both Display and Active Enum would not make the code panic.

} else {
return Err(meta.error(format!(
"Unknown attribute parameter found: {:?}",
Expand Down Expand Up @@ -158,7 +160,7 @@ impl ActiveEnum {
}

variants.push(ActiveEnumVariant {
ident: variant.ident,
ident: variant.ident.clone(),
string_value,
num_value,
});
Expand Down Expand Up @@ -379,14 +381,6 @@ impl ActiveEnum {
}
}

#[automatically_derived]
impl std::fmt::Display for #ident {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let v: sea_orm::sea_query::Value = <Self as sea_orm::ActiveEnum>::to_value(&self).into();
write!(f, "{}", v)
}
}

#impl_not_u8
)
}
Expand Down
128 changes: 128 additions & 0 deletions sea-orm-macros/src/derives/active_enum_display.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned, ToTokens};
use syn::{LitStr, LitInt};

enum Error {
InputNotEnum,
Syn(syn::Error),
TT(TokenStream),
}

struct Display {
ident: syn::Ident,
variants: Vec<DisplayVariant>,
}

struct DisplayVariant {
ident: syn::Ident,
display_value: TokenStream,
}

impl Display {
fn new(input: syn::DeriveInput) -> Result<Self, Error> {
let ident = input.ident;

let variant_vec = match input.data {
syn::Data::Enum(syn::DataEnum { variants, .. }) => variants,
_ => return Err(Error::InputNotEnum),
};


let mut variants = Vec::new();
for variant in variant_vec {
let mut display_value = "".into_token_stream();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe?

let mut display_value = TokenStream::new();

https://docs.rs/proc-macro2/latest/proc_macro2/struct.TokenStream.html

let variant_span = variant.ident.span();
for attr in variant.attrs.iter() {
if !attr.path().is_ident("sea_orm") {
continue;
}
display_value = variant.ident.clone().to_token_stream();
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("string_value") {
Some(meta.value()?.parse::<LitStr>()?);
} else if meta.path.is_ident("num_value") {
Some(meta.value()?.parse::<LitInt>()?);
} else if meta.path.is_ident("display_value") {
display_value = meta.value()?.parse::<LitStr>()?.to_token_stream();
} else {
return Err(meta.error(format!(
"Unknown attribute parameter found: {:?}",
meta.path.get_ident()
)));
}

Ok(())
})
.map_err(Error::Syn)?;
}


variants.push(DisplayVariant {
ident: variant.ident,
display_value,
});
}
Ok(Display {
ident,
variants,
})
}

fn expand(&self) -> syn::Result<TokenStream> {
let expanded_impl_active_enum = self.impl_active_enum();

Ok(expanded_impl_active_enum)
}

fn impl_active_enum(&self) -> TokenStream {
let Self {
ident,
variants
} = self;

let variant_idents: Vec<syn::Ident> = variants
.iter()
.map(|variant| variant.ident.clone())
.collect();

let variant_display: Vec<TokenStream> = variants
.iter()
.map(|variant| {
variant.display_value.to_owned()
})
.collect();
let debug_token = quote!(
impl #ident {
fn to_display_value(&self) -> String {
match self {
#( Self::#variant_idents => #variant_display, )*
}
.to_owned()
}
}

#[automatically_derived]
impl std::fmt::Display for #ident {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let v: sea_orm::sea_query::Value = Self::to_display_value(&self).into();
write!(f, "{}", v)
}
}
);
dbg!(debug_token.clone().to_string());
debug_token
}
}

pub fn expand_derive_active_enum_display(input: syn::DeriveInput) -> syn::Result<TokenStream> {
let ident_span = input.ident.span();

match Display::new(input) {
Ok(model) => model.expand(),
Err(Error::InputNotEnum) => Ok(quote_spanned! {
ident_span => compile_error!("you can only derive activeenum_Display on enums");
}),
Err(Error::TT(token_stream)) => Ok(token_stream),
Err(Error::Syn(e)) => Err(e),
}
}
2 changes: 2 additions & 0 deletions sea-orm-macros/src/derives/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ mod related_entity;
mod relation;
mod try_getable_from_json;
mod util;
mod active_enum_display;

pub use active_enum::*;
pub use active_model::*;
Expand All @@ -31,3 +32,4 @@ pub use primary_key::*;
pub use related_entity::*;
pub use relation::*;
pub use try_getable_from_json::*;
pub use active_enum_display::*;
10 changes: 10 additions & 0 deletions sea-orm-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -832,3 +832,13 @@ pub fn enum_iter(input: TokenStream) -> TokenStream {
.unwrap_or_else(Error::into_compile_error)
.into()
}

#[cfg(feature = "derive")]
#[proc_macro_derive(DeriveDisplay, attributes(sea_orm))]
pub fn derive_active_enum_display(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match derives::expand_derive_active_enum_display(input) {
Ok(ts) => ts.into(),
Err(e) => e.to_compile_error().into(),
}
}
18 changes: 9 additions & 9 deletions src/entity/active_enum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use sea_query::{DynIden, Expr, Nullable, SimpleExpr, Value, ValueType};
/// use sea_orm::entity::prelude::*;
///
/// // Using the derive macro
/// #[derive(Debug, PartialEq, EnumIter, DeriveActiveEnum)]
/// #[derive(Debug, PartialEq, EnumIter, DeriveActiveEnum, DeriveDisplay)]
/// #[sea_orm(
/// rs_type = "String",
/// db_type = "String(Some(1))",
Expand Down Expand Up @@ -85,7 +85,7 @@ use sea_query::{DynIden, Expr, Nullable, SimpleExpr, Value, ValueType};
/// use sea_orm::entity::prelude::*;
///
/// // Define the `Category` active enum
/// #[derive(Debug, Clone, PartialEq, EnumIter, DeriveActiveEnum)]
/// #[derive(Debug, Clone, PartialEq, EnumIter, DeriveActiveEnum, DeriveDisplay)]
/// #[sea_orm(rs_type = "String", db_type = "String(Some(1))")]
/// pub enum Category {
/// #[sea_orm(string_value = "B")]
Expand Down Expand Up @@ -216,7 +216,7 @@ mod tests {
}
}

#[derive(Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum)]
#[derive(Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum, DeriveDisplay)]
#[sea_orm(
rs_type = "String",
db_type = "String(Some(1))",
Expand Down Expand Up @@ -276,7 +276,7 @@ mod tests {
fn active_enum_derive_signed_integers() {
macro_rules! test_num_value_int {
($ident: ident, $rs_type: expr, $db_type: expr, $col_def: ident) => {
#[derive(Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum)]
#[derive(Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum, DeriveDisplay)]
#[sea_orm(rs_type = $rs_type, db_type = $db_type)]
pub enum $ident {
#[sea_orm(num_value = -10)]
Expand All @@ -293,7 +293,7 @@ mod tests {

macro_rules! test_fallback_int {
($ident: ident, $fallback_type: ident, $rs_type: expr, $db_type: expr, $col_def: ident) => {
#[derive(Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum)]
#[derive(Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum, DeriveDisplay)]
#[sea_orm(rs_type = $rs_type, db_type = $db_type)]
#[repr(i32)]
pub enum $ident {
Expand Down Expand Up @@ -346,7 +346,7 @@ mod tests {
fn active_enum_derive_unsigned_integers() {
macro_rules! test_num_value_uint {
($ident: ident, $rs_type: expr, $db_type: expr, $col_def: ident) => {
#[derive(Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum)]
#[derive(Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum, DeriveDisplay)]
#[sea_orm(rs_type = $rs_type, db_type = $db_type)]
pub enum $ident {
#[sea_orm(num_value = 1)]
Expand All @@ -361,7 +361,7 @@ mod tests {

macro_rules! test_fallback_uint {
($ident: ident, $fallback_type: ident, $rs_type: expr, $db_type: expr, $col_def: ident) => {
#[derive(Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum)]
#[derive(Debug, PartialEq, Eq, EnumIter, DeriveActiveEnum, DeriveDisplay)]
#[sea_orm(rs_type = $rs_type, db_type = $db_type)]
#[repr($fallback_type)]
pub enum $ident {
Expand Down Expand Up @@ -408,7 +408,7 @@ mod tests {

#[test]
fn escaped_non_uax31() {
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum, Copy)]
#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum, Copy, DeriveDisplay)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we have a few test cases NOT deriving DeriveDisplay where it is not needed?

Just want to make sure we have test coverage for both cases.

#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "pop_os_names_typos")]
pub enum PopOSTypos {
#[sea_orm(string_value = "Pop!_OS")]
Expand Down Expand Up @@ -459,7 +459,7 @@ mod tests {
assert_eq!(PopOSTypos::try_from_value(&val.to_owned()), Ok(variant));
}

#[derive(Clone, Debug, PartialEq, EnumIter, DeriveActiveEnum)]
#[derive(Clone, Debug, PartialEq, EnumIter, DeriveActiveEnum, DeriveDisplay)]
#[sea_orm(
rs_type = "String",
db_type = "String(None)",
Expand Down
2 changes: 1 addition & 1 deletion src/entity/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub use crate::{
pub use crate::{
DeriveActiveEnum, DeriveActiveModel, DeriveActiveModelBehavior, DeriveColumn,
DeriveCustomColumn, DeriveEntity, DeriveEntityModel, DeriveIntoActiveModel, DeriveModel,
DerivePrimaryKey, DeriveRelatedEntity, DeriveRelation, FromJsonQueryResult,
DerivePrimaryKey, DeriveRelatedEntity, DeriveRelation, FromJsonQueryResult, DeriveDisplay,
};

pub use async_trait;
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ pub use sea_orm_macros::{
DeriveActiveEnum, DeriveActiveModel, DeriveActiveModelBehavior, DeriveColumn,
DeriveCustomColumn, DeriveEntity, DeriveEntityModel, DeriveIntoActiveModel,
DeriveMigrationName, DeriveModel, DerivePartialModel, DerivePrimaryKey, DeriveRelatedEntity,
DeriveRelation, FromJsonQueryResult, FromQueryResult,
DeriveRelation, FromJsonQueryResult, FromQueryResult, DeriveDisplay
};

pub use sea_query;
Expand Down
9 changes: 9 additions & 0 deletions tests/common/features/sea_orm_active_enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,12 @@ pub enum MediaType {
#[sea_orm(string_value = "3D")]
_3D,
}

#[derive(Debug, Clone, PartialEq, Eq, EnumIter, DeriveActiveEnum, DeriveDisplay)]
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "tea")]
pub enum DisplayTea {
#[sea_orm(string_value = "EverydayTea", display_value = "Everyday")]
EverydayTea,
#[sea_orm(string_value = "BreakfastTea", display_value = "Breakfast")]
BreakfastTea,
}