From 40fc6fe15fd7061e9c37ecc103c6485203c0adb2 Mon Sep 17 00:00:00 2001 From: Jeremy Wall Date: Fri, 2 Aug 2019 18:02:45 -0500 Subject: [PATCH] DEV: Modulus operator works. --- src/build/opcode/mod.rs | 1 + src/build/opcode/test.rs | 2 ++ src/build/opcode/translate.rs | 7 ++++++- src/build/opcode/vm.rs | 18 ++++++++++++++++++ 4 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/build/opcode/mod.rs b/src/build/opcode/mod.rs index 31858b3..eb77eb5 100644 --- a/src/build/opcode/mod.rs +++ b/src/build/opcode/mod.rs @@ -103,6 +103,7 @@ pub enum Op { Sub, Div, Mul, + Mod, // Comparison Ops Equal, Gt, diff --git a/src/build/opcode/test.rs b/src/build/opcode/test.rs index 1c528ea..c4bb49a 100644 --- a/src/build/opcode/test.rs +++ b/src/build/opcode/test.rs @@ -588,6 +588,8 @@ fn simple_binary_expr() { "2-1;" => P(Int(1)), "2*2;" => P(Int(4)), "6/2;" => P(Int(3)), + "4 %% 2;" => P(Int(0)), + "5 %% 2;" => P(Int(1)), "1.0+1.0;" => P(Float(2.0)), "\"foo\"+\"bar\";" => P(Str("foobar".to_owned())), "1==1;" => P(Bool(true)), diff --git a/src/build/opcode/translate.rs b/src/build/opcode/translate.rs index ea6a878..4d635f3 100644 --- a/src/build/opcode/translate.rs +++ b/src/build/opcode/translate.rs @@ -131,7 +131,12 @@ impl AST { let jptr = (ops.len() - 1 - idx) as i32; ops[idx] = Op::Or(jptr); } - BinaryExprType::IN | BinaryExprType::Mod | BinaryExprType::DOT => { + BinaryExprType::Mod => { + Self::translate_expr(*def.right, &mut ops); + Self::translate_expr(*def.left, &mut ops); + ops.push(Op::Mod); + } + BinaryExprType::IN | BinaryExprType::DOT => { unimplemented!("Binary expressions are not implmented yet") // TODO } diff --git a/src/build/opcode/vm.rs b/src/build/opcode/vm.rs index 9867f39..0c66f65 100644 --- a/src/build/opcode/vm.rs +++ b/src/build/opcode/vm.rs @@ -83,6 +83,7 @@ impl<'a> VM { Op::Sym(s) => self.push(Rc::new(S(s.clone())))?, Op::DeRef(s) => self.op_deref(s.clone())?, Op::Add => self.op_add()?, + Op::Mod => self.op_mod()?, Op::Sub => self.op_sub()?, Op::Mul => self.op_mul()?, Op::Div => self.op_div()?, @@ -398,6 +399,15 @@ impl<'a> VM { Ok(()) } + fn op_mod(&mut self) -> Result<(), Error> { + // Adds the previous two items in the stack. + let left = self.pop()?; + let right = self.pop()?; + // Then pushes the result onto the stack. + self.push(Rc::new(P(self.modulus(&left, &right)?)))?; + Ok(()) + } + fn op_add(&mut self) -> Result<(), Error> { // Adds the previous two items in the stack. let left = self.pop()?; @@ -674,6 +684,14 @@ impl<'a> VM { }) } + fn modulus(&self, left: &Value, right: &Value) -> Result { + Ok(match (left, right) { + (P(Int(i)), Value::P(Int(ii))) => Int(i % ii), + (P(Float(f)), Value::P(Float(ff))) => Float(f % ff), + _ => return Err(dbg!(Error {})), + }) + } + fn add(&self, left: &Value, right: &Value) -> Result { Ok(match (left, right) { (P(Int(i)), Value::P(Int(ii))) => Int(i + ii),