Skip to content

Commit

Permalink
Adding OutputHandler trait
Browse files Browse the repository at this point in the history
Implemented the ConsoleOutputHandler for printing to the console.
Will add a OutputHandler to write into an in memory buffer so I can implement tests to check the output of the vm.
  • Loading branch information
patbuc committed Aug 18, 2024
1 parent 15df2e6 commit 4d7425d
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 6 deletions.
3 changes: 3 additions & 0 deletions src/vm/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::vm::utils::output_handler::OutputHandler;
use std::fmt::Debug;
use std::rc::Rc;

Expand All @@ -7,6 +8,7 @@ mod value;
mod block;
pub(crate) mod opcodes;

mod utils;
mod virtual_machine;

#[derive(Debug, Clone, PartialEq)]
Expand All @@ -28,6 +30,7 @@ pub struct VirtualMachine {
ip: usize,
stack: Vec<Value>,
block: Option<Rc<Block>>,
output_handler: Box<dyn OutputHandler>,
}

#[derive(Debug)]
Expand Down
1 change: 1 addition & 0 deletions src/vm/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub(crate) mod output_handler;
13 changes: 13 additions & 0 deletions src/vm/utils/output_handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use crate::vm::Value;

pub(crate) trait OutputHandler {
fn println(&self, value: Value);
}

pub(crate) struct ConsoleOutputHandler {}

impl OutputHandler for ConsoleOutputHandler {
fn println(&self, value: Value) {
println!("{}", value);
}
}
11 changes: 5 additions & 6 deletions src/vm/virtual_machine.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::compiler::Compiler;
use crate::vm::opcodes::OpCode;
use crate::vm::utils::output_handler::ConsoleOutputHandler;
use crate::vm::{Block, Result, Value, VirtualMachine};
use std::rc::Rc;

Expand All @@ -11,6 +12,7 @@ impl VirtualMachine {
ip: 0,
stack: Vec::new(),
block: None,
output_handler: Box::new(ConsoleOutputHandler {}),
}
}

Expand Down Expand Up @@ -137,7 +139,7 @@ impl VirtualMachine {
}
OpCode::Print => {
let value = self.pop();
println!("{}", value);
self.output_handler.println(value);
}
OpCode::Pop => {
self.pop();
Expand Down Expand Up @@ -214,11 +216,7 @@ mod tests {
block.write_op_code(super::OpCode::Divide, 0);
block.write_op_code(super::OpCode::Return, 0);

let mut vm = super::VirtualMachine {
ip: 0,
stack: Vec::new(),
block: None,
};
let mut vm = super::VirtualMachine::new();

let result = vm.run(&block);
assert_eq!(super::Result::Ok, result);
Expand Down Expand Up @@ -248,6 +246,7 @@ mod tests {

assert_eq!(super::Result::Ok, result);
}

#[test]
fn can_run_multi_line_statements() {
let program = r#"
Expand Down

0 comments on commit 4d7425d

Please sign in to comment.