serde_valid_derive 1.0.5

JSON Schema based validation tool using serde.
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use crate::attribute::{
    MetaListCustomMessage, MetaListFieldValidation, MetaListStructValidation,
    MetaNameValueCustomMessage, MetaNameValueFieldValidation, MetaNameValueStructValidation,
    MetaPathCustomMessage, MetaPathFieldValidation, MetaPathStructValidation,
};
use itertools::Itertools;
use proc_macro2::TokenStream;
use quote::quote;
use syn::spanned::Spanned;

pub fn object_errors_tokens() -> TokenStream {
    quote!(::serde_valid::validation::Errors::Object(
        ::serde_valid::validation::ObjectErrors::new(
            __rule_vec_errors,
            __property_vec_errors_map
                .into_iter()
                .map(|(field, errors)| {
                    let mut __field_items_errors = vec![];
                    let mut __field_properties_errors = None;
                    let mut __field_errors: ::serde_valid::validation::VecErrors = errors
                        .into_iter()
                        .filter_map(|error| match error {
                            ::serde_valid::validation::Error::Items(__array_errors) => {
                                __field_items_errors.push(__array_errors);
                                None
                            }
                            ::serde_valid::validation::Error::Properties(__object_errors) => {
                                __field_properties_errors = Some(__object_errors);
                                None
                            }
                            _ => Some(error),
                        })
                        .collect();

                    if let Some(__object_errors) = __field_properties_errors {
                        __field_errors.extend(__object_errors.errors);

                        (
                            field,
                            ::serde_valid::validation::Errors::Object(
                                ::serde_valid::validation::ObjectErrors::new(
                                    __field_errors,
                                    __object_errors.properties,
                                ),
                            ),
                        )
                    } else if !__field_items_errors.is_empty() {
                        let __array_errors = __field_items_errors
                            .into_iter()
                            .reduce(|a, b| a.merge(b))
                            .unwrap();
                        __field_errors.extend(__array_errors.errors);

                        (
                            field,
                            ::serde_valid::validation::Errors::Array(
                                ::serde_valid::validation::error::ArrayErrors::new(
                                    __field_errors,
                                    __array_errors.items,
                                ),
                            ),
                        )
                    } else {
                        (
                            field,
                            ::serde_valid::validation::Errors::NewType(__field_errors),
                        )
                    }
                })
                .collect()
        )
    ))
}

pub fn array_errors_tokens() -> TokenStream {
    quote!(::serde_valid::validation::Errors::Array(
        ::serde_valid::validation::error::ArrayErrors::new(
            __rule_vec_errors,
            __item_vec_errors_map
                .into_iter()
                .map(|(index, errors)| {
                    let mut __field_items_errors = vec![];
                    let mut __field_properties_errors = None;
                    let mut __field_errors: ::serde_valid::validation::VecErrors = errors
                        .into_iter()
                        .filter_map(|error| match error {
                            ::serde_valid::validation::Error::Items(__array_errors) => {
                                __field_items_errors.push(__array_errors);
                                None
                            }
                            ::serde_valid::validation::Error::Properties(__object_errors) => {
                                __field_properties_errors = Some(__object_errors);
                                None
                            }
                            _ => Some(error),
                        })
                        .collect();

                    if let Some(__object_errors) = __field_properties_errors {
                        __field_errors.extend(__object_errors.errors);

                        (
                            index,
                            ::serde_valid::validation::Errors::Object(
                                ::serde_valid::validation::ObjectErrors::new(
                                    __field_errors,
                                    __object_errors.properties,
                                ),
                            ),
                        )
                    } else if !__field_items_errors.is_empty() {
                        let __array_errors = __field_items_errors
                            .into_iter()
                            .reduce(|a, b| a.merge(b))
                            .unwrap();
                        __field_errors.extend(__array_errors.errors);

                        (
                            index,
                            ::serde_valid::validation::Errors::Array(
                                ::serde_valid::validation::error::ArrayErrors::new(
                                    __field_errors,
                                    __array_errors.items,
                                ),
                            ),
                        )
                    } else {
                        (
                            index,
                            ::serde_valid::validation::Errors::NewType(__field_errors),
                        )
                    }
                })
                .collect()
        )
    ))
}

