rod-macros 0.1.1

Procedural macros for the Rod validation library
Documentation
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use proc_macro::TokenStream;
use quote::{quote, quote_spanned};
use syn::{
    parse_macro_input, Data, DeriveInput, Fields, GenericArgument, Lit, Path, PathArguments, Type,
};

#[proc_macro_derive(Rod, attributes(rod))]
pub fn derive_rod(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;

    // Inject generic bounds (T: RodSchema)
    let generics = add_trait_bounds(input.generics);
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    // Check for unsupported types
    match input.data {
        Data::Struct(data) => match impl_struct_schema(&data.fields) {
            Ok((validator_expanded, spec_expanded)) => {
                let expanded = quote! {
                    impl #impl_generics ::rod_rs::RodSchema for #name #ty_generics #where_clause {
                        fn schema() -> Box<dyn ::rod_rs::RodValidator> {
                            use ::rod_rs::OptionalExtension as _;
                            use ::rod_rs::NullableExtension as _;
                            #validator_expanded
                        }

                        fn spec() -> ::rod_rs::RodSpec {
                            #spec_expanded
                        }
                    }

                    impl #impl_generics #name #ty_generics #where_clause {
                        pub fn json_schema() -> ::serde_json::Value {
                            let mut s = <Self as ::rod_rs::RodSchema>::spec().to_json_schema();
                            if let Some(obj) = s.as_object_mut() {
                                obj.insert("$schema".into(), "https://json-schema.org/draft/2020-12/schema".into());
                            }
                            s
                        }
                    }
                };
                TokenStream::from(expanded)
            }
            Err(e) => TokenStream::from(e.to_compile_error()),
        },
        Data::Enum(_) => {
            return quote_spanned! {
                name.span() => compile_error!("#[derive(Rod)] currently supports Structs only.");
            }
            .into();
        }
        Data::Union(_) => {
            return quote_spanned! {
                name.span() => compile_error!("#[derive(Rod)] does not support Unions.");
            }
            .into();
        }
    }
}

#[derive(Default)]
struct FieldAttributes {
    min: Option<f64>,
    max: Option<f64>,
    email: bool,
    url: bool,
    uuid: bool,
    cuid: bool,
    regex: Option<String>,
}

