1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#![recursion_limit = "128"]
extern crate proc_macro;
use proc_macro::TokenStream;
use syn::DeriveInput;
#[proc_macro_derive(Validate)]
pub fn derive_validate(input: TokenStream) -> TokenStream {
expand(&syn::parse_macro_input!(input as DeriveInput)).into()
}
fn expand(ast: &DeriveInput) -> proc_macro2::TokenStream {
use proc_macro2::TokenStream;
use quote::quote;
let fields = match ast.data {
syn::Data::Struct(ref data_struct) => &data_struct.fields,
_ => panic!("#[derive(Validate)] only works on `struct`s"),
};
let ident = &ast.ident;
let validations: Vec<TokenStream> = fields
.iter()
.map(|f| f.ident.as_ref().unwrap())
.map(|ident| {
use inflections::Inflect;
let field = ident.to_string().to_camel_case();
quote!(
self.#ident.validate(
_root,
|| _path().field(#field),
_report,
)
)
})
.collect();
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
quote!(
impl #impl_generics crate::validation::Validate
for #ident #ty_generics #where_clause
{
fn validate<P, R>(
&self,
_root: &crate::Root,
_path: P,
_report: &mut R
) where
P: Fn() -> crate::Path,
R: FnMut(&Fn() -> crate::Path, crate::validation::Error),
{
#(
#validations;
)*
}
}
)
}