From fc2320cb817e3674ae8ba610b3da1f8b1c48aad2 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Sun, 16 Oct 2022 21:12:10 -0700 Subject: [PATCH] 15.3.1 --- rust/src/chunk.rs | 8 ++++++++ rust/src/main.rs | 7 +++++++ rust/src/vm.rs | 12 ++++++++++++ 3 files changed, 27 insertions(+) diff --git a/rust/src/chunk.rs b/rust/src/chunk.rs index 9274b3f..3b20be1 100644 --- a/rust/src/chunk.rs +++ b/rust/src/chunk.rs @@ -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")?, } diff --git a/rust/src/main.rs b/rust/src/main.rs index 153f8eb..73bf577 100644 --- a/rust/src/main.rs +++ b/rust/src/main.rs @@ -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"); diff --git a/rust/src/vm.rs b/rust/src/vm.rs index efc7910..e13ef97 100644 --- a/rust/src/vm.rs +++ b/rust/src/vm.rs @@ -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 Value>(&mut self, op: T) { + let b = self.pop(); + let a = self.pop(); + self.push(op(a, b)); + } }