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
use pyo3::{FromPyObject, PyAny, PyResult};
use crate::codegen::{Node};
//use crate::pytypes::{ListLike};
use proc_macro2::TokenStream;
use quote::{quote, format_ident};

use serde::{Serialize, Deserialize};

use crate::tree::{BinOp, BoolOp, Call, Constant, UnaryOp, Name, Compare};
use crate::codegen::{CodeGen, CodeGenError, PythonOptions, CodeGenContext};
use crate::symbols::SymbolTableScopes;

/// Mostly this shouldn't be used, but it exists so that we don't have to manually implement FromPyObject on all of ExprType
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[repr(transparent)]
pub struct Container<T>(pub T);

impl<'a> FromPyObject<'a> for Container<crate::pytypes::List<ExprType>> {
    fn extract(ob: &'a PyAny) -> PyResult<Self> {
        let list = crate::pytypes::List::<ExprType>::new();

        log::debug!("pylist: {}", crate::ast_dump(ob, Some(4))?);
        let _converted_list: Vec<&PyAny> = ob.extract()?;
        for item in ob.iter().expect("extracting list") {
            log::debug!("item: {:?}", item);
        }

        Ok(Self(list))
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum ExprType {
    BoolOp(BoolOp),/*
    NamedExpr(NamedExpr),*/
    BinOp(BinOp),
    UnaryOp(UnaryOp),
    /*Lambda(Lamda),
    IfExp(IfExp),
    Dict(Dict),
    Set(Set),
    ListComp(ListComp),
    SetComp(SetComp),
    DictComp(DictComp),
    GeneratorExp(),
    Await(),
    Yield(),
    YieldFrom(),*/
    Compare(Compare),
    Call(Call),
    /*FormattedValue(),
    JoinedStr(),*/
    Constant(Constant),
    /*Attribute(),
    Subscript(),
    Starred(),*/
    Name(Name),
    List(Vec<ExprType>),
    /*Tuple(),
    Slice(),*/
    NoneType(Constant),

    Unimplemented(String),
}

impl<'a> FromPyObject<'a> for ExprType {
    fn extract(ob: &'a PyAny) -> PyResult<Self> {
        log::debug!("exprtype ob: {}", crate::ast_dump(ob, Some(4))?);

        let expr_type = ob.get_type().name().expect(
            ob.error_message("<unknown>", format!("extracting type name {:?} in expression", ob).as_str()).as_str()
        );
        log::debug!("expression type: {}, value: {}", expr_type, crate::ast_dump(ob, None)?);

        let r = match expr_type {
            "Name" => {
                let name = Name::extract(ob).expect(
                    ob.error_message("<unknown>", format!("parsing Call expression {:?}", ob).as_str()).as_str()
                );
                Ok(Self::Name(name))
            }
            "Call" => {
                let et = Call::extract(ob).expect(
                    ob.error_message("<unknown>", format!("parsing Call expression {:?}", ob).as_str()).as_str()
                );
                Ok(Self::Call(et))
            },
            "Compare" => {
                let c = Compare::extract(ob)
                    .expect(
                        ob.error_message("<unknown>",
                            format!("extracting Compare in expression {:?}", crate::ast_dump(ob, None)?
                        ).as_str()).as_str()
                    );
                Ok(Self::Compare(c))
            },
            "Constant" => {
                log::debug!("constant: {}", crate::ast_dump(ob, None)?);
                let c = Constant::extract(ob)
                    .expect(
                        ob.error_message("<unknown>",
                            format!("extracting Constant in expression {:?}", crate::ast_dump(ob, None)?
                        ).as_str()).as_str()
                    );
                Ok(Self::Constant(c))
            },
            "List" => {
                //let list = crate::pytypes::List::<ExprType>::new();
                let list: Vec<ExprType> = ob.extract().expect("extracting List");
                Ok(Self::List(list))
            }
            "UnaryOp" => {
                let c = UnaryOp::extract(ob)
                    .expect(
                        ob.error_message("<unknown>",
                            format!("extracting UnaryOp in expression {:?}", crate::ast_dump(ob, None)?
                        ).as_str()).as_str()
                    );
                Ok(Self::UnaryOp(c))
            },
            "BinOp" => {
                let c = BinOp::extract(ob)
                    .expect(
                        ob.error_message("<unknown>",
                            format!("extracting BinOp in expression {:?}", crate::ast_dump(ob, None)?
                        ).as_str()).as_str()
                    );
                Ok(Self::BinOp(c))
            },
            _ => {
                let err_msg = format!("Unimplemented expression type {}, {}", expr_type, crate::ast_dump(ob, None)?);
                Err(pyo3::exceptions::PyValueError::new_err(
                    ob.error_message("<unknown>", err_msg.as_str())
                ))
            }
        };
        r
    }
}

impl<'a> CodeGen for ExprType {
    type Context = CodeGenContext;
    type Options = PythonOptions;
    type SymbolTable = SymbolTableScopes;

    fn to_rust(self, ctx: Self::Context, options: Self::Options, symbols: Self::SymbolTable) -> Result<TokenStream, Box<dyn std::error::Error>> {
        match self {
            ExprType::BinOp(binop) => binop.to_rust(ctx, options, symbols),
            ExprType::Call(call) => {
                let name = format_ident!("{}", call.func.id);
                let mut arg_stream = proc_macro2::TokenStream::new();

                for s in call.args {
                    arg_stream.extend(s.clone().to_rust(ctx, options.clone(), symbols.clone()).expect(format!("parsing argument {:?}", s).as_str()));
                }
                Ok(quote!{#name(#arg_stream)})
            },
            ExprType::Compare(c) => c.to_rust(ctx, options, symbols),
            ExprType::Constant(c) => c.to_rust(ctx, options, symbols),
            ExprType::List(l) => {
                let mut ts = TokenStream::new();
                for li in l {
                    let code = li.clone().to_rust(ctx, options.clone(), symbols.clone()).expect(format!("Extracting list item {:?}", li).as_str());
                    ts.extend(code);
                    ts.extend(quote!(,));
                }
                Ok(ts)
            },
            ExprType::Name(name) => name.to_rust(ctx, options, symbols),
            ExprType::NoneType(c) => c.to_rust(ctx, options, symbols),
            ExprType::UnaryOp(operand) => operand.to_rust(ctx, options, symbols),

            _ => {
                let error = CodeGenError(format!("Expr not implemented converting to Rust {:?}", self), None);
                Err(Box::new(error))
            }
        }
    }
}

/// An Expr only contains a single value key, which leads to the actual expression,
/// which is one of several types.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct Expr {
    pub value: ExprType,
    pub ctx: Option<String>,
}

impl<'a> FromPyObject<'a> for Expr {
    fn extract(ob: &'a PyAny) -> PyResult<Self> {
        let err_msg = format!("extracting object value {:?} in expression", ob);

        let ob_value = ob.getattr("value").expect(
            ob.error_message("<unknown>", err_msg.as_str()).as_str()
        );
        log::debug!("ob_value: {}", crate::ast_dump(ob_value, None)?);

        // The context is Load, Store, etc. For some types of expressions such as Constants, it does not exist.
        let ctx: Option<String> = if let Ok(pyany) = ob_value.getattr("ctx") {
            pyany.get_type().extract().unwrap_or_default()
        } else { None };

        let expr_type = ob_value.get_type().name().expect(
            ob.error_message("<unknown>", format!("extracting type name {:?} in expression", ob_value).as_str()).as_str()
        );
        log::debug!("expression type: {}, value: {}", expr_type, crate::ast_dump(ob_value, None)?);
        let r = match expr_type {
            "Name" => {
                let name = Name::extract(ob_value).expect(
                    ob.error_message("<unknown>", format!("parsing Call expression {:?}", ob_value).as_str()).as_str()
                );
                Ok(Self{ctx: ctx, value: ExprType::Name(name)})
            }
            "BinOp" => {
                let c = BinOp::extract(ob_value)
                    .expect(
                        ob.error_message("<unknown>",
                            format!("extracting BinOp in expression {:?}", crate::ast_dump(ob_value, None)?
                        ).as_str()).as_str()
                    );
                Ok(Self {
                    ctx: ctx,
                    value: ExprType::BinOp(c)
                })

            },
            "BoolOp" => {
                let c = BoolOp::extract(ob_value)
                    .expect(
                        ob.error_message("<unknown>",
                            format!("extracting BinOp in expression {:?}", crate::ast_dump(ob_value, None)?
                        ).as_str()).as_str()
                    );
                Ok(Self {
                    ctx: ctx,
                    value: ExprType::BoolOp(c)
                })

            },
            "Call" => {
                let et = Call::extract(ob_value).expect(
                    ob.error_message("<unknown>", format!("parsing Call expression {:?}", ob_value).as_str()).as_str()
                );
                Ok(Self{ctx: ctx, value: ExprType::Call(et)})
            },
            "Constant" => {
                let c = Constant::extract(ob_value)
                    .expect(
                        ob.error_message("<unknown>",
                            format!("extracting Constant in expression {:?}", crate::ast_dump(ob_value, None)?
                        ).as_str()).as_str()
                    );
                Ok(Self {
                    ctx: ctx,
                    value: ExprType::Constant(c)
                })
            },
            "Compare" => {
                let c = Compare::extract(ob_value)
                    .expect(
                        ob.error_message("<unknown>",
                            format!("extracting Compare in expression {:?}", crate::ast_dump(ob_value, None)?
                        ).as_str()).as_str()
                    );
                Ok(Self {
                    ctx: ctx,
                    value: ExprType::Compare(c)
                })
            },
            "List" => {
                //let list = crate::pytypes::List::<ExprType>::new();
                let list: Vec<ExprType> = ob.extract().expect("extracting List");
                Ok(Self {
                    value: ExprType::List(list),
                    ctx: None,
                })
            }
            "UnaryOp" => {
                let c = UnaryOp::extract(ob_value)
                    .expect(
                        ob.error_message("<unknown>",
                            format!("extracting UnaryOp in expression {:?}", crate::ast_dump(ob_value, None)?
                        ).as_str()).as_str()
                    );
                Ok(Self {
                    ctx: ctx,
                    value: ExprType::UnaryOp(c)
                })

            },
            // In sitations where an expression is optional, we may see a NoneType expressions.
            "NoneType" => Ok(Expr{ctx: ctx, value: ExprType::NoneType(Constant(None))}),
            _ => {
                let err_msg = format!("Unimplemented expression type {}, {}", expr_type, crate::ast_dump(ob, None)?);
                Err(pyo3::exceptions::PyValueError::new_err(
                    ob.error_message("<unknown>", err_msg.as_str())
                ))
            }
        };
        r
    }
}

impl<'a> CodeGen for Expr {
    type Context = CodeGenContext;
    type Options = PythonOptions;
    type SymbolTable = SymbolTableScopes;

    fn to_rust(self, ctx: Self::Context, options: Self::Options, symbols: Self::SymbolTable) -> Result<TokenStream, Box<dyn std::error::Error>> {
        match self.value {
            ExprType::BinOp(binop) => binop.to_rust(ctx, options, symbols),
            ExprType::BoolOp(boolop) => boolop.to_rust(ctx, options, symbols),
            ExprType::Call(call) => {
                let name = format_ident!("{}", call.func.id);
                let mut arg_stream = proc_macro2::TokenStream::new();

                for s in call.args {
                    arg_stream.extend(s.clone().to_rust(ctx, options.clone(), symbols.clone()).expect(format!("parsing argument {:?}", s).as_str()));
                }
                Ok(quote!{#name(#arg_stream)})
            },
            ExprType::Constant(constant) => constant.to_rust(ctx, options, symbols),
            ExprType::Compare(compare) => compare.to_rust(ctx, options, symbols),
            ExprType::UnaryOp(operand) => operand.to_rust(ctx, options, symbols),
            ExprType::Name(name) => name.to_rust(ctx, options, symbols),
            // NoneType expressions generate no code.
            ExprType::NoneType(_c) => Ok(quote!()),
            _ => {
                let error = CodeGenError(format!("Expr not implemented converting to Rust {:?}", self), None);
                Err(Box::new(error))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tree::Name;


    #[test]
    fn check_call_expression() {
        let expression = Expr{
            value: ExprType::Call(Call{
                func: Name{id: "test".to_string()},
                args: Vec::new(),
                keywords: Vec::new(),
            }),
            ctx: None,
        };
        let options = PythonOptions::default();
        let symbols = SymbolTableScopes::new();
        let tokens = expression.clone().to_rust(CodeGenContext::Module, options, symbols).unwrap();
        assert_eq!(tokens.to_string(), quote!(test()).to_string());
    }

}