main
Alpha Chen 2 years ago
parent cc6d837f49
commit fc2320cb81
Signed by: alpha
SSH Key Fingerprint: SHA256:3fOT8fiYQG/aK9ntivV3Bqtg8AYQ7q4nV6ZgihOA20g

@ -5,6 +5,10 @@ use crate::value::Value;
#[derive(Debug)]
pub enum OpCode {
Constant(usize),
Add,
Subtract,
Multiply,
Divide,
Negate,
Return,
}
@ -68,6 +72,10 @@ impl fmt::Display for DisassembledInstruction<'_> {
"{:<16} {:4} '{}'",
"OP_CONSTANT", constant, self.chunk.constants[constant]
)?,
OpCode::Add => write!(f, "OP_ADD")?,
OpCode::Subtract => write!(f, "OP_SUBTRACT")?,
OpCode::Multiply => write!(f, "OP_MULTIPLY")?,
OpCode::Divide => write!(f, "OP_DIVIDE")?,
OpCode::Negate => write!(f, "OP_NEGATE")?,
OpCode::Return => write!(f, "OP_RETURN")?,
}

@ -19,7 +19,14 @@ fn main() -> Result<()> {
let mut chunk = Chunk::default();
chunk.push_constant(1.2, 123);
chunk.push_constant(3.4, 123);
chunk.push(OpCode::Add, 123);
chunk.push_constant(5.6, 123);
chunk.push(OpCode::Divide, 123);
chunk.push(OpCode::Negate, 123);
chunk.push(OpCode::Return, 123);
chunk.disassemble("test chunk");

@ -1,3 +1,5 @@
use std::ops::{Add, Div, Mul, Sub};
use color_eyre::eyre::Result;
use thiserror::Error;
@ -42,6 +44,10 @@ impl VM {
let value = self.chunk.constants[*constant];
self.push(value);
}
OpCode::Add => self.binary_op(Value::add),
OpCode::Subtract => self.binary_op(Value::sub),
OpCode::Multiply => self.binary_op(Value::mul),
OpCode::Divide => self.binary_op(Value::div),
OpCode::Negate => {
let value = self.pop();
self.push(-value);
@ -65,4 +71,10 @@ impl VM {
self.stack_top -= 1;
self.stack[self.stack_top]
}
fn binary_op<T: Fn(Value, Value) -> Value>(&mut self, op: T) {
let b = self.pop();
let a = self.pop();
self.push(op(a, b));
}
}

Loading…
Cancel
Save