fn impl_struct_schema(
    fields: &Fields,
) -> Result<(proc_macro2::TokenStream, proc_macro2::TokenStream), syn::Error> {
    match fields {
        Fields::Named(named) => {
            let mut validator_inserts = Vec::new();
            let mut spec_inserts = Vec::new();

            for f in &named.named {
                let ident = f.ident.as_ref().unwrap();
                let name_str = ident.to_string().trim_start_matches("r#").to_string();
                let ty = &f.ty;
                let (inner_type, is_optional) = split_outer_option(ty);
                let is_string_like = is_type_string(inner_type);

                let mut attrs = FieldAttributes::default();
                for attr in &f.attrs {
                    if attr.path().is_ident("rod") {
                        attr.parse_nested_meta(|meta| {
                            if meta.path.is_ident("min") {
                                attrs.min = Some(parse_lit_to_f64(&meta.value()?.parse()?)?);
                            } else if meta.path.is_ident("max") {
                                attrs.max = Some(parse_lit_to_f64(&meta.value()?.parse()?)?);
                            } else if meta.path.is_ident("email") {
                                attrs.email = true;
                            } else if meta.path.is_ident("url") {
                                attrs.url = true;
                            } else if meta.path.is_ident("uuid") {
                                attrs.uuid = true;
                            } else if meta.path.is_ident("cuid") {
                                attrs.cuid = true;
                            } else if meta.path.is_ident("regex") {
                                let val: Lit = meta.value()?.parse()?;
                                if let Lit::Str(s) = val {
                                    attrs.regex = Some(s.value());
                                }
                            }
                            Ok(())
                        })?;
                    }
                }

                let mut v_code = map_type_recursive(inner_type);
                if let Some(n) = attrs.min {
                    v_code = if is_string_like {
                        quote! { #v_code.min(#n as usize) }
                    } else {
                        quote! { #v_code.min(#n) }
                    };
                }
                if let Some(n) = attrs.max {
                    v_code = if is_string_like {
                        quote! { #v_code.max(#n as usize) }
                    } else {
                        quote! { #v_code.max(#n) }
                    };
                }
                if attrs.email {
                    v_code = quote! { #v_code.email() };
                }
                if attrs.url {
                    v_code = quote! { #v_code.url() };
                }
                if attrs.uuid {
                    v_code = quote! { #v_code.uuid() };
                }
                if attrs.cuid {
                    v_code = quote! { #v_code.cuid() };
                }
                if let Some(ref re) = attrs.regex {
                    v_code = quote! { #v_code.regex(#re) };
                }
                if is_optional {
                    v_code = quote! { #v_code.nullable().optional() };
                }

                validator_inserts.push(quote! { map.insert(#name_str.to_string(), Box::new(#v_code) as Box<dyn ::rod_rs::RodValidator>); });

                let mut s_code = map_type_to_spec_recursive(inner_type, &attrs);
                if is_optional {
                    s_code = quote! { ::rod_rs::RodSpec::Optional(Box::new(::rod_rs::RodSpec::Nullable(Box::new(#s_code)))) };
                }
                spec_inserts.push(quote! { properties.insert(#name_str.to_string(), #s_code); });
            }

            let v_final = quote! { let mut map = std::collections::HashMap::new(); #(#validator_inserts)* Box::new(::rod_rs::object(map)) };
            let s_final = quote! { let mut properties = std::collections::HashMap::new(); #(#spec_inserts)* ::rod_rs::RodSpec::Object { properties, strict: Some(false) } };
            Ok((v_final, s_final))
        }

        Fields::Unnamed(unnamed) => {
            let mut validator_items = Vec::new();
            let mut spec_items = Vec::new();

            for f in &unnamed.unnamed {
                let ty = &f.ty;
                let v_code = map_type_recursive(ty);
                let s_code = map_type_to_spec_recursive(ty, &FieldAttributes::default());

                validator_items
                    .push(quote! { Box::new(#v_code) as Box<dyn ::rod_rs::RodValidator> });
                spec_items.push(quote! { #s_code });
            }

            let v_final = quote! { Box::new(::rod_rs::tuple(vec![ #(#validator_items),* ])) };
            let s_final = quote! { ::rod_rs::RodSpec::Tuple { items: vec![ #(#spec_items),* ] } };

            Ok((v_final, s_final))
        }

        Fields::Unit => Ok((
            quote! { Box::new(::rod_rs::object(std::collections::HashMap::new())) },
            quote! { ::rod_rs::RodSpec::Object { properties: std::collections::HashMap::new(), strict: Some(false) } },
        )),
    }
}

fn map_type_to_spec_recursive(ty: &Type, attrs: &FieldAttributes) -> proc_macro2::TokenStream {
    if let Type::Reference(tr) = ty {
        return map_type_to_spec_recursive(&tr.elem, attrs);
    }

    if let Type::Path(tp) = ty {
        let path = &tp.path;

        if is_type_string(ty) {
            let min = opt_to_tokens(attrs.min.map(|n| n as usize));
            let max = opt_to_tokens(attrs.max.map(|n| n as usize));
            let email = attrs.email;
            let url = attrs.url;
            let uuid = attrs.uuid;
            let cuid = attrs.cuid;
            let regex = opt_to_tokens(attrs.regex.clone());

            return quote! {
                ::rod_rs::RodSpec::String {
                    min: #min, max: #max, length: None, email: Some(#email), url: Some(#url),
                    uuid: Some(#uuid), cuid: Some(#cuid), datetime: None, ip: None,
                    regex: #regex, starts_with: None, ends_with: None, includes: None, trim: false
                }
            };
        }

        if is_int_type(path) || path_is(path, "f32") || path_is(path, "f64") {
            let min = opt_to_tokens(attrs.min);
            let max = opt_to_tokens(attrs.max);
            let is_int = is_int_type(path);
            return quote! { ::rod_rs::RodSpec::Number { min: #min, max: #max, int: Some(#is_int) } };
        }

        if path_is(path, "bool") {
            return quote! { ::rod_rs::RodSpec::Boolean };
        }

        if path_is(path, "Vec") {
            if let Some(inner) = get_first_generic(path) {
                let inner_spec = map_type_to_spec_recursive(inner, &FieldAttributes::default());
                return quote! {
                    ::rod_rs::RodSpec::Array { items: Box::new(#inner_spec), min: None, max: None }
                };
            }
        }

        return quote! { <#ty as ::rod_rs::RodSchema>::spec() };
    }

    quote! { ::rod_rs::RodSpec::Any }
}

fn opt_to_tokens<T: quote::ToTokens>(opt: Option<T>) -> proc_macro2::TokenStream {
    match opt {
        Some(v) => quote! { Some(#v) },
        None => quote! { None },
    }
}

fn get_first_generic(path: &Path) -> Option<&Type> {
    let segment = path.segments.last()?;
    if let PathArguments::AngleBracketed(args) = &segment.arguments {
        if let Some(GenericArgument::Type(ty)) = args.args.first() {
            return Some(ty);
        }
    }
    None
}

fn is_int_type(path: &Path) -> bool {
    [
        "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize",
    ]
    .iter()
    .any(|&t| path_is(path, t))
}

fn path_is(path: &Path, name: &str) -> bool {
    path.segments.last().map_or(false, |s| s.ident == name)
}

fn add_trait_bounds(mut generics: syn::Generics) -> syn::Generics {
    for param in &mut generics.params {
        if let syn::GenericParam::Type(ref mut type_param) = *param {
            type_param
                .bounds
                .push(syn::parse_quote!(::rod_rs::RodSchema));
        }
    }
    generics
}

fn split_outer_option(ty: &Type) -> (&Type, bool) {
    if let Type::Path(tp) = ty {
        if path_is(&tp.path, "Option") {
            if let Some(inner) = get_first_generic(&tp.path) {
                return (inner, true);
            }
        }
    }
    (ty, false)
}

fn is_type_string(ty: &Type) -> bool {
    if let Type::Path(tp) = ty {
        let path = &tp.path;
        if path_is(path, "String") || path_is(path, "str") || path_is(path, "Cow") {
            return true;
        }
        if path_is(path, "Option") {
            if let Some(inner) = get_first_generic(path) {
                return is_type_string(inner);
            }
        }
    }
    if let Type::Reference(tr) = ty {
        return is_type_string(&tr.elem);
    }
    false
}

fn parse_lit_to_f64(lit: &Lit) -> Result<f64, syn::Error> {
    match lit {
        Lit::Int(i) => i.base10_parse::<f64>(),
        Lit::Float(f) => f.base10_parse::<f64>(),
        _ => Err(syn::Error::new_spanned(lit, "Expected a number")),
    }
}

fn map_type_recursive(ty: &Type) -> proc_macro2::TokenStream {
    if let Type::Reference(tr) = ty {
        return map_type_recursive(&tr.elem);
    }
    if let Type::Array(arr) = ty {
        let inner = map_type_recursive(&arr.elem);
        return quote! { ::rod_rs::array(#inner) };
    }
    if let Type::Tuple(tup) = ty {
        let items = tup.elems.iter().map(|elem| {
            let val = map_type_recursive(elem);
            quote! { Box::new(#val) }
        });
        return quote! { ::rod_rs::tuple(vec![ #(#items),* ]) };
    }
    if let Type::Path(tp) = ty {
        let path = &tp.path;
        if path_is(path, "Option") {
            if let Some(inner) = get_first_generic(path) {
                let v = map_type_recursive(inner);
                return quote! { #v.nullable().optional() };
            }
        }
        if path_is(path, "Vec") || path_is(path, "VecDeque") || path_is(path, "LinkedList") {
            if let Some(inner) = get_first_generic(path) {
                let v = map_type_recursive(inner);
                return quote! { ::rod_rs::array(#v) };
            }
        }
        if path_is(path, "HashSet") || path_is(path, "BTreeSet") {
            if let Some(inner) = get_first_generic(path) {
                let v = map_type_recursive(inner);
                return quote! { ::rod_rs::set(#v) };
            }
        }
        if path_is(path, "HashMap") || path_is(path, "BTreeMap") {
            if let Some(segment) = path.segments.last() {
                if let PathArguments::AngleBracketed(args) = &segment.arguments {
                    let types: Vec<&Type> = args
                        .args
                        .iter()
                        .filter_map(|arg| {
                            if let GenericArgument::Type(t) = arg {
                                Some(t)
                            } else {
                                None
                            }
                        })
                        .collect();
                    if types.len() >= 2 {
                        let key_v = map_type_recursive(types[0]);
                        let val_v = map_type_recursive(types[1]);
                        return quote! { ::rod_rs::record(#key_v, #val_v) };
                    }
                }
            }
        }
        if ["Box", "Arc", "Rc", "Cell", "RefCell", "Mutex", "RwLock"]
            .iter()
            .any(|&s| path_is(path, s))
        {
            if let Some(inner) = get_first_generic(path) {
                return map_type_recursive(inner);
            }
        }
        if path_is(path, "Cow") {
            if let Some(segment) = path.segments.last() {
                if let PathArguments::AngleBracketed(args) = &segment.arguments {
                    for arg in &args.args {
                        if let GenericArgument::Type(inner) = arg {
                            return map_type_recursive(inner);
                        }
                    }
                }
            }
        }
        if is_type_string(ty) {
            return quote! { ::rod_rs::string() };
        }
        if path_is(path, "bool") {
            return quote! { ::rod_rs::boolean() };
        }
        if path_is(path, "f32") || path_is(path, "f64") {
            return quote! { ::rod_rs::number() };
        }
        if is_int_type(path) {
            return quote! { ::rod_rs::number().int() };
        }
        if ["DateTime", "NaiveDate", "NaiveDateTime", "SystemTime"]
            .iter()
            .any(|&s| path_is(path, s))
        {
            return quote! { ::rod_rs::date() };
        }

        return quote! { <#ty as ::rod_rs::RodSchema>::schema() };
    }

    quote! { ::rod_rs::any() }
}