Skip to content
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

DeriveDisplay macro for enum #1726

Merged
merged 17 commits into from
Jul 10, 2023
Merged
10 changes: 2 additions & 8 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") {
let _display_value = Some(meta.value()?.parse::<LitStr>()?);
} else {
return Err(meta.error(format!(
"Unknown attribute parameter found: {:?}",
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
129 changes: 129 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,129 @@
use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::{LitStr, Lit};

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

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

struct DisplayVariant {
ident: syn::Ident,
display_value: Option<LitStr>,
}

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

let mut name = ident.to_string();


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 = None;
let variant_span = variant.ident.span();
for attr in variant.attrs.iter() {
if !attr.path().is_ident("sea_orm") {
continue;
}
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("display_value") {
display_value = Some(meta.value()?.parse::<LitStr>()?);
} else {let _other_value = Some(meta.value()?.parse::<Lit>()?);}

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


variants.push(DisplayVariant {
ident: variant.ident,
display_value,
});
}
Ok(Display {
ident,
name,
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,
name,
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| {
if let Some(display_value) = &variant.display_value {
let string = display_value.value();
quote! { #string }
} else {
let ident = &variant.ident;
quote! { #ident }
}
})
.collect();

quote!(
impl #ident {
darkmmon marked this conversation as resolved.
Show resolved Hide resolved
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)
}
}
)
}
}

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,
}