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
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
//! # Macros
//!
//! `Model` - Macro for converting Structure to mango-orm Model.
//! The model can access the database.
//! The model can create, update, and delete documents in collections.
//!
//! `Form` - Macro for converting Structure to mango-orm Form.
//! The form does not have access to the database.
//! Form are needed where it makes no sense to use a model -
//! To create a search form, to recover a password, to combine models, etc.
//!

use proc_macro::TokenStream;
use quote::quote;
use serde::Serialize;
use syn::{parse_macro_input, Attribute, AttributeArgs, DeriveInput, MetaNameValue, NestedMeta};

// MODEL - MACRO FOR CONVERTING STRUCTURE TO MANGO-ORM MODEL
// #################################################################################################
/// Macro for converting Structure to mango-orm Model.
/// The model can access the database.
/// The model can create, update, and delete documents in collections.
///
/// # Example:
///
/// ```
/// use mango_orm::*;
/// use metamorphose::Model;
/// use serde::{Deserialize, Serialize};
///
/// // Get settings of service/sub-application.
/// use crate::settings::{
///     default::{DATABASE_NAME, DB_CLIENT_NAME, DB_QUERY_DOCS_LIMIT, SERVICE_NAME},
///     PROJECT_NAME, UNIQUE_PROJECT_KEY,
/// };
///
/// #[Model(
///     is_del_docs = false,
///     is_use_add_valid = true,
///     ignore_fields = "confirm_password"
/// )]
/// #[derive(Serialize, Deserialize, Default, Debug)]
/// pub struct AdminProfile {
///    #[serde(default)]
///    #[field_attrs(
///        widget = "inputText",
///        label = "Username",
///        placeholder = "Enter your username",
///        unique = true,
///        required = true,
///        maxlength = 150,
///        hint = "Valid characters: a-z A-Z 0-9 _ @ + .<br>Max size: 150"
///    )]
///    pub username: Option<String>,
///    //
///    #[serde(default)]
///    #[field_attrs(
///        widget = "inputImage",
///        label = "Photo",
///        value = r#"{
///                "path":"./media/no_avatar.png",
///                "url":"/media/no_avatar.png"
///            }"#,
///        placeholder = "Upload your photo",
///        accept = "image/jpeg,image/png",
///        hint = "Image in JPEG or PNG format",
///        thumbnails = r#"[["xs",150],["sm",300]]"#
///    )]
///    pub photo: Option<String>,
///    //
///    #[serde(default)]
///    #[field_attrs(
///        widget = "inputText",
///        label = "First name",
///        placeholder = "Enter your First name",
///        maxlength = 150
///    )]
///    pub first_name: Option<String>,
///    //
///    #[serde(default)]
///    #[field_attrs(
///        widget = "inputText",
///        label = "Last name",
///        placeholder = "Enter your Last name",
///        maxlength = 150
///    )]
///    pub last_name: Option<String>,
///    //
///    #[serde(default)]
///    #[field_attrs(
///        widget = "inputEmail",
///        label = "E-mail",
///        placeholder = "Please enter your email",
///        required = true,
///        unique = true,
///        maxlength = 320,
///        hint = "Your actual E-mail"
///    )]
///    pub email: Option<String>,
///    //
///    #[serde(default)]
///    #[field_attrs(
///        widget = "inputPhone",
///        label = "Phone number",
///        placeholder = "Please enter your phone number",
///        unique = true,
///        maxlength = 30,
///        hint = "Your actual phone number"
///    )]
///    pub phone: Option<String>,
///    //
///    #[serde(default)]
///    #[field_attrs(
///        widget = "inputPassword",
///        label = "Password",
///        placeholder = "Enter your password",
///        required = true,
///        minlength = 8,
///        hint = "Valid characters: a-z A-Z 0-9 @ # $ % ^ & + = * ! ~ ) (<br>Min size: 8"
///    )]
///    pub password: Option<String>,
///    //
///    #[serde(default)]
///    #[field_attrs(
///        widget = "inputPassword",
///        label = "Confirm password",
///        placeholder = "Repeat your password",
///        required = true,
///        minlength = 8,
///        hint = "Repeat your password"
///    )]
///    pub confirm_password: Option<String>,
///    //
///    #[serde(default)]
///    #[field_attrs(
///        widget = "checkBox",
///        label = "is staff?",
///        hint = "User can access the admin site?"
///    )]
///    pub is_staff: Option<bool>,
///    //
///    #[serde(default)]
///    #[field_attrs(
///        widget = "checkBox",
///        label = "is active?",
///        hint = "Is this an active account?"
///    )]
///    pub is_active: Option<bool>,
/// }
/// ```
///
#[allow(non_snake_case)]
#[proc_macro_attribute]
pub fn Model(args: TokenStream, input: TokenStream) -> TokenStream {
    let args = parse_macro_input!(args as AttributeArgs);
    let mut ast = parse_macro_input!(input as DeriveInput);
    impl_create_model(&args, &mut ast)
}

