Make example work for sub/rsub. Still work in progress.

This commit is contained in:
Windel Bouwman
2018-11-06 22:13:49 +01:00
parent 60f29149ef
commit bacaef0ec5
2 changed files with 44 additions and 21 deletions

View File

@@ -226,7 +226,7 @@ fn int_sub(vm: &mut VirtualMachine, args: PyFuncArgs) -> PyResult {
.ctx
.new_float(i.to_f64().unwrap() - objfloat::get_value(i2)))
} else {
Err(vm.new_type_error(format!("Cannot substract {:?} and {:?}", i, i2)))
Err(vm.new_not_implemented_error(format!("Cannot substract {:?} and {:?}", i, i2)))
}
}

View File

@@ -78,6 +78,11 @@ impl VirtualMachine {
self.new_exception(value_error, msg)
}
pub fn new_not_implemented_error(&mut self, msg: String) -> PyObjectRef {
let value_error = self.ctx.exceptions.not_implemented_error.clone();
self.new_exception(value_error, msg)
}
pub fn new_scope(&mut self, parent_scope: Option<PyObjectRef>) -> PyObjectRef {
// let parent_scope = self.current_frame_mut().locals.clone();
self.ctx.new_scope(parent_scope)
@@ -437,32 +442,50 @@ impl VirtualMachine {
}
pub fn _sub(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult {
// Try __sub__, next __rsub__, next, give up
// 1. Try __sub__, next __rsub__, next, give up
if let Ok(method) = self.get_method(a.clone(), "__sub__") {
self.invoke(
match self.invoke(
method,
PyFuncArgs {
args: vec![b],
args: vec![b.clone()],
kwargs: vec![],
},
)
} else if let Ok(method) = self.get_method(b.clone(), "__rsub__") {
self.invoke(
method,
PyFuncArgs {
args: vec![a],
kwargs: vec![],
},
)
} else {
// Cannot sub a and b
let a_type_name = objtype::get_type_name(&a.typ());
let b_type_name = objtype::get_type_name(&b.typ());
Err(self.new_type_error(format!(
"Unsupported operand types for '-': '{}' and '{}'",
a_type_name, b_type_name
)))
) {
Ok(value) => return Ok(value),
Err(err) => {
if !objtype::isinstance(&err, &self.ctx.exceptions.not_implemented_error) {
return Err(err);
}
}
}
}
// 2. try __rsub__
if let Ok(method) = self.get_method(b.clone(), "__rsub__") {
match self.invoke(
method,
PyFuncArgs {
args: vec![a.clone()],
kwargs: vec![],
},
) {
Ok(value) => return Ok(value),
Err(err) => {
if !objtype::isinstance(&err, &self.ctx.exceptions.not_implemented_error) {
return Err(err);
}
}
}
}
// 3. It all failed :(
// Cannot sub a and b
let a_type_name = objtype::get_type_name(&a.typ());
let b_type_name = objtype::get_type_name(&b.typ());
Err(self.new_type_error(format!(
"Unsupported operand types for '-': '{}' and '{}'",
a_type_name, b_type_name
)))
}
pub fn _add(&mut self, a: PyObjectRef, b: PyObjectRef) -> PyResult {