macha 0.1.0

A fast minimal embedded scripting language.
Documentation
use std::fmt::Display;
pub use ux::*;

#[derive(Debug, Clone)]
pub enum PrettyOp {
    Halt,
    Loadi { i: u8, val: u48 },
    LoadCi { i: u8, c: u48 },
    Pushi { val: u56 },
    Addi { r: u8, i: u8, k: u8 },
    Call { func: u32, args: u16, rets: u8 },
    JmpRaw { offset: i56 },
}

impl Display for PrettyOp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.to_string())
    }
}

impl PrettyOp {
    pub fn to_string(&self) -> String {
        match self {
            PrettyOp::Halt => "HALT".to_string(),
            PrettyOp::Loadi { i, val } => format!("LOADI R{}, {}", i, val),
            PrettyOp::LoadCi { i, c } => format!("LOADCI R{}, C{}", i, c),
            PrettyOp::Pushi { val } => format!("PUSHI {}", val),
            PrettyOp::Addi { r, i, k } => format!("ADDI R{}, R{}, R{}", r, i, k),
            PrettyOp::Call { func, args, rets } => {
                format!("CALL func_{:x}, {} args, {} rets", func, args, rets)
            }
            PrettyOp::JmpRaw { offset } => format!("JMPRAW {}", offset),
        }
    }

    pub fn into_slice(self) -> [u8; 8] {
        match self {
            PrettyOp::Halt => [Opcode::Halt as u8, 0, 0, 0, 0, 0, 0, 0],
            PrettyOp::Loadi { i, val } => {
                let val = u64::from(val).to_le_bytes();
                [
                    Opcode::Loadi as u8,
                    i,
                    val[0],
                    val[1],
                    val[2],
                    val[3],
                    val[4],
                    val[5],
                ]
            }
            PrettyOp::LoadCi { i, c } => {
                let c = u64::from(c).to_le_bytes();
                [Opcode::LoadCi as u8, i, c[0], c[1], c[2], c[3], c[4], c[5]]
            }
            PrettyOp::Pushi { val } => {
                let v = u64::from(val).to_le_bytes();
                [
                    Opcode::Pushi as u8,
                    v[0],
                    v[1],
                    v[2],
                    v[3],
                    v[4],
                    v[5],
                    v[6],
                ]
            }
            PrettyOp::Addi { r, i, k } => [Opcode::Addi as u8, r, i, k, 0, 0, 0, 0],
            PrettyOp::Call { func, args, rets } => {
                let func = func.to_le_bytes();
                let args = args.to_le_bytes();
                [
                    Opcode::Call as u8,
                    func[0],
                    func[1],
                    func[2],
                    func[3],
                    args[0],
                    args[1],
                    rets,
                ]
            }
            PrettyOp::JmpRaw { offset } => {
                let off = i64::from(offset).to_le_bytes();
                [
                    Opcode::JmpRaw as u8,
                    off[0],
                    off[1],
                    off[2],
                    off[3],
                    off[4],
                    off[5],
                    off[6],
                ]
            }
        }
    }
}

#[repr(u8)]
pub enum Opcode {
    Halt = 0x00,
    Loadi = 0x01,
    LoadCi = 0x02,
    Pushi = 0x10,
    Addi = 0x20,
    // IncRef = 0x30,
    // DecRef = 0x31,
    // MoveRef = 0x33,
    Call = 0x40,
    JmpRaw = 0x50,
}

pub struct Bytecode {
    data: Vec<u8>,
}

#[macro_export]
macro_rules! bytes_to_ux {
    ($ux:ty, $bytes:expr) => {{
        const SIZE: usize = <$ux>::BITS as usize / 8;
        assert!(
            $bytes.len() >= SIZE,
            "bytes slice too short for {}",
            stringify!($ux)
        );
        let val = $bytes
            .iter()
            .take(SIZE)
            .enumerate()
            .fold(0u64, |acc, (i, &b)| acc | ((b as u64) << (8 * i)));
        <$ux>::new(val)
    }};
}