pub fn new_type_errors_tokens() -> TokenStream {
    quote!(::serde_valid::validation::Errors::NewType(
        __rule_vec_errors
            .into_iter()
            .chain(
                __item_vec_errors_map
                    .remove(&0)
                    .unwrap_or(vec![])
                    .into_iter()
            )
            .collect()
    ))
}

#[derive(Debug)]
pub struct Error(syn::Error);

impl Error {
    fn new<Message: Into<String>>(span: proc_macro2::Span, message: Message) -> Self {
        Self(syn::Error::new(span, message.into()))
    }

    #[allow(dead_code)]
    pub fn macro_debug<Message: Into<String>>(span: proc_macro2::Span, message: Message) -> Self {
        Error::new(span, message)
    }

    pub fn unit_struct_not_supported(input: &syn::DeriveInput) -> Self {
        Self::new(
            input.span(),
            "#[derive(Validate)] does not support Unit Struct.",
        )
    }

    pub fn union_not_supported(input: &syn::DeriveInput) -> Self {
        Self::new(input.span(), "#[derive(Validate)] does not support Union.")
    }

    pub fn validate_meta_name_value_not_supported(name_value: &syn::MetaNameValue) -> Self {
        Self::new(name_value.span(), "#[validate = ???] not supported.")
    }

    pub fn meta_path_validation_need_value(path: &syn::Path, validation_type: &str) -> Self {
        Self::new(
            path.span(),
            format!("#[validate({validation_type}(???))] needs validation path."),
        )
    }

    pub fn meta_path_custom_message_need_value(
        path: &syn::Path,
        custom_message_type: &str,
    ) -> Self {
        Self::new(
            path.span(),
            format!("#[validate(..., {custom_message_type}(???))] needs custom message path."),
        )
    }

    pub fn meta_list_validation_need_value(path: &syn::Path, validation_type: &str) -> Self {
        Self::new(
            path.span(),
            format!("#[validate({validation_type}(???, ...))] needs validation list."),
        )
    }

    pub fn meta_list_custom_message_need_value(
        path: &syn::Path,
        custom_message_type: &str,
    ) -> Self {
        Self::new(
            path.span(),
            format!("#[validate(..., {custom_message_type}(???, ...))] needs custom message list."),
        )
    }

    pub fn meta_name_value_validation_need_value(path: &syn::Path, validation_type: &str) -> Self {
        Self::new(
            path.span(),
            format!("#[validate({validation_type} = ???)] needs validation value."),
        )
    }

    pub fn meta_name_value_custom_message_need_value(
        path: &syn::Path,
        validation_type: &str,
    ) -> Self {
        Self::new(
            path.span(),
            format!("#[validate(..., {validation_type} = ???)] needs custom message value."),
        )
    }

    pub fn validate_attribute_parse_error(attribute: &syn::Attribute, error: &syn::Error) -> Self {
        Self::new(
            attribute.span(),
            format!("#[validate] parse error: {error}"),
        )
    }

    pub fn field_validation_type_required(attribute: &syn::Attribute) -> Self {
        let filterd_candidates: Vec<&str> = (MetaPathFieldValidation::iter().map(|x| x.name()))
            .chain(MetaListFieldValidation::iter().map(|x| x.name()))
            .chain(MetaNameValueFieldValidation::iter().map(|x| x.name()))
            .collect::<Vec<_>>();

        Self::new(
            attribute.meta.span(),
            format!("#[validate(???)] needs validation type. Is it one of the following?\n{filterd_candidates:#?}"),
        )
    }

