python_ast/ast/tree/
list.rs1use proc_macro2::TokenStream;
2use pyo3::{Bound, FromPyObject, PyAny, types::PyAnyMethods};
3use quote::quote;
4
5use crate::{dump, CodeGen, CodeGenContext, PythonOptions, SymbolTableScopes};
6
7pub type ListContents = crate::pytypes::List<dyn CodeGen>;
11
12#[derive(Clone, Default)]
13pub struct List<'a> {
14 pub elts: Vec<Bound<'a, PyAny>>,
15 pub ctx: Option<String>,
16}
17
18impl std::fmt::Debug for List<'_> {
19 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 f.debug_struct("List")
21 .field("elts", &format!("Vec<Bound<PyAny>> (len: {})", self.elts.len()))
22 .field("ctx", &self.ctx)
23 .finish()
24 }
25}
26
27impl<'a> FromPyObject<'a> for List<'a> {
28 fn extract_bound(ob: &Bound<'a, PyAny>) -> pyo3::PyResult<Self> {
29 let elts: Vec<Bound<'a, PyAny>> = ob.getattr("elts")?.extract()?;
30 let ctx: Option<String> = ob.getattr("ctx").ok().and_then(|v| v.extract().ok());
31 Ok(List { elts, ctx })
32 }
33}
34
35impl<'a> CodeGen for List<'a> {
36 type Context = CodeGenContext;
37 type Options = PythonOptions;
38 type SymbolTable = SymbolTableScopes;
39
40 fn to_rust(
41 self,
42 _ctx: Self::Context,
43 _options: Self::Options,
44 _symbols: Self::SymbolTable,
45 ) -> Result<TokenStream, Box<dyn std::error::Error>> {
46 let ts = TokenStream::new();
47 log::debug!("================self:{:#?}", self);
48 for elt in self.elts {
49 log::debug!("elt: {}", dump(&elt, None)?);
50 }
52 Ok(quote!(vec![#ts]))
53 }
54}
55
56#[cfg(test)]
59mod tests {
60 use crate::ExprType;
61 use crate::StatementType;
62 use std::panic;
63 use test_log::test;
64
65 #[test]
66 fn parse_list() {
67 let module = crate::parse("[1, 2, 3]", "nothing.py").unwrap();
68 let statement = module.raw.body[0].statement.clone();
69 match statement {
70 StatementType::Expr(e) => match e.value {
71 ExprType::List(list) => {
72 log::debug!("{:#?}", list);
73 assert_eq!(list.len(), 3);
74 }
75 _ => panic!("Could not find inner expression"),
76 },
77 _ => panic!("Could not find outer expression."),
78 }
79 }
80}