Skip to main content

python_ast/ast/tree/
with_stmt.rs

1use proc_macro2::TokenStream;
2use pyo3::{Borrowed, FromPyObject, PyAny, PyResult};
3use quote::quote;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    CodeGen, CodeGenContext, Node, PythonOptions, Statement, SymbolTableScopes,
8    extract_list, WithItem,
9};
10
11/// Regular with statement (with context as var: ...)
12#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
13pub struct With {
14    /// The with items (context managers)
15    pub items: Vec<WithItem>,
16    /// The body of the with statement
17    pub body: Vec<Statement>,
18    /// Position information
19    pub lineno: Option<usize>,
20    pub col_offset: Option<usize>,
21    pub end_lineno: Option<usize>,
22    pub end_col_offset: Option<usize>,
23}
24
25impl<'a, 'py> FromPyObject<'a, 'py> for With {
26    type Error = pyo3::PyErr;
27    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
28        // Extract items (list of withitem objects)
29        let items: Vec<WithItem> = extract_list(&ob, "items", "with items")?;
30        
31        // Extract body
32        let body: Vec<Statement> = extract_list(&ob, "body", "with body")?;
33        
34        Ok(With {
35            items,
36            body,
37            lineno: ob.lineno(),
38            col_offset: ob.col_offset(),
39            end_lineno: ob.end_lineno(),
40            end_col_offset: ob.end_col_offset(),
41        })
42    }
43}
44
45impl Node for With {
46    fn lineno(&self) -> Option<usize> { self.lineno }
47    fn col_offset(&self) -> Option<usize> { self.col_offset }
48    fn end_lineno(&self) -> Option<usize> { self.end_lineno }
49    fn end_col_offset(&self) -> Option<usize> { self.end_col_offset }
50}
51
52impl CodeGen for With {
53    type Context = CodeGenContext;
54    type Options = PythonOptions;
55    type SymbolTable = SymbolTableScopes;
56
57    fn find_symbols(self, symbols: Self::SymbolTable) -> Self::SymbolTable {
58        // Process items and body
59        let symbols = self.items.into_iter().fold(symbols, |acc, item| {
60            let acc = item.context_expr.find_symbols(acc);
61            if let Some(vars) = item.optional_vars {
62                vars.find_symbols(acc)
63            } else {
64                acc
65            }
66        });
67        self.body.into_iter().fold(symbols, |acc, stmt| stmt.find_symbols(acc))
68    }
69
70    fn to_rust(
71        self,
72        ctx: Self::Context,
73        options: Self::Options,
74        symbols: Self::SymbolTable,
75    ) -> Result<TokenStream, Box<dyn std::error::Error>> {
76        // Evaluate each context manager and bind its `as` target (or a
77        // throwaway binding when there is none, so side effects still run).
78        // __enter__/__exit__ protocol semantics are not modeled yet, but the
79        // expression is no longer dropped and the target is in scope; Rust's
80        // Drop at end of block approximates __exit__ cleanup.
81        let mut item_tokens = Vec::new();
82        for item in self.items {
83            let context_expr =
84                item.context_expr
85                    .to_rust(ctx.clone(), options.clone(), symbols.clone())?;
86            match item.optional_vars {
87                Some(vars) => {
88                    let target = vars.to_rust(ctx.clone(), options.clone(), symbols.clone())?;
89                    item_tokens.push(quote! { let mut #target = #context_expr; });
90                }
91                None => {
92                    item_tokens.push(quote! { let _ = #context_expr; });
93                }
94            }
95        }
96
97        let body_tokens: Result<Vec<TokenStream>, Box<dyn std::error::Error>> = self.body.into_iter()
98            .map(|stmt| stmt.to_rust(ctx.clone(), options.clone(), symbols.clone()))
99            .collect();
100        let body_tokens = body_tokens?;
101
102        Ok(quote! {
103            {
104                #(#item_tokens)*
105                #(#body_tokens;)*
106            }
107        })
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    // Tests would go here - currently commented out as they need full AST infrastructure
114    // create_parse_test!(test_simple_with, "with context:\n    pass", "test.py");
115}