From acc95c36e96425894211d42f5edcfe3b9912fd8f Mon Sep 17 00:00:00 2001 From: ctsk <9384305+ctsk@users.noreply.github.com> Date: Thu, 30 Mar 2023 11:49:38 +0200 Subject: [PATCH] [rlox] Implement VM Stack --- rlox/src/vm.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 59 insertions(+), 4 deletions(-) diff --git a/rlox/src/vm.rs b/rlox/src/vm.rs index 535e75c..885b105 100644 --- a/rlox/src/vm.rs +++ b/rlox/src/vm.rs @@ -8,11 +8,17 @@ pub enum Op { Constant { offset: usize }, } -#[derive(Debug)] +#[derive(Copy, Clone)] pub struct Value { val: f64, } +impl fmt::Debug for Value { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + write!(f, "{}", self.val) + } +} + impl From for Value { fn from(value: f64) -> Self { Value { val: value } @@ -56,10 +62,10 @@ impl fmt::Debug for Chunk { let line = self.debug_info[idx]; if idx > 0 && self.debug_info[idx-1] == line { - write!(f, " | ")?; + write!(f, " | ") } else { - write!(f, "{:4} ", line)?; - } + write!(f, "{:4} ", line) + }?; match op { Op::Return => writeln!(f, "{:?}", op), @@ -73,3 +79,52 @@ impl fmt::Debug for Chunk { return Ok(()); } } + +const VM_STACK_SIZE: usize = 256; + +struct VM { + trace: bool, + stack: Vec, + code: Chunk +} + +enum VMError { + Compile, + Runtime +} + +impl VM { + fn push(&mut self, value: Value) { + self.stack.push(value); + } + + fn pop(&mut self) -> Value { + self.stack.pop().unwrap() + } + + pub fn interpret(&mut self, chunk: &Chunk) -> Result<(), VMError> { + for instr in chunk.code.iter().copied() { + if self.trace { + print!(" ["); + for value in self.stack.iter() { + println!("{:?} | ", value); + } + println!("_ ]"); + + println!("{:?}", instr); + } + + match instr { + Op::Return => { + print!("{:?}", self.pop()); + return Ok(()) + }, + Op::Constant { offset } => { + self.push(self.code.constants[offset]) + } + } + } + + return Ok(()) + } +}