Skip to content

Commit 2df7414

Browse files
Merge pull request #523 from AdamGS/complex_and_ints_addition
Complex and ints addition
2 parents c22fb58 + f333c75 commit 2df7414

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

tests/snippets/builtin_complex.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,9 @@
3838

3939
assert a.imag == 4
4040
assert b.imag == 4
41+
42+
# int and complex addition
43+
assert 1 + 1j == complex(1, 1)
44+
assert 1j + 1 == complex(1, 1)
45+
assert (1j + 1) + 3 == complex(4, 1)
46+
assert 3 + (1j + 1) == complex(4, 1)

vm/src/obj/objcomplex.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ pub fn init(context: &PyContext) {
1717

1818
context.set_attr(&complex_type, "__abs__", context.new_rustfunc(complex_abs));
1919
context.set_attr(&complex_type, "__add__", context.new_rustfunc(complex_add));
20+
context.set_attr(
21+
&complex_type,
22+
"__radd__",
23+
context.new_rustfunc(complex_radd),
24+
);
2025
context.set_attr(&complex_type, "__eq__", context.new_rustfunc(complex_eq));
2126
context.set_attr(&complex_type, "__neg__", context.new_rustfunc(complex_neg));
2227
context.set_attr(&complex_type, "__new__", context.new_rustfunc(complex_new));
@@ -106,6 +111,30 @@ fn complex_add(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
106111
let v1 = get_value(i);
107112
if objtype::isinstance(i2, &vm.ctx.complex_type()) {
108113
Ok(vm.ctx.new_complex(v1 + get_value(i2)))
114+
} else if objtype::isinstance(i2, &vm.ctx.int_type()) {
115+
Ok(vm.ctx.new_complex(Complex64::new(
116+
v1.re + objint::get_value(i2).to_f64().unwrap(),
117+
v1.im,
118+
)))
119+
} else {
120+
Err(vm.new_type_error(format!("Cannot add {} and {}", i.borrow(), i2.borrow())))
121+
}
122+
}
123+
124+
fn complex_radd(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
125+
arg_check!(
126+
vm,
127+
args,
128+
required = [(i, Some(vm.ctx.complex_type())), (i2, None)]
129+
);
130+
131+
let v1 = get_value(i);
132+
133+
if objtype::isinstance(i2, &vm.ctx.int_type()) {
134+
Ok(vm.ctx.new_complex(Complex64::new(
135+
v1.re + objint::get_value(i2).to_f64().unwrap(),
136+
v1.im,
137+
)))
109138
} else {
110139
Err(vm.new_type_error(format!("Cannot add {} and {}", i.borrow(), i2.borrow())))
111140
}

0 commit comments

Comments
 (0)