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 383c8f7
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 1 deletion.
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);
}
}
4 changes: 3 additions & 1 deletion 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

0 comments on commit 383c8f7

Please sign in to comment.