Skip to content

Commit

Permalink
Support #[ts(as = "...")] and #[ts(type = "...")] on enum variants (
Browse files Browse the repository at this point in the history
#284)

Co-authored-by: Gustavo Shigueo <gustavo.gsmn@gmail.com>
  • Loading branch information
escritorio-gustavo and gustavo-shigueo authored Sep 16, 2024
1 parent 6651d92 commit 9763ca0
Show file tree
Hide file tree
Showing 3 changed files with 291 additions and 213 deletions.
42 changes: 40 additions & 2 deletions macros/src/attr/variant.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
use syn::{Attribute, Fields, Ident, Result, Variant};
use syn::{Attribute, Fields, Ident, Result, Type, Variant};

use super::{Attr, Serde};
use crate::{
attr::{parse_assign_inflection, parse_assign_str, Inflection},
attr::{parse_assign_from_str, parse_assign_inflection, parse_assign_str, Inflection},
utils::parse_attrs,
};

#[derive(Default)]
pub struct VariantAttr {
pub type_as: Option<Type>,
pub type_override: Option<String>,
pub rename: Option<String>,
pub rename_all: Option<Inflection>,
pub inline: bool,
Expand All @@ -31,6 +33,8 @@ impl Attr for VariantAttr {

fn merge(self, other: Self) -> Self {
Self {
type_as: self.type_as.or(other.type_as),
type_override: self.type_override.or(other.type_override),
rename: self.rename.or(other.rename),
rename_all: self.rename_all.or(other.rename_all),
inline: self.inline || other.inline,
Expand All @@ -40,6 +44,38 @@ impl Attr for VariantAttr {
}

fn assert_validity(&self, item: &Self::Item) -> Result<()> {
if self.type_as.is_some() {
if self.type_override.is_some() {
syn_err_spanned!(
item;
"`as` is not compatible with `type`"
)
}

if self.rename_all.is_some() {
syn_err_spanned!(
item;
"`as` is not compatible with `rename_all`"
)
}
}

if self.type_override.is_some() {
if self.rename_all.is_some() {
syn_err_spanned!(
item;
"`type` is not compatible with `rename_all`"
)
}

if self.inline {
syn_err_spanned!(
item;
"`type` is not compatible with `inline`"
)
}
}

if !matches!(item.fields, Fields::Named(_)) && self.rename_all.is_some() {
syn_err_spanned!(
item;
Expand All @@ -53,6 +89,8 @@ impl Attr for VariantAttr {

impl_parse! {
VariantAttr(input, out) {
"as" => out.type_as = Some(parse_assign_from_str(input)?),
"type" => out.type_override = Some(parse_assign_str(input)?),
"rename" => out.rename = Some(parse_assign_str(input)?),
"rename_all" => out.rename_all = Some(parse_assign_inflection(input)?),
"inline" => out.inline = true,
Expand Down
Loading

0 comments on commit 9763ca0

Please sign in to comment.