// Parsing fields and attributes of a structure, creating implementation of methods.
// *************************************************************************************************
fn impl_create_model(args: &Vec<NestedMeta>, ast: &mut DeriveInput) -> TokenStream {
    // Clear the field type from `Option <>`
    let re_clear_field_type = regex::RegexBuilder::new(r"^Option < ([a-z\d\s<>]+) >$")
        .case_insensitive(true)
        .build()
        .unwrap();
    let model_name = &ast.ident;
    if model_name.to_string().len() > 31 {
        panic!(
            "Model: `{}` : Model name - Max size: 31 characters.",
            model_name.to_string()
        )
    }
    let mut trans_meta = Meta {
        model_name: ast.ident.to_string(),
        ..Default::default()
    };
    let mut trans_map_widgets: TransMapWidgets = Default::default();
    let mut add_trait_custom_valid = quote! {impl AdditionalValidation for #model_name {}};

    // Get Model attributes.
    // *********************************************************************************************
    for nested_meta in args {
        if let NestedMeta::Meta(meta) = nested_meta {
            if let syn::Meta::NameValue(mnv) = meta {
                if mnv.path.is_ident("database") {
                    if let syn::Lit::Str(lit_str) = &mnv.lit {
                        trans_meta.database_name = lit_str.value().trim().to_string();
                    } else {
                        panic!(
                            "Model: `{}` : Could not determine value for \
                            parameter `database`. Use the `&str` type.",
                            model_name.to_string()
                        )
                    }
                } else if mnv.path.is_ident("db_client_name") {
                    if let syn::Lit::Str(lit_str) = &mnv.lit {
                        trans_meta.db_client_name = lit_str.value().trim().to_string();
                    } else {
                        panic!(
                            "Model: `{}` : Could not determine value for \
                            parameter `db_client_name`. Use the `&str` type.",
                            model_name.to_string(),
                        )
                    }
                } else if mnv.path.is_ident("db_query_docs_limit") {
                    if let syn::Lit::Int(lit_int) = &mnv.lit {
                        trans_meta.db_query_docs_limit = lit_int.base10_parse::<u32>().unwrap();
                    } else {
                        panic!(
                            "Model: `{}` : Could not determine value for \
                            parameter `db_client_name`. Use the `&str` type.",
                            model_name.to_string(),
                        )
                    }
                } else if mnv.path.is_ident("is_add_docs") {
                    if let syn::Lit::Bool(lit_bool) = &mnv.lit {
                        trans_meta.is_add_docs = lit_bool.value;
                    } else {
                        panic!(
                            "Model: `{}` : Could not determine value for \
                            parameter `is_add_docs`. Use the `bool` type.",
                            model_name.to_string(),
                        )
                    }
                } else if mnv.path.is_ident("is_up_docs") {
                    if let syn::Lit::Bool(lit_bool) = &mnv.lit {
                        trans_meta.is_up_docs = lit_bool.value;
                    } else {
                        panic!(
                            "Model: `{}` : Could not determine value for \
                            parameter `is_up_docs`. Use the `bool` type.",
                            model_name.to_string(),
                        )
                    }
                } else if mnv.path.is_ident("is_del_docs") {
                    if let syn::Lit::Bool(lit_bool) = &mnv.lit {
                        trans_meta.is_del_docs = lit_bool.value;
                    } else {
                        panic!(
                            "Model: `{}` : Could not determine value for \
                            parameter `is_del_docs`. Use the `bool` type.",
                            model_name.to_string(),
                        )
                    }
                } else if mnv.path.is_ident("ignore_fields") {
                    if let syn::Lit::Str(lit_str) = &mnv.lit {
                        let mut value = lit_str.value();
                        value.retain(|chr| !chr.is_whitespace());
                        trans_meta.ignore_fields = value
                            .to_lowercase()
                            .split(',')
                            .map(|item| item.to_string())
                            .collect();
                    } else {
                        panic!(
                            "Model: `{}` : Could not determine value for \
                            parameter `ignore_fields`. Use the type `&str` in \
                            the format - <field_name, field_name>.",
                            model_name.to_string(),
                        )
                    }
                } else if mnv.path.is_ident("is_use_add_valid") {
                    if let syn::Lit::Bool(lit_bool) = &mnv.lit {
                        if lit_bool.value {
                            add_trait_custom_valid = quote! {};
                        }
                    } else {
                        panic!(
                            "Model: `{}` : Could not determine value for \
                            parameter `is_use_add_valid`. Use the `bool` type.",
                            model_name.to_string(),
                        )
                    }
                }
            }
        }
    }

    // Get fields of Model.
    // *********************************************************************************************
    if let syn::Data::Struct(ref mut data) = &mut ast.data {
        if let syn::Fields::Named(ref mut fields) = &mut data.fields {
            let fields = &mut fields.named;

            // Add new field `hash`.
            let new_field: syn::FieldsNamed = syn::parse2(quote! {
                {#[serde(default)] #[field_attrs(widget = "hiddenText")] pub hash: Option<String>}
            })
            .unwrap_or_else(|err| panic!("{}", err.to_string()));
            let new_field = new_field.named.first().unwrap().to_owned();
            &fields.push(new_field);

            // Get the number of fields.
            trans_meta.fields_count = fields.len();

            // Loop over fields.
            // -------------------------------------------------------------------------------------
            for field in fields {
                let mut field_name = String::new();
                let mut field_type = String::new();

                // Get field name.
                if let Some(ident) = &field.ident {
                    field_name = ident.to_string();

                    // Check for fields with reserved names - `created_at`, `updated_at`.
                    if field_name == "created_at".to_string() {
                        panic!(
                            "Model: `{}` : The field named `created_at` is reserved.",
                            model_name.to_string()
                        )
                    } else if field_name == "updated_at".to_string() {
                        panic!(
                            "Model: `{}` : The field named `updated_at` is reserved.",
                            model_name.to_string()
                        )
                    }

                    trans_meta.fields_name.push(field_name.clone());
                }
                // Get field type.
                if let syn::Type::Path(ty) = &field.ty {
                    field_type = quote! {#ty}.to_string();
                    let cap = &re_clear_field_type
                        .captures_iter(field_type.as_str())
                        .next();
                    if cap.is_some() {
                        field_type = cap.as_ref().unwrap()[1].to_string();
                    } else {
                        panic!(
                            "Model: `{}` > Field: `{}` : Change field type to `Option < {} >`.",
                            model_name.to_string(),
                            field_name,
                            field_type
                        )
                    }
                    trans_meta
                        .map_field_type
                        .insert(field_name.clone(), field_type.clone());
                }

                // Get the attribute of the field `field_attrs`.
                let attrs: Option<&Attribute> = get_field_attr(&field, "field_attrs");
                let mut widget = Widget {
                    id: get_id(model_name.to_string(), field_name.clone()),
                    name: field_name.clone(),
                    ..Default::default()
                };
                // Allow Validation - Whether the Widget supports the current field type.
                let mut check_field_type = true;

                // Get field attributes.
                if attrs.is_some() {
                    match attrs.unwrap().parse_meta() {
                        Ok(meta) => {
                            if let syn::Meta::List(meta_list) = meta {
                                for nested_meta in meta_list.nested {
                                    if let NestedMeta::Meta(meta) = nested_meta {
                                        if let syn::Meta::NameValue(mnv) = meta {
                                            let attr_name =
                                                &mnv.path.get_ident().unwrap().to_string()[..];
                                            get_param_value(
                                                attr_name,
                                                &mnv,
                                                &mut widget,
                                                model_name.to_string().as_ref(),
                                                field_name.as_ref(),
                                                field_type.as_ref(),
                                                &mut check_field_type,
                                            );
                                        }
                                    }
                                }
                            }
                        }
                        Err(err) => panic!("{}", err.to_string()),
                    }
                }

                // Match widget type and field type.
                if check_field_type {
                    let widget_name = widget.widget.clone();
                    let widget_info = get_widget_info(&widget_name).unwrap_or_else(|err| {
                        panic!(
                            "Model: `{}` > Field: `{}` : {}",
                            model_name.to_string(),
                            field_name,
                            err.to_string()
                        )
                    });
                    if widget_info.0 != field_type {
                        panic!(
                            "Model: `{}` > Field: `{}` > Type: {}: \
                            The widget type `{}` is not the same \
                            as the field type.",
                            model_name.to_string(),
                            field_name,
                            field_type,
                            widget_info.0
                        )
                    }
                }
                // Validation the `min` and` max` parameters for date and time.
                if widget.widget == "inputDate".to_string() {
                    let re_valid_date = regex::RegexBuilder::new(
                    r"^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)$"
                        )
                        .build()
                        .unwrap();
                    if !widget.value.is_empty() {
                        if !re_valid_date.is_match(widget.value.as_str()) {
                            panic!(
                                "Model: `{}` > Field: `{}` > Parameter: `default` : \
                                Incorrect date format. Example: \"1970-02-28\"",
                                model_name, field_name
                            )
                        }
                    }
                    if !widget.min.is_empty() {
                        if !re_valid_date.is_match(widget.min.as_str()) {
                            panic!(
                                "Model: `{}` > Field: `{}` > Parameter: `min` : \
                                Incorrect date format. Example: \"1970-02-28\"",
                                model_name, field_name
                            )
                        }
                    }
                    if !widget.max.is_empty() {
                        if !re_valid_date.is_match(widget.max.as_str()) {
                            panic!(
                                "Model: `{}` > Field: `{}` > Parameter: `max` : \
                                Incorrect date format. Example: \"1970-02-28\"",
                                model_name, field_name
                            )
                        }
                    }
                }
                if widget.widget == "inputDateTime".to_string() {
                    let re_valid_datetime = regex::RegexBuilder::new(
                    r"^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:[01]\d|2[0-3]):[0-5]\d$"
                        )
                        .build()
                        .unwrap();
                    if !widget.value.is_empty() {
                        if !re_valid_datetime.is_match(widget.value.as_str()) {
                            panic!(
                                "Model: `{}` > Field: `{}` > Parameter: `default` : \
                                Incorrect date and time format. Example: \"1970-02-28T00:00\"",
                                model_name, field_name
                            )
                        }
                    }
                    if !widget.min.is_empty() {
                        if !re_valid_datetime.is_match(widget.min.as_str()) {
                            panic!(
                                "Model: `{}` > Field: `{}` > Parameter: `min` : \
                                Incorrect date and time format. Example: \"1970-02-28T00:00\"",
                                model_name, field_name
                            )
                        }
                    }
                    if !widget.max.is_empty() {
                        if !re_valid_datetime.is_match(widget.max.as_str()) {
                            panic!(
                                "Model: `{}` > Field: `{}` > Parameter: `max` : \
                                Incorrect date and time format. Example: \"1970-02-28T00:00\"",
                                model_name, field_name
                            )
                        }
                    }
                }
                // Add field name and widget name to the map.
                trans_meta
                    .map_widget_type
                    .insert(field_name.clone(), widget.widget.clone());
                // Add widget to map.
                trans_map_widgets
                    .map_widgets
                    .insert(field_name.clone(), widget);

                // Delete field attributes.
                // ( To avoid conflicts with the compiler )
                field.attrs = Vec::new();
            }
        } else {
            panic!(
                "Model: `{}` : Expected a struct with named fields.",
                model_name.to_string()
            )
        }
    }

    // Post processing.
    // *********************************************************************************************
    // Checking the name of ignored fields.
    for field_name in trans_meta.ignore_fields.iter() {
        if !trans_meta.fields_name.contains(field_name) {
            panic!(
                "Model: `{}` : Model does not have an ignored field named `{}`.",
                model_name.to_string(),
                field_name,
            )
        }
    }
    // Collect `map_default_values` and add to `trans_meta`.
    for field_name in trans_meta.fields_name.iter() {
        let widget = trans_map_widgets
            .map_widgets
            .get_mut(field_name.as_str())
            .unwrap();
        // For dynamic widgets, the default is invalid.
        if widget.widget.contains("Dyn") {
            if !widget.value.is_empty() {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    For dynamic widgets, it is unacceptable to use default values.",
                    model_name.to_string(),
                    field_name,
                )
            } else if !widget.options.is_empty() {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    For dynamic widgets, it is unacceptable to use `select` parameter.",
                    model_name.to_string(),
                    field_name,
                )
            } else if trans_meta.ignore_fields.contains(&widget.name) {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Dynamic widgets for ignored fields are not allowed.",
                    model_name.to_string(),
                    field_name,
                )
            }
        // Validation the `slug_sources` parameter for widgets of the `Slug` type.
        } else if widget.widget.contains("Slug") {
            if !widget.value.is_empty() {
                panic!(
                    "Model: `{}` > Field: `{}` > Parameter: `value` : \
                    No default value is allowed for fields of type Slug.",
                    model_name, field_name
                )
            }
            if widget.slug_sources.is_empty() {
                panic!(
                    "Model: `{}` > Field: `{}` > Parameter: `slug_sources` : \
                    An empty array is not valid. \
                    Example: [\"title\"] or [\"username\",] or [\"email\", \"first_name\", \"last_name\"]",
                    model_name, field_name
                )
            } else {
                for source_field in widget.slug_sources.iter() {
                    if !trans_meta.fields_name.contains(source_field) {
                        panic!(
                            "Model: `{}` > Field: `{}` > Attribute: `slug_sources` : \
                            The field `{}` is missing.",
                            model_name.to_string(),
                            field_name,
                            source_field
                        )
                    }
                }
            }
        // File fields must not be ignored.
        } else if (widget.widget == "inputFile" || widget.widget == "inputImage")
            && trans_meta.ignore_fields.contains(field_name)
        {
            panic!(
                "Model: `{}` > Field: `{}` : \
                     Ignored fields are incompatible with fields of type `file`.",
                model_name.to_string(),
                field_name,
            )
        // For widgets of the `select` type,
        // the default value must correspond to one of the proposed options.
        } else if widget.widget.contains("select") {
            if !widget.value.is_empty()
                && widget
                    .options
                    .iter()
                    .filter(|item| item.0 == widget.value)
                    .count()
                    == 0
            {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    There is no default value in the `options` parameter.",
                    model_name.to_string(),
                    field_name,
                )
            }
        // For widgets with support for u32 numbers, parameter min = 0
        } else if widget.widget.contains("U32") {
            widget.min = 0_usize.to_string();
        }
        // Add default values in the map.
        trans_meta.map_default_values.insert(
            field_name.clone(),
            (
                widget.widget.clone(),
                if widget.widget != "checkBox" {
                    widget.value.clone()
                } else {
                    widget.checked.to_string()
                },
            ),
        );
    }

    // trans_meta to Json-line.
    // ---------------------------------------------------------------------------------------------
    let trans_meta: String = match serde_json::to_string(&trans_meta) {
        Ok(json_string) => json_string,
        Err(err) => panic!("Model: `{}` : {}", model_name.to_string(), err),
    };
    // TransMapWidgets to Json-line.
    let trans_map_widgets: String = match serde_json::to_string(&trans_map_widgets) {
        Ok(json_string) => json_string,
        Err(err) => panic!("Model: `{}` : {}", model_name.to_string(), err.to_string()),
    };

    // Implementation of methods.
    // *********************************************************************************************
    let output = quote! {
        #ast

        // All methods that directly depend on the macro.
        // *****************************************************************************************
        impl ToModel for #model_name {
            // Get model key.
            // (To access data in the cache)
            // -------------------------------------------------------------------------------------
            fn key() -> String {
                let re = regex::Regex::new(r"(?P<upper_chr>[A-Z])").unwrap();
                format!(
                    "{}__{}__{}",
                    SERVICE_NAME.trim(),
                    re.replace_all(stringify!(#model_name), "_$upper_chr"),
                    UNIQUE_PROJECT_KEY.trim().to_string()
                )
                .to_lowercase()
            }

            // Get metadata of Model.
            // -------------------------------------------------------------------------------------
            fn meta() -> Result<Meta, Box<dyn std::error::Error>> {
                let re = regex::Regex::new(r"(?P<upper_chr>[A-Z])").unwrap();
                let mut meta = serde_json::from_str::<Meta>(&#trans_meta)?;
                let service_name: String = SERVICE_NAME.trim().to_string();
                // Add project name.
                meta.project_name = PROJECT_NAME.trim().to_string();
                // Add unique project key.
                meta.unique_project_key = UNIQUE_PROJECT_KEY.trim().to_string();
                // Add service name.
                meta.service_name = service_name.clone();
                // Add database name.
                if meta.database_name.is_empty() {
                    meta.database_name = format!(
                        "{}__{}__{}",
                        meta.project_name,
                        DATABASE_NAME.trim().to_string(),
                        meta.unique_project_key);
                }
                // Add database client name.
                if meta.db_client_name.is_empty() {
                    meta.db_client_name = DB_CLIENT_NAME.trim().to_string();
                }
                // Add a limit on the number of documents when querying the database.
                if meta.db_query_docs_limit == 0 {
                    meta.db_query_docs_limit = DB_QUERY_DOCS_LIMIT;
                }
                // Add collection name.
                meta.collection_name = format!(
                    "{}_{}",
                    service_name,
                    re.replace_all(&meta.model_name[..], "_$upper_chr")
                )
                .to_lowercase();

                Ok(meta)
            }

            // Get map of widgets for model fields.
            // Hint: <field name, Widget>
            // -------------------------------------------------------------------------------------
            fn widgets() -> Result<std::collections::HashMap<String, Widget>,
                Box<dyn std::error::Error>> {
                Ok(serde_json::from_str::<TransMapWidgets>(&#trans_map_widgets)?.map_widgets)
            }

            // Getter and Setter for field `hash`.
            // -------------------------------------------------------------------------------------
            fn get_hash(&self) -> Option<String> {
                self.hash.clone()
            }
            fn set_hash(&mut self, value: String) {
                self.hash = Some(value);
            }

            // Serialize model to json-line.
            // -------------------------------------------------------------------------------------
            fn self_to_json(&self)
                -> Result<serde_json::value::Value, Box<dyn std::error::Error>> {
                Ok(serde_json::to_value(self)?)
            }
        }

        // Caching information about Models for speed up work.
        // *****************************************************************************************
        impl CachingModel for #model_name {}

        // Validating Model fields for save and update.
        // *****************************************************************************************
        impl ValidationModel for #model_name {}

        // A set of methods for custom validation.
        // *****************************************************************************************
        #add_trait_custom_valid

        // Database Query API
        // *****************************************************************************************
        // Common database query methods.
        impl QCommon for #model_name {}
        // Query methods for a Model instance.
        impl QPaladins for #model_name {}

        // Rendering HTML-controls code for Form.
        // *****************************************************************************************
        impl HtmlControls for #model_name {}
    };

    // Hand the output tokens back to the compiler.
    TokenStream::from(output)
}

// AUXILIARY STRUCTURES AND FUNCTIONS
// #################################################################################################
// Get field attribute.
// *************************************************************************************************
fn get_field_attr<'a>(field: &'a syn::Field, attr_name: &'a str) -> Option<&'a Attribute> {
    let attr: Option<&Attribute> = field
        .attrs
        .iter()
        .find(|attr| attr.path.is_ident(attr_name));
    attr
}

// Get ID for Widget.
// *************************************************************************************************
fn get_id(model_name: String, field_name: String) -> String {
    let re = regex::Regex::new(r"(?P<upper_chr>[A-Z])").unwrap();
    format!(
        "{}--{}",
        re.replace_all(model_name.as_ref(), "-$upper_chr"),
        field_name.replace('_', "-")
    )[1..]
        .to_lowercase()
}

// Transporting of metadate to implementation of methods.
// *************************************************************************************************
#[derive(Serialize)]
struct Meta {
    pub model_name: String,
    pub project_name: String,
    pub unique_project_key: String,
    pub service_name: String,
    pub database_name: String,
    pub db_client_name: String,
    pub db_query_docs_limit: u32,
    pub collection_name: String,
    pub fields_count: usize,
    pub fields_name: Vec<String>,
    pub is_add_docs: bool,
    pub is_up_docs: bool,
    pub is_del_docs: bool,
    pub map_field_type: std::collections::HashMap<String, String>,
    pub map_widget_type: std::collections::HashMap<String, String>,
    // <field_name, (widget_type, value)>
    pub map_default_values: std::collections::HashMap<String, (String, String)>,
    // List of field names that will not be saved to the database.
    pub ignore_fields: Vec<String>,
}

impl Default for Meta {
    fn default() -> Self {
        Meta {
            model_name: String::new(),
            project_name: String::new(),
            unique_project_key: String::new(),
            service_name: String::new(),
            database_name: String::new(),
            db_client_name: String::new(),
            db_query_docs_limit: 0_u32,
            collection_name: String::new(),
            fields_count: 0_usize,
            fields_name: Vec::new(),
            is_add_docs: true,
            is_up_docs: true,
            is_del_docs: true,
            map_field_type: std::collections::HashMap::new(),
            map_widget_type: std::collections::HashMap::new(),
            map_default_values: std::collections::HashMap::new(),
            // List of field names that will not be saved to the database
            ignore_fields: Vec::new(),
        }
    }
}

// Widget attributes.
// *************************************************************************************************
#[derive(Serialize)]
struct Widget {
    pub id: String, // "model-name--field-name" ( The value is determined automatically )
    pub label: String,
    pub widget: String,
    pub input_type: String, // The value is determined automatically
    pub name: String,
    pub value: String,
    pub accept: String, // Hint: accept="image/jpeg,image/png,image/gif"
    pub placeholder: String,
    pub pattern: String, // Validating a field using a client-side regex
    pub minlength: usize,
    pub maxlength: usize,
    pub required: bool,
    pub checked: bool, // For <input type="checkbox|radio">
    pub unique: bool,
    pub disabled: bool,
    pub readonly: bool,
    pub step: String,
    pub min: String,
    pub max: String,
    pub options: Vec<(String, String)>, // Hint: <value, Title> - <option value="value1">Title 1</option>
    pub thumbnails: Vec<(String, u32)>,
    pub slug_sources: Vec<String>, // Example: r#"["title"]"# or r#"["title", "hash"]"#
    pub is_hide: bool,
    pub other_attrs: String, // "autofocus tabindex=\"some number\" size=\"some number\" ..."
    pub css_classes: String, // "class-name class-name ..."
    pub hint: String,
    pub warning: String,    // The value is determined automatically
    pub error: String,      // The value is determined automatically
    pub common_msg: String, // Messages common to the entire Form
}

impl Default for Widget {
    fn default() -> Self {
        Widget {
            id: String::new(),
            label: String::new(),
            widget: String::from("inputText"),
            input_type: String::from("text"),
            name: String::new(),
            value: String::new(),
            accept: String::new(),
            placeholder: String::new(),
            pattern: String::new(),
            minlength: 0_usize,
            maxlength: 256_usize,
            required: false,
            checked: false,
            unique: false,
            disabled: false,
            readonly: false,
            step: String::from("1"),
            min: String::new(),
            max: String::new(),
            options: Vec::new(),
            thumbnails: Vec::new(),
            slug_sources: Vec::new(),
            is_hide: false,
            other_attrs: String::new(),
            css_classes: String::new(),
            hint: String::new(),
            warning: String::new(),
            error: String::new(),
            common_msg: String::new(),
        }
    }
}

// For transporting of Widgets map to implementation of methods.
// Hint: <field name, Widget>
// *************************************************************************************************
#[derive(Default, Serialize)]
struct TransMapWidgets {
    pub map_widgets: std::collections::HashMap<String, Widget>,
}

// Get widget info.
// *************************************************************************************************
fn get_widget_info<'a>(
    widget_name: &'a str,
) -> Result<(&'a str, &'a str), Box<dyn std::error::Error>> {
    let info: (&'a str, &'a str) = match widget_name {
        "checkBox" => ("bool", "checkbox"),
        "inputColor" => ("String", "color"),
        "inputDate" => ("String", "date"),
        "inputDateTime" => ("String", "datetime"),
        "inputEmail" => ("String", "email"),
        "inputFile" => ("String", "file"),
        "inputImage" => ("String", "file"),
        "numberI32" => ("i32", "number"),
        "numberU32" => ("u32", "number"),
        "numberI64" => ("i64", "number"),
        "numberF64" => ("f64", "number"),
        "inputPassword" => ("String", "password"),
        "radioText" => ("String", "radio"),
        "radioI32" => ("i32", "radio"),
        "radioU32" => ("u32", "radio"),
        "radioI64" => ("i64", "radio"),
        "radioF64" => ("f64", "radio"),
        "rangeI32" => ("i32", "range"),
        "rangeU32" => ("u32", "range"),
        "rangeI64" => ("i64", "range"),
        "rangeF64" => ("f64", "range"),
        "inputPhone" => ("String", "tel"),
        "inputText" => ("String", "text"),
        "inputSlug" => ("String", "text"),
        "inputUrl" => ("String", "url"),
        "inputIP" => ("String", "text"),
        "inputIPv4" => ("String", "text"),
        "inputIPv6" => ("String", "text"),
        "textArea" => ("String", "textarea"),
        "selectText" => ("String", "select"),
        "selectTextDyn" => ("String", "select"),
        "selectTextMult" => ("Vec < String >", "select"),
        "selectTextMultDyn" => ("Vec < String >", "select"),
        "selectI32" => ("i32", "select"),
        "selectI32Dyn" => ("i32", "select"),
        "selectI32Mult" => ("Vec < i32 >", "select"),
        "selectI32MultDyn" => ("Vec < i32 >", "select"),
        "selectU32" => ("u32", "select"),
        "selectU32Dyn" => ("u32", "select"),
        "selectU32Mult" => ("Vec < u32 >", "select"),
        "selectU32MultDyn" => ("Vec < u32 >", "select"),
        "selectI64" => ("i64", "select"),
        "selectI64Dyn" => ("i64", "select"),
        "selectI64Mult" => ("Vec < i64 >", "select"),
        "selectI64MultDyn" => ("Vec < i64 >", "select"),
        "selectF64" => ("f64", "select"),
        "selectF64Dyn" => ("f64", "select"),
        "selectF64Mult" => ("Vec < f64 >", "select"),
        "selectF64MultDyn" => ("Vec < f64 >", "select"),
        "hiddenText" => ("String", "hidden"),
        "hiddenI32" => ("i32", "hidden"),
        "hiddenU32" => ("u32", "hidden"),
        "hiddenI64" => ("i64", "hidden"),
        "hiddenF64" => ("f64", "hidden"),
        _ => Err("Invalid widget type.")?,
    };
    Ok(info)
}

// Get parameter value from model field attribute.
// *************************************************************************************************
fn get_param_value<'a>(
    attr_name: &'a str,
    mnv: &MetaNameValue,
    widget: &mut Widget,
    model_name: &'a str,
    field_name: &'a str,
    field_type: &'a str,
    check_field_type: &mut bool,
) {
    match attr_name {
        "label" => {
            if let syn::Lit::Str(lit_str) = &mnv.lit {
                widget.label = lit_str.value().trim().to_string();
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `label`. \
                    Example: \"Some text\"",
                    model_name, field_name
                )
            }
        }
        "accept" => {
            if let syn::Lit::Str(lit_str) = &mnv.lit {
                widget.accept = lit_str.value().trim().to_string();
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `accept`. \
                    Example: \"image/jpeg,image/png\"",
                    model_name, field_name
                )
            }
        }
        "widget" => {
            if let syn::Lit::Str(lit_str) = &mnv.lit {
                let widget_name = lit_str.value();
                let widget_info = get_widget_info(widget_name.as_ref()).unwrap_or_else(|err| {
                    panic!(
                        "Model: `{}` > Field: `{}` : {}",
                        model_name,
                        field_name,
                        err.to_string()
                    )
                });
                if widget_info.0 != field_type {
                    panic!(
                        "Model: `{}` > Field: `{}` : \
                        The widget type is not the same as the field type.",
                        model_name, field_name,
                    )
                }
                widget.widget = widget_name.clone();
                widget.input_type = widget_info.1.to_string();
                *check_field_type = false;
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `widget`. \
                    Example: \"inputEmail\"",
                    model_name, field_name
                )
            }
        }
        "value" => match field_type {
            "i32" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.value = lit_int.base10_parse::<i32>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `value`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "u32" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.value = lit_int.base10_parse::<u32>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `value`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "i64" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.value = lit_int.base10_parse::<i64>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `value`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "f64" => {
                if let syn::Lit::Float(lit_float) = &mnv.lit {
                    widget.value = lit_float.base10_parse::<f64>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `value`. \
                        Example: 10.2",
                        model_name, field_name, field_type
                    )
                }
            }
            "String" => {
                if let syn::Lit::Str(lit_str) = &mnv.lit {
                    widget.value = lit_str.value().trim().to_string()
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `value`. \
                        Example: \"Some text\"",
                        model_name, field_name, field_type
                    )
                }
            }
            _ => panic!(
                "Model: `{}` > Field: `{}` > Type: {} : \
                Unsupported field type for `default` parameter.",
                model_name.to_string(),
                field_name,
                field_type
            ),
        },
        "placeholder" => {
            if let syn::Lit::Str(lit_str) = &mnv.lit {
                widget.placeholder = lit_str.value().trim().to_string();
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `placeholder`. \
                    Example: \"Some text\"",
                    model_name, field_name
                )
            }
        }
        "pattern" => {
            if let syn::Lit::Str(lit_str) = &mnv.lit {
                widget.pattern = lit_str.value().trim().to_string();
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `pattern`. \
                    Example: \"some regular expression\"",
                    model_name, field_name
                )
            }
        }
        "minlength" => {
            if let syn::Lit::Int(lit_int) = &mnv.lit {
                widget.minlength = lit_int.base10_parse::<usize>().unwrap();
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `minlength`. \
                    Example: 10",
                    model_name, field_name
                )
            }
        }
        "maxlength" => {
            if let syn::Lit::Int(lit_int) = &mnv.lit {
                widget.maxlength = lit_int.base10_parse::<usize>().unwrap();
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `maxlength`. \
                    Example: 10",
                    model_name, field_name
                )
            }
        }
        "required" => {
            if let syn::Lit::Bool(lit_bool) = &mnv.lit {
                widget.required = lit_bool.value;
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `required`. \
                    Example: true. Default = false.",
                    model_name, field_name
                )
            }
        }
        "checked" => {
            if let syn::Lit::Bool(lit_bool) = &mnv.lit {
                widget.checked = lit_bool.value;
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `checked`. \
                    Example: true. Default = false.",
                    model_name, field_name
                )
            }
        }
        "unique" => {
            if let syn::Lit::Bool(lit_bool) = &mnv.lit {
                widget.unique = lit_bool.value;
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `unique`. \
                    Example: true. Default = false.",
                    model_name, field_name
                )
            }
        }
        "disabled" => {
            if let syn::Lit::Bool(lit_bool) = &mnv.lit {
                widget.disabled = lit_bool.value;
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `disabled`. \
                    Example: true. Default = false.",
                    model_name, field_name
                )
            }
        }
        "readonly" => {
            if let syn::Lit::Bool(lit_bool) = &mnv.lit {
                widget.readonly = lit_bool.value;
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `readonly`. \
                    Example: true. Default = false.",
                    model_name, field_name
                )
            }
        }
        "step" => match field_type {
            "i32" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.step = lit_int.base10_parse::<i32>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `step`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "u32" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.step = lit_int.base10_parse::<u32>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `step`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "i64" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.step = lit_int.base10_parse::<i64>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `step`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "f64" => {
                if let syn::Lit::Float(lit_float) = &mnv.lit {
                    widget.step = lit_float.base10_parse::<f64>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `step`. \
                        Example: 10.2",
                        model_name, field_name, field_type
                    )
                }
            }
            "String" => {
                if let syn::Lit::Str(lit_str) = &mnv.lit {
                    widget.step = lit_str.value().trim().to_string()
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `step`.
                        Example: not supported.",
                        model_name, field_name, field_type
                    )
                }
            }
            _ => panic!(
                "Model: `{}` > Field: `{}` > Type: {} : \
                Unsupported field type for `step` parameter.",
                model_name, field_name, field_type
            ),
        },
        "min" => match field_type {
            "i32" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.min = lit_int.base10_parse::<i32>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `min`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "u32" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.min = lit_int.base10_parse::<u32>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `min`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "i64" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.min = lit_int.base10_parse::<i64>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `min`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "f64" => {
                if let syn::Lit::Float(lit_float) = &mnv.lit {
                    widget.min = lit_float.base10_parse::<f64>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `min`. \
                        Example: 10.2",
                        model_name, field_name, field_type
                    )
                }
            }
            "String" => {
                if let syn::Lit::Str(lit_str) = &mnv.lit {
                    widget.min = lit_str.value().trim().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `min`. \
                        Example: \"1970-02-28\" or \"1970-02-28T00:00\"",
                        model_name, field_name, field_type
                    )
                }
            }
            _ => panic!(
                "Model: `{}` > Field: `{}` > Type: {} : \
                Unsupported field type for `min` parameter.",
                model_name, field_name, field_type
            ),
        },
        "max" => match field_type {
            "i32" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.max = lit_int.base10_parse::<i32>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `max`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "u32" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.max = lit_int.base10_parse::<u32>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `max`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "i64" => {
                if let syn::Lit::Int(lit_int) = &mnv.lit {
                    widget.max = lit_int.base10_parse::<i64>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `max`. \
                        Example: 10",
                        model_name, field_name, field_type
                    )
                }
            }
            "f64" => {
                if let syn::Lit::Float(lit_float) = &mnv.lit {
                    widget.max = lit_float.base10_parse::<f64>().unwrap().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `max`. \
                        Example: 10.2",
                        model_name, field_name, field_type,
                    )
                }
            }
            "String" => {
                if let syn::Lit::Str(lit_str) = &mnv.lit {
                    widget.max = lit_str.value().trim().to_string();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `max`. \
                        Example: \"1970-02-28\" or \"1970-02-28T00:00\"",
                        model_name, field_name, field_type
                    )
                }
            }
            _ => panic!(
                "Model: `{}` > Field: `{}` > Type: {} : \
                Unsupported field type for `max` parameter.",
                model_name, field_name, field_type
            ),
        },
        "options" => match field_type {
            "i32" | "Vec < i32 >" => {
                if let syn::Lit::Str(lit_str) = &mnv.lit {
                    let json = lit_str.value().replace('_', "");
                    let raw_options: Vec<(i32, String)> = if json.matches("[").count() > 1 {
                        serde_json::from_str(json.as_str()).unwrap()
                    } else {
                        let arr: Vec<i32> = serde_json::from_str(json.as_str()).unwrap();
                        arr.iter().map(|item| (*item, item.to_string())).collect()
                    };
                    widget.options = raw_options
                        .iter()
                        .map(|item| (item.0.to_string(), item.1.to_string()))
                        .collect();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `options`. \
                        Example: [[10, \"Title 1\"], [20, \"Title 2\"], ...] OR \
                        Example: [10, 20, ...]",
                        model_name, field_name, field_type
                    )
                }
            }
            "u32" | "Vec < u32 >" => {
                if let syn::Lit::Str(lit_str) = &mnv.lit {
                    let json = lit_str.value().replace('_', "");
                    let raw_options: Vec<(u32, String)> = if json.matches("[").count() > 1 {
                        serde_json::from_str(json.as_str()).unwrap()
                    } else {
                        let arr: Vec<u32> = serde_json::from_str(json.as_str()).unwrap();
                        arr.iter().map(|item| (*item, item.to_string())).collect()
                    };
                    widget.options = raw_options
                        .iter()
                        .map(|item| (item.0.to_string(), item.1.to_string()))
                        .collect();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `options`. \
                        Example: [[10, \"Title 1\"], [20, \"Title 2\"], ...] OR \
                        Example: [10, 20, ...]",
                        model_name, field_name, field_type
                    )
                }
            }
            "i64" | "Vec < i64 >" => {
                if let syn::Lit::Str(lit_str) = &mnv.lit {
                    let json = lit_str.value().replace('_', "");
                    let raw_options: Vec<(i64, String)> = if json.matches("[").count() > 1 {
                        serde_json::from_str(json.as_str()).unwrap()
                    } else {
                        let arr: Vec<i64> = serde_json::from_str(json.as_str()).unwrap();
                        arr.iter().map(|item| (*item, item.to_string())).collect()
                    };
                    widget.options = raw_options
                        .iter()
                        .map(|item| (item.0.to_string(), item.1.to_string()))
                        .collect();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `options`. \
                        Example: [[10, \"Title 1\"], [20, \"Title 2\"], ...] OR \
                        Example: [10, 20, ...]",
                        model_name, field_name, field_type
                    )
                }
            }
            "f64" | "Vec < f64 >" => {
                if let syn::Lit::Str(lit_str) = &mnv.lit {
                    let json = lit_str.value().replace('_', "");
                    let raw_options: Vec<(f64, String)> = if json.matches("[").count() > 1 {
                        serde_json::from_str(json.as_str()).unwrap()
                    } else {
                        let arr: Vec<f64> = serde_json::from_str(json.as_str()).unwrap();
                        arr.iter().map(|item| (*item, item.to_string())).collect()
                    };
                    widget.options = raw_options
                        .iter()
                        .map(|item| (item.0.to_string(), item.1.to_string()))
                        .collect();
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `options`. \
                        Example: [[10.1, \"Title 1\"], [20.2, \"Title 2\"], ...] OR \
                        Example: [10.1, 20.2, ...]",
                        model_name, field_name, field_type
                    )
                }
            }
            "String" | "Vec < String >" => {
                if let syn::Lit::Str(lit_str) = &mnv.lit {
                    let json = lit_str.value();
                    widget.options = if json.matches("[").count() > 1 {
                        serde_json::from_str(json.as_str()).unwrap()
                    } else {
                        let arr: Vec<String> = serde_json::from_str(json.as_str()).unwrap();
                        arr.iter()
                            .map(|item| {
                                let item = item.to_string();
                                (item.clone(), item)
                            })
                            .collect()
                    };
                } else {
                    panic!(
                        "Model: `{}` > Field: `{}` > Type: {} : \
                        Could not determine value for parameter `options`. \
                        Example: [[\"value\", \"Title 1\"], [value, \"Title 2\"], ...] OR \
                        Example: [\"Item\", \"Item 2\", ...]",
                        model_name, field_name, field_type
                    )
                }
            }
            _ => panic!(
                "Model: `{}` > Field: `{}` > Type: {} : \
                Unsupported field type for `options` parameter.",
                model_name, field_name, field_type
            ),
        },
        "thumbnails" => {
            if let syn::Lit::Str(lit_str) = &mnv.lit {
                let json = lit_str.value().replace('_', "");
                let mut sizes = serde_json::from_str::<Vec<(String, u32)>>(json.as_str()).unwrap();
                sizes.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
                let valid_size_names: [&str; 4] = ["xs", "sm", "md", "lg"];
                for size in sizes.iter() {
                    if !valid_size_names.contains(&size.0.as_str()) {
                        panic!(
                            "Model: `{}` > Field: `{}` : Valid size names - `xs`, `sm`, `md`, `lg`",
                            model_name, field_name
                        )
                    }
                }
                widget.thumbnails = sizes;
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `thumbnails`. \
                    Example: [[\"xs\",150],[\"sm\",300],[\"md\",600],[\"lg\",1200]] \
                    from one to four inclusive",
                    model_name, field_name
                )
            }
        }
        "slug_sources" => {
            if let syn::Lit::Str(lit_str) = &mnv.lit {
                let json = lit_str.value().replace('_', "");
                widget.slug_sources = serde_json::from_str::<Vec<String>>(json.as_str()).unwrap();
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `slug_sources`. \
                    Example: [\"title\"] or [\"title\", \"hash\"]",
                    model_name, field_name
                )
            }
        }
        "is_hide" => {
            if let syn::Lit::Bool(lit_bool) = &mnv.lit {
                widget.is_hide = lit_bool.value;
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `is_hide`. \
                    Example: true. Default = false.",
                    model_name, field_name
                )
            }
        }
        "other_attrs" => {
            if let syn::Lit::Str(lit_str) = &mnv.lit {
                widget.other_attrs = lit_str.value().trim().to_string();
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `other_attrs`. \
                    Example: \"autofocus multiple size=\\\"some number\\\"\"",
                    model_name, field_name
                )
            }
        }
        "css_classes" => {
            if let syn::Lit::Str(lit_str) = &mnv.lit {
                widget.css_classes = lit_str.value().trim().to_string();
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `css_classes`. \
                    Example: \"class_name, class_name\"",
                    model_name, field_name
                )
            }
        }
        "hint" => {
            if let syn::Lit::Str(lit_str) = &mnv.lit {
                widget.hint = lit_str.value().trim().to_string();
            } else {
                panic!(
                    "Model: `{}` > Field: `{}` : \
                    Could not determine value for parameter `hint`. \
                    Example: \"Some text\".",
                    model_name, field_name
                )
            }
        }
        "id" => panic!(
            "Model: `{}` > Field: `{}` : The `id` parameter is determined automatically.",
            model_name, field_name
        ),
        "name" => panic!(
            "Model: `{}` > Field: `{}` : The `name` parameter is determined automatically.",
            model_name, field_name
        ),
        "input_type" => panic!(
            "Model: `{}` > Field: `{}` : The `input_type` parameter is determined automatically.",
            model_name, field_name
        ),
        "warning" => panic!(
            "Model: `{}` > Field: `{}` : The `warning` parameter is determined automatically.",
            model_name, field_name
        ),
        "error" => panic!(
            "Model: `{}` > Field: `{}` : The `error` parameter is determined automatically.",
            model_name, field_name
        ),
        _ => panic!(
            "Model: `{}` > Field: `{}` : Undefined field attribute `{}`.",
            model_name.to_string(),
            field_name,
            attr_name
        ),
    };
}