Skip to content

Commit

Permalink
fixes #186 - DataTypeFrom rename
Browse files Browse the repository at this point in the history
  • Loading branch information
oscartbeaumont committed Dec 4, 2023
1 parent 05ca302 commit 21b5371
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
9 changes: 9 additions & 0 deletions macros/src/data_type_from/attr/field.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
use proc_macro2::TokenStream;
use quote::ToTokens;
use syn::Result;

use crate::utils::Attribute;

#[derive(Default)]
pub struct FieldAttr {
pub skip: bool,
pub rename: Option<TokenStream>,
}

impl_parse! {
FieldAttr(attr, out) {
"skip" => out.skip = true,
"rename" => {
let attr = attr.parse_string()?;
out.rename = out.rename.take().or_else(|| Some(
attr.to_token_stream()
))
},
}
}

Expand Down
8 changes: 6 additions & 2 deletions macros/src/data_type_from/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
mod attr;

use quote::quote;
use quote::{quote, ToTokens};
use syn::{parse_macro_input, Data, DeriveInput, Fields};

use attr::*;
Expand Down Expand Up @@ -47,7 +47,11 @@ pub fn derive(input: proc_macro::TokenStream) -> syn::Result<proc_macro::TokenSt
.as_ref()
// TODO: Proper syn error would be nice
.expect("'specta::DataTypeFrom' requires named fields.");
let ident_str = ident.to_string();

let ident_str = match &attrs.rename {
Some(rename) => rename.to_token_stream(),
None => ident.to_string().to_token_stream(),
};

let ty = then_option(attrs.skip, quote!(t.#ident.into()));

Expand Down
16 changes: 16 additions & 0 deletions tests/datatype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ struct Procedures8 {}
#[derive(DataTypeFrom)]
struct Procedures9(DataType, DataType);

#[derive(DataTypeFrom)]
struct Procedures10 {
#[specta(rename = "b")]
pub a: DataType,
}

#[test]
fn test_datatype() {
let val: DataType = Procedures1(vec![
Expand Down Expand Up @@ -159,4 +165,14 @@ fn test_datatype() {
ts::datatype(&Default::default(), &val, &Default::default()),
Ok("[any, string]".into())
);

let val: StructType = Procedures10 { a: DataType::Any }.into();
assert_eq!(
ts::datatype(
&Default::default(),
&val.clone().to_anonymous(),
&Default::default()
),
Ok("{ b: any }".into())
);
}

0 comments on commit 21b5371

Please sign in to comment.