Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions tests/snippets/builtin_complex.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,9 @@

assert a.imag == 4
assert b.imag == 4

# int and complex addition
assert 1 + 1j == complex(1, 1)
assert 1j + 1 == complex(1, 1)
assert (1j + 1) + 3 == complex(4, 1)
assert 3 + (1j + 1) == complex(4, 1)
29 changes: 29 additions & 0 deletions vm/src/obj/objcomplex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ pub fn init(context: &PyContext) {

context.set_attr(&complex_type, "__abs__", context.new_rustfunc(complex_abs));
context.set_attr(&complex_type, "__add__", context.new_rustfunc(complex_add));
context.set_attr(
&complex_type,
"__radd__",
context.new_rustfunc(complex_radd),
);
context.set_attr(&complex_type, "__eq__", context.new_rustfunc(complex_eq));
context.set_attr(&complex_type, "__neg__", context.new_rustfunc(complex_neg));
context.set_attr(&complex_type, "__new__", context.new_rustfunc(complex_new));
Expand Down Expand Up @@ -106,6 +111,30 @@ fn complex_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
let v1 = get_value(i);
if objtype::isinstance(i2, &vm.ctx.complex_type()) {
Ok(vm.ctx.new_complex(v1 + get_value(i2)))
} else if objtype::isinstance(i2, &vm.ctx.int_type()) {
Ok(vm.ctx.new_complex(Complex64::new(
v1.re + objint::get_value(i2).to_f64().unwrap(),
v1.im,
)))
} else {
Err(vm.new_type_error(format!("Cannot add {} and {}", i.borrow(), i2.borrow())))
}
}

fn complex_radd(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
arg_check!(
vm,
args,
required = [(i, Some(vm.ctx.complex_type())), (i2, None)]
);

let v1 = get_value(i);

if objtype::isinstance(i2, &vm.ctx.int_type()) {
Ok(vm.ctx.new_complex(Complex64::new(
v1.re + objint::get_value(i2).to_f64().unwrap(),
v1.im,
)))
} else {
Err(vm.new_type_error(format!("Cannot add {} and {}", i.borrow(), i2.borrow())))
}
Expand Down