Skip to main content

python_ast/ast/tree/
while_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 While {
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 While {
25    type Error = pyo3::PyErr;
26    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
27        let test = ob.extract_attr_with_context("test", "while test condition")?;
28        let test = test
29            .extract()
30            .map_err(|e| crate::extraction_failure("while condition", &ob, e))?;
31        
32        let body: Vec<Statement> = extract_list(&ob, "body", "while body statements")?;
33        let orelse: Vec<Statement> = extract_list(&ob, "orelse", "while else statements")?;
34        
35        Ok(While {
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!(While { lineno, col_offset, end_lineno, end_col_offset });
48
49impl CodeGen for While {
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        let test =
67            crate::condition_to_rust(&self.test, ctx.clone(), options.clone(), symbols.clone())?;
68
69        let has_else = !self.orelse.is_empty();
70        // Break-tracking is only needed when the else clause could be skipped
71        // by a break belonging to this loop; otherwise the flag would be
72        // declared mutable but never written.
73        let tracks_break = has_else && crate::loop_body_has_direct_break(&self.body);
74        // Body statements compile inside a Loop context so `break` can honor
75        // the else clause; the test and else clause are outside the loop.
76        let body_ctx = crate::CodeGenContext::Loop {
77            has_else: tracks_break,
78            parent: Box::new(ctx.clone()),
79        };
80        let body_stmts: Result<Vec<_>, _> = self.body
81            .into_iter()
82            .map(|stmt| stmt.to_rust(body_ctx.clone(), options.clone(), symbols.clone()))
83            .collect();
84        let body_stmts = body_stmts?;
85
86        if !has_else {
87            Ok(quote! {
88                while #test {
89                    #(#body_stmts;)*
90                }
91            })
92        } else {
93            // Python's while/else: the else clause runs iff the loop exited
94            // because the condition became false, not via `break`.
95            let else_stmts: Result<Vec<_>, _> = self.orelse
96                .into_iter()
97                .map(|stmt| stmt.to_rust(ctx.clone(), options.clone(), symbols.clone()))
98                .collect();
99            let else_stmts = else_stmts?;
100
101            if tracks_break {
102                Ok(quote! {
103                    {
104                        let mut __rython_broke = false;
105                        while #test {
106                            #(#body_stmts;)*
107                        }
108                        if !__rython_broke {
109                            #(#else_stmts;)*
110                        }
111                    }
112                })
113            } else {
114                // No break can skip the else clause; run it unconditionally.
115                Ok(quote! {
116                    {
117                        while #test {
118                            #(#body_stmts;)*
119                        }
120                        #(#else_stmts;)*
121                    }
122                })
123            }
124        }
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131    use crate::create_parse_test;
132
133    create_parse_test!(test_simple_while, "while x > 0:\n    x -= 1", "while_test.py");
134    create_parse_test!(test_while_else, "while x > 0:\n    x -= 1\nelse:\n    print('done')", "while_test.py");
135    create_parse_test!(test_while_true, "while True:\n    break", "while_test.py");
136}