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


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

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

    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,
    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)})
            }
            "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)
                })
            },
            "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;

    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),
            ExprType::UnaryOp(operand) => operand.to_rust(ctx, options),
            ExprType::Name(name) => name.to_rust(ctx, options),
            // 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 tokens = expression.clone().to_rust(CodeGenContext::Module, options).unwrap();
        assert_eq!(tokens.to_string(), quote!(test()).to_string());
    }

}