|
| 1 | +use crate::chunk::{Chunk, OpCode}; |
| 2 | +use crate::debug::disassemble_instruction; |
| 3 | +use crate::value::{print_value, Value}; |
| 4 | + |
| 5 | +macro_rules! binary_op{ |
| 6 | + ( $sel:ident, $op:tt ) => { |
| 7 | + { |
| 8 | + let b = $sel.stack.pop().expect("The stack was empty!"); |
| 9 | + let a = $sel.stack.pop().expect("The stack was empty!"); |
| 10 | + $sel.stack.push(a $op b); |
| 11 | + } |
| 12 | + }; |
| 13 | +} |
| 14 | + |
| 15 | +static STACK_MAX: usize = 245; |
| 16 | + |
| 17 | +pub struct VM<'a> { |
| 18 | + chunk: &'a Chunk, |
| 19 | + ip: *const OpCode, |
| 20 | + stack: Vec<Value>, |
| 21 | +} |
| 22 | + |
| 23 | +// TODO: replace with Result<_, Error> |
| 24 | +pub enum InterpretResult { |
| 25 | + Ok, |
| 26 | + CompileError, |
| 27 | + RuntimeError, |
| 28 | +} |
| 29 | + |
| 30 | +impl<'a> VM<'a> { |
| 31 | + pub fn new(chunk: &'a Chunk) -> Self { |
| 32 | + VM { |
| 33 | + chunk: chunk, |
| 34 | + ip: chunk.code, |
| 35 | + stack: Vec::with_capacity(STACK_MAX), |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + pub fn interpret(mut self) -> InterpretResult { |
| 40 | + self.run() |
| 41 | + } |
| 42 | + |
| 43 | + fn run(mut self) -> InterpretResult { |
| 44 | + let mut position: usize = 0; // TODO: infer position from self.ip. |
| 45 | + loop { |
| 46 | + let instruction: OpCode = unsafe { |
| 47 | + let r = self.ip.read(); |
| 48 | + self.ip = self.ip.add(1); |
| 49 | + r |
| 50 | + }; |
| 51 | + |
| 52 | + if cfg!(feature = "debug_trace_execution") { |
| 53 | + print!(" "); |
| 54 | + for slot in &self.stack { |
| 55 | + print!("[{:?}]", slot); |
| 56 | + } |
| 57 | + println!(); |
| 58 | + disassemble_instruction(self.chunk, &instruction, position); |
| 59 | + position += 1; |
| 60 | + } |
| 61 | + |
| 62 | + match instruction { |
| 63 | + OpCode::OpConstant(index) => { |
| 64 | + let constant = self.read_constant(index); |
| 65 | + self.stack.push(constant); |
| 66 | + } |
| 67 | + OpCode::OpAdd => binary_op!(self, +), |
| 68 | + OpCode::OpSubtract => binary_op!(self, -), |
| 69 | + OpCode::OpMultiply => binary_op!(self, *), |
| 70 | + OpCode::OpDivide => binary_op!(self, /), |
| 71 | + OpCode::OpNegate => { |
| 72 | + let value = self.stack.pop().expect("The stack was empty!"); |
| 73 | + self.stack.push(-value); |
| 74 | + } |
| 75 | + OpCode::OpReturn => { |
| 76 | + print_value(self.stack.pop().expect("The stack was empty!")); |
| 77 | + println!(); |
| 78 | + return InterpretResult::Ok; |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + fn read_constant(&self, index: usize) -> Value { |
| 85 | + self.chunk.constants[index] |
| 86 | + } |
| 87 | +} |
0 commit comments