DEV: Modulus operator works.

This commit is contained in:
Jeremy Wall 2019-08-02 18:02:45 -05:00
parent a36322461e
commit 40fc6fe15f
4 changed files with 27 additions and 1 deletions

View File

@ -103,6 +103,7 @@ pub enum Op {
Sub,
Div,
Mul,
Mod,
// Comparison Ops
Equal,
Gt,

View File

@ -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)),

View File

@ -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
}

View File

@ -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<Primitive, Error> {
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<Primitive, Error> {
Ok(match (left, right) {
(P(Int(i)), Value::P(Int(ii))) => Int(i + ii),