Skip to content

Commit

Permalink
Replacing Value printing with a Display implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
patbuc committed Jul 5, 2024
1 parent 2f1e2f9 commit 7459a49
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 25 deletions.
16 changes: 16 additions & 0 deletions src/vm/value.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,20 @@
use crate::vm::Value;
use std::fmt::{Display, Formatter};

impl Display for Value {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
Value::Number(val) => val.to_string(),
Value::Boolean(val) => val.to_string(),
Value::String(val) => val.to_string(),
Value::Nil => "nil".to_string(),
}
)
}
}

#[macro_export]
macro_rules! number {
Expand Down
26 changes: 1 addition & 25 deletions src/vm/virtual_machine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ impl VirtualMachine {
let start = std::time::Instant::now();
return if let Some(block) = block {
let result = self.run(block);

info!("Run time: {}ms", start.elapsed().as_millis());

result
} else {
Result::CompileError
Expand All @@ -46,7 +44,7 @@ impl VirtualMachine {
match OpCode::from_u8(block.read_u8(self.ip)) {
OpCode::Return => {
let value = self.pop();
VirtualMachine::print(value);
println!("{}", value);
return Result::Ok;
}
OpCode::Constant => {
Expand Down Expand Up @@ -136,28 +134,6 @@ impl VirtualMachine {
self.push(Value::Number(as_number!(a) / as_number!(b)));
}

fn print(value: Value) {
pub(crate) fn print_nil() {
print!("nil")
}
pub(crate) fn print_string(value: String) {
print!("{}", value)
}
pub(crate) fn print_bool(value: bool) {
print!("{}", value);
}
pub(crate) fn print_number(value: f64) {
print!("{}", value);
}

match value {
Value::Number(val) => print_number(val),
Value::Boolean(val) => print_bool(val),
Value::String(val) => print_string(val),
Value::Nil => print_nil(),
}
}

fn push(&mut self, value: Value) {
self.stack.push(value);
}
Expand Down

0 comments on commit 7459a49

Please sign in to comment.