python_ast/ast/tree/
arguments.rs

1//! The module defines Python-syntax arguments and maps them into Rust-syntax versions.
2use proc_macro2::TokenStream;
3use pyo3::{FromPyObject, PyAny, PyResult};
4use quote::quote;
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    CodeGen, CodeGenContext, Constant, Error, Node, PythonOptions, SymbolTableScopes,
9};
10
11/// An argument.
12#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
13pub enum Arg {
14    #[default]
15    Unknown,
16    //Constant(Constant),
17    Constant(Constant),
18}
19
20impl<'a> CodeGen for Arg {
21    type Context = CodeGenContext;
22    type Options = PythonOptions;
23    type SymbolTable = SymbolTableScopes;
24
25    fn to_rust(
26        self,
27        ctx: Self::Context,
28        options: Self::Options,
29        symbols: Self::SymbolTable,
30    ) -> std::result::Result<TokenStream, Box<dyn std::error::Error>> {
31        match self {
32            Self::Constant(c) => {
33                let v = c
34                    .to_rust(ctx, options, symbols)
35                    .expect(format!("Error generating constant argument.").as_str());
36                println!("{:?}", v);
37                Ok(quote!(#v))
38            }
39            _ => {
40                let error = Error::UnknownType("Unknown argument type".to_string());
41                Err(error.into())
42            }
43        }
44    }
45}
46
47impl<'a> FromPyObject<'a> for Arg {
48    fn extract(ob: &'a PyAny) -> PyResult<Self> {
49        let ob_type = ob.get_type().name().expect(
50            ob.error_message("<unknown>", "Could not extract argument type")
51                .as_str(),
52        );
53        // FIXME: Hangle the rest of argument types.
54        let r = match ob_type.as_ref() {
55            "Constant" => {
56                let err_msg = format!("parsing argument {:?} as a constant", ob);
57
58                Self::Constant(
59                    Constant::extract(ob)
60                        .expect(ob.error_message("<unknown>", err_msg.as_str()).as_str()),
61                )
62            }
63            _ => {
64                return Err(pyo3::exceptions::PyValueError::new_err(format!(
65                    "Argument {} is of unknown type {}",
66                    ob, ob_type
67                )))
68            }
69        };
70        Ok(r)
71    }
72}