From 4e6071aee97a26610aeee423d830a695b8c4d563 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edvard=20Th=C3=B6rnros?= Date: Thu, 14 Jan 2021 20:18:23 +0100 Subject: Pass printing as an argument --- src/vm.rs | 48 +++++++++++++++++++++++++++++------------------- 1 file changed, 29 insertions(+), 19 deletions(-) (limited to 'src/vm.rs') diff --git a/src/vm.rs b/src/vm.rs index 46b4105..f880b4a 100644 --- a/src/vm.rs +++ b/src/vm.rs @@ -155,22 +155,30 @@ struct Frame { pub struct VM { stack: Vec, frames: Vec, + print_blocks: bool, + print_ops: bool, } -pub fn run_block(block: Rc) -> Result<(), Error> { - let mut vm = VM { - stack: Vec::new(), - frames: vec![Frame { - stack_offset: 0, - block, - ip: 0 - }], - }; +impl VM { + pub fn new() -> Self { + Self { + stack: Vec::new(), + frames: Vec::new(), + print_blocks: false, + print_ops: false, + } + } - vm.run() -} + pub fn print_blocks(mut self, b: bool) -> Self { + self.print_blocks = b; + self + } + + pub fn print_ops(mut self, b: bool) -> Self { + self.print_ops = b; + self + } -impl VM { fn pop_twice(&mut self) -> (Value, Value) { let len = self.stack.len(); let res = (self.stack[len-2].clone(), self.stack[len-1].clone()); @@ -202,17 +210,19 @@ impl VM { } } - pub fn run(&mut self) -> Result<(), Error>{ - //TODO better system so tests dont print - const PRINT_WHILE_RUNNING: bool = true; - const PRINT_BLOCK: bool = true; + pub fn run(&mut self, block: Rc) -> Result<(), Error>{ + self.frames.push(Frame { + stack_offset: 0, + block, + ip: 0 + }); - if PRINT_BLOCK { + if self.print_blocks { self.frame().block.debug_print(); } loop { - if PRINT_WHILE_RUNNING { + if self.print_ops { let start = self.frame().stack_offset; print!(" {:3} [", start); for (i, s) in self.stack.iter().skip(start).enumerate() { @@ -380,7 +390,7 @@ impl VM { format!("Invalid number of arguments, got {} expected {}.", num_args, arity)); } - if PRINT_BLOCK { + if self.print_blocks { block.debug_print(); } self.frames.push(Frame { -- cgit v1.2.1