python_ast/ast/tree/
lambda.rs1use proc_macro2::TokenStream;
2use pyo3::{Bound, FromPyObject, PyAny, PyResult, types::PyAnyMethods};
3use quote::quote;
4use serde::{Deserialize, Serialize};
5
6use crate::{
7 CodeGen, CodeGenContext, ExprType, PythonOptions, SymbolTableScopes,
8 Node, impl_node_with_positions, ParameterList, PyAttributeExtractor
9};
10
11#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
12pub struct Lambda {
13 pub args: ParameterList,
14 pub body: Box<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> FromPyObject<'a> for Lambda {
22 fn extract_bound(ob: &Bound<'a, PyAny>) -> PyResult<Self> {
23 let args = ob.extract_attr_with_context("args", "lambda arguments")?;
24 let body = ob.extract_attr_with_context("body", "lambda body")?;
25
26 let args = args.extract().expect("getting lambda arguments");
27 let body = body.extract().expect("getting lambda body");
28
29 Ok(Lambda {
30 args,
31 body: Box::new(body),
32 lineno: ob.lineno(),
33 col_offset: ob.col_offset(),
34 end_lineno: ob.end_lineno(),
35 end_col_offset: ob.end_col_offset(),
36 })
37 }
38}
39
40impl_node_with_positions!(Lambda { lineno, col_offset, end_lineno, end_col_offset });
41
42impl CodeGen for Lambda {
43 type Context = CodeGenContext;
44 type Options = PythonOptions;
45 type SymbolTable = SymbolTableScopes;
46
47 fn to_rust(
48 self,
49 ctx: Self::Context,
50 options: Self::Options,
51 symbols: Self::SymbolTable,
52 ) -> Result<TokenStream, Box<dyn std::error::Error>> {
53 let args = self.args.to_rust(ctx.clone(), options.clone(), symbols.clone())?;
54 let body = self.body.to_rust(ctx, options, symbols)?;
55
56 Ok(quote! {
57 |#args| #body
58 })
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65 use crate::create_parse_test;
66
67 create_parse_test!(test_simple_lambda, "lambda x: x + 1", "lambda_test.py");
68 create_parse_test!(test_lambda_with_args, "lambda x, y: x * y", "lambda_test.py");
69 create_parse_test!(test_lambda_no_args, "lambda: 42", "lambda_test.py");
70}