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, SymbolTableScopes,
8 BinOps, FromPythonString, PyAttributeExtractor,
9};
10
11#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
13pub struct AugAssign {
14 pub target: ExprType,
16 pub op: BinOps,
18 pub value: ExprType,
20 pub lineno: Option<usize>,
22 pub col_offset: Option<usize>,
23 pub end_lineno: Option<usize>,
24 pub end_col_offset: Option<usize>,
25}
26
27impl<'a, 'py> FromPyObject<'a, 'py> for AugAssign {
28 type Error = pyo3::PyErr;
29 fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
30 let target = ob.extract_attr_with_context("target", "augmented assignment target")?;
32 let target: ExprType = target.extract()?;
33
34 let op = ob.extract_attr_with_context("op", "augmented assignment operator")?;
36 let op_type_str = op.extract_type_name("augmented assignment operator")?;
37 let op = BinOps::parse_or_unknown(&op_type_str);
38
39 let value = ob.extract_attr_with_context("value", "augmented assignment value")?;
41 let value: ExprType = value.extract()?;
42
43 Ok(AugAssign {
44 target,
45 op,
46 value,
47 lineno: ob.lineno(),
48 col_offset: ob.col_offset(),
49 end_lineno: ob.end_lineno(),
50 end_col_offset: ob.end_col_offset(),
51 })
52 }
53}
54
55impl Node for AugAssign {
56 fn lineno(&self) -> Option<usize> { self.lineno }
57 fn col_offset(&self) -> Option<usize> { self.col_offset }
58 fn end_lineno(&self) -> Option<usize> { self.end_lineno }
59 fn end_col_offset(&self) -> Option<usize> { self.end_col_offset }
60}
61
62impl CodeGen for AugAssign {
63 type Context = CodeGenContext;
64 type Options = PythonOptions;
65 type SymbolTable = SymbolTableScopes;
66
67 fn find_symbols(self, symbols: Self::SymbolTable) -> Self::SymbolTable {
68 self.value.find_symbols(symbols)
70 }
71
72 fn to_rust(
73 self,
74 ctx: Self::Context,
75 options: Self::Options,
76 symbols: Self::SymbolTable,
77 ) -> Result<TokenStream, Box<dyn std::error::Error>> {
78 if let ExprType::Subscript(sub) = &self.target {
83 let receiver = crate::subscript_receiver_place(
86 &sub.value,
87 ctx.clone(),
88 options.clone(),
89 symbols.clone(),
90 )?;
91 let index = match &sub.kind {
92 crate::SubscriptKind::Index(index) => index
93 .clone()
94 .to_rust(ctx.clone(), options.clone(), symbols.clone())?,
95 crate::SubscriptKind::Slice { .. } => {
96 return Err(
97 "augmented assignment to a slice (`x[a:b] += ...`) is not supported"
98 .to_string()
99 .into(),
100 )
101 }
102 };
103 let value = self.value.to_rust(ctx, options, symbols)?;
104 let elem = quote!(__rython_elem);
105 let combined = combine_op(&self.op, &elem, &value)?;
106 return Ok(quote! {
110 {
111 let __rython_recv = &mut (#receiver);
112 let __rython_idx = #index;
113 let __rython_elem = (__rython_recv).py_index(__rython_idx.clone())?;
114 (__rython_recv).py_set_index(__rython_idx, #combined)?;
115 }
116 });
117 }
118
119 let target = self.target.to_rust(ctx.clone(), options.clone(), symbols.clone())?;
120 let value = self.value.to_rust(ctx, options, symbols)?;
121
122 match self.op {
124 BinOps::Add => Ok(quote!(#target = (#target).py_add(&(#value)))),
127 BinOps::Sub => Ok(quote!(#target -= #value)),
128 BinOps::Mult => Ok(quote!(#target *= #value)),
129 BinOps::Div => Ok(quote!(#target = (#target) as f64 / (#value) as f64)),
134 BinOps::FloorDiv => Ok(quote!(#target = py_floordiv(#target, #value))),
138 BinOps::Mod => Ok(quote!(#target = py_mod(#target, #value))),
139 BinOps::BitAnd => Ok(quote!(#target &= #value)),
140 BinOps::BitOr => Ok(quote!(#target |= #value)),
141 BinOps::BitXor => Ok(quote!(#target ^= #value)),
142 BinOps::LShift => Ok(quote!(#target <<= #value)),
143 BinOps::RShift => Ok(quote!(#target >>= #value)),
144 BinOps::Pow => {
145 Ok(quote!(#target = py_pow(#target, #value)))
147 },
148 BinOps::MatMult => {
149 Err(format!("Matrix multiplication assignment not supported in Rust").into())
152 },
153 BinOps::Unknown => {
154 Err(format!("Unknown augmented assignment operator").into())
155 },
156 }
157 }
158}
159
160fn combine_op(
163 op: &BinOps,
164 elem: &TokenStream,
165 value: &TokenStream,
166) -> Result<TokenStream, Box<dyn std::error::Error>> {
167 Ok(match op {
168 BinOps::Add => quote!((#elem).py_add(&(#value))),
169 BinOps::Sub => quote!(#elem - #value),
170 BinOps::Mult => quote!(#elem * #value),
171 BinOps::Div => quote!((#elem) as f64 / (#value) as f64),
172 BinOps::FloorDiv => quote!(py_floordiv(#elem, #value)),
173 BinOps::Mod => quote!(py_mod(#elem, #value)),
174 BinOps::Pow => quote!(py_pow(#elem, #value)),
175 BinOps::BitAnd => quote!(#elem & #value),
176 BinOps::BitOr => quote!(#elem | #value),
177 BinOps::BitXor => quote!(#elem ^ #value),
178 BinOps::LShift => quote!(#elem << #value),
179 BinOps::RShift => quote!(#elem >> #value),
180 other => {
181 return Err(format!(
182 "augmented assignment operator {:?} not supported on subscripts",
183 other
184 )
185 .into())
186 }
187 })
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193 use crate::create_parse_test;
194
195 create_parse_test!(test_add_assign, "x += 1", "test.py");
196 create_parse_test!(test_sub_assign, "x -= 1", "test.py");
197 create_parse_test!(test_mul_assign, "x *= 2", "test.py");
198 create_parse_test!(test_div_assign, "x /= 3", "test.py");
199 create_parse_test!(test_mod_assign, "x %= 4", "test.py");
200 create_parse_test!(test_pow_assign, "x **= 2", "test.py");
201 create_parse_test!(test_bitand_assign, "x &= 5", "test.py");
202 create_parse_test!(test_bitor_assign, "x |= 6", "test.py");
203 create_parse_test!(test_bitxor_assign, "x ^= 7", "test.py");
204 create_parse_test!(test_lshift_assign, "x <<= 2", "test.py");
205 create_parse_test!(test_rshift_assign, "x >>= 3", "test.py");
206}