Skip to main content

python_ast/ast/tree/
async_with.rs

1use proc_macro2::TokenStream;
2use pyo3::{Borrowed, FromPyObject, PyAny, PyResult, prelude::PyAnyMethods};
3use quote::quote;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    CodeGen, CodeGenContext, ExprType, Node, PythonOptions, Statement, SymbolTableScopes,
8    extract_list,
9};
10
11/// Async with statement (async with context as var: ...)
12#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
13pub struct AsyncWith {
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
25/// A with item (context_expr as optional_vars)
26#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
27pub struct WithItem {
28    /// The context expression (the thing being entered)
29    pub context_expr: ExprType,
30    /// Optional variable to bind the context to
31    pub optional_vars: Option<ExprType>,
32}
33
34impl<'a, 'py> FromPyObject<'a, 'py> for AsyncWith {
35    type Error = pyo3::PyErr;
36    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
37        // Extract items (list of withitem objects)
38        let items: Vec<WithItem> = extract_list(&ob, "items", "async with items")?;
39        
40        // Extract body
41        let body: Vec<Statement> = extract_list(&ob, "body", "async with body")?;
42        
43        Ok(AsyncWith {
44            items,
45            body,
46            lineno: ob.lineno(),
47            col_offset: ob.col_offset(),
48            end_lineno: ob.end_lineno(),
49            end_col_offset: ob.end_col_offset(),
50        })
51    }
52}
53
54impl<'a, 'py> FromPyObject<'a, 'py> for WithItem {
55    type Error = pyo3::PyErr;
56    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
57        // Extract context_expr
58        let context_expr: ExprType = ob.getattr("context_expr")?.extract()?;
59        
60        // Extract optional_vars (optional)
61        let optional_vars: Option<ExprType> = if let Ok(vars_attr) = ob.getattr("optional_vars") {
62            if vars_attr.is_none() {
63                None
64            } else {
65                Some(vars_attr.extract()?)
66            }
67        } else {
68            None
69        };
70        
71        Ok(WithItem {
72            context_expr,
73            optional_vars,
74        })
75    }
76}
77
78impl Node for AsyncWith {
79    fn lineno(&self) -> Option<usize> { self.lineno }
80    fn col_offset(&self) -> Option<usize> { self.col_offset }
81    fn end_lineno(&self) -> Option<usize> { self.end_lineno }
82    fn end_col_offset(&self) -> Option<usize> { self.end_col_offset }
83}
84
85impl CodeGen for AsyncWith {
86    type Context = CodeGenContext;
87    type Options = PythonOptions;
88    type SymbolTable = SymbolTableScopes;
89
90    fn find_symbols(self, symbols: Self::SymbolTable) -> Self::SymbolTable {
91        // Process items and body
92        let symbols = self.items.into_iter().fold(symbols, |acc, item| {
93            let acc = item.context_expr.find_symbols(acc);
94            if let Some(vars) = item.optional_vars {
95                vars.find_symbols(acc)
96            } else {
97                acc
98            }
99        });
100        self.body.into_iter().fold(symbols, |acc, stmt| stmt.find_symbols(acc))
101    }
102
103    fn to_rust(
104        self,
105        ctx: Self::Context,
106        options: Self::Options,
107        symbols: Self::SymbolTable,
108    ) -> Result<TokenStream, Box<dyn std::error::Error>> {
109        // Evaluate each context manager and bind its `as` target, mirroring
110        // the synchronous `with` lowering (async __aenter__/__aexit__
111        // protocol semantics are not modeled yet).
112        let mut item_tokens = Vec::new();
113        for item in self.items {
114            let context_expr =
115                item.context_expr
116                    .to_rust(ctx.clone(), options.clone(), symbols.clone())?;
117            match item.optional_vars {
118                Some(vars) => {
119                    let target = vars.to_rust(ctx.clone(), options.clone(), symbols.clone())?;
120                    item_tokens.push(quote! { let mut #target = #context_expr; });
121                }
122                None => {
123                    item_tokens.push(quote! { let _ = #context_expr; });
124                }
125            }
126        }
127
128        let body_tokens: Result<Vec<TokenStream>, Box<dyn std::error::Error>> = self.body.into_iter()
129            .map(|stmt| stmt.to_rust(ctx.clone(), options.clone(), symbols.clone()))
130            .collect();
131        let body_tokens = body_tokens?;
132
133        Ok(quote! {
134            {
135                #(#item_tokens)*
136                #(#body_tokens;)*
137            }
138        })
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    // Tests would go here - currently commented out as they need full AST infrastructure
145    // create_parse_test!(test_simple_async_with, "async with context:\n    pass", "test.py");
146}