Skip to main content

python_ast/ast/tree/
if_stmt.rs

1use proc_macro2::TokenStream;
2use pyo3::{Borrowed, FromPyObject, PyAny, PyResult, types::PyAnyMethods};
3use quote::quote;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    CodeGen, CodeGenContext, ExprType, PythonOptions, SymbolTableScopes,
8    Node, impl_node_with_positions, PyAttributeExtractor, extract_list
9};
10
11use super::Statement;
12
13#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
14pub struct If {
15    pub test: ExprType,
16    pub body: Vec<Statement>,
17    pub orelse: Vec<Statement>,
18    pub lineno: Option<usize>,
19    pub col_offset: Option<usize>,
20    pub end_lineno: Option<usize>,
21    pub end_col_offset: Option<usize>,
22}
23
24impl<'a, 'py> FromPyObject<'a, 'py> for If {
25    type Error = pyo3::PyErr;
26    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
27        let test = ob.extract_attr_with_context("test", "if test condition")?;
28        let test = test
29            .extract()
30            .map_err(|e| crate::extraction_failure("if condition", &ob, e))?;
31        
32        let body: Vec<Statement> = extract_list(&ob, "body", "if body statements")?;
33        let orelse: Vec<Statement> = extract_list(&ob, "orelse", "if else statements")?;
34        
35        Ok(If {
36            test,
37            body,
38            orelse,
39            lineno: ob.lineno(),
40            col_offset: ob.col_offset(),
41            end_lineno: ob.end_lineno(),
42            end_col_offset: ob.end_col_offset(),
43        })
44    }
45}
46
47impl_node_with_positions!(If { lineno, col_offset, end_lineno, end_col_offset });
48
49impl CodeGen for If {
50    type Context = CodeGenContext;
51    type Options = PythonOptions;
52    type SymbolTable = SymbolTableScopes;
53
54    fn find_symbols(self, symbols: Self::SymbolTable) -> Self::SymbolTable {
55        let symbols = self.test.find_symbols(symbols);
56        let symbols = self.body.into_iter().fold(symbols, |acc, stmt| stmt.find_symbols(acc));
57        self.orelse.into_iter().fold(symbols, |acc, stmt| stmt.find_symbols(acc))
58    }
59
60    fn to_rust(
61        self,
62        ctx: Self::Context,
63        options: Self::Options,
64        symbols: Self::SymbolTable,
65    ) -> Result<TokenStream, Box<dyn std::error::Error>> {
66        // Regular if statement handling; the test is a condition position,
67        // so Python truthiness applies.
68        let test =
69            crate::condition_to_rust(&self.test, ctx.clone(), options.clone(), symbols.clone())?;
70        
71        let body_stmts: Result<Vec<_>, _> = self.body
72            .into_iter()
73            .map(|stmt| stmt.to_rust(ctx.clone(), options.clone(), symbols.clone()))
74            .collect();
75        let body_stmts = body_stmts?;
76        
77        if self.orelse.is_empty() {
78            Ok(quote! {
79                if #test {
80                    #(#body_stmts;)*
81                }
82            })
83        } else {
84            let else_stmts: Result<Vec<_>, _> = self.orelse
85                .into_iter()
86                .map(|stmt| stmt.to_rust(ctx.clone(), options.clone(), symbols.clone()))
87                .collect();
88            let else_stmts = else_stmts?;
89            
90            Ok(quote! {
91                if #test {
92                    #(#body_stmts;)*
93                } else {
94                    #(#else_stmts;)*
95                }
96            })
97        }
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::create_parse_test;
105
106    create_parse_test!(test_simple_if, "if x > 5:\n    print('big')", "if_test.py");
107    create_parse_test!(test_if_else, "if x > 5:\n    print('big')\nelse:\n    print('small')", "if_test.py");
108    create_parse_test!(test_if_elif, "if x > 10:\n    print('huge')\nelif x > 5:\n    print('big')\nelse:\n    print('small')", "if_test.py");
109}