valibuk_core 0.2.0

Internal library of Valibuk
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
use proc_macro2::TokenStream;
use quote::quote;
use syn::{spanned::Spanned, Error};

#[derive(Debug)]
pub(crate) struct ValidatedFieldDeriv<'a> {
    name: &'a syn::Ident,
    ty: &'a syn::Type,
    custom_validation_error_ty: syn::Type,
    field_validator: FieldValidator,
}

impl<'a> ValidatedFieldDeriv<'a> {
    pub fn new(field: &'a syn::Field, error: syn::Type) -> Result<ValidatedFieldDeriv<'a>, Error> {
        if let Some(ref name) = field.ident {
            let field_validator = Self::parse_field_validator(field); // dbg!(&field_validator);
            Ok(ValidatedFieldDeriv {
                name: &name,
                ty: &field.ty,
                custom_validation_error_ty: error,
                field_validator,
            })
        } else {
            Err(Error::new(field.span(), "Nameless field in struct"))
        }
    }

    fn parse_field_validator(field: &'a syn::Field) -> FieldValidator {
        field
            .attrs
            .iter()
            .filter(|a| a.path.is_ident("validator"))
            .map(FieldValidator::from)
            .last()
            .unwrap_or(FieldValidator::None)
    }

    /// Name of the field as token stream
    pub fn get_name(&self) -> TokenStream {
        let name = self.name;
        quote!(#name)
    }

    /// True when the field has a validator attached
    pub fn is_validated(&self) -> bool {
        self.field_validator.is_some()
    }

    /// Used to construct the validated instance from the unvalidated
    ///
    /// When there are no validators attached, its a simple field copy
    pub fn build_unvalidated_constructor(&self) -> TokenStream {
        let name = self.name;
        quote! {
            #name: unvalidated.#name
        }
    }

    /// Emits code to execute the validator attached to field, if any
    ///
    /// The emitted code should yield a value of the type Result<T, E>
    /// where [T][ValidatedFieldDeriv.ty] is the type of the current field and E is the error type
    /// of the current field
    pub fn build_match_validator_call(&self) -> TokenStream {
        let field = self.name;
        let validator = &self.field_validator;
        match validator {
            crate::field::FieldValidator::Ident(v) => quote! {
                (#v)(unvalidated.#field)
            },
            crate::field::FieldValidator::Closure(v) => quote! {
                (#v)(unvalidated.#field)
            },
            crate::field::FieldValidator::None => quote! {
                unvalidated.#field
            },
        }
    }

    /// Builds the PatExpr that matches when the validator was successful
    ///
    /// This is used in the match expr to collect all the validated fields
    pub fn build_match_validator_ok(&self) -> TokenStream {
        let name = self.name;
        let validator = &self.field_validator;
        if validator.is_some() {
            quote! {
                ::std::result::Result::Ok(#name)
            }
        } else {
            quote! {
                #name
            }
        }
    }

    /// Builds error handling for when the validator fails
    pub fn build_validator_error_push(&self) -> TokenStream {
        let name = self.name;
        let validator = &self.field_validator;
        if validator.is_some() {
            quote! {
                if let ::std::result::Result::Err(e) = #name {
                    errors.push(e);
                }
            }
        } else {
            quote! {}
        }
    }

    /// Emits dummy code that fails to compile when the declared
    /// type of the custom error does not match the signature of
    /// the validator for this field.
    pub fn build_field_assertions(&self) -> TokenStream {
        let ty = self.ty;
        let err = &self.custom_validation_error_ty;
        let validator = &self.field_validator;
        match validator {
            FieldValidator::Ident(v) => quote! {
                let _: fn(#ty) -> ::std::result::Result<#ty, #err> = #v;
            },
            FieldValidator::Closure(v) => quote! {
                let _: fn(#ty) -> ::std::result::Result<#ty, #err> = #v;
            },
            FieldValidator::None => quote!(),
        }
    }

    /// Builds fields for the unvalidated struct
    pub fn build_unvalidated_struct_repr(&self) -> TokenStream {
        let name = self.name;
        let ty = self.ty;
        quote! {
            pub #name: #ty
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum FieldValidator {
    Ident(syn::Ident),
    Closure(syn::ExprClosure),
    None,
}

impl FieldValidator {
    pub fn is_some(&self) -> bool {
        self != &FieldValidator::None
    }
}

impl From<&syn::Attribute> for FieldValidator {
    fn from(value: &syn::Attribute) -> Self {
        let ident = value
            .parse_args::<syn::Ident>()
            .map(|i| FieldValidator::Ident(i));
        let closure = value
            .parse_args::<syn::ExprClosure>()
            .map(|i| FieldValidator::Closure(i));
        ident.or(closure).unwrap_or(FieldValidator::None)
    }
}

#[cfg(test)]
mod test {
    use syn::parse_quote;

    use super::*;
    use assert_tokens_eq::assert_tokens_eq;

    /// Helper to extract the ValidatedFieldDeriv for the first field of the input struct
    fn first_field_deriv_from_struct<'a>(s: &'a syn::DeriveInput) -> ValidatedFieldDeriv<'a> {
        let fields = match &s.data {
            syn::Data::Struct(data) => match &data.fields {
                syn::Fields::Named(f) => f,
                _ => unimplemented!(),
            },
            _ => unimplemented!(),
        };
        ValidatedFieldDeriv::new(fields.named.iter().last().unwrap(), parse_quote!(String)).unwrap()
    }

    #[test]
    fn test_name() {
        let s: syn::DeriveInput = parse_quote! {
            struct A {
                a: i32
            }
        };
        let f = first_field_deriv_from_struct(&s);
        assert_tokens_eq!(
            &f.get_name(),
            &quote!(a),
            "get_name returns the name of the field "
        );
    }

    #[test]
    fn test_unvalidated_constructor() {
        let s: syn::DeriveInput = parse_quote! {
            struct A {
                a: i32
            }
        };
        let f = first_field_deriv_from_struct(&s).build_unvalidated_constructor();
        let actual: syn::ExprStruct = parse_quote! {
            B {
                #f
            }
        };
        let expected: syn::ExprStruct = parse_quote! {
            B {
                a: unvalidated.a,
            }
        };
        assert_tokens_eq!(
            &actual,
            &expected,
            "get_name returns the name of the field "
        );
    }

    #[test]
    fn test_is_validated() {
        {
            let s: syn::DeriveInput = parse_quote! {
                struct A {
                    a: i32
                }
            };
            let f = first_field_deriv_from_struct(&s);
            assert_eq!(f.is_validated(), false, "field a is not validated");
        }
        {
            let s: syn::DeriveInput = parse_quote! {
                struct A {
                    #[validator(abc)]
                    a: i32
                }
            };
            let f = first_field_deriv_from_struct(&s);
            assert_eq!(f.is_validated(), true, "field a is validated");
        }
    }

    #[test]
    fn test_build_match_validator_call() {
        {
            // fn validator case
            let s: syn::DeriveInput = parse_quote! {
                struct A {
                    #[validator(abc)]
                    a: i32
                }
            };
            let f = first_field_deriv_from_struct(&s);
            let expected: syn::ExprCall = parse_quote! {
                (abc)(unvalidated.a)
            };
            assert_tokens_eq!(
                f.build_match_validator_call(),
                &expected,
                "validator call for fn validator"
            );
        }
        {
            // inline fn validator case
            let s: syn::DeriveInput = parse_quote! {
                struct A {
                    #[validator(|a| if a > 0 { Ok(a) } else { Err("err") })]
                    a: i32
                }
            };
            let f = first_field_deriv_from_struct(&s);
            let expected: syn::ExprCall = parse_quote! {
                (|a| if a > 0 { Ok(a) } else { Err("err") })(unvalidated.a)
            };
            assert_tokens_eq!(
                f.build_match_validator_call(),
                &expected,
                "validator call for fn validator"
            );
        }
        {
            // inline "bool fn validator, error string" case
            let s: syn::DeriveInput = parse_quote! {
                struct A {
                    #[validator(|ref a| a > 0, "Validation Err".to_string())]
                    a: i32
                }
            };
            let f = first_field_deriv_from_struct(&s);
            let expected: syn::Expr = parse_quote! {
                if (|ref a | a > 0)(unvalidated.a) {
                    Ok(unvalidated.a)
                } else {
                    Err("Validation Err".to_string())
                }
            };
            assert_tokens_eq!(
                f.build_match_validator_call(),
                &expected,
                "validator call for fn validator"
            );
        }
        {
            // unvalidated case
            let s: syn::DeriveInput = parse_quote! {
                struct A {
                    a: i32
                }
            };
            let f = first_field_deriv_from_struct(&s);
            let expected: syn::ExprField = parse_quote! {
                unvalidated.a
            };
            assert_tokens_eq!(
                f.build_match_validator_call(),
                &expected,
                "validator call for unvalidated field"
            );
        }
    }

    #[test]
    fn test_build_match_validator_ok() {
        let s: syn::DeriveInput = parse_quote! {
            struct A {
                a: i32
            }
        };
        let f = first_field_deriv_from_struct(&s);
        let expected: syn::Pat = parse_quote! {
            a
        };
        assert_tokens_eq!(&f.build_match_validator_ok(), &expected, "_ pat");
        let s: syn::DeriveInput = parse_quote! {
            struct A {
                #[validator(abc)]
                a: i32
            }
        };
        let f = first_field_deriv_from_struct(&s);
        let expected: syn::Pat = parse_quote! {
            ::std::result::Result::Ok(a)
        };
        assert_tokens_eq!(&f.build_match_validator_ok(), &expected, "ok extractor pat");
    }

    #[test]
    fn test_build_validator_error_push() {
        let s: syn::DeriveInput = parse_quote! {
            struct A {
                a: i32
            }
        };
        let f = first_field_deriv_from_struct(&s);
        let expected: TokenStream = quote! {};
        assert_tokens_eq!(
            &f.build_validator_error_push(),
            &expected,
            "no error handling for unvalidated"
        );
        let s: syn::DeriveInput = parse_quote! {
            struct A {
                #[validator(abc)]
                a: i32
            }
        };
        let f = first_field_deriv_from_struct(&s);
        let expected: syn::Expr = parse_quote! {
            if let ::std::result::Result::Err(e) = a {
                errors.push(e);
            }
        };
        assert_tokens_eq!(
            &f.build_validator_error_push(),
            &expected,
            "if expr for validated"
        );
    }

    #[test]
    fn test_build_unvalidated_struct_repr() {
        let s: syn::DeriveInput = parse_quote! {
            struct A {
                a: i32
            }
        };
        let f = first_field_deriv_from_struct(&s).build_unvalidated_struct_repr();
        let actual: syn::ItemStruct = parse_quote! {
            struct B {
                #f
            }
        };
        let expected: syn::ItemStruct = parse_quote! {
            struct B {
                pub a: i32
            }
        };
        assert_tokens_eq!(&actual, &expected, "unvalidated struct field");
    }
}