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

use crate::tree::{FunctionDef, Import, ImportFrom, Expr, Call, ClassDef};
use crate::codegen::{CodeGen, CodeGenError, PythonOptions, Node, CodeGenContext};

use log::debug;

#[derive(Clone, Debug)]
pub struct Statement {
    pub lineno: Option<usize>,
    pub col_offset: Option<usize>,
    pub end_lineno: Option<usize>,
    pub end_col_offset: Option<usize>,
    pub statement: StatementType,
}

impl<'a> FromPyObject<'a> for Statement {
    fn extract(ob: &'a PyAny) -> PyResult<Self> {
        Ok(Self {
            lineno: ob.lineno(),
            col_offset: ob.col_offset(),
            end_lineno: ob.end_lineno(),
            end_col_offset: ob.end_col_offset(),
            statement: StatementType::extract(ob)?,
        })
    }
}

impl<'a> Node<'a> for Statement {
    fn lineno(&self) -> Option<usize> {
        self.lineno
    }
    fn col_offset(&self) -> Option<usize> {
        self.col_offset
    }
    fn end_lineno(&self) -> Option<usize> {
        self.end_lineno
    }
    fn end_col_offset(&self) -> Option<usize> {
        self.end_col_offset
    }
}

impl<'a> CodeGen for Statement {
    type Context = CodeGenContext;
    type Options = PythonOptions;

    fn to_rust(self, ctx: Self::Context, options: Self::Options) -> Result<TokenStream, Box<dyn std::error::Error>> {
        Ok(self.statement.clone().to_rust(ctx, options).expect(
            self.error_message("<unknown>", "failed to compile statement").as_str()
        ))
    }
}

#[derive(Clone, Debug)]
pub enum StatementType {
    Break,
    Continue,
    ClassDef(ClassDef),
    Call(Call),
    Pass,
    Import(Import),
    ImportFrom(ImportFrom),
    Expr(Expr),
    FunctionDef(FunctionDef),

    Unimplemented(String),
}

impl<'a> FromPyObject<'a> for StatementType {
    fn extract(ob: &'a PyAny) -> PyResult<Self> {
        let err_msg = format!("getting type for statement {:?}", ob);
        let ob_type = ob.get_type().name().expect(
            ob.error_message("<unknown>", err_msg.as_str()).as_str()
        );

        debug!("statement ob_type: {}...{}", ob_type, crate::ast_dump(ob, Some(4))?);
        match ob_type {
            "Pass" => Ok(StatementType::Pass),
            "Call" => {
                let call = Call::extract(
                    ob.getattr("value").expect(format!("getting value from {:?} in call statement", ob).as_str())
                ).expect(format!("extracting call statement {:?}", ob).as_str());
                debug!("call: {:?}", call);
                Ok(StatementType::Call(call))
        },
            "ClassDef" => Ok(StatementType::ClassDef(ClassDef::extract(ob).expect(format!("Class definition {:?}", ob).as_str()))),
            "Continue" => Ok(StatementType::Continue),
            "Break" => Ok(StatementType::Break),
            "FunctionDef" => Ok(StatementType::FunctionDef(FunctionDef::extract(ob).expect(format!("Function definition {:?}", ob).as_str()))),
            "Import" => Ok(StatementType::Import(Import::extract(ob).expect(format!("Import {:?}", ob).as_str()))),
            "ImportFrom" => Ok(StatementType::ImportFrom(ImportFrom::extract(ob).expect(format!("ImportFrom {:?}", ob).as_str()))),
            "Expr" => {
                let expr = Expr::extract(
                    ob.extract().expect(format!("extracting Expr {:?}", ob).as_str())
                ).expect(format!("Expr {:?}", ob).as_str());
                Ok(StatementType::Expr(expr))
            },
            _ => Err(pyo3::exceptions::PyValueError::new_err(format!("Unimplemented statement type {}, {}", ob_type, crate::ast_dump(ob, None)?)))
        }
    }
}

impl<'a> CodeGen for StatementType {
    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 {
            StatementType::Break => Ok(quote!{break;}),
            StatementType::Call(c) => c.to_rust(ctx, options),
            StatementType::ClassDef(c) => c.to_rust(ctx, options),
            StatementType::Continue => Ok(quote!{continue;}),
            StatementType::Pass => Ok(quote!{}),
            StatementType::FunctionDef(s) => s.to_rust(ctx, options),
            StatementType::Import(s) => s.to_rust(ctx, options),
            StatementType::ImportFrom(s) => s.to_rust(ctx, options),
            StatementType::Expr(s) => s.to_rust(ctx, options),
            _ => {
                let error = CodeGenError(format!("StatementType not implemented {:?}", self), None);
                Err(Box::new(error))
            }
        }
    }
}

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

    #[test]
    fn check_pass_statement() {
        let statement = StatementType::Pass;
        let options = PythonOptions::default();
        let tokens = statement.clone().to_rust(CodeGenContext::Module, options);

        debug!("statement: {:?}, tokens: {:?}", statement, tokens);
        assert_eq!(tokens.unwrap().is_empty(), true);
    }

    #[test]
    fn check_break_statement() {
        let statement = StatementType::Break;
        let options = PythonOptions::default();
        let tokens = statement.clone().to_rust(CodeGenContext::Module, options);

        debug!("statement: {:?}, tokens: {:?}", statement, tokens);
        assert_eq!(tokens.unwrap().is_empty(), false);
    }

    #[test]
    fn check_continue_statement() {
        let statement = StatementType::Continue;
        let options = PythonOptions::default();
        let tokens = statement.clone().to_rust(CodeGenContext::Module, options);

        debug!("statement: {:?}, tokens: {:?}", statement, tokens);
        assert_eq!(tokens.unwrap().is_empty(), false);
    }
}