gltf_v1_derive/
lib.rs

1#![recursion_limit = "128"]
2
3extern crate proc_macro;
4
5use proc_macro::TokenStream;
6use syn::DeriveInput;
7
8#[proc_macro_derive(Validate, attributes(gltf))]
9pub fn derive_validate(input: TokenStream) -> TokenStream {
10    expand(&syn::parse_macro_input!(input as DeriveInput)).into()
11}
12
13struct ValidateHook(pub syn::Ident);
14
15impl syn::parse::Parse for ValidateHook {
16    fn parse(input: syn::parse::ParseStream<'_>) -> syn::parse::Result<Self> {
17        let tag = input.parse::<syn::Ident>()?;
18        if tag == "validate_hook" {
19            let _eq = input.parse::<syn::Token![=]>()?;
20            let literal = input.parse::<syn::LitStr>()?;
21            let ident = syn::Ident::new(&literal.value(), tag.span());
22            Ok(ValidateHook(ident))
23        } else {
24            panic!("unrecognized gltf attribute");
25        }
26    }
27}
28
29fn expand(ast: &DeriveInput) -> proc_macro2::TokenStream {
30    use proc_macro2::TokenStream;
31    use quote::quote;
32
33    let mut validate_hook = quote! {};
34    for attr in &ast.attrs {
35        if attr.path().is_ident("gltf") {
36            let ValidateHook(ident) = attr
37                .parse_args::<ValidateHook>()
38                .expect("failed to parse attribute");
39            validate_hook = quote! {
40                #ident(self, _root, _path, _report);
41            };
42        }
43    }
44
45    let fields = match ast.data {
46        syn::Data::Struct(ref data_struct) => &data_struct.fields,
47        _ => panic!("#[derive(Validate)] only works on `struct`s"),
48    };
49    let ident = &ast.ident;
50    let validations: Vec<TokenStream> = fields
51        .iter()
52        .map(|f| f.ident.as_ref().unwrap())
53        .map(|ident| {
54            use inflections::Inflect;
55            let field = ident.to_string().to_camel_case();
56            quote!(
57                self.#ident.validate(
58                    _root,
59                    || _path().field(#field),
60                    _report,
61                )
62            )
63        })
64        .collect();
65    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
66    quote!(
67        impl #impl_generics crate::validation::Validate
68            for #ident #ty_generics #where_clause
69        {
70            fn validate<P, R>(
71                &self,
72                _root: &crate::Root,
73                _path: P,
74                _report: &mut R
75            ) where
76                P: Fn() -> crate::Path,
77                R: FnMut(&dyn Fn() -> crate::Path, crate::validation::Error),
78            {
79                #(
80                    #validations;
81                )*
82
83                #validate_hook
84            }
85        }
86    )
87}