#[macro_export]
macro_rules! bytes_to_ix {
    ($ix:ty, $bytes:expr) => {{
        const SIZE: usize = <$ix>::BITS as usize / 8;
        assert!(
            $bytes.len() >= SIZE,
            "bytes slice too short for {}",
            stringify!($ix)
        );
        let val = $bytes
            .iter()
            .take(SIZE)
            .enumerate()
            .fold(0i64, |acc, (i, &b)| acc | ((b as i64) << (8 * i)));
        <$ix>::new(val)
    }};
}

impl Bytecode {
    pub fn new() -> Self {
        Self { data: Vec::new() }
    }

    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            data: Vec::with_capacity(capacity),
        }
    }

    pub fn emit(&mut self, bytes: [u8; 8]) {
        self.data.extend_from_slice(&bytes);
    }

    pub fn into_bytes(self) -> Vec<u8> {
        self.data
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_prettyop_into_slice_halt() {
        let op = PrettyOp::Halt;
        assert_eq!(op.into_slice(), [0x00, 0, 0, 0, 0, 0, 0, 0]);
    }

    #[test]
    fn test_prettyop_into_slice_loadi_max() {
        let op = PrettyOp::Loadi {
            i: u8::MAX,
            val: u48::MAX,
        };
        let val = u64::from(u48::MAX).to_le_bytes();
        assert_eq!(
            op.into_slice(),
            [
                Opcode::Loadi as u8,
                u8::MAX,
                val[0],
                val[1],
                val[2],
                val[3],
                val[4],
                val[5]
            ]
        );
    }

    #[test]
    fn test_prettyop_into_slice_loadci_max() {
        let op = PrettyOp::LoadCi {
            i: u8::MAX,
            c: u48::MAX,
        };
        let c = u64::from(u48::MAX).to_le_bytes();
        assert_eq!(
            op.into_slice(),
            [
                Opcode::LoadCi as u8,
                u8::MAX,
                c[0],
                c[1],
                c[2],
                c[3],
                c[4],
                c[5]
            ]
        );
    }

    #[test]
    fn test_prettyop_into_slice_pushi_max() {
        let op = PrettyOp::Pushi { val: u56::MAX };
        let v = u64::from(u56::MAX).to_le_bytes();
        assert_eq!(
            op.into_slice(),
            [
                Opcode::Pushi as u8,
                v[0],
                v[1],
                v[2],
                v[3],
                v[4],
                v[5],
                v[6]
            ]
        );
    }

    #[test]
    fn test_prettyop_into_slice_addi_max() {
        let op = PrettyOp::Addi {
            r: u8::MAX,
            i: u8::MAX,
            k: u8::MAX,
        };
        assert_eq!(
            op.into_slice(),
            [Opcode::Addi as u8, u8::MAX, u8::MAX, u8::MAX, 0, 0, 0, 0]
        );
    }

    #[test]
    fn test_prettyop_into_slice_call_max() {
        let op = PrettyOp::Call {
            func: u32::MAX,
            args: u16::MAX,
            rets: u8::MAX,
        };
        let func = u32::MAX.to_le_bytes();
        let args = u16::MAX.to_le_bytes();
        assert_eq!(
            op.into_slice(),
            [
                Opcode::Call as u8,
                func[0],
                func[1],
                func[2],
                func[3],
                args[0],
                args[1],
                u8::MAX
            ]
        );
    }

    #[test]
    fn test_bytes_to_u56_zero() {
        let bytes = [0u8; 7];
        let val = bytes_to_ux!(u56, &bytes);
        assert_eq!(val, u56::new(0));
    }

    #[test]
    fn test_bytes_to_u56_max() {
        let bytes = [0xFFu8; 7];
        let val = bytes_to_ux!(u56, &bytes);
        assert_eq!(val, u56::new(0x00FFFFFFFFFFFFFF));
    }

    #[test]
    fn test_bytes_to_u56_middle() {
        let bytes = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07];
        let val = bytes_to_ux!(u56, &bytes);
        // Little endian: 0x07060504030201
        assert_eq!(val, u56::new(0x07060504030201));
    }

    #[test]
    #[should_panic]
    fn test_bytes_to_u56_too_short() {
        let bytes = [0x01, 0x02, 0x03];
        // Should panic due to out-of-bounds access
        bytes_to_ux!(u56, &bytes);
    }
}