diff --git a/example/Cargo.toml b/example/Cargo.toml index bf5ae30..b12617b 100644 --- a/example/Cargo.toml +++ b/example/Cargo.toml @@ -5,4 +5,5 @@ authors = ["Moritz Bischof "] edition = "2018" [dependencies] -ts-rs = { path = "../ts-rs" } +ts-rs = { path = "../ts-rs", features = ["serde-compat"] } +serde = { version = "1", features = ["derive"] } \ No newline at end of file diff --git a/example/src/lib.rs b/example/src/lib.rs index 0f888db..6e616be 100644 --- a/example/src/lib.rs +++ b/example/src/lib.rs @@ -1,29 +1,31 @@ #![allow(dead_code)] +use serde::Serialize; use ts_rs::TS; -#[derive(TS)] +#[derive(Serialize, TS)] enum Role { User, Admin, } -#[derive(TS)] +#[derive(Serialize, TS)] +#[serde(rename_all = "UPPERCASE")] #[ts(rename_all = "lowercase")] enum Gender { Male, Female, - Other + Other, } -#[derive(TS)] +#[derive(Serialize, TS)] struct User { user_id: i32, first_name: String, last_name: String, role: Role, #[ts(inline)] - gender: Gender + gender: Gender, } #[cfg(test)] diff --git a/macros/Cargo.toml b/macros/Cargo.toml index a1a25ee..62206ca 100644 --- a/macros/Cargo.toml +++ b/macros/Cargo.toml @@ -8,6 +8,9 @@ license = "MIT" homepage = "https://github.com/Aleph-Alpha/ts-rs" repository = "https://github.com/Aleph-Alpha/ts-rs" +[features] +serde-compat = [] + [lib] proc-macro = true diff --git a/macros/src/attr/enum.rs b/macros/src/attr/enum.rs index 0475571..4007bbf 100644 --- a/macros/src/attr/enum.rs +++ b/macros/src/attr/enum.rs @@ -1,10 +1,8 @@ use std::convert::TryFrom; -use syn::{Attribute, Error, Ident, Result, Token}; -use syn::ext::IdentExt; -use syn::parse::{Parse, ParseStream}; +use syn::{Attribute, Ident, Result}; -use crate::attr::{parse_assign_string_lit, Inflection}; +use crate::attr::{parse_assign_inflection, parse_assign_str, Inflection}; #[derive(Default)] pub struct EnumAttr { @@ -12,16 +10,15 @@ pub struct EnumAttr { pub rename: Option, } -impl TryFrom<&Attribute> for EnumAttr { - type Error = Error; - - fn try_from(attr: &Attribute) -> Result { - attr.parse_args() - } -} - impl EnumAttr { pub fn from_attrs(attrs: &[Attribute]) -> Result { + println!( + "{:?}", + attrs + .iter() + .map(|a| a.path.is_ident("serde")) + .collect::>() + ); attrs .iter() .filter(|a| a.path.is_ident("ts")) @@ -40,25 +37,9 @@ impl EnumAttr { } } -impl Parse for EnumAttr { - fn parse(input: ParseStream) -> Result { - let mut out = EnumAttr::default(); - loop { - let key = input.call(Ident::parse_any)?; - match &*key.to_string() { - "rename" => out.rename = Some(parse_assign_string_lit(input)?), - "rename_all" => out.rename_all = Some(parse_assign_string_lit(input).and_then(Inflection::try_from)?), - _ => return Err(Error::new(input.span(), "unexpected key")), - }; - - match input.is_empty() { - true => break, - false => { - input.parse::()?; - } - }; - } - - Ok(out) +impl_parse! { + EnumAttr(input, out) { + "rename" => out.rename = Some(parse_assign_str(input)?), + "rename_all" => out.rename_all = Some(parse_assign_inflection(input)?), } } diff --git a/macros/src/attr/field.rs b/macros/src/attr/field.rs index 268f4c2..a5eb122 100644 --- a/macros/src/attr/field.rs +++ b/macros/src/attr/field.rs @@ -1,8 +1,6 @@ -use super::parse_assign_string_lit; +use super::parse_assign_str; use std::convert::TryFrom; -use syn::ext::IdentExt; -use syn::parse::{Parse, ParseStream}; -use syn::{Attribute, Error, Ident, Result, Token}; +use syn::{Attribute, Ident, Result}; #[derive(Default)] pub struct FieldAttr { @@ -32,34 +30,10 @@ impl FieldAttr { } } -impl TryFrom<&Attribute> for FieldAttr { - type Error = Error; - - fn try_from(attr: &Attribute) -> Result { - attr.parse_args() - } -} - -impl Parse for FieldAttr { - fn parse(input: ParseStream) -> Result { - let mut out = FieldAttr::default(); - loop { - let key = input.call(Ident::parse_any)?; - match &*key.to_string() { - "type" => out.type_override = Some(parse_assign_string_lit(input)?), - "rename" => out.rename = Some(parse_assign_string_lit(input)?), - "inline" => out.inline = true, - _ => return Err(Error::new(input.span(), "unexpected key")), - }; - - match input.is_empty() { - true => break, - false => { - input.parse::()?; - } - }; - } - - Ok(out) +impl_parse! { + FieldAttr(input, out) { + "type" => out.type_override = Some(parse_assign_str(input)?), + "rename" => out.rename = Some(parse_assign_str(input)?), + "inline" => out.inline = true, } } diff --git a/macros/src/attr/mod.rs b/macros/src/attr/mod.rs index 1521fe5..24530a8 100644 --- a/macros/src/attr/mod.rs +++ b/macros/src/attr/mod.rs @@ -1,13 +1,13 @@ use std::convert::TryFrom; -use syn::{Error, Lit, parse::Parse, parse::ParseStream, Result, Token}; +use syn::{parse::Parse, parse::ParseStream, Error, Lit, Result, Token}; pub use field::*; pub use r#enum::*; pub use r#struct::*; -mod field; mod r#enum; +mod field; mod r#struct; #[derive(Copy, Clone, Debug)] @@ -30,7 +30,7 @@ impl Inflection { Inflection::Camel => string.to_camel_case(), Inflection::Snake => string.to_snake_case(), Inflection::Pascal => string.to_pascal_case(), - Inflection::ScreamingSnake => string.to_screaming_snake_case() + Inflection::ScreamingSnake => string.to_screaming_snake_case(), } } } @@ -46,15 +46,19 @@ impl TryFrom for Inflection { "snake_case" | "snakecase" => Self::Snake, "pascalcase" => Self::Pascal, "screaming_snake_case" | "screamingsnakecase" => Self::ScreamingSnake, - _ => syn_err!("invalid inflection: '{}'", value) + _ => syn_err!("invalid inflection: '{}'", value), }) } } -fn parse_assign_string_lit(input: ParseStream) -> Result { +fn parse_assign_str(input: ParseStream) -> Result { input.parse::()?; match Lit::parse(input)? { Lit::Str(string) => Ok(string.value()), other => Err(Error::new(other.span(), "expected string")), } } + +fn parse_assign_inflection(input: ParseStream) -> Result { + parse_assign_str(input).and_then(Inflection::try_from) +} diff --git a/macros/src/attr/struct.rs b/macros/src/attr/struct.rs index 6649e3e..e7d57fc 100644 --- a/macros/src/attr/struct.rs +++ b/macros/src/attr/struct.rs @@ -1,8 +1,8 @@ -use crate::attr::{Inflection, parse_assign_string_lit}; -use syn::{Attribute, Error, Result, Token, Ident}; use std::convert::TryFrom; -use syn::parse::{Parse, ParseStream}; -use syn::ext::IdentExt; + +use syn::{Attribute, Ident, Result}; + +use crate::attr::{parse_assign_str, Inflection}; #[derive(Default)] pub struct StructAttr { @@ -10,15 +10,6 @@ pub struct StructAttr { pub rename: Option, } -impl TryFrom<&Attribute> for StructAttr { - type Error = Error; - - fn try_from(attr: &Attribute) -> Result { - attr.parse_args() - } -} - - impl StructAttr { pub fn from_attrs(attrs: &[Attribute]) -> Result { attrs @@ -39,25 +30,9 @@ impl StructAttr { } } -impl Parse for StructAttr { - fn parse(input: ParseStream) -> Result { - let mut out = StructAttr::default(); - loop { - let key = input.call(Ident::parse_any)?; - match &*key.to_string() { - "rename" => out.rename = Some(parse_assign_string_lit(input)?), - "rename_all" => out.rename_all = Some(parse_assign_string_lit(input).and_then(Inflection::try_from)?), - _ => return Err(Error::new(input.span(), "unexpected key")), - }; - - match input.is_empty() { - true => break, - false => { - input.parse::()?; - } - }; - } - - Ok(out) +impl_parse! { + StructAttr(input, out) { + "rename" => out.rename = Some(parse_assign_str(input)?), + "rename_all" => out.rename_all = Some(parse_assign_str(input).and_then(Inflection::try_from)?), } } diff --git a/macros/src/enum/mod.rs b/macros/src/enum/mod.rs index 8109f9d..e2cdfc2 100644 --- a/macros/src/enum/mod.rs +++ b/macros/src/enum/mod.rs @@ -1,7 +1,7 @@ use quote::quote; use syn::{ItemEnum, Result}; -use crate::attr::{FieldAttr, EnumAttr}; +use crate::attr::{EnumAttr, FieldAttr}; use crate::DerivedTS; pub(crate) fn r#enum(s: &ItemEnum) -> Result { @@ -20,7 +20,7 @@ pub(crate) fn r#enum(s: &ItemEnum) -> Result { let name = match (rename, &rename_all) { (Some(rn), _) => rn, (None, None) => variant.ident.to_string(), - (None, Some(rn)) => rn.apply(&variant.ident.to_string()) + (None, Some(rn)) => rn.apply(&variant.ident.to_string()), }; if type_override.is_some() { syn_err!("`type_override` is not applicable to enum variants") diff --git a/macros/src/macros.rs b/macros/src/macros.rs index b5ff5f9..c366437 100644 --- a/macros/src/macros.rs +++ b/macros/src/macros.rs @@ -6,3 +6,37 @@ macro_rules! syn_err { return Err(syn::Error::new($s, format!($l $(, $a)*))); }; } + +macro_rules! impl_parse { + ($i:ident ($input:ident, $out:ident) { $($k:literal => $e:expr),* $(,)? }) => { + impl std::convert::TryFrom<&syn::Attribute> for $i { + type Error = syn::Error; + + fn try_from(attr: &syn::Attribute) -> syn::Result { + attr.parse_args() + } + } + + impl syn::parse::Parse for $i { + fn parse($input: syn::parse::ParseStream) -> syn::Result { + let mut $out = $i::default(); + loop { + let key: Ident = $input.call(syn::ext::IdentExt::parse_any)?; + match &*key.to_string() { + $($k => $e,)* + other => syn_err!("unexpected attribute key `{}`", other) + } + + match $input.is_empty() { + true => break, + false => { + $input.parse::()?; + } + } + } + + Ok($out) + } + } + }; +} diff --git a/macros/src/struct/named.rs b/macros/src/struct/named.rs index c966e1b..7b0a814 100644 --- a/macros/src/struct/named.rs +++ b/macros/src/struct/named.rs @@ -2,7 +2,7 @@ use proc_macro2::TokenStream; use quote::quote; use syn::{Field, FieldsNamed, ItemStruct, Result}; -use crate::attr::{FieldAttr, StructAttr, Inflection}; +use crate::attr::{FieldAttr, Inflection, StructAttr}; use crate::DerivedTS; pub(crate) fn named(s: &ItemStruct, i: &FieldsNamed) -> Result { @@ -43,7 +43,7 @@ fn format_field(field: &Field, rename_all: &Option) -> Result rn, (None, Some(rn)) => rn.apply(&field.ident.as_ref().unwrap().to_string()), - (None, None) => field.ident.as_ref().unwrap().to_string() + (None, None) => field.ident.as_ref().unwrap().to_string(), }; Ok(quote! { diff --git a/macros/src/struct/newtype.rs b/macros/src/struct/newtype.rs index b72b2b6..f4d1294 100644 --- a/macros/src/struct/newtype.rs +++ b/macros/src/struct/newtype.rs @@ -4,7 +4,10 @@ use quote::quote; use syn::{FieldsUnnamed, ItemStruct, Result}; pub(crate) fn newtype(s: &ItemStruct, i: &FieldsUnnamed) -> Result { - let StructAttr { rename_all, rename: rename_outer } = StructAttr::from_attrs(&s.attrs)?; + let StructAttr { + rename_all, + rename: rename_outer, + } = StructAttr::from_attrs(&s.attrs)?; if rename_all.is_some() { syn_err!("`rename_all` is not applicable to tuple structs"); } diff --git a/ts-rs/Cargo.toml b/ts-rs/Cargo.toml index b30f95a..b3be4b9 100644 --- a/ts-rs/Cargo.toml +++ b/ts-rs/Cargo.toml @@ -8,5 +8,8 @@ description = "generate typescript bindings from rust types" homepage = "https://github.com/Aleph-Alpha/ts-rs" repository = "https://github.com/Aleph-Alpha/ts-rs" +[features] +serde-compat = ["ts-rs-macros/serde-compat"] + [dependencies] ts-rs-macros = { version = "0.1", path = "../macros" } \ No newline at end of file diff --git a/ts-rs/src/lib.rs b/ts-rs/src/lib.rs index fdb6ac8..310b660 100644 --- a/ts-rs/src/lib.rs +++ b/ts-rs/src/lib.rs @@ -1,5 +1,5 @@ use std::fs::OpenOptions; -use std::io::{Write, BufWriter}; +use std::io::{BufWriter, Write}; use std::path::Path; pub use ts_rs_macros::TS; @@ -16,7 +16,11 @@ pub trait TS { fn dump(out: impl AsRef) -> std::io::Result<()> { let out = out.as_ref(); - let file = OpenOptions::new().append(true).create(true).truncate(false).open(out)?; + let file = OpenOptions::new() + .append(true) + .create(true) + .truncate(false) + .open(out)?; let mut writer = BufWriter::new(file); writer.write_all(Self::decl().expect("Type has no declaration").as_bytes())?; writer.write_all(b"\n\n")?; diff --git a/ts-rs/tests/type_override.rs b/ts-rs/tests/type_override.rs index 4fb80a3..3a78289 100644 --- a/ts-rs/tests/type_override.rs +++ b/ts-rs/tests/type_override.rs @@ -1,7 +1,7 @@ #![allow(dead_code)] -use ts_rs::TS; use std::time::Instant; +use ts_rs::TS; #[derive(TS)] struct Override { @@ -9,7 +9,7 @@ struct Override { #[ts(type = "0 | 1 | 2")] b: i32, #[ts(type = "string")] - x: Instant + x: Instant, } #[test]