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
use proc_macro::TokenStream;
use quote::quote;
use std::str::FromStr;
mod validators;
use validators::{validate_bool_constraints, validate_num_constraints, Constraint};
struct KeyValue {
    key: String,
    ty: String,
    constraints: Option<Vec<Constraint>>,
}

impl FromStr for KeyValue {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split("=>").collect();

        let kv_parts: Vec<&str> = parts[0].split(':').collect();

        if kv_parts.len() != 2 {
            return Err(());
        }
        let key = kv_parts[0].trim().to_string();
        let ty = kv_parts[1].trim().to_string();

        if parts.len() != 2 {
            return Ok(KeyValue {
                key,
                ty,
                constraints: None,
            });
        }

        let splitted_constraints: Vec<String> = parts[1]
            .trim()
            .split_ascii_whitespace()
            .map(|cons| cons.trim().to_string())
            .collect();

        let mut constraints = vec![];

        for constraint in splitted_constraints {
            if constraint.starts_with("min(") && constraint.ends_with(')') {
                let value = constraint[4..constraint.len() - 1].trim().parse::<i64>();
                if value.is_err() {
                    panic!("Wrong value for constraint Min provided");
                }
                constraints.push(Constraint::Min(value.unwrap()));
                continue;
            } else if constraint.starts_with("max(") && constraint.ends_with(')') {
                let value = constraint[4..constraint.len() - 1].trim().parse::<i64>();
                if value.is_err() {
                    panic!("Wrong value for constraint Max provided");
                }
                constraints.push(Constraint::Max(value.unwrap()));
                continue;
            } else if constraint.to_ascii_lowercase() == "notempty" {
                constraints.push(Constraint::NotEmpty);
                continue;
            } else if constraint.to_ascii_lowercase() == "optional" {
                constraints.push(Constraint::Optional);
                continue;
            } else if constraint.starts_with("len(") && constraint.ends_with(')') {
                let value = constraint[4..constraint.len() - 1].trim().parse::<usize>();
                if value.is_err() {
                    panic!("Wrong value for constraint Len provided");
                }
                constraints.push(Constraint::Len(value.unwrap()));
                continue;
            } else {
                panic!("Wrong constraint syntax {key}: {constraint}.");
            }
        }

        Ok(KeyValue {
            key,
            ty,
            constraints: Some(constraints),
        })
    }
}

fn generate_mask(constraints: &Option<Vec<Constraint>>) -> String {
    let constraints = constraints.as_ref().unwrap();
    let mut mask = [
        "".to_string(),
        "".to_string(),
        "".to_string(),
        "".to_string(),
        "".to_string(),
        "".to_string(),
    ];
    for cons in constraints {
        match cons {
            Constraint::Max(val) => mask[0].push_str(&format!("{val}")),
            Constraint::Min(val) => mask[1].push_str(&format!("{val}")),
            Constraint::Optional => mask[2].push('1'),
            Constraint::NotEmpty => mask[3].push('1'),

            Constraint::Len(len) => mask[4].push_str(&format!("{len}")),
        }
    }

    mask.join(",")
}

#[proc_macro]
pub fn convert(input: TokenStream) -> TokenStream {
    let input = input.to_string();
    let input = input.trim();
    let input = input.strip_prefix('{').unwrap_or(input);
    let input = input.strip_suffix('}').unwrap_or(input);
    let input = input.trim();

    let key_values: Vec<KeyValue> = input
        .split(',')
        .map(|s| s.trim().parse())
        .collect::<Result<Vec<KeyValue>, _>>()
        .unwrap_or_else(|_| panic!("Invalid input: {:?}", input));

    let result = key_values.iter().map(
        |KeyValue {
             key,
             ty,
             constraints,
         }| {
            let key_str = key.as_str();
            let typing = match ty.to_ascii_lowercase().as_str() {
                "int" | "integer" | "i32" => {
                    if constraints.is_some() {
                        validate_num_constraints(key, constraints.as_ref().unwrap());
                    }

                    quote! { Value::Int }
                }
                "str" | "string" => {
                    quote! { Value::Str }
                }
                "long" | "i64" => {
                    if constraints.is_some() {
                        validate_num_constraints(key, constraints.as_ref().unwrap());
                    }
                    quote! {Value::Long }
                }
                "bool" | "boolean" => {
                    if constraints.is_some() {
                        validate_bool_constraints(key, constraints.as_ref().unwrap());
                    }
                    quote! { Value::Bool }
                }
                _ => panic!("Unsupported type: {:?}", ty),
            };

            if constraints.is_none() {
                quote! { (#key_str, #typing, "".to_string() ) }
            } else {
                let mask = generate_mask(constraints);
                quote! { (#key_str, #typing, #mask.to_string() ) }
            }
        },
    );

    let output = quote! { [ #( #result ),* ] };

    output.into()
}