use proc_macro2::TokenStream;
use quote::quote;
use serde::{Deserialize, Serialize};
use crate::python_ast::{BoolOpNotYetImplemented, CodeGen, CodeGenContext, ExprType, PythonOptions, SymbolTableScopes, dump, err_from};
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum BoolOps {
And,
Or,
Unknown,
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct BoolOp {
pub op: BoolOps,
pub values: Vec<ExprType>,
}
impl<'a> CodeGen for BoolOp {
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 mut rendered = Vec::new();
for value in self.values.clone() {
rendered.push(value.to_rust(ctx.clone(), options.clone(), symbols.clone())?);
}
match self.op {
BoolOps::Or => {
if let Some(last) = rendered.last() {
if last.to_string().trim() == "None" && rendered.len() == 2 {
let first = &rendered[0];
return Ok(quote!({
let __rython_or = #first;
if (__rython_or).is_truthy() { Some(__rython_or) } else { None }
}));
}
}
Ok(quote!(#((#rendered))||*))
}
BoolOps::And => Ok(quote!(#((#rendered))&&*)),
_ => Err(err_from(BoolOpNotYetImplemented(self)).into()),
}
}
}
#[cfg(python_ast_upstream_tests)]
mod tests {
use super::*;
#[test]
fn test_and() {
let options = PythonOptions::default();
let result = crate::python_ast::parse("1 and 2", "test_case.py").unwrap();
tracing::info!("Python tree: {:?}", result);
let code = result.to_rust(CodeGenContext::Module("test_case".to_string()), options, SymbolTableScopes::new()).unwrap();
tracing::info!("module: {:?}", code);
}
#[test]
fn test_or() {
let options = PythonOptions::default();
let result = crate::python_ast::parse("1 or 2", "test_case.py").unwrap();
tracing::info!("Python tree: {:?}", result);
let code = result.to_rust(CodeGenContext::Module("test_case".to_string()), options, SymbolTableScopes::new()).unwrap();
tracing::info!("module: {:?}", code);
}
}