use proc_macro2::TokenStream;
use quote::quote;
use serde::{Deserialize, Serialize};
use crate::python_ast::{BinOps, CodeGen, CodeGenContext, ExprType, FromPythonString, Node, PythonOptions, SymbolTableScopes};
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct AugAssign {
pub target: ExprType,
pub op: BinOps,
pub value: ExprType,
pub lineno: Option<usize>,
pub col_offset: Option<usize>,
pub end_lineno: Option<usize>,
pub end_col_offset: Option<usize>,
}
impl Node for AugAssign {
fn lineno(&self) -> Option<usize> {
self.lineno
}
fn col_offset(&self) -> Option<usize> {
self.col_offset
}
fn end_lineno(&self) -> Option<usize> {
self.end_lineno
}
fn end_col_offset(&self) -> Option<usize> {
self.end_col_offset
}
}
impl CodeGen for AugAssign {
type Context = CodeGenContext;
type Options = PythonOptions;
type SymbolTable = SymbolTableScopes;
fn find_symbols(self, symbols: Self::SymbolTable) -> Self::SymbolTable {
self.value.find_symbols(symbols)
}
fn to_rust(self, ctx: Self::Context, options: Self::Options, symbols: Self::SymbolTable) -> Result<TokenStream, Box<dyn std::error::Error>> {
if let ExprType::Subscript(sub) = &self.target {
let receiver = crate::python_ast::subscript_receiver_place(&sub.value, ctx.clone(), options.clone(), symbols.clone())?;
let index = match &sub.kind {
crate::python_ast::SubscriptKind::Index(index) => index.clone().to_rust(ctx.clone(), options.clone(), symbols.clone())?,
crate::python_ast::SubscriptKind::Slice { .. } => {
return Err("augmented assignment to a slice (`x[a:b] += ...`) is not supported".to_string().into());
}
};
let value = self.value.to_rust(ctx, options, symbols)?;
let elem = quote!(__rython_elem);
let combined = combine_op(&self.op, &elem, &value)?;
return Ok(quote! {
{
let __rython_recv = &mut (#receiver);
let __rython_idx = #index;
let __rython_elem = (__rython_recv).py_index(__rython_idx.clone())?;
(__rython_recv).py_set_index(__rython_idx, #combined)?;
}
});
}
let target = self.target.to_rust(ctx.clone(), options.clone(), symbols.clone())?;
let value = self.value.to_rust(ctx, options, symbols)?;
match self.op {
BinOps::Add => Ok(quote!(#target = (#target).py_add(&(#value)))),
BinOps::Sub => Ok(quote!(#target -= #value)),
BinOps::Mult => Ok(quote!(#target *= #value)),
BinOps::Div => Ok(quote!(#target = (#target) as f64 / (#value) as f64)),
BinOps::FloorDiv => Ok(quote!(#target = py_floordiv(#target, #value))),
BinOps::Mod => Ok(quote!(#target = py_mod(#target, #value))),
BinOps::BitAnd => Ok(quote!(#target &= #value)),
BinOps::BitOr => Ok(quote!(#target |= #value)),
BinOps::BitXor => Ok(quote!(#target ^= #value)),
BinOps::LShift => Ok(quote!(#target <<= #value)),
BinOps::RShift => Ok(quote!(#target >>= #value)),
BinOps::Pow => {
Ok(quote!(#target = py_pow(#target, #value)))
}
BinOps::MatMult => {
Err(format!("Matrix multiplication assignment not supported in Rust").into())
}
BinOps::Unknown => Err(format!("Unknown augmented assignment operator").into()),
}
}
}
fn combine_op(op: &BinOps, elem: &TokenStream, value: &TokenStream) -> Result<TokenStream, Box<dyn std::error::Error>> {
Ok(match op {
BinOps::Add => quote!((#elem).py_add(&(#value))),
BinOps::Sub => quote!(#elem - #value),
BinOps::Mult => quote!(#elem * #value),
BinOps::Div => quote!((#elem) as f64 / (#value) as f64),
BinOps::FloorDiv => quote!(py_floordiv(#elem, #value)),
BinOps::Mod => quote!(py_mod(#elem, #value)),
BinOps::Pow => quote!(py_pow(#elem, #value)),
BinOps::BitAnd => quote!(#elem & #value),
BinOps::BitOr => quote!(#elem | #value),
BinOps::BitXor => quote!(#elem ^ #value),
BinOps::LShift => quote!(#elem << #value),
BinOps::RShift => quote!(#elem >> #value),
other => return Err(format!("augmented assignment operator {:?} not supported on subscripts", other).into()),
})
}
#[cfg(python_ast_upstream_tests)]
mod tests {
use super::*;
use crate::python_ast::create_parse_test;
create_parse_test!(test_add_assign, "x += 1", "test.py");
create_parse_test!(test_sub_assign, "x -= 1", "test.py");
create_parse_test!(test_mul_assign, "x *= 2", "test.py");
create_parse_test!(test_div_assign, "x /= 3", "test.py");
create_parse_test!(test_mod_assign, "x %= 4", "test.py");
create_parse_test!(test_pow_assign, "x **= 2", "test.py");
create_parse_test!(test_bitand_assign, "x &= 5", "test.py");
create_parse_test!(test_bitor_assign, "x |= 6", "test.py");
create_parse_test!(test_bitxor_assign, "x ^= 7", "test.py");
create_parse_test!(test_lshift_assign, "x <<= 2", "test.py");
create_parse_test!(test_rshift_assign, "x >>= 3", "test.py");
}