Add floats.{__truediv__, __mul__}

This commit is contained in:
janczer
2019-02-08 20:34:33 +01:00
parent a4b99253c9
commit d4b82007df
2 changed files with 45 additions and 0 deletions

View File

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

View File

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