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
use darling::FromDeriveInput;
use proc_macro::{self, TokenStream};
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[derive(FromDeriveInput, Default)]
#[darling(default, attributes(table), forward_attrs(allow, doc, cfg))]
struct Opts {
    name: Option<String>,
}

#[proc_macro_derive(TableSerialize, attributes(table))]
pub fn derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input);
    let opts = Opts::from_derive_input(&input).expect("Wrong options");
    let DeriveInput { ident, .. } = input;
    let answer = match opts.name {
        Some(x) => quote! {
            fn name(&self) -> String {
                #x.to_string()
            }
        },
        None => quote! {
            fn name(&self) -> String {
                let r = format!("{:?}", #ident);
                r
            }
        },
    };

    let output = quote! {
        impl ormlib::TableSerialize for #ident {
            #answer
        }
    };
    output.into()
}

#[proc_macro_derive(TableDeserialize, attributes(table))]
pub fn derive_de(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input);
    let opts = Opts::from_derive_input(&input).expect("Wrong options");
    let DeriveInput { ident, .. } = input;

    let syn::Data::Struct(data) = input.data else {
        unimplemented!()
    };

    let mut fields: Vec<String> = Vec::new();
    for f in data.fields.iter() {
        fields.push(f.ident.as_ref().unwrap().to_string());

    }
    let code1: String = r#"
    fn fields() -> Vec<String> {

        let mut fields: Vec<String> = Vec::new();

    "#.to_string();

    let mut code2: String = String::new();

    for f in fields.iter() {
        code2.push_str(&format!("fields.push(\"{}\".to_string());\n", f));
    }

    let code3: String = r#"

        fields
    }

    "#.to_string();

    let code_all = format!("{}{}{}", code1, code2, code3);
    let code = code_all.as_str();

    let code_token: proc_macro2::TokenStream = code.parse().unwrap(); // Преобразование строки в TokenStream

    let  answer = match opts.name {
        Some(x) => quote! {
            fn same_name() -> String {
                #x.to_string()
            }
        },
        None => quote! {
        },
    };

    let output = quote! {
        impl ormlib::TableDeserialize for #ident {
            #answer

            #code_token
        }
    };

    output.into()
}