diff --git a/rlox/src/main.rs b/rlox/src/main.rs index 4d7d6e3..ffa3a95 100644 --- a/rlox/src/main.rs +++ b/rlox/src/main.rs @@ -1,36 +1,5 @@ mod vm; + fn main() { - let mut chunk = vm::Chunk::new("TEST".to_string()); - chunk.add_constant(vm::Value::from(3.)); - chunk.add_constant(vm::Value::from(7.)); - chunk.add_constant(vm::Value::from(11.)); - chunk.add_constant(vm::Value::from(17.)); - chunk.add_constant(vm::Value::from(500.)); - chunk.add_constant(vm::Value::from(1000.)); - chunk.add_constant(vm::Value::from(250.)); - - - chunk.add_op(vm::Op::Constant { offset: 0 }, 1); - chunk.add_op(vm::Op::Constant { offset: 1 }, 1); - chunk.add_op(vm::Op::Multiply, 1); - chunk.add_op(vm::Op::Constant { offset: 2 }, 1); - chunk.add_op(vm::Op::Constant { offset: 3 }, 1); - chunk.add_op(vm::Op::Multiply, 1); - chunk.add_op(vm::Op::Multiply, 1); - chunk.add_op(vm::Op::Negate, 1); - chunk.add_op(vm::Op::Constant { offset: 4 }, 2); - chunk.add_op(vm::Op::Constant { offset: 5 }, 2); - chunk.add_op(vm::Op::Add, 2); - chunk.add_op(vm::Op::Constant { offset: 6 }, 2); - chunk.add_op(vm::Op::Subtract, 2); - chunk.add_op(vm::Op::Negate, 2); - chunk.add_op(vm::Op::Divide, 2); - chunk.add_op(vm::Op::Return, 3); - - println!("{:?}", chunk); - - let mut interpreter = vm::VM::new(); - interpreter.trace = true; - interpreter.interpret(&chunk).unwrap() } diff --git a/rlox/src/vm.rs b/rlox/src/vm.rs index e13952f..86e9e72 100644 --- a/rlox/src/vm.rs +++ b/rlox/src/vm.rs @@ -13,7 +13,7 @@ pub enum Op { Divide, } -#[derive(Copy, Clone)] +#[derive(Copy, Clone, PartialEq)] pub struct Value { val: f64, } @@ -191,3 +191,42 @@ impl VM { return Ok(()); } } + +#[cfg(test)] +mod tests { + use super::{Chunk, Op, Value, VM}; + + #[test] + fn simple_arithmetic() { + let mut chunk = Chunk::new("TEST".to_string()); + chunk.add_constant(Value::from(3.)); + chunk.add_constant(Value::from(7.)); + chunk.add_constant(Value::from(11.)); + chunk.add_constant(Value::from(17.)); + chunk.add_constant(Value::from(500.)); + chunk.add_constant(Value::from(1000.)); + chunk.add_constant(Value::from(250.)); + + + chunk.add_op(Op::Constant { offset: 0 }, 1); + chunk.add_op(Op::Constant { offset: 1 }, 1); + chunk.add_op(Op::Multiply, 1); + chunk.add_op(Op::Constant { offset: 2 }, 1); + chunk.add_op(Op::Constant { offset: 3 }, 1); + chunk.add_op(Op::Multiply, 1); + chunk.add_op(Op::Multiply, 1); + chunk.add_op(Op::Negate, 1); + chunk.add_op(Op::Constant { offset: 4 }, 2); + chunk.add_op(Op::Constant { offset: 5 }, 2); + chunk.add_op(Op::Add, 2); + chunk.add_op(Op::Constant { offset: 6 }, 2); + chunk.add_op(Op::Subtract, 2); + chunk.add_op(Op::Negate, 2); + chunk.add_op(Op::Divide, 2); + + let mut interpreter = VM::new(); + interpreter.interpret(&chunk).unwrap(); + + assert_eq!(interpreter.stack[0], Value::from(3.1416)); + } +}