macha 0.2.0

A fast minimal embedded scripting language.
Documentation
use std::{fmt::Display, ops::BitAnd};

#[derive(Debug)]
pub struct Frame {
    start: usize,
    end: usize,
    result_count: usize,
    args_count: usize,
    locals_start: usize,
}
#[derive(Debug)]
pub struct Stack {
    pub raw: Vec<u64>,
    frames: Vec<Frame>,
}

impl Display for Stack {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Stack {{");
        for (i, val) in self.raw.iter().enumerate() {
            writeln!(f, "    [{}]: i64 = {:?}, f64 = {:?}", i, val, f64::from_bits(*val));
        }
        writeln!(f, "}}");
        Ok(())
    }
}

impl Stack {
    pub fn new() -> Self {
        Self {
            raw: Vec::with_capacity(4096),
            frames: Vec::with_capacity(512),
        }
    }

    #[inline]
    pub fn get_slice(&self, frame: &Frame) -> &[u64] {
        &self.raw[frame.start + frame.result_count + frame.args_count..frame.end]
    }

    #[inline]
    pub fn get_results_slice(&self, frame: &Frame) -> &[u64] {
        &self.raw[frame.start..frame.start + frame.result_count]
    }

    #[inline]
    pub fn get_args_slice(&self, frame: &Frame) -> &[u64] {
        &self.raw
            [frame.start + frame.result_count..frame.start + frame.result_count + frame.args_count]
    }

    #[inline]
    pub fn push_local_uint(&mut self, value: u64) {
        self.frames
            .last_mut()
            .expect("No frame to push local to")
            .end += 1;
        self.raw.push(value);
    }

    #[inline]
    pub fn push_local_int(&mut self, value: i64) {
        self.frames
            .last_mut()
            .expect("No frame to push local to")
            .end += 1;
        self.raw.push(value.cast_unsigned());
    }

    #[inline]
    pub fn push_local_float(&mut self, value: f64) {
        self.frames
            .last_mut()
            .expect("No frame to push local to")
            .end += 1;
        self.raw.push(value.to_bits());
    }

    pub fn push_frame(&mut self, result_count: usize, args_count: usize) {
        // PERF: .map_or is unlikely
        let mut start = self.frames.last().map_or(0, |f| f.end);
        // PERF: unlikely
        if start == 0 && (args_count > 0 || result_count > 0) {
            panic!(
                "Cannot push a frame with arguments or results when there are no previous frames."
            );
        }
        // these already exist so we assume ownership
        start -= result_count + args_count;
        // and reduce the size of the previous frame
        // PERF: likely
        if let Some(prev_frame) = self.frames.last_mut() {
            prev_frame.end = start;
        }
        self.frames.push(Frame {
            start,
            end: start + result_count + args_count,
            result_count,
            args_count,
            locals_start: start + result_count + args_count,
        });
    }

    pub fn push_frame_with_locals(
        &mut self,
        result_count: usize,
        args_count: usize,
        local_count: usize,
    ) {
        self.raw.reserve(local_count);
        self.push_frame(result_count, args_count);
        for _ in 0..local_count {
            self.raw.push(0);
        }
        let frame = self.frames.last_mut().expect("No frame to push locals to");
        frame.end += local_count;
    }

    pub fn push_frame_with_locals_init(
        &mut self,
        result_count: usize,
        args_count: usize,
        locals: &[u64],
    ) {
        self.raw.reserve(locals.len());
        self.push_frame(result_count, args_count);
        for &local in locals {
            self.raw.push(local);
        }
        let frame = self.frames.last_mut().expect("No frame to push locals to");
        frame.end += locals.len();
    }

    #[inline]
    pub fn get_local_uint(&self, i: usize) -> u64 {
        let frame = self.frames.last().expect("No frame to get local from");
        self.raw[frame.locals_start + i]
    }

    #[inline]
    pub fn get_local_int(&self, i: usize) -> i64 {
        let frame = self.frames.last().expect("No frame to get local from");
        self.raw[frame.locals_start + i].cast_signed()
    }

    #[inline]
    pub fn get_local_float(&self, i: usize) -> f64 {
        let frame = self.frames.last().expect("No frame to get local from");
        f64::from_bits(self.raw[frame.locals_start + i])
    }

    #[inline]
    pub fn set_local_uint(&mut self, r: usize, val: u64) {
        let frame = self.frames.last().expect("No frame to set local from");
        self.raw[frame.locals_start + r] = val;
    }

    #[inline]
    pub fn set_local_int(&mut self, r: usize, val: i64) {
        let frame = self.frames.last().expect("No frame to set local from");
        self.raw[frame.locals_start + r] = val.cast_unsigned();
    }

    #[inline]
    pub fn set_local_float(&mut self, r: usize, val: f64) {
        let frame = self.frames.last().expect("No frame to set local from");
        self.raw[frame.locals_start + r] = val.to_bits();
    }

    #[inline]
    pub fn has_frames(&self) -> bool {
        !self.frames.is_empty()
    }
}

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

    #[test]
    fn test_stack() {
        let mut stack = Stack::new();
        stack.push_frame(0, 0);
        stack.push_local_uint(1);
        stack.push_local_uint(2);
        stack.push_local_uint(3);
        stack.push_local_uint(0); // space for result
        stack.push_local_uint(5); // arg 1
        stack.push_local_uint(6); // arg 2

        stack.push_frame(1, 2);
        let frame = stack.frames.last().unwrap();
        assert_eq!(frame.start, 3);
        assert_eq!(frame.end, 6);
        assert_eq!(frame.result_count, 1);
        assert_eq!(frame.args_count, 2);
        assert_eq!(stack.get_args_slice(frame), &[5, 6]);
        assert_eq!(stack.get_results_slice(frame), &[0]);
        assert_eq!(stack.get_slice(frame), &[]);
    }

    #[test]
    fn test_stack_with_locals_init() {
        let mut stack = Stack::new();
        stack.push_frame_with_locals_init(0, 0, &[1, 2, 3, 0, 5, 6]);
        stack.push_frame_with_locals_init(1, 2, &[7, 8, 9]);
        let frame = stack.frames.last().unwrap();
        assert_eq!(frame.start, 3);
        assert_eq!(frame.end, 9);
        assert_eq!(frame.result_count, 1);
        assert_eq!(frame.args_count, 2);
        assert_eq!(stack.get_args_slice(frame), &[5, 6]);
        assert_eq!(stack.get_results_slice(frame), &[0]);
        assert_eq!(stack.get_slice(frame), &[7, 8, 9]);
    }
}