From d4b82007dfc8db396b847a746abc26517e067883 Mon Sep 17 00:00:00 2001 From: janczer Date: Fri, 8 Feb 2019 20:34:33 +0100 Subject: [PATCH] Add floats.{__truediv__, __mul__} --- tests/snippets/floats.py | 3 +++ vm/src/obj/objfloat.rs | 42 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/tests/snippets/floats.py b/tests/snippets/floats.py index cf6a9a0c0..b2b2cad8c 100644 --- a/tests/snippets/floats.py +++ b/tests/snippets/floats.py @@ -15,3 +15,6 @@ assert b >= a assert c >= a assert not a >= b +assert a + b == 2.5 +assert a - c == 0 +assert a / c == 1 diff --git a/vm/src/obj/objfloat.rs b/vm/src/obj/objfloat.rs index 1bb57e572..4e4b09807 100644 --- a/vm/src/obj/objfloat.rs +++ b/vm/src/obj/objfloat.rs @@ -266,6 +266,46 @@ fn float_pow(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { } } +fn float_truediv(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { + arg_check!( + vm, + args, + required = [(i, Some(vm.ctx.float_type())), (i2, None)] + ); + let v1 = get_value(i); + if objtype::isinstance(i2, &vm.ctx.float_type) { + Ok(vm + .ctx + .new_float(v1 / get_value(i2))) + } else if objtype::isinstance(i2, &vm.ctx.int_type) { + Ok(vm + .ctx + .new_float(v1 / objint::get_value(i2).to_f64().unwrap())) + } else { + Err(vm.new_type_error(format!("Cannot divide {} and {}", i.borrow(), i2.borrow()))) + } +} + +fn float_mul(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult { + arg_check!( + vm, + args, + required = [(i, Some(vm.ctx.float_type())), (i2, None)] + ); + let v1 = get_value(i); + if objtype::isinstance(i2, &vm.ctx.float_type) { + Ok(vm + .ctx + .new_float(v1 * get_value(i2))) + } else if objtype::isinstance(i2, &vm.ctx.int_type) { + Ok(vm + .ctx + .new_float(v1 * objint::get_value(i2).to_f64().unwrap())) + } else { + Err(vm.new_type_error(format!("Cannot divide {} and {}", i.borrow(), i2.borrow()))) + } +} + pub fn init(context: &PyContext) { let float_type = &context.float_type; @@ -299,4 +339,6 @@ pub fn init(context: &PyContext) { "__doc__", context.new_str(float_doc.to_string()), ); + context.set_attr(&float_type, "__truediv__", context.new_rustfunc(float_truediv)); + context.set_attr(&float_type, "__mul__", context.new_rustfunc(float_mul)); }