Skip to main content

python_ast/ast/tree/
dict.rs

1use proc_macro2::TokenStream;
2use pyo3::{Borrowed, FromPyObject, PyAny, PyResult};
3use quote::quote;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7    CodeGen, CodeGenContext, ExprType, PythonOptions, SymbolTableScopes,
8    Node, impl_node_with_positions, extract_list
9};
10
11#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
12pub struct Dict {
13    pub keys: Vec<Option<ExprType>>,
14    pub values: Vec<ExprType>,
15    pub lineno: Option<usize>,
16    pub col_offset: Option<usize>,
17    pub end_lineno: Option<usize>,
18    pub end_col_offset: Option<usize>,
19}
20
21impl<'a, 'py> FromPyObject<'a, 'py> for Dict {
22    type Error = pyo3::PyErr;
23    fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
24        let keys: Vec<Option<ExprType>> = extract_list(&ob, "keys", "dictionary keys")?;
25        let values: Vec<ExprType> = extract_list(&ob, "values", "dictionary values")?;
26        
27        Ok(Dict {
28            keys,
29            values,
30            lineno: ob.lineno(),
31            col_offset: ob.col_offset(),
32            end_lineno: ob.end_lineno(),
33            end_col_offset: ob.end_col_offset(),
34        })
35    }
36}
37
38impl_node_with_positions!(Dict { lineno, col_offset, end_lineno, end_col_offset });
39
40impl CodeGen for Dict {
41    type Context = CodeGenContext;
42    type Options = PythonOptions;
43    type SymbolTable = SymbolTableScopes;
44
45    fn to_rust(
46        self,
47        ctx: Self::Context,
48        options: Self::Options,
49        symbols: Self::SymbolTable,
50    ) -> Result<TokenStream, Box<dyn std::error::Error>> {
51        let mut pairs = Vec::new();
52        
53        for (key, value) in self.keys.iter().zip(self.values.iter()) {
54            match key {
55                Some(k) => {
56                    let key_tokens = k.clone().to_rust(ctx.clone(), options.clone(), symbols.clone())?;
57                    let value_tokens = value.clone().to_rust(ctx.clone(), options.clone(), symbols.clone())?;
58                    pairs.push(quote! { (#key_tokens, #value_tokens) });
59                }
60                None => {
61                    // `{**other}` has no direct HashMap-literal equivalent;
62                    // fail the conversion rather than emitting invalid Rust.
63                    return Err("dictionary unpacking (`{**other}`) is not yet supported \
64                                in dict literals"
65                        .to_string()
66                        .into());
67                }
68            }
69        }
70        
71        // PyDict (an insertion-ordered map) rather than HashMap: Python
72        // dicts preserve insertion order, and keys()/items()/iteration
73        // must match.
74        Ok(quote! {
75            PyDict::from([#(#pairs),*])
76        })
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83    use crate::create_parse_test;
84
85    create_parse_test!(test_empty_dict, "{}", "dict_test.py");
86    create_parse_test!(test_simple_dict, "{'a': 1, 'b': 2}", "dict_test.py");
87    create_parse_test!(test_dict_with_variables, "{x: y, z: w}", "dict_test.py");
88}