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
use proc_macro2::{Ident, Span};
use quote::quote;
use quote::ToTokens;
use syn;
use syn::{BinOp, Expr, ItemFn, Lit, Member};

use crate::codegen::proc_macro::TokenStream;

fn token_steam_string(arg: proc_macro2::TokenStream) -> String {
    arg.to_token_stream().to_string().trim().to_string()
}

fn convert_to_arg_access(context: &str, arg: Expr, as_proxy: bool, ignore: &[String]) -> Expr {
    match arg {
        Expr::Path(b) => {
            let token = b.to_token_stream().to_string();
            if token == "null" {
                return syn::parse_str::<Expr>("rbs::Value::Null").expect("codegen_func fail");
            }
            if token == "sql" {
                return Expr::Path(b);
            }
            let param = token_steam_string(b.to_token_stream());
            let mut fetch_from_arg = true;
            for x in ignore {
                if param.eq(x) {
                    fetch_from_arg = false;
                }
            }
            if fetch_from_arg {
                return syn::parse_str::<Expr>(&format!("&arg[\"{}\"]", param))
                    .expect("codegen_func fail");
            } else {
                return syn::parse_str::<Expr>(&format!("{}", param)).expect("codegen_func fail");
            }
        }
        Expr::MethodCall(mut b) => {
            //receiver is named need to convert to arg["xxx"]
            b.receiver = Box::new(convert_to_arg_access(
                context,
                *b.receiver.clone(),
                as_proxy,
                ignore,
            ));
            return Expr::MethodCall(b);
        }
        Expr::Binary(mut b) => {
            b.left = Box::new(convert_to_arg_access(
                context,
                *b.left.clone(),
                as_proxy,
                ignore,
            ));
            b.right = Box::new(convert_to_arg_access(
                context,
                *b.right.clone(),
                as_proxy,
                ignore,
            ));
            match b.op {
                BinOp::Add(_) => {
                    let left_token = b.left.to_token_stream().to_string();
                    let right_token = b.right.to_token_stream().to_string();
                    if left_token.trim().ends_with("\"") && left_token.trim().starts_with("\"") {
                        return syn::parse_str::<Expr>(&format!(
                            "(String::from({})).op_add({})",
                            b.left.to_token_stream(),
                            b.right.to_token_stream()
                        ))
                        .expect("codegen_func fail");
                    } else {
                        return syn::parse_str::<Expr>(&format!(
                            "({}).op_add(&{})",
                            b.left.to_token_stream(),
                            b.right.to_token_stream()
                        ))
                        .expect("codegen_func fail");
                    }
                }
                BinOp::And(_) => {
                    b.left = Box::new(
                        syn::parse_str::<Expr>(&format!(
                            "bool::op_from({})",
                            b.left.to_token_stream().to_string().trim()
                        ))
                        .expect("codegen_func fail"),
                    );
                    b.right = Box::new(
                        syn::parse_str::<Expr>(&format!(
                            "bool::op_from({})",
                            b.right.to_token_stream().to_string().trim()
                        ))
                        .expect("codegen_func fail"),
                    );
                }
                BinOp::Or(_) => {
                    b.left = Box::new(
                        syn::parse_str::<Expr>(&format!(
                            "bool::op_from({})",
                            b.left.to_token_stream().to_string().trim()
                        ))
                        .expect("codegen_func fail"),
                    );
                    b.right = Box::new(
                        syn::parse_str::<Expr>(&format!(
                            "bool::op_from({})",
                            b.right.to_token_stream().to_string().trim()
                        ))
                        .expect("codegen_func fail"),
                    );
                }

                // The `-` operator (subtraction)
                BinOp::Sub(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_sub(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `*` operator (multiplication)
                BinOp::Mul(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_mul(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `/` operator (division)
                BinOp::Div(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_div(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `%` operator (modulus)
                BinOp::Rem(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_rem(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `&` operator (bitwise and)
                BinOp::BitAnd(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_bitand(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `|` operator (bitwise or)
                BinOp::BitOr(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_bitor(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `==` operator (equality)
                BinOp::Eq(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_eq(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `<` operator (less than)
                BinOp::Lt(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_lt(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `<=` operator (less than or equal to)
                BinOp::Le(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_le(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `!=` operator (not equal to)
                BinOp::Ne(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_ne(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `>=` operator (greater than or equal to)
                BinOp::Ge(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_ge(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `>` operator (greater than)
                BinOp::Gt(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_gt(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `^` operator (bitwise xor)
                BinOp::BitXor(_) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}).op_bitxor(&{})",
                        b.left.to_token_stream(),
                        b.right.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                // The `<<` operator (shift left)
                BinOp::Shl(_) => {
                    panic!("unsupported token << ")
                }
                // The `>>` operator (shift right)
                BinOp::Shr(_) => {
                    panic!("unsupported token >> ")
                }
                // The `+=` operator
                BinOp::AddEq(_) => {
                    panic!("unsupported token += ")
                }
                // The `-=` operator
                BinOp::SubEq(_) => {
                    panic!("unsupported token -= ")
                }
                // The `*=` operator
                BinOp::MulEq(_) => {
                    panic!("unsupported token *= ")
                }
                // The `/=` operator
                BinOp::DivEq(_) => {
                    panic!("unsupported token /= ")
                }
                // The `%=` operator
                BinOp::RemEq(_) => {
                    panic!("unsupported token %= ")
                }
                // The `^=` operator
                BinOp::BitXorEq(_) => {
                    panic!("unsupported token ^= ")
                }
                // The `&=` operator
                BinOp::BitAndEq(_) => {
                    panic!("unsupported token &= ")
                }
                // The `|=` operator
                BinOp::BitOrEq(_) => {
                    panic!("unsupported token |= ")
                }
                // The `<<=` operator
                BinOp::ShlEq(_) => {
                    panic!("unsupported token <<= ")
                }
                // The `>>=` operator
                BinOp::ShrEq(_) => {
                    panic!("unsupported token >>= ")
                }
            }
            return Expr::Binary(b);
        }
        Expr::Unary(mut b) => {
            b.expr = Box::new(convert_to_arg_access(context, *b.expr, as_proxy, ignore));
            if b.op.to_token_stream().to_string().trim() == "-" {
                return syn::parse_str::<Expr>(&format!(
                    " (0.op_sub(&{}))",
                    b.expr.to_token_stream().to_string().trim()
                ))
                .expect("codegen_func fail");
            }
            return Expr::Unary(b);
        }
        Expr::Paren(mut b) => {
            b.expr = Box::new(convert_to_arg_access(context, *b.expr, as_proxy, ignore));
            return Expr::Paren(b);
        }
        Expr::Field(mut b) => {
            b.base = Box::new(convert_to_arg_access(
                context,
                *b.base.clone(),
                as_proxy,
                ignore,
            ));
            match b.member {
                Member::Named(named) => {
                    return syn::parse_str::<Expr>(&format!(
                        "({}[\"{}\"])",
                        b.base.to_token_stream(),
                        named.to_token_stream()
                    ))
                    .expect("codegen_func fail");
                }
                Member::Unnamed(_) => {}
            }
            return Expr::Field(b);
        }
        Expr::Reference(mut b) => {
            b.expr = Box::new(convert_to_arg_access(context, *b.expr, as_proxy, ignore));
            let result = Expr::Reference(b);
            return result;
        }
        Expr::Index(mut b) => {
            b.expr = Box::new(convert_to_arg_access(context, *b.expr, as_proxy, ignore));
            return syn::parse_str::<Expr>(&format!(
                "{}[{}]",
                b.expr.to_token_stream(),
                b.index.to_token_stream()
            ))
            .expect("codegen_func fail");
        }
        Expr::Let(mut let_expr) => {
            let_expr.expr = Box::new(convert_to_arg_access(
                context,
                *let_expr.expr,
                as_proxy,
                ignore,
            ));
            return Expr::Let(let_expr);
        }
        Expr::Lit(b) => {
            match b.lit.clone() {
                Lit::Str(_) => {}
                Lit::ByteStr(_) => {}
                Lit::Byte(_) => {}
                Lit::Char(_) => {}
                Lit::Int(i) => {
                    //cast int to i64
                    return syn::parse_str::<Expr>(&format!("{}i64", i))
                        .expect("codegen_func fail");
                }
                Lit::Float(f) => {
                    //cast int to f64
                    return syn::parse_str::<Expr>(&format!("{}f64", f))
                        .expect("codegen_func fail");
                }
                Lit::Bool(_) => {}
                Lit::Verbatim(_) => {}
            }
            return Expr::Lit(b);
        }
        _ => {
            return arg;
        }
    }
}

/// gen method or body(if func_name_ident is empty)
pub fn impl_fn(
    context: &str,
    func_name_ident: &str,
    args: &str,
    serialize_result: bool,
    as_proxy: bool,
    ignore: &[String],
) -> proc_macro2::TokenStream {
    let mut string_data = args.to_string();
    string_data = string_data[1..string_data.len() - 1].to_string();
    string_data = string_data.replace(".string()", ".to_string()");
    //convert string define
    let mut last_char = '_';
    let mut string_data_new = String::new();
    for x in string_data.chars() {
        if x == '\'' && last_char != '\\' {
            string_data_new.push('\"');
        } else {
            string_data_new.push(x);
        }
        last_char = x;
    }
    string_data = string_data_new;
    let t = syn::parse_str::<Expr>(&string_data);
    if t.is_err() {
        panic!(
            "[rexpr]syn::parse_str: {} fail for: {}",
            string_data,
            t.err().expect("codegen_func fail").to_string()
        )
    }
    let mut t = t.expect("codegen_func fail");
    t = convert_to_arg_access(context, t, as_proxy, ignore);
    string_data = t.to_token_stream().to_string();
    string_data = string_data.replace(" . ", ".");
    let t = syn::parse_str::<Expr>(&string_data);
    if t.is_err() {
        panic!(
            "[rexpr]syn::parse_str: {} fail for: {}",
            string_data,
            t.err().expect("codegen_func fail").to_string()
        )
    }
    let t = t.expect("codegen_func fail");
    let mut result_impl = quote! { {#t} };
    if serialize_result {
        result_impl = quote! {rbs::to_value({#t}).unwrap_or_default()};
    }
    if func_name_ident.is_empty() || func_name_ident.eq("\"\"") {
        return quote! {
               #result_impl
        }
        .to_token_stream();
    } else {
        let func_name_ident = Ident::new(&func_name_ident.to_string(), Span::call_site());
        return quote! {
            pub fn #func_name_ident(arg:&rbs::Value) -> rbs::Value {
               use rbatis_codegen::ops::*;
               #result_impl
            }
        }
        .to_token_stream();
    }
}