    pub fn field_validation_type_unknown(path: &syn::Path, unknown: &str) -> Self {
        let candidates = &(MetaPathFieldValidation::iter().map(|x| x.name()))
            .chain(MetaListFieldValidation::iter().map(|x| x.name()))
            .chain(MetaNameValueFieldValidation::iter().map(|x| x.name()))
            .unique()
            .sorted()
            .collect::<Vec<_>>();

        let filterd_candidates =
            did_you_mean(unknown, candidates).unwrap_or_else(|| candidates.to_vec());

        Self::new(
            path.span(),
            format!("`{unknown}` is unknown validation type. Is it one of the following?\n{filterd_candidates:#?}"),
        )
    }

    pub fn struct_validation_type_required(attribute: &syn::Attribute) -> Self {
        let filterd_candidates: Vec<&str> = (MetaPathStructValidation::iter().map(|x| x.name()))
            .chain(MetaListStructValidation::iter().map(|x| x.name()))
            .chain(MetaNameValueStructValidation::iter().map(|x| x.name()))
            .collect::<Vec<_>>();

        Self::new(
            attribute.meta.span(),
            format!("#[validate(???)] needs validation type. Is it one of the following?\n{filterd_candidates:#?}"),
        )
    }

    pub fn struct_validation_type_unknown(path: &syn::Path, unknown: &str) -> Self {
        let candidates = &(MetaPathStructValidation::iter().map(|x| x.name()))
            .chain(MetaListStructValidation::iter().map(|x| x.name()))
            .chain(MetaNameValueStructValidation::iter().map(|x| x.name()))
            .collect::<Vec<_>>();

        let filterd_candidates =
            did_you_mean(unknown, candidates).unwrap_or_else(|| candidates.to_vec());

        Self::new(
            path.span(),
            format!("`{unknown}` is unknown validation type. Is it one of the following?\n{filterd_candidates:#?}"),
        )
    }

    pub fn unknown_custom_message_type(path: &syn::Path, unknown: &str) -> Self {
        let candidates = &(MetaPathCustomMessage::iter().map(|x| x.name()))
            .chain(MetaListCustomMessage::iter().map(|x| x.name()))
            .chain(MetaNameValueCustomMessage::iter().map(|x| x.name()))
            .unique()
            .sorted()
            .collect::<Vec<_>>();

        let filterd_candidates =
            did_you_mean(unknown, candidates).unwrap_or_else(|| candidates.to_vec());

        Self::new(
            path.span(),
            format!("`{unknown}` is unkown error message type. Is it one of the following?\n{filterd_candidates:#?}"),
        )
    }

    pub fn validate_enumerate_need_array(path: impl Spanned) -> Self {
        Self::new(
            path.span(),
            "#[validate(enumerate = ???)] needs literal array only.",
        )
    }

    pub fn validate_custom_meta_list_need_function_or_closure(span: impl Spanned) -> Self {
        Self::new(
            span.span(),
            "#[validate(custom(???))] needs function or closure.",
        )
    }

    pub fn validate_custom_tail_error(nested: &crate::types::NestedMeta) -> Self {
        Self::new(
            nested.span(),
            "#[validate(custom(???))] supports only 1 item.",
        )
    }

    pub fn validate_custom_meta_name_value_need_function_or_closure(span: impl Spanned) -> Self {
        Self::new(
            span.span(),
            "#[validate(custom = ???)] needs function or closure.",
        )
    }

    pub fn custom_message_parse_error(ident: &syn::Ident, error: &syn::Error) -> Self {
        Self::new(
            ident.span(),
            format!("#[validate(..., {ident})] parse error: {error}"),
        )
    }

    pub fn message_fn_meta_name_value_needs_function_or_closure(
        meta_name_value: &syn::MetaNameValue,
    ) -> Self {
        Self::new(
            meta_name_value.span(),
            "#[validate(..., message_fn = ???)] needs function or closure.",
        )
    }

    #[cfg(feature = "fluent")]
    pub fn fluent_need_item(message_type: &MetaListCustomMessage, path: &syn::Path) -> Self {
        Self::new(
            path.span(),
            format!("`{}` needs items.", message_type.name()),
        )
    }

    #[cfg(feature = "fluent")]
    pub fn fluent_allow_key(
        message_type: &MetaListCustomMessage,
        nested_meta: &crate::types::NestedMeta,
    ) -> Self {
        Self::new(
            nested_meta.span(),
            format!(
                "#[validate(..., {}(???, ...))] allows only fluent key str",
                message_type.name()
            ),
        )
    }

    #[cfg(feature = "fluent")]
    pub fn fluent_allow_args(
        message_type: &MetaListCustomMessage,
        nested_meta: &crate::types::NestedMeta,
    ) -> Self {
        Self::new(
            nested_meta.span(),
            format!(
                "#[validate(..., {}(..., ???))] allows only fluent args key value.",
                message_type.name()
            ),
        )
    }

    #[cfg(feature = "fluent")]
    pub fn l10n_need_fn_call(expr: &syn::Expr) -> Self {
        Self::new(
            expr.span(),
            "#[validate(..., message_l10n = ???)] needs fn calling.".to_string(),
        )
    }

    #[cfg(feature = "fluent")]
    pub fn l10n_fn_name_not_allow(fn_name: &syn::Expr) -> Self {
        Self::new(
            fn_name.span(),
            "#[validate(..., message_l10n = ???(...))] allows only \"fluent\".".to_string(),
        )
    }

    #[cfg(feature = "fluent")]
    pub fn fluent_id_must_be_str_lit(expr: &syn::Expr) -> Self {
        Self::new(
            expr.span(),
            "#[validate(..., message_l10n = fluent(???, ...))] allow only string literal of the fluent id.",
        )
    }

    #[cfg(feature = "fluent")]
    pub fn fluent_id_not_found(paren: &syn::token::Paren) -> Self {
        Self::new(
            paren.span.span(),
            "#[validate(..., message_l10n = fluent(???))] need the fluent id.",
        )
    }

    #[cfg(feature = "fluent")]
    pub fn fluent_allow_arg(expr: &syn::Expr) -> Self {
        Self::new(
            expr.span(),
            "#[validate(..., message_l10n = fluent(..., ???))] allows only \"key=value\" of the fluent arg."
                .to_string(),
        )
    }

    pub fn literal_only(span: impl Spanned) -> Self {
        Self::new(span.span(), "Allow literal only.")
    }

    pub fn numeric_literal_only(lit: &syn::Lit) -> Self {
        Self::new(lit.span(), "Allow numeric literal only.")
    }

    pub fn str_literal_only(lit: &syn::Lit) -> Self {
        Self::new(lit.span(), "Allow str literal only.")
    }

    pub fn too_many_list_items(nested_meta: &syn::Meta) -> Self {
        Self::new(nested_meta.span(), "Too many list items.")
    }

    pub fn to_compile_error(&self) -> TokenStream {
        self.0.to_compile_error()
    }

    pub fn validate_custom_does_not_support_custom_message(meta: &syn::Meta) -> Self {
        Self::new(
            meta.span(),
            "#[validate(custon(...), ???)] does not support custom error message.",
        )
    }
}

fn did_you_mean<'a, T, I>(unknown: &'a str, candidates: I) -> Option<Vec<&'a str>>
where
    T: AsRef<str> + 'a,
    I: IntoIterator<Item = &'a T>,
{
    let mut filterd = candidates
        .into_iter()
        .map(|candidate| {
            (
                ::strsim::jaro_winkler(unknown, candidate.as_ref()),
                candidate.as_ref(),
            )
        })
        .filter(|(confidence, _)| *confidence > 0.8)
        .collect::<Vec<_>>();

    if filterd.is_empty() {
        None
    } else {
        filterd.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
        Some(
            filterd
                .into_iter()
                .map(|(_, candidate)| candidate)
                .collect(),
        )
    }
}

pub type Errors = Vec<Error>;

pub fn to_compile_errors(errors: Errors) -> TokenStream {
    let compile_errors = errors.iter().map(Error::to_compile_error);
    quote!(#(#compile_errors)*)
}