aboutsummaryrefslogtreecommitdiff
path: root/crates/sloth_vm/src/lib.rs
blob: 77f7a256443bc862f6c35c9cedd772a6a8e4ce04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#![allow(dead_code)]
#![warn(
    clippy::wildcard_imports,
    clippy::string_add,
    clippy::string_add_assign,
    clippy::manual_ok_or,
    unused_lifetimes
)]

pub mod native;
pub mod obj;
pub mod vm;

pub use crate::vm::VM;

pub struct Chunk {
    constants: Vec<Data>,
    code: Vec<u8>,
}

pub struct Function {
    chunk: Chunk,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Data {
    Integer(i128),
    Float(f64),
    Bool(bool),
    Empty,
}

const STACK_SIZE: usize = 1024;

#[derive(Debug)]
pub struct Stack {
    pointer: usize,
    stack: [Data; STACK_SIZE],
}

impl Default for Stack {
    fn default() -> Self {
        Self {
            pointer: Default::default(),
            stack: [Data::Empty; STACK_SIZE],
        }
    }
}

impl Stack {
    #[inline(always)]
    pub fn push(&mut self, value: Data) {
        if self.pointer >= STACK_SIZE {
            panic!("Stack overflow");
        }

        self.stack[self.pointer] = value;
        self.pointer += 1;
    }

    #[inline(always)]
    pub fn pop(&mut self) -> Data {
        if self.pointer == 0 {
            panic!("Stack underflow");
        }

        self.pointer -= 1;
        self.stack[self.pointer]
    }

    #[inline(always)]
    pub fn pop2(&mut self) -> (Data, Data) {
        (self.pop(), self.pop())
    }
}

pub struct ObjectMap {}