Skip to content

Commit

Permalink
feat: setup runtime vm
Browse files Browse the repository at this point in the history
  • Loading branch information
viddrobnic committed May 31, 2024
1 parent b047618 commit 8284942
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub mod object;

mod bytecode;
mod compiler;
mod vm;

#[cfg(test)]
mod test;
Expand Down
1 change: 1 addition & 0 deletions runtime/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ pub enum Object {
Float(f64),
Boolean(bool),
String(Rc<String>),
Null,
}
File renamed without changes.
1 change: 1 addition & 0 deletions runtime/src/test/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mod compiler;
47 changes: 47 additions & 0 deletions runtime/src/vm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use crate::{bytecode::Bytecode, object::Object};

const STACK_SIZE: usize = 4096;

#[derive(Debug)]
pub struct VirtualMachine {
stack: Vec<Object>,
// StackPointer which points to the next value.
// Top of the stack is stack[sp-1]
sp: usize,
}

impl VirtualMachine {
pub fn new() -> Self {
Self {
stack: vec![Object::Null; STACK_SIZE],
sp: 0,
}
}

fn push(&mut self, obj: Object) {
if self.sp >= self.stack.len() {
panic!("stack overflow");
}

self.stack[self.sp] = obj;
self.sp += 1;
}

fn pop(&mut self) -> Object {
self.sp -= 1;
self.stack[self.sp].clone()
}

pub fn run(&mut self, bytecode: &Bytecode) {
for inst in &bytecode.instructions {
match inst {
crate::bytecode::Instruction::Constant(idx) => {
self.push(bytecode.constants[*idx].clone())
}
crate::bytecode::Instruction::Pop => {
self.pop();
}
}
}
}
}

0 comments on commit 8284942

Please sign in to comment.