weirdnet-code-spaces 0.1.0

Weirdnet code spaces: math, Polars, Rust and typed Python sources compiled into plugins against the weirdnet-plugin SDK, content-addressed builds, ABI-checked loading, trust hashes and space line-ups, under an application profile.
Documentation
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 {
            // `~x` is Rust's bitwise complement, but `not x` is a
            // TRUTHINESS test: `not 5` is False, where `!5i64` is -6.
            Ops::Invert => Ok(quote!(!#operand)),
            Ops::Not => Ok(quote!(!(#operand).is_truthy())),
            // Rust has no unary plus; Python's `+x` is the identity for
            // numbers, so emit the operand alone (parenthesized).
            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);
        //tracing::info!("{}", result);

        let code = result.to_rust(CodeGenContext::Module("test".to_string()), options, SymbolTableScopes::new()).unwrap();
        tracing::info!("module: {:?}", code);
    }
}