Skip to main content

rod_macros/
lib.rs

1use proc_macro::TokenStream;
2use quote::{quote, quote_spanned};
3use syn::{
4    parse_macro_input, Data, DeriveInput, Fields, GenericArgument, Lit, Path, PathArguments, Type,
5};
6
7#[proc_macro_derive(Rod, attributes(rod))]
8pub fn derive_rod(input: TokenStream) -> TokenStream {
9    let input = parse_macro_input!(input as DeriveInput);
10    let name = input.ident;
11
12    // Inject generic bounds (T: RodSchema)
13    let generics = add_trait_bounds(input.generics);
14    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
15
16    // Check for unsupported types
17    match input.data {
18        Data::Struct(data) => match impl_struct_schema(&data.fields) {
19            Ok((validator_expanded, spec_expanded)) => {
20                let expanded = quote! {
21                    impl #impl_generics ::rod_rs::RodSchema for #name #ty_generics #where_clause {
22                        fn schema() -> Box<dyn ::rod_rs::RodValidator> {
23                            use ::rod_rs::OptionalExtension as _;
24                            use ::rod_rs::NullableExtension as _;
25                            #validator_expanded
26                        }
27
28                        fn spec() -> ::rod_rs::RodSpec {
29                            #spec_expanded
30                        }
31                    }
32
33                    impl #impl_generics #name #ty_generics #where_clause {
34                        pub fn json_schema() -> ::serde_json::Value {
35                            let mut s = <Self as ::rod_rs::RodSchema>::spec().to_json_schema();
36                            if let Some(obj) = s.as_object_mut() {
37                                obj.insert("$schema".into(), "https://json-schema.org/draft/2020-12/schema".into());
38                            }
39                            s
40                        }
41                    }
42                };
43                TokenStream::from(expanded)
44            }
45            Err(e) => TokenStream::from(e.to_compile_error()),
46        },
47        Data::Enum(_) => {
48            return quote_spanned! {
49                name.span() => compile_error!("#[derive(Rod)] currently supports Structs only.");
50            }
51            .into();
52        }
53        Data::Union(_) => {
54            return quote_spanned! {
55                name.span() => compile_error!("#[derive(Rod)] does not support Unions.");
56            }
57            .into();
58        }
59    }
60}
61
62#[derive(Default)]
63struct FieldAttributes {
64    min: Option<f64>,
65    max: Option<f64>,
66    email: bool,
67    url: bool,
68    uuid: bool,
69    cuid: bool,
70    regex: Option<String>,
71}
72
73fn impl_struct_schema(
74    fields: &Fields,
75) -> Result<(proc_macro2::TokenStream, proc_macro2::TokenStream), syn::Error> {
76    match fields {
77        Fields::Named(named) => {
78            let mut validator_inserts = Vec::new();
79            let mut spec_inserts = Vec::new();
80
81            for f in &named.named {
82                let ident = f.ident.as_ref().unwrap();
83                let name_str = ident.to_string().trim_start_matches("r#").to_string();
84                let ty = &f.ty;
85                let (inner_type, is_optional) = split_outer_option(ty);
86                let is_string_like = is_type_string(inner_type);
87
88                let mut attrs = FieldAttributes::default();
89                for attr in &f.attrs {
90                    if attr.path().is_ident("rod") {
91                        attr.parse_nested_meta(|meta| {
92                            if meta.path.is_ident("min") {
93                                attrs.min = Some(parse_lit_to_f64(&meta.value()?.parse()?)?);
94                            } else if meta.path.is_ident("max") {
95                                attrs.max = Some(parse_lit_to_f64(&meta.value()?.parse()?)?);
96                            } else if meta.path.is_ident("email") {
97                                attrs.email = true;
98                            } else if meta.path.is_ident("url") {
99                                attrs.url = true;
100                            } else if meta.path.is_ident("uuid") {
101                                attrs.uuid = true;
102                            } else if meta.path.is_ident("cuid") {
103                                attrs.cuid = true;
104                            } else if meta.path.is_ident("regex") {
105                                let val: Lit = meta.value()?.parse()?;
106                                if let Lit::Str(s) = val {
107                                    attrs.regex = Some(s.value());
108                                }
109                            }
110                            Ok(())
111                        })?;
112                    }
113                }
114
115                let mut v_code = map_type_recursive(inner_type);
116                if let Some(n) = attrs.min {
117                    v_code = if is_string_like {
118                        quote! { #v_code.min(#n as usize) }
119                    } else {
120                        quote! { #v_code.min(#n) }
121                    };
122                }
123                if let Some(n) = attrs.max {
124                    v_code = if is_string_like {
125                        quote! { #v_code.max(#n as usize) }
126                    } else {
127                        quote! { #v_code.max(#n) }
128                    };
129                }
130                if attrs.email {
131                    v_code = quote! { #v_code.email() };
132                }
133                if attrs.url {
134                    v_code = quote! { #v_code.url() };
135                }
136                if attrs.uuid {
137                    v_code = quote! { #v_code.uuid() };
138                }
139                if attrs.cuid {
140                    v_code = quote! { #v_code.cuid() };
141                }
142                if let Some(ref re) = attrs.regex {
143                    v_code = quote! { #v_code.regex(#re) };
144                }
145                if is_optional {
146                    v_code = quote! { #v_code.nullable().optional() };
147                }
148
149                validator_inserts.push(quote! { map.insert(#name_str.to_string(), Box::new(#v_code) as Box<dyn ::rod_rs::RodValidator>); });
150
151                let mut s_code = map_type_to_spec_recursive(inner_type, &attrs);
152                if is_optional {
153                    s_code = quote! { ::rod_rs::RodSpec::Optional(Box::new(::rod_rs::RodSpec::Nullable(Box::new(#s_code)))) };
154                }
155                spec_inserts.push(quote! { properties.insert(#name_str.to_string(), #s_code); });
156            }
157
158            let v_final = quote! { let mut map = std::collections::HashMap::new(); #(#validator_inserts)* Box::new(::rod_rs::object(map)) };
159            let s_final = quote! { let mut properties = std::collections::HashMap::new(); #(#spec_inserts)* ::rod_rs::RodSpec::Object { properties, strict: Some(false) } };
160            Ok((v_final, s_final))
161        }
162
163        Fields::Unnamed(unnamed) => {
164            let mut validator_items = Vec::new();
165            let mut spec_items = Vec::new();
166
167            for f in &unnamed.unnamed {
168                let ty = &f.ty;
169                let v_code = map_type_recursive(ty);
170                let s_code = map_type_to_spec_recursive(ty, &FieldAttributes::default());
171
172                validator_items
173                    .push(quote! { Box::new(#v_code) as Box<dyn ::rod_rs::RodValidator> });
174                spec_items.push(quote! { #s_code });
175            }
176
177            let v_final = quote! { Box::new(::rod_rs::tuple(vec![ #(#validator_items),* ])) };
178            let s_final = quote! { ::rod_rs::RodSpec::Tuple { items: vec![ #(#spec_items),* ] } };
179
180            Ok((v_final, s_final))
181        }
182
183        Fields::Unit => Ok((
184            quote! { Box::new(::rod_rs::object(std::collections::HashMap::new())) },
185            quote! { ::rod_rs::RodSpec::Object { properties: std::collections::HashMap::new(), strict: Some(false) } },
186        )),
187    }
188}
189
190fn map_type_to_spec_recursive(ty: &Type, attrs: &FieldAttributes) -> proc_macro2::TokenStream {
191    if let Type::Reference(tr) = ty {
192        return map_type_to_spec_recursive(&tr.elem, attrs);
193    }
194
195    if let Type::Path(tp) = ty {
196        let path = &tp.path;
197
198        if is_type_string(ty) {
199            let min = opt_to_tokens(attrs.min.map(|n| n as usize));
200            let max = opt_to_tokens(attrs.max.map(|n| n as usize));
201            let email = attrs.email;
202            let url = attrs.url;
203            let uuid = attrs.uuid;
204            let cuid = attrs.cuid;
205            let regex = opt_to_tokens(attrs.regex.clone());
206
207            return quote! {
208                ::rod_rs::RodSpec::String {
209                    min: #min, max: #max, length: None, email: Some(#email), url: Some(#url),
210                    uuid: Some(#uuid), cuid: Some(#cuid), datetime: None, ip: None,
211                    regex: #regex, starts_with: None, ends_with: None, includes: None, trim: false
212                }
213            };
214        }
215
216        if is_int_type(path) || path_is(path, "f32") || path_is(path, "f64") {
217            let min = opt_to_tokens(attrs.min);
218            let max = opt_to_tokens(attrs.max);
219            let is_int = is_int_type(path);
220            return quote! { ::rod_rs::RodSpec::Number { min: #min, max: #max, int: Some(#is_int) } };
221        }
222
223        if path_is(path, "bool") {
224            return quote! { ::rod_rs::RodSpec::Boolean };
225        }
226
227        if path_is(path, "Vec") {
228            if let Some(inner) = get_first_generic(path) {
229                let inner_spec = map_type_to_spec_recursive(inner, &FieldAttributes::default());
230                return quote! {
231                    ::rod_rs::RodSpec::Array { items: Box::new(#inner_spec), min: None, max: None }
232                };
233            }
234        }
235
236        return quote! { <#ty as ::rod_rs::RodSchema>::spec() };
237    }
238
239    quote! { ::rod_rs::RodSpec::Any }
240}
241
242fn opt_to_tokens<T: quote::ToTokens>(opt: Option<T>) -> proc_macro2::TokenStream {
243    match opt {
244        Some(v) => quote! { Some(#v) },
245        None => quote! { None },
246    }
247}
248
249fn get_first_generic(path: &Path) -> Option<&Type> {
250    let segment = path.segments.last()?;
251    if let PathArguments::AngleBracketed(args) = &segment.arguments {
252        if let Some(GenericArgument::Type(ty)) = args.args.first() {
253            return Some(ty);
254        }
255    }
256    None
257}
258
259fn is_int_type(path: &Path) -> bool {
260    [
261        "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize",
262    ]
263    .iter()
264    .any(|&t| path_is(path, t))
265}
266
267fn path_is(path: &Path, name: &str) -> bool {
268    path.segments.last().map_or(false, |s| s.ident == name)
269}
270
271fn add_trait_bounds(mut generics: syn::Generics) -> syn::Generics {
272    for param in &mut generics.params {
273        if let syn::GenericParam::Type(ref mut type_param) = *param {
274            type_param
275                .bounds
276                .push(syn::parse_quote!(::rod_rs::RodSchema));
277        }
278    }
279    generics
280}
281
282fn split_outer_option(ty: &Type) -> (&Type, bool) {
283    if let Type::Path(tp) = ty {
284        if path_is(&tp.path, "Option") {
285            if let Some(inner) = get_first_generic(&tp.path) {
286                return (inner, true);
287            }
288        }
289    }
290    (ty, false)
291}
292
293fn is_type_string(ty: &Type) -> bool {
294    if let Type::Path(tp) = ty {
295        let path = &tp.path;
296        if path_is(path, "String") || path_is(path, "str") || path_is(path, "Cow") {
297            return true;
298        }
299        if path_is(path, "Option") {
300            if let Some(inner) = get_first_generic(path) {
301                return is_type_string(inner);
302            }
303        }
304    }
305    if let Type::Reference(tr) = ty {
306        return is_type_string(&tr.elem);
307    }
308    false
309}
310
311fn parse_lit_to_f64(lit: &Lit) -> Result<f64, syn::Error> {
312    match lit {
313        Lit::Int(i) => i.base10_parse::<f64>(),
314        Lit::Float(f) => f.base10_parse::<f64>(),
315        _ => Err(syn::Error::new_spanned(lit, "Expected a number")),
316    }
317}
318
319fn map_type_recursive(ty: &Type) -> proc_macro2::TokenStream {
320    if let Type::Reference(tr) = ty {
321        return map_type_recursive(&tr.elem);
322    }
323    if let Type::Array(arr) = ty {
324        let inner = map_type_recursive(&arr.elem);
325        return quote! { ::rod_rs::array(#inner) };
326    }
327    if let Type::Tuple(tup) = ty {
328        let items = tup.elems.iter().map(|elem| {
329            let val = map_type_recursive(elem);
330            quote! { Box::new(#val) }
331        });
332        return quote! { ::rod_rs::tuple(vec![ #(#items),* ]) };
333    }
334    if let Type::Path(tp) = ty {
335        let path = &tp.path;
336        if path_is(path, "Option") {
337            if let Some(inner) = get_first_generic(path) {
338                let v = map_type_recursive(inner);
339                return quote! { #v.nullable().optional() };
340            }
341        }
342        if path_is(path, "Vec") || path_is(path, "VecDeque") || path_is(path, "LinkedList") {
343            if let Some(inner) = get_first_generic(path) {
344                let v = map_type_recursive(inner);
345                return quote! { ::rod_rs::array(#v) };
346            }
347        }
348        if path_is(path, "HashSet") || path_is(path, "BTreeSet") {
349            if let Some(inner) = get_first_generic(path) {
350                let v = map_type_recursive(inner);
351                return quote! { ::rod_rs::set(#v) };
352            }
353        }
354        if path_is(path, "HashMap") || path_is(path, "BTreeMap") {
355            if let Some(segment) = path.segments.last() {
356                if let PathArguments::AngleBracketed(args) = &segment.arguments {
357                    let types: Vec<&Type> = args
358                        .args
359                        .iter()
360                        .filter_map(|arg| {
361                            if let GenericArgument::Type(t) = arg {
362                                Some(t)
363                            } else {
364                                None
365                            }
366                        })
367                        .collect();
368                    if types.len() >= 2 {
369                        let key_v = map_type_recursive(types[0]);
370                        let val_v = map_type_recursive(types[1]);
371                        return quote! { ::rod_rs::record(#key_v, #val_v) };
372                    }
373                }
374            }
375        }
376        if ["Box", "Arc", "Rc", "Cell", "RefCell", "Mutex", "RwLock"]
377            .iter()
378            .any(|&s| path_is(path, s))
379        {
380            if let Some(inner) = get_first_generic(path) {
381                return map_type_recursive(inner);
382            }
383        }
384        if path_is(path, "Cow") {
385            if let Some(segment) = path.segments.last() {
386                if let PathArguments::AngleBracketed(args) = &segment.arguments {
387                    for arg in &args.args {
388                        if let GenericArgument::Type(inner) = arg {
389                            return map_type_recursive(inner);
390                        }
391                    }
392                }
393            }
394        }
395        if is_type_string(ty) {
396            return quote! { ::rod_rs::string() };
397        }
398        if path_is(path, "bool") {
399            return quote! { ::rod_rs::boolean() };
400        }
401        if path_is(path, "f32") || path_is(path, "f64") {
402            return quote! { ::rod_rs::number() };
403        }
404        if is_int_type(path) {
405            return quote! { ::rod_rs::number().int() };
406        }
407        if ["DateTime", "NaiveDate", "NaiveDateTime", "SystemTime"]
408            .iter()
409            .any(|&s| path_is(path, s))
410        {
411            return quote! { ::rod_rs::date() };
412        }
413
414        return quote! { <#ty as ::rod_rs::RodSchema>::schema() };
415    }
416
417    quote! { ::rod_rs::any() }
418}