dade_derive 0.1.4

dade is data definition for Rust structures.
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{DataStruct, Fields, GenericArgument, Ident, PathArguments, Type, Visibility};

use crate::fields::ModelField;
use crate::terms::{Condition, DefaultTerm, ToSchema, ToToken};

enum ModelType {
    Null,
    Number,
    String,
    Bool,
    Optional(Box<ModelType>),
    Array,
    Object,
}

const NUMBER_TYPES: [&str; 14] = [
    "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize", "f32",
    "f64",
];

impl ModelType {
    fn new(ty: &Type) -> Self {
        match ty {
            Type::Path(type_path) => {
                let type_token = type_path.to_token_stream().to_string();
                if NUMBER_TYPES.iter().any(|&s| s == type_token) {
                    ModelType::Number
                } else if type_token == "String" {
                    ModelType::String
                } else if type_token == "bool" {
                    ModelType::Bool
                } else {
                    let segment = type_path.path.segments.iter().next().unwrap();
                    let ident = &segment.ident;
                    if ident == "Option" {
                        ModelType::Optional(Box::new({
                            match &segment.arguments {
                                PathArguments::AngleBracketed(angle_bracketed) => {
                                    if angle_bracketed.args.is_empty()
                                        || angle_bracketed.args.len() > 1
                                    {
                                        panic!("Invalid type")
                                    }
                                    match angle_bracketed.args.first().unwrap() {
                                        GenericArgument::Type(inner_type) => {
                                            ModelType::new(inner_type)
                                        }
                                        _ => {
                                            panic!("Invalid type")
                                        }
                                    }
                                }
                                _ => {
                                    panic!("Invalid type")
                                }
                            }
                        }))
                    } else if ident == "Vec" {
                        ModelType::Array
                    } else {
                        ModelType::Object
                    }
                }
            }
            Type::Tuple(type_tuple) => {
                if type_tuple.to_token_stream().to_string() == "()" {
                    ModelType::Null
                } else {
                    panic!("Invalid type")
                }
            }
            _ => panic!("Invalid type"),
        }
    }
}

fn handle_null_type(
    model_field: &ModelField,
    variable: &Ident,
    variable_type: &Type,
    variable_key: &str,
    statements: &mut Vec<TokenStream>,
    conds: &mut Vec<TokenStream>,
) {
    let default_val = if let Some(DefaultTerm::Ident(term)) = &model_field.default {
        let val = &term.value;
        if val == "null" {
            conds.push(quote! {
                "default".to_string(), dade::JsonValue::Null
            });
            quote! { () }
        } else {
            panic!("Support default condition is only `null`")
        }
    } else {
        quote! { () }
    };
    statements.push(quote! {
        let #variable: #variable_type = match dict.get(#variable_key) {
            Some(val) => dade::FromJsonValue::from_json_value(val)?,
            None => #default_val,
        };
    });
    if !model_field.conditions.is_empty() {
        panic!("Support condition is alias, default and validate")
    }
}

fn handle_number_type(
    model_field: &ModelField,
    variable: &Ident,
    variable_type: &Type,
    variable_key: &str,
    statements: &mut Vec<TokenStream>,
    conds: &mut Vec<TokenStream>,
) {
    let default_val = if let Some(DefaultTerm::Lit(term)) = &model_field.default {
        let val = &term.value;
        conds.push(quote! {
            "default".to_string(), dade::JsonValue::Number(dade::Number::from(#val))
        });
        quote! { #val }
    } else {
        let msg = format!("not found key, {}", variable_key);
        quote! {
            return Err(dade::Error::new_validate_err(#msg))
        }
    };
    statements.push(quote! {
        // TODO: set a correct error.
        let #variable: #variable_type = match dict.get(#variable_key) {
            Some(val) => dade::FromJsonValue::from_json_value(val)?,
            None => #default_val,
        };
    });
    let mut terms = Vec::new();
    for cond in model_field.conditions.iter() {
        match cond {
            Condition::Gt(term) => {
                terms.push(term.to_token(variable));
                conds.push(term.to_schema());
            }
            Condition::Ge(term) => {
                terms.push(term.to_token(variable));
                conds.push(term.to_schema());
            }
            Condition::Lt(term) => {
                terms.push(term.to_token(variable));
                conds.push(term.to_schema());
            }
            Condition::Le(term) => {
                terms.push(term.to_token(variable));
                conds.push(term.to_schema());
            }
            _ => {
                panic!("Support condition is gt, ge, lt, le, alias, default and validate")
            }
        }
    }
    if !terms.is_empty() {
        statements.push(quote! {
            if !( #(#terms)&&* ) {
                return Err(dade::Error::new_validate_err("invalid number"))
            }
        })
    }
    if let Some(term) = &model_field.validate {
        let fn_name = &term.value;
        statements.push(quote! {
            let #variable: #variable_type = #fn_name(#variable)?;
        });
    }
}

fn handle_string_type(
    model_field: &ModelField,
    variable: &Ident,
    variable_type: &Type,
    variable_key: &str,
    statements: &mut Vec<TokenStream>,
    conds: &mut Vec<TokenStream>,
) {
    let default_val = if let Some(DefaultTerm::Lit(term)) = &model_field.default {
        let val = &term.value;
        conds.push(quote! {
            "default".to_string(), dade::JsonValue::String(#val.to_string())
        });
        quote! { #val.to_string() }
    } else {
        let msg = format!("not found key, {}", variable_key);
        quote! {
            return Err(dade::Error::new_validate_err(#msg))
        }
    };
    statements.push(quote! {
        let #variable: #variable_type = match dict.get(#variable_key) {
            Some(val) => dade::FromJsonValue::from_json_value(val)?,
            None => #default_val,
        };
    });

    let mut terms = Vec::new();
    for cond in model_field.conditions.iter() {
        match cond {
            Condition::MinLength(term) => {
                terms.push(term.to_token(variable));
                conds.push(term.to_schema());
            }
            Condition::MaxLength(term) => {
                terms.push(term.to_token(variable));
                conds.push(term.to_schema());
            }
            _ => panic!("Support condition is min_length, max_length, alias, default and validate"),
        }
    }
    if !terms.is_empty() {
        statements.push(quote! {
            if !( #(#terms)&&* ) {
                return Err(dade::Error::new_validate_err("invalid string"))
            }
        });
    }
    if let Some(term) = &model_field.validate {
        let fn_name = &term.value;
        statements.push(quote! {
            let #variable: #variable_type = #fn_name(#variable)?;
        });
    }
}

fn handle_bool_type(
    model_field: &ModelField,
    variable: &Ident,
    variable_type: &Type,
    variable_key: &str,
    statements: &mut Vec<TokenStream>,
    conds: &mut Vec<TokenStream>,
) {
    let default_val = if let Some(DefaultTerm::Lit(term)) = &model_field.default {
        let val = &term.value;
        conds.push(quote! {
            "default".to_string(), dade::JsonValue::Bool(#val)
        });
        quote! { #val }
    } else {
        let msg = format!("not found key, {}", variable_key);
        quote! {
            return Err(dade::Error::new_validate_err(#msg))
        }
    };
    statements.push(quote! {
        let #variable: #variable_type = match dict.get(#variable_key) {
            Some(val) => dade::FromJsonValue::from_json_value(val)?,
            None => #default_val,
        };
    });
    if !model_field.conditions.is_empty() {
        panic!("Support condition is alias, default and validate")
    }
    if let Some(term) = &model_field.validate {
        let fn_name = &term.value;
        statements.push(quote! {
            let #variable: #variable_type = #fn_name(#variable)?;
        });
    }
}

fn handle_optional_type(
    inner_type: &ModelType,
    model_field: &ModelField,
    variable: &Ident,
    variable_type: &Type,
    variable_key: &str,
    statements: &mut Vec<TokenStream>,
    conds: &mut Vec<TokenStream>,
) {
    let default_val = if let Some(term) = &model_field.default {
        match inner_type {
            ModelType::Null => panic!("invalid type. You only use `()`."),
            ModelType::Number => match term {
                DefaultTerm::Ident(term) if term.value == "null" => {
                    conds.push(quote! {
                        "default".to_string(), dade::JsonValue::Null
                    });
                    quote! { None }
                }
                DefaultTerm::Lit(term) => {
                    let val = &term.value;
                    conds.push(quote! {
                        "default".to_string(), dade::JsonValue::Number(dade::Number::from(#val))
                    });
                    quote! { #val }
                }
                _ => panic!("Support default condition is `null` or Number"),
            },
            ModelType::String => match term {
                DefaultTerm::Ident(term) if term.value == "null" => {
                    conds.push(quote! {
                        "default".to_string(), dade::JsonValue::Null
                    });
                    quote! { None }
                }
                DefaultTerm::Lit(term) => {
                    let val = &term.value;
                    conds.push(quote! {
                        "default".to_string(), dade::JsonValue::String(#val.to_string())
                    });
                    quote! { #val.to_string() }
                }
                _ => panic!("Support default condition is `null` or String"),
            },
            ModelType::Bool => match term {
                DefaultTerm::Ident(term) if term.value == "null" => {
                    conds.push(quote! {
                        "default".to_string(), dade::JsonValue::Null
                    });
                    quote! { None }
                }
                DefaultTerm::Lit(term) => {
                    let val = &term.value;
                    conds.push(quote! {
                        "default".to_string(), dade::JsonValue::Bool(#val)
                    });
                    quote! { #val }
                }
                _ => panic!("Support default condition is `null`, `false`, `true`"),
            },
            ModelType::Optional(_) => panic!("invalid type"),
            ModelType::Array => {
                panic!("Support default condition is only `null`")
            }
            ModelType::Object => {
                panic!("Support default condition is only `null`")
            }
        }
    } else {
        quote! { None }
    };

    statements.push(quote! {
        let #variable: #variable_type = match dict.get(#variable_key) {
            Some(val) => dade::FromJsonValue::from_json_value(val)?,
            None => #default_val,
        };
    });
    if !model_field.conditions.is_empty() {
        let mut terms = Vec::new();
        let inner_type_name = match inner_type {
            ModelType::Number => {
                for cond in model_field.conditions.iter() {
                    match cond {
                        Condition::Gt(term) => {
                            terms.push(term.to_token(variable));
                            conds.push(term.to_schema());
                        }
                        Condition::Ge(term) => {
                            terms.push(term.to_token(variable));
                            conds.push(term.to_schema());
                        }
                        Condition::Lt(term) => {
                            terms.push(term.to_token(variable));
                            conds.push(term.to_schema());
                        }
                        Condition::Le(term) => {
                            terms.push(term.to_token(variable));
                            conds.push(term.to_schema());
                        }
                        _ => {
                            panic!(
                                "Support condition is gt, ge, lt, le, alias, default and validate"
                            )
                        }
                    }
                }
                "number"
            }
            ModelType::String => {
                for cond in model_field.conditions.iter() {
                    match cond {
                        Condition::MinLength(term) => {
                            terms.push(term.to_token(variable));
                            conds.push(term.to_schema());
                        },
                        Condition::MaxLength(term) => {
                            terms.push(term.to_token(variable));
                            conds.push(term.to_schema());
                        },
                        _ => panic!("Support condition is min_length, max_length, alias, default and validate"),
                    }
                }
                "string"
            }
            ModelType::Array => {
                for cond in model_field.conditions.iter() {
                    match cond {
                        Condition::MinItems(term) => {
                            terms.push(term.to_token(variable));
                            conds.push(term.to_schema());
                        }
                        Condition::MaxItems(term) => {
                            terms.push(term.to_token(variable));
                            conds.push(term.to_schema());
                        }
                        _ => {
                            panic!("Support condition is min_items, max_items, alias and validate")
                        }
                    }
                }
                "array"
            }
            _ => {
                panic!("Support condition is alias, default and validate")
            }
        };
        if !terms.is_empty() {
            let err_msg = format!("invalid {}", inner_type_name);
            statements.push(quote! {
                if let Some(ref #variable) = #variable {
                    if !( #(#terms)&&* ) {
                        return Err(dade::Error::new_validate_err(#err_msg))
                    }
                }
            });
        }
    }

    if let Some(term) = &model_field.validate {
        let fn_name = &term.value;
        statements.push(quote! {
            let #variable: #variable_type = #fn_name(#variable)?;
        });
    }
}

fn handle_array_type(
    model_field: &ModelField,
    variable: &Ident,
    variable_type: &Type,
    variable_key: &str,
    statements: &mut Vec<TokenStream>,
    conds: &mut Vec<TokenStream>,
) {
    if model_field.default.is_some() {
        panic!("Support condition is min_items, max_items, alias and validate")
    }
    let msg = format!("not found key, {}", variable_key);
    statements.push(quote! {
        let #variable: #variable_type = match dict.get(#variable_key) {
            Some(val) => dade::FromJsonValue::from_json_value(val)?,
            None => return Err(dade::Error::new_validate_err(#msg)),
        };
    });
    let mut terms = Vec::new();
    for cond in model_field.conditions.iter() {
        match cond {
            Condition::MinItems(term) => {
                terms.push(term.to_token(variable));
                conds.push(term.to_schema());
            }
            Condition::MaxItems(term) => {
                terms.push(term.to_token(variable));
                conds.push(term.to_schema());
            }
            _ => panic!("Support condition is min_items, max_items, alias and validate"),
        }
    }
    if !terms.is_empty() {
        statements.push(quote! {
            if !( #(#terms)&&* ) {
                return Err(dade::Error::new_validate_err("invalid array"))
            }
        });
    }
    if let Some(term) = &model_field.validate {
        let fn_name = &term.value;
        statements.push(quote! {
            let #variable: #variable_type = #fn_name(#variable)?;
        });
    }
}

fn handle_object_type(
    model_field: &ModelField,
    variable: &Ident,
    variable_type: &Type,
    variable_key: &str,
    statements: &mut Vec<TokenStream>,
    _conds: &mut Vec<TokenStream>,
) {
    if model_field.default.is_some() {
        panic!("Support condition is alias and validate")
    }
    let msg = format!("not found key, {}", variable_key);
    statements.push(quote! {
        let #variable: #variable_type = match dict.get(#variable_key) {
            Some(val) => dade::FromJsonValue::from_json_value(val)?,
            None => return Err(dade::Error::new_validate_err(#msg)),
        };
    });
    if !model_field.conditions.is_empty() {
        panic!("Support condition is alias, default and validate")
    }
    if let Some(term) = &model_field.validate {
        let fn_name = &term.value;
        statements.push(quote! {
            let #variable: #variable_type = #fn_name(#variable)?;
        });
    }
}

pub(crate) fn handle_struct(ident: Ident, vis: Visibility, data: DataStruct) -> TokenStream {
    match data.fields {
        Fields::Named(fields_named) => {
            let mut fields = Vec::new();
            let mut maps = Vec::new();
            let mut keys = Vec::new();
            let mut statements = Vec::new();
            let mut schemas = Vec::new();
            let mut required = Vec::new();

            for field in fields_named.named.iter() {
                let (attrs, model_field) = {
                    let mut bag = Vec::new();
                    let mut model_field = ModelField::default();
                    for attr in field.attrs.iter() {
                        if attr.path.get_ident().unwrap() == "field" {
                            if !attr.tokens.is_empty() {
                                model_field = attr.parse_args().unwrap();
                            }
                        } else {
                            bag.push(attr)
                        }
                    }
                    (quote! {#(#bag)*}, model_field)
                };
                let variable: &Ident = field.ident.as_ref().unwrap();
                let variable_vis = &field.vis;
                let variable_key = if let Some(alias) = &model_field.alias {
                    alias.value.value()
                } else {
                    format!("{}", variable)
                };
                maps.push(quote! {
                    (
                        #variable_key.to_string(),
                        dade::ToJsonValue::to_json_value(&self.#variable)
                    )
                });
                keys.push(quote! {#variable});
                let ty = &field.ty;
                let mut conds: Vec<TokenStream> = Vec::from([quote! {
                    "title".to_string(),
                    dade::JsonValue::String(dade::ToTitle::to_title(#variable_key))
                }]);
                let model_type = ModelType::new(ty);
                if model_field.default.is_none() {
                    match model_type {
                        ModelType::Optional(_) => (),
                        _ => required.push(quote! { #variable_key }),
                    }
                }
                match model_type {
                    ModelType::Null => handle_null_type(
                        &model_field,
                        variable,
                        ty,
                        &variable_key,
                        &mut statements,
                        &mut conds,
                    ),
                    ModelType::Number => handle_number_type(
                        &model_field,
                        variable,
                        ty,
                        &variable_key,
                        &mut statements,
                        &mut conds,
                    ),
                    ModelType::String => handle_string_type(
                        &model_field,
                        variable,
                        ty,
                        &variable_key,
                        &mut statements,
                        &mut conds,
                    ),
                    ModelType::Bool => handle_bool_type(
                        &model_field,
                        variable,
                        ty,
                        &variable_key,
                        &mut statements,
                        &mut conds,
                    ),
                    ModelType::Optional(inner_type) => handle_optional_type(
                        &inner_type,
                        &model_field,
                        variable,
                        ty,
                        &variable_key,
                        &mut statements,
                        &mut conds,
                    ),
                    ModelType::Array => handle_array_type(
                        &model_field,
                        variable,
                        ty,
                        &variable_key,
                        &mut statements,
                        &mut conds,
                    ),
                    ModelType::Object => handle_object_type(
                        &model_field,
                        variable,
                        ty,
                        &variable_key,
                        &mut statements,
                        &mut conds,
                    ),
                }
                schemas.push(quote! {
                    (
                        #variable_key.to_string(),
                        {
                            let mut s = <#ty as dade::RegisterSchema>::register_schema(defs);
                            if let dade::JsonValue::Object(ref mut dict) = s {
                                #(dict.insert(#conds));*;
                            }
                            s
                        }
                    )
                });
                let colon_token = field.colon_token;
                fields.push(quote! {#attrs #variable_vis #variable #colon_token #ty});
            }

            let name = format!("{}", ident);
            let data_type = data.struct_token;
            let def_name = format!("#/definitions/{}", ident);
            quote! {
                #vis #data_type #ident { #(#fields),* }
                impl dade::ToJsonValue for #ident {
                    fn to_json_value(&self) -> dade::JsonValue {
                        dade::JsonValue::Object(
                            std::collections::BTreeMap::from( [#(#maps),*] )
                        )
                    }
                }
                impl dade::FromJsonValue for #ident {
                    fn from_json_value(value: &dade::JsonValue) -> dade::Result<Self> {
                        match value {
                            dade::JsonValue::Object(dict) => {
                                #(#statements)*
                                Ok(#ident { #(#keys),* })
                            }
                            _ => Err(dade::Error::new_validate_err("expect `JsonValue::Object`")),
                        }
                    }
                }
                impl dade::RegisterSchema for #ident {
                    fn register_schema(defs: &mut std::collections::BTreeMap<String, dade::JsonValue>) -> dade::JsonValue {
                        if !defs.contains_key(&#name.to_string()) {
                            // Insert temporarily value.
                            defs.insert(#name.to_string(), dade::JsonValue::Null);
                            let json_value = dade::JsonValue::Object(
                                    std::collections::BTreeMap::from([
                                        (
                                            "title".to_string(),
                                            dade::JsonValue::String(dade::ToTitle::to_title(#name))
                                        ),
                                        (
                                            "type".to_string(),
                                            dade::JsonValue::String("object".to_string())
                                        ),
                                        (
                                            "properties".to_string(),
                                            dade::JsonValue::Object(
                                                std::collections::BTreeMap::from([#(#schemas),*])
                                            )
                                        ),
                                        (
                                            "required".to_string(),
                                            dade::JsonValue::Array(
                                                Vec::from([
                                                    #(dade::JsonValue::String(#required.to_string())),*
                                                ])
                                            )
                                        ),
                                    ])
                                );
                            // Swap to proper value.
                            defs.insert(#name.to_string(), json_value);
                        }
                        dade::JsonValue::Object(
                            std::collections::BTreeMap::from([
                                (
                                    "$ref".to_string(),
                                    dade::JsonValue::String(#def_name.to_string())
                                ),
                            ])
                        )
                    }
                }
            }
        }
        _ => panic!("Only support named field."),
    }
}