use proc_macro2::TokenStream;
use quote::quote;
use crate::python_ast::{CodeGen, CodeGenContext, ExprType, PythonOptions, SymbolTableScopes, UnaryOpNotYetImplemented, dump, err_from};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum Ops {
Invert,
Not,
UAdd,
USub,
Unknown,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct UnaryOp {
pub op: Ops,
pub operand: Box<ExprType>,
}
impl CodeGen for UnaryOp {
type Context = CodeGenContext;
type Options = PythonOptions;
type SymbolTable = SymbolTableScopes;
fn to_rust(self, ctx: Self::Context, options: Self::Options, symbols: Self::SymbolTable) -> Result<TokenStream, Box<dyn std::error::Error>> {
let operand = self.operand.clone().to_rust(ctx, options, symbols)?;
match self.op {
Ops::Invert => Ok(quote!(!#operand)),
Ops::Not => Ok(quote!(!(#operand).is_truthy())),
Ops::UAdd => Ok(quote!((#operand))),
Ops::USub => Ok(quote!(-#operand)),
_ => Err(err_from(UnaryOpNotYetImplemented(self)).into()),
}
}
}
#[cfg(python_ast_upstream_tests)]
mod tests {
use super::*;
#[test]
fn test_not() {
let options = PythonOptions::default();
let result = crate::python_ast::parse("not True", "test").unwrap();
tracing::info!("Python tree: {:?}", result);
let code = result.to_rust(CodeGenContext::Module("test".to_string()), options, SymbolTableScopes::new()).unwrap();
tracing::info!("module: {:?}", code);
}
}