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


use crate::tree::{Call, Constant};
use crate::codegen::{CodeGen, CodeGenError, PythonOptions, CodeGenContext};

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

    Unimplemented(String),
}

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

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()
        );
        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()
        );
        let r = match expr_type {
            "Call" => {
                let et = Call::extract(ob_value).expect(
                    ob.error_message("<unknown>", format!("parsing Call expression {:?}", ob_value).as_str()).as_str()
                );
                Ok(Self{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 {
                    value: ExprType::Constant(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 Expr {
    type Context = CodeGenContext;
    type Options = PythonOptions;

    fn to_rust(self, ctx: Self::Context, options: Self::Options) -> Result<TokenStream, Box<dyn std::error::Error>> {
        match self.value {
            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()).expect(format!("parsing argument {:?}", s).as_str()));
                }
                Ok(quote!{#name(#arg_stream)})
            },
            ExprType::Constant(constant) => {
                constant.to_rust(ctx, options)
            },
                //Expr::Break => Ok(quote!{break;}),
            _ => {
                let error = CodeGenError(format!("Expr not implemented {:?}", 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(),
                    })
        };
        let options = PythonOptions::default();
        let tokens = expression.clone().to_rust(CodeGenContext::Module, options).unwrap();
        assert_eq!(tokens.to_string(), quote!(test()).to_string());
    }

}