From 61455ce26125e24ac6699ee4eabdb447a6dc6421 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Tue, 4 Aug 2020 22:57:19 +0900 Subject: [PATCH] Separate IntoPyObject and IntoPyResult --- derive/src/pyclass.rs | 2 +- vm/src/dictdatatype.rs | 2 +- vm/src/format.rs | 3 +- vm/src/function.rs | 14 ++++----- vm/src/obj/objbool.rs | 10 +++--- vm/src/obj/objbytes.rs | 4 +-- vm/src/obj/objcomplex.rs | 10 +++--- vm/src/obj/objdict.rs | 4 +-- vm/src/obj/objfloat.rs | 20 ++++++------ vm/src/obj/objgetset.rs | 14 ++++----- vm/src/obj/objint.rs | 14 ++++----- vm/src/obj/objnone.rs | 8 ++--- vm/src/obj/objstr.rs | 22 ++++++------- vm/src/obj/objtuple.rs | 4 +-- vm/src/pyobject.rs | 67 ++++++++++++++++++++++++---------------- vm/src/stdlib/array.rs | 30 +++++++++--------- vm/src/stdlib/csv.rs | 6 ++-- vm/src/stdlib/socket.rs | 2 +- vm/src/stdlib/ssl.rs | 2 +- vm/src/stdlib/string.rs | 16 +++++----- vm/src/sysmodule.rs | 8 ++--- 21 files changed, 135 insertions(+), 127 deletions(-) diff --git a/derive/src/pyclass.rs b/derive/src/pyclass.rs index bbcec3a3f..7c1d4a3b9 100644 --- a/derive/src/pyclass.rs +++ b/derive/src/pyclass.rs @@ -524,7 +524,7 @@ pub fn impl_pystruct_sequence(attr: AttributeArgs, item: Item) -> Result Dict { hash_value, } => { // New key: - self.unchecked_push(hash_index, hash_value, key.into_pyobject(vm)?, value); + self.unchecked_push(hash_index, hash_value, key.into_pyobject(vm), value); break Ok(()); } } diff --git a/vm/src/format.rs b/vm/src/format.rs index 133cc9409..0f88af928 100644 --- a/vm/src/format.rs +++ b/vm/src/format.rs @@ -564,6 +564,7 @@ pub(crate) enum FormatParseError { } impl FormatParseError { + // TODO: IntoPyException pub fn into_pyobject(self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { FormatParseError::UnmatchedBracket => { @@ -823,7 +824,7 @@ impl FormatString { } FieldNamePart::Index(index) => { // TODO Implement DictKey for usize so we can pass index directly - argument = argument.get_item(&index.into_pyobject(vm)?, vm)?; + argument = argument.get_item(&index.into_pyobject(vm), vm)?; } FieldNamePart::StringIndex(index) => { argument = argument.get_item(&index, vm)?; diff --git a/vm/src/function.rs b/vm/src/function.rs index b26318ced..9d2f156b0 100644 --- a/vm/src/function.rs +++ b/vm/src/function.rs @@ -10,7 +10,7 @@ use crate::exceptions::PyBaseExceptionRef; use crate::obj::objtuple::PyTupleRef; use crate::obj::objtype::{isinstance, PyClassRef}; use crate::pyobject::{ - IntoPyObject, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol, + IntoPyResult, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol, }; use crate::vm::VirtualMachine; @@ -524,13 +524,13 @@ macro_rules! into_py_native_func_tuple { where F: Fn($($T,)* &VirtualMachine) -> R + 'static + Send + Sync, $($T: FromArgs,)* - R: IntoPyObject, + R: IntoPyResult, { fn into_func(self) -> PyNativeFunc { smallbox!(move |vm: &VirtualMachine, args: PyFuncArgs| { let ($($n,)*) = args.bind::<($($T,)*)>(vm)?; - (self)($($n,)* vm).into_pyobject(vm) + (self)($($n,)* vm).into_pyresult(vm) }) } } @@ -540,13 +540,13 @@ macro_rules! into_py_native_func_tuple { F: Fn(&S, $($T,)* &VirtualMachine) -> R + 'static + Send + Sync, S: PyValue, $($T: FromArgs,)* - R: IntoPyObject, + R: IntoPyResult, { fn into_func(self) -> PyNativeFunc { smallbox!(move |vm: &VirtualMachine, args: PyFuncArgs| { let (zelf, $($n,)*) = args.bind::<(PyRef, $($T,)*)>(vm)?; - (self)(&zelf, $($n,)* vm).into_pyobject(vm) + (self)(&zelf, $($n,)* vm).into_pyresult(vm) }) } } @@ -555,7 +555,7 @@ macro_rules! into_py_native_func_tuple { where F: Fn($($T,)*) -> R + 'static + Send + Sync, $($T: FromArgs,)* - R: IntoPyObject, + R: IntoPyResult, { fn into_func(self) -> PyNativeFunc { IntoPyNativeFunc::into_func(move |$($n,)* _vm: &VirtualMachine| (self)($($n,)*)) @@ -567,7 +567,7 @@ macro_rules! into_py_native_func_tuple { F: Fn(&S, $($T,)*) -> R + 'static + Send + Sync, S: PyValue, $($T: FromArgs,)* - R: IntoPyObject, + R: IntoPyResult, { fn into_func(self) -> PyNativeFunc { IntoPyNativeFunc::into_func(move |zelf: &S, $($n,)* _vm: &VirtualMachine| (self)(zelf, $($n,)*)) diff --git a/vm/src/obj/objbool.rs b/vm/src/obj/objbool.rs index 0ce748d15..16b168c78 100644 --- a/vm/src/obj/objbool.rs +++ b/vm/src/obj/objbool.rs @@ -13,8 +13,8 @@ use super::objstr::PyStringRef; use super::objtype; impl IntoPyObject for bool { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_bool(self)) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_bool(self) } } @@ -112,7 +112,7 @@ impl PyBool { #[pymethod(name = "__ror__")] #[pymethod(magic)] - fn or(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn or(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&lhs, &vm.ctx.types.bool_type) && objtype::isinstance(&rhs, &vm.ctx.types.bool_type) { @@ -126,7 +126,7 @@ impl PyBool { #[pymethod(name = "__rand__")] #[pymethod(magic)] - fn and(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn and(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&lhs, &vm.ctx.types.bool_type) && objtype::isinstance(&rhs, &vm.ctx.types.bool_type) { @@ -140,7 +140,7 @@ impl PyBool { #[pymethod(name = "__rxor__")] #[pymethod(magic)] - fn xor(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn xor(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if objtype::isinstance(&lhs, &vm.ctx.types.bool_type) && objtype::isinstance(&rhs, &vm.ctx.types.bool_type) { diff --git a/vm/src/obj/objbytes.rs b/vm/src/obj/objbytes.rs index d1c0d87ab..46003f1f3 100644 --- a/vm/src/obj/objbytes.rs +++ b/vm/src/obj/objbytes.rs @@ -59,8 +59,8 @@ impl From> for PyBytes { } impl IntoPyObject for Vec { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_bytes(self)) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_bytes(self) } } diff --git a/vm/src/obj/objcomplex.rs b/vm/src/obj/objcomplex.rs index 367db543b..bfb01bcf3 100644 --- a/vm/src/obj/objcomplex.rs +++ b/vm/src/obj/objcomplex.rs @@ -32,8 +32,8 @@ impl PyValue for PyComplex { } impl IntoPyObject for Complex64 { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_complex(self)) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_complex(self) } } @@ -81,10 +81,10 @@ impl PyComplex { where F: Fn(Complex64, Complex64) -> Complex64, { - try_complex(&other, vm)?.map_or_else( - || Ok(vm.ctx.not_implemented()), + Ok(try_complex(&other, vm)?.map_or_else( + || vm.ctx.not_implemented(), |other| op(self.value, other).into_pyobject(vm), - ) + )) } #[pymethod(name = "__add__")] diff --git a/vm/src/obj/objdict.rs b/vm/src/obj/objdict.rs index c792c5dfc..a31e66a31 100644 --- a/vm/src/obj/objdict.rs +++ b/vm/src/obj/objdict.rs @@ -282,7 +282,7 @@ impl PyDictRef { if let Some(method_or_err) = vm.get_method(self.clone().into_object(), "__missing__") { let method = method_or_err?; - Ok(Some(vm.invoke(&method, vec![key.into_pyobject(vm)?])?)) + Ok(Some(vm.invoke(&method, vec![key.into_pyobject(vm)])?)) } else { Ok(None) } @@ -419,7 +419,7 @@ impl PyDictRef { } pub fn contains_key(&self, key: T, vm: &VirtualMachine) -> bool { - let key = key.into_pyobject(vm).unwrap(); + let key = key.into_pyobject(vm); self.entries.contains(vm, &key).unwrap() } diff --git a/vm/src/obj/objfloat.rs b/vm/src/obj/objfloat.rs index 894d241f4..f0c0a239d 100644 --- a/vm/src/obj/objfloat.rs +++ b/vm/src/obj/objfloat.rs @@ -10,8 +10,8 @@ use super::objtype::PyClassRef; use crate::format::FormatSpec; use crate::function::{OptionalArg, OptionalOption}; use crate::pyobject::{ - IntoPyObject, PyArithmaticValue::*, PyClassImpl, PyComparisonValue, PyContext, PyObjectRef, - PyRef, PyResult, PyValue, TryFromObject, TypeProtocol, + IntoPyObject, IntoPyResult, PyArithmaticValue::*, PyClassImpl, PyComparisonValue, PyContext, + PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol, }; use crate::vm::VirtualMachine; use rustpython_common::{float_ops, hash}; @@ -36,13 +36,13 @@ impl PyValue for PyFloat { } impl IntoPyObject for f64 { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_float(self)) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_float(self) } } impl IntoPyObject for f32 { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_float(f64::from(self))) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_float(f64::from(self)) } } @@ -142,9 +142,9 @@ pub fn float_pow(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult { } else if v1.is_sign_negative() && (v2.floor() - v2).abs() > f64::EPSILON { let v1 = Complex64::new(v1, 0.); let v2 = Complex64::new(v2, 0.); - v1.powc(v2).into_pyobject(vm) + Ok(v1.powc(v2).into_pyobject(vm)) } else { - v1.powf(v2).into_pyobject(vm) + Ok(v1.powf(v2).into_pyobject(vm)) } } @@ -259,7 +259,7 @@ impl PyFloat { { try_float(&other, vm)?.map_or_else( || Ok(vm.ctx.not_implemented()), - |other| op(self.value, other).into_pyobject(vm), + |other| op(self.value, other).into_pyresult(vm), ) } @@ -270,7 +270,7 @@ impl PyFloat { { try_float(&other, vm)?.map_or_else( || Ok(vm.ctx.not_implemented()), - |other| op(self.value, other).into_pyobject(vm), + |other| op(self.value, other).into_pyresult(vm), ) } diff --git a/vm/src/obj/objgetset.rs b/vm/src/obj/objgetset.rs index 1f0cb4214..b97adf1d3 100644 --- a/vm/src/obj/objgetset.rs +++ b/vm/src/obj/objgetset.rs @@ -4,7 +4,7 @@ use super::objtype::PyClassRef; use crate::function::{FunctionBox, OptionalArg, OwnedParam, RefParam}; use crate::pyobject::{ - IntoPyObject, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, + IntoPyResult, PyClassImpl, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol, }; use crate::slots::SlotDescriptor; @@ -22,12 +22,12 @@ impl IntoPyGetterFunc<(OwnedParam, R, VirtualMachine)> for F where F: Fn(T, &VirtualMachine) -> R + 'static + Send + Sync, T: TryFromObject, - R: IntoPyObject, + R: IntoPyResult, { fn into_getter(self) -> PyGetterFunc { smallbox::smallbox!(move |vm: &VirtualMachine, obj| { let obj = T::try_from_object(vm, obj)?; - (self)(obj, vm).into_pyobject(vm) + (self)(obj, vm).into_pyresult(vm) }) } } @@ -36,12 +36,12 @@ impl IntoPyGetterFunc<(RefParam, R, VirtualMachine)> for F where F: Fn(&S, &VirtualMachine) -> R + 'static + Send + Sync, S: PyValue, - R: IntoPyObject, + R: IntoPyResult, { fn into_getter(self) -> PyGetterFunc { smallbox::smallbox!(move |vm: &VirtualMachine, obj| { let zelf = PyRef::::try_from_object(vm, obj)?; - (self)(&zelf, vm).into_pyobject(vm) + (self)(&zelf, vm).into_pyresult(vm) }) } } @@ -50,7 +50,7 @@ impl IntoPyGetterFunc<(OwnedParam, R)> for F where F: Fn(T) -> R + 'static + Send + Sync, T: TryFromObject, - R: IntoPyObject, + R: IntoPyResult, { fn into_getter(self) -> PyGetterFunc { IntoPyGetterFunc::into_getter(move |obj, _vm: &VirtualMachine| (self)(obj)) @@ -61,7 +61,7 @@ impl IntoPyGetterFunc<(RefParam, R)> for F where F: Fn(&S) -> R + 'static + Send + Sync, S: PyValue, - R: IntoPyObject, + R: IntoPyResult, { fn into_getter(self) -> PyGetterFunc { IntoPyGetterFunc::into_getter(move |zelf: &S, _vm: &VirtualMachine| (self)(zelf)) diff --git a/vm/src/obj/objint.rs b/vm/src/obj/objint.rs index f846c9f76..97be9bd6f 100644 --- a/vm/src/obj/objint.rs +++ b/vm/src/obj/objint.rs @@ -16,8 +16,8 @@ use crate::bytesinner::PyBytesInner; use crate::format::FormatSpec; use crate::function::{OptionalArg, PyFuncArgs}; use crate::pyobject::{ - IdProtocol, IntoPyObject, PyArithmaticValue, PyClassImpl, PyComparisonValue, PyContext, - PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol, + IdProtocol, IntoPyObject, IntoPyResult, PyArithmaticValue, PyClassImpl, PyComparisonValue, + PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, TypeProtocol, }; use crate::stdlib::array::PyArray; use crate::vm::VirtualMachine; @@ -62,8 +62,8 @@ impl PyInt { } impl IntoPyObject for BigInt { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_int(self)) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_int(self) } } @@ -76,8 +76,8 @@ impl PyValue for PyInt { macro_rules! impl_into_pyobject_int { ($($t:ty)*) => {$( impl IntoPyObject for $t { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_int(self)) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_int(self) } } )*}; @@ -121,7 +121,7 @@ fn inner_pow(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult { if int2.is_negative() { let v1 = try_float(int1, vm)?; let v2 = try_float(int2, vm)?; - objfloat::float_pow(v1, v2, vm).into_pyobject(vm) + objfloat::float_pow(v1, v2, vm).into_pyresult(vm) } else { Ok(if let Some(v2) = int2.to_u64() { vm.ctx.new_int(Pow::pow(int1, v2)) diff --git a/vm/src/obj/objnone.rs b/vm/src/obj/objnone.rs index f618927e1..09ea8ce64 100644 --- a/vm/src/obj/objnone.rs +++ b/vm/src/obj/objnone.rs @@ -18,16 +18,16 @@ impl PyValue for PyNone { // This allows a built-in function to not return a value, mapping to // Python's behavior of returning `None` in this situation. impl IntoPyObject for () { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.none()) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.none() } } impl IntoPyObject for Option { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { match self { Some(x) => x.into_pyobject(vm), - None => Ok(vm.ctx.none()), + None => vm.ctx.none(), } } } diff --git a/vm/src/obj/objstr.rs b/vm/src/obj/objstr.rs index 8de7e1ff5..1ec987096 100644 --- a/vm/src/obj/objstr.rs +++ b/vm/src/obj/objstr.rs @@ -953,7 +953,7 @@ impl PyString { let mut translated = String::new(); for c in self.value.chars() { - match table.get_item(&(c as u32).into_pyobject(vm)?, vm) { + match table.get_item(&(c as u32).into_pyobject(vm), vm) { Ok(value) => { if let Some(text) = value.payload::() { translated.push_str(&text.value); @@ -1000,7 +1000,7 @@ impl PyString { new_dict.set_item(vm.new_int(c as u32), vm.get_none(), vm)?; } } - new_dict.into_pyobject(vm) + Ok(new_dict.into_pyobject(vm)) } else { Err(vm.new_value_error( "the first two maketrans arguments must have equal length".to_owned(), @@ -1019,14 +1019,14 @@ impl PyString { for (key, val) in dict { if let Some(num) = key.payload::() { new_dict.set_item( - num.as_bigint().to_i32().into_pyobject(vm)?, + num.as_bigint().to_i32().into_pyobject(vm), val, vm, )?; } else if let Some(string) = key.payload::() { if string.len() == 1 { let num_value = string.value.chars().next().unwrap() as u32; - new_dict.set_item(num_value.into_pyobject(vm)?, val, vm)?; + new_dict.set_item(num_value.into_pyobject(vm), val, vm)?; } else { return Err(vm.new_value_error( "string keys in translate table must be of length 1".to_owned(), @@ -1034,7 +1034,7 @@ impl PyString { } } } - new_dict.into_pyobject(vm) + Ok(new_dict.into_pyobject(vm)) } _ => Err(vm.new_value_error( "if you give only one argument to maketrans it must be a dict".to_owned(), @@ -1100,20 +1100,20 @@ impl PyValue for PyString { } impl IntoPyObject for String { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_str(self)) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_str(self) } } impl IntoPyObject for &str { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_str(self.to_owned())) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_str(self.to_owned()) } } impl IntoPyObject for &String { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_str(self.clone())) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_str(self.clone()) } } diff --git a/vm/src/obj/objtuple.rs b/vm/src/obj/objtuple.rs index 92e591f46..6fca5bb9c 100644 --- a/vm/src/obj/objtuple.rs +++ b/vm/src/obj/objtuple.rs @@ -45,8 +45,8 @@ impl PyValue for PyTuple { macro_rules! impl_intopyobj_tuple { ($(($T:ident, $idx:tt)),+) => { impl<$($T: IntoPyObject),*> IntoPyObject for ($($T,)*) { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(vm.ctx.new_tuple(vec![$(self.$idx.into_pyobject(vm)?),*])) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.new_tuple(vec![$(self.$idx.into_pyobject(vm)),*]) } } }; diff --git a/vm/src/pyobject.rs b/vm/src/pyobject.rs index 2cc60f9aa..6f295918c 100644 --- a/vm/src/pyobject.rs +++ b/vm/src/pyobject.rs @@ -965,15 +965,15 @@ where T: IntoPyObject, { fn get_item(&self, key: T, vm: &VirtualMachine) -> PyResult { - vm.call_method(self, "__getitem__", key.into_pyobject(vm)?) + vm.call_method(self, "__getitem__", key.into_pyobject(vm)) } fn set_item(&self, key: T, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { - vm.call_method(self, "__setitem__", vec![key.into_pyobject(vm)?, value]) + vm.call_method(self, "__setitem__", vec![key.into_pyobject(vm), value]) } fn del_item(&self, key: T, vm: &VirtualMachine) -> PyResult { - vm.call_method(self, "__delitem__", key.into_pyobject(vm)?) + vm.call_method(self, "__delitem__", key.into_pyobject(vm)) } } @@ -1151,45 +1151,36 @@ pub trait TryFromObject: Sized { /// and should be implemented by many primitive Rust types, allowing a built-in /// function to simply return a `bool` or a `usize` for example. pub trait IntoPyObject { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult; + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef; } impl IntoPyObject for PyRef { - fn into_pyobject(self, _vm: &VirtualMachine) -> PyResult { - Ok(self.obj) + fn into_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { + self.obj } } impl IntoPyObject for &PyRef { - fn into_pyobject(self, _vm: &VirtualMachine) -> PyResult { - Ok(self.obj.clone()) + fn into_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { + self.obj.clone() } } impl IntoPyObject for PyCallable { - fn into_pyobject(self, _vm: &VirtualMachine) -> PyResult { - Ok(self.into_object()) + fn into_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { + self.into_object() } } impl IntoPyObject for PyObjectRef { - fn into_pyobject(self, _vm: &VirtualMachine) -> PyResult { - Ok(self) + fn into_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { + self } } impl IntoPyObject for &PyObjectRef { - fn into_pyobject(self, _vm: &VirtualMachine) -> PyResult { - Ok(self.clone()) - } -} - -impl IntoPyObject for PyResult -where - T: IntoPyObject, -{ - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - self.and_then(|res| T::into_pyobject(res, vm)) + fn into_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { + self.clone() } } @@ -1199,8 +1190,30 @@ impl IntoPyObject for T where T: PyValue + Sized, { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { - Ok(PyObject::new(self, T::class(vm), None)) + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { + PyObject::new(self, T::class(vm), None) + } +} + +pub trait IntoPyResult { + fn into_pyresult(self, vm: &VirtualMachine) -> PyResult; +} + +impl IntoPyResult for T +where + T: IntoPyObject, +{ + fn into_pyresult(self, vm: &VirtualMachine) -> PyResult { + Ok(self.into_pyobject(vm)) + } +} + +impl IntoPyResult for PyResult +where + T: IntoPyObject, +{ + fn into_pyresult(self, vm: &VirtualMachine) -> PyResult { + self.map(|res| T::into_pyobject(res, vm)) } } @@ -1434,10 +1447,10 @@ impl IntoPyObject for PyArithmaticValue where T: IntoPyObject, { - fn into_pyobject(self, vm: &VirtualMachine) -> PyResult { + fn into_pyobject(self, vm: &VirtualMachine) -> PyObjectRef { match self { PyArithmaticValue::Implemented(v) => v.into_pyobject(vm), - PyArithmaticValue::NotImplemented => Ok(vm.ctx.not_implemented()), + PyArithmaticValue::NotImplemented => vm.ctx.not_implemented(), } } } diff --git a/vm/src/stdlib/array.rs b/vm/src/stdlib/array.rs index 4e397d1f4..1a79b591f 100644 --- a/vm/src/stdlib/array.rs +++ b/vm/src/stdlib/array.rs @@ -78,7 +78,7 @@ macro_rules! def_array_enum { Ok(()) } - fn pop(&mut self, i: usize, vm: &VirtualMachine) -> PyResult { + fn pop(&mut self, i: usize, vm: &VirtualMachine) -> PyObjectRef { match self { $(ArrayContentType::$n(v) => { v.remove(i).into_pyobject(vm) @@ -182,7 +182,7 @@ macro_rules! def_array_enum { Ok(i) } - fn getitem_by_idx(&self, i: usize, vm: &VirtualMachine) -> Option { + fn getitem_by_idx(&self, i: usize, vm: &VirtualMachine) -> Option { match self { $(ArrayContentType::$n(v) => v.get(i).map(|x| x.into_pyobject(vm)),)* } @@ -191,11 +191,9 @@ macro_rules! def_array_enum { fn getitem(&self, needle: Either, vm: &VirtualMachine) -> PyResult { match needle { Either::A(i) => { - let i = match self.idx(i, "array", vm) { - Ok(v) => v, - Err(e) => return Err(e), - }; - self.getitem_by_idx(i, vm).unwrap() + self.idx(i, "array", vm).map(|i| { + self.getitem_by_idx(i, vm).unwrap() + }) } Either::B(_slice) => Err(vm.new_not_implemented_error("array slice is not implemented".to_owned())), } @@ -214,7 +212,7 @@ macro_rules! def_array_enum { } } - fn iter<'a>(&'a self, vm: &'a VirtualMachine) -> impl Iterator + 'a { + fn iter<'a>(&'a self, vm: &'a VirtualMachine) -> impl Iterator + 'a { let mut i = 0; std::iter::from_fn(move || { let ret = self.getitem_by_idx(i, vm); @@ -379,7 +377,7 @@ impl PyArray { Err(vm.new_index_error("pop from empty array".to_owned())) } else { let i = self.borrow_value().idx(i.unwrap_or(-1), "pop", vm)?; - self.borrow_value_mut().pop(i, vm) + Ok(self.borrow_value_mut().pop(i, vm)) } } @@ -393,7 +391,7 @@ impl PyArray { let array = self.borrow_value(); let mut v = Vec::with_capacity(array.len()); for obj in array.iter(vm) { - v.push(obj?); + v.push(obj); } Ok(vm.ctx.new_list(v)) } @@ -428,7 +426,7 @@ impl PyArray { Ok(vm.new_bool(false)) } else { for (a, b) in lhs.iter(vm).zip(rhs.iter(vm)) { - let ne = objbool::boolval(vm, vm._ne(a?, b?)?)?; + let ne = objbool::boolval(vm, vm._ne(a, b)?)?; if ne { return Ok(vm.new_bool(false)); } @@ -445,7 +443,7 @@ impl PyArray { let rhs = rhs.borrow_value(); for (a, b) in lhs.iter(vm).zip(rhs.iter(vm)) { - let lt = objbool::boolval(vm, vm._lt(a?, b?)?)?; + let lt = objbool::boolval(vm, vm._lt(a, b)?)?; if lt { return Ok(vm.new_bool(true)); @@ -463,7 +461,7 @@ impl PyArray { let rhs = rhs.borrow_value(); for (a, b) in lhs.iter(vm).zip(rhs.iter(vm)) { - let le = objbool::boolval(vm, vm._le(a?, b?)?)?; + let le = objbool::boolval(vm, vm._le(a, b)?)?; if le { return Ok(vm.new_bool(true)); @@ -481,7 +479,7 @@ impl PyArray { let rhs = rhs.borrow_value(); for (a, b) in lhs.iter(vm).zip(rhs.iter(vm)) { - let gt = objbool::boolval(vm, vm._gt(a?, b?)?)?; + let gt = objbool::boolval(vm, vm._gt(a, b)?)?; if gt { return Ok(vm.new_bool(true)); @@ -499,7 +497,7 @@ impl PyArray { let rhs = rhs.borrow_value(); for (a, b) in lhs.iter(vm).zip(rhs.iter(vm)) { - let ge = objbool::boolval(vm, vm._ge(a?, b?)?)?; + let ge = objbool::boolval(vm, vm._ge(a, b)?)?; if ge { return Ok(vm.new_bool(true)); @@ -542,7 +540,7 @@ impl PyArrayIter { fn next(&self, vm: &VirtualMachine) -> PyResult { let pos = self.position.fetch_add(1); if let Some(item) = self.array.borrow_value().getitem_by_idx(pos, vm) { - Ok(item?) + Ok(item) } else { Err(objiter::new_stop_iteration(vm)) } diff --git a/vm/src/stdlib/csv.rs b/vm/src/stdlib/csv.rs index 452650c75..7db15d984 100644 --- a/vm/src/stdlib/csv.rs +++ b/vm/src/stdlib/csv.rs @@ -68,7 +68,7 @@ pub fn build_reader( ) -> PyResult { let config = ReaderOption::new(args, vm)?; - Reader::new(iterable, config).into_ref(vm).into_pyobject(vm) + Ok(Reader::new(iterable, config).into_ref(vm).into_pyobject(vm)) } fn into_strings(iterable: &PyIterable, vm: &VirtualMachine) -> PyResult> { @@ -152,7 +152,7 @@ impl Reader { #[pymethod(name = "__iter__")] fn iter(this: PyRef, vm: &VirtualMachine) -> PyResult { this.state.write().cast_to_reader(vm)?; - this.into_pyobject(vm) + Ok(this.into_pyobject(vm)) } #[pymethod(name = "__next__")] @@ -167,7 +167,7 @@ impl Reader { let iter = records .into_iter() .map(|bytes| bytes.into_pyobject(vm)) - .collect::>>()?; + .collect::>(); Ok(vm.ctx.new_list(iter)) } Err(_err) => { diff --git a/vm/src/stdlib/socket.rs b/vm/src/stdlib/socket.rs index 8238c4d64..2ae76905e 100644 --- a/vm/src/stdlib/socket.rs +++ b/vm/src/stdlib/socket.rs @@ -551,7 +551,7 @@ fn socket_getaddrinfo(opts: GAIOptions, vm: &VirtualMachine) -> PyResult { Some(s) => vm.new_str(s), None => vm.get_none(), }, - get_addr_tuple(ai.sockaddr).into_pyobject(vm).unwrap(), + get_addr_tuple(ai.sockaddr).into_pyobject(vm), ]) }) }) diff --git a/vm/src/stdlib/ssl.rs b/vm/src/stdlib/ssl.rs index 0263f748c..a862cb8e0 100644 --- a/vm/src/stdlib/ssl.rs +++ b/vm/src/stdlib/ssl.rs @@ -770,7 +770,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef { // Constants "OPENSSL_VERSION" => ctx.new_str(openssl::version::version().to_owned()), "OPENSSL_VERSION_NUMBER" => ctx.new_int(openssl::version::number()), - "OPENSSL_VERSION_INFO" => parse_version_info(openssl::version::number()).into_pyobject(vm).unwrap(), + "OPENSSL_VERSION_INFO" => parse_version_info(openssl::version::number()).into_pyobject(vm), "PROTOCOL_SSLv2" => ctx.new_int(SslVersion::Ssl2 as u32), "PROTOCOL_SSLv3" => ctx.new_int(SslVersion::Ssl3 as u32), "PROTOCOL_SSLv23" => ctx.new_int(SslVersion::Tls as u32), diff --git a/vm/src/stdlib/string.rs b/vm/src/stdlib/string.rs index 8319f04b8..8e73815c8 100644 --- a/vm/src/stdlib/string.rs +++ b/vm/src/stdlib/string.rs @@ -21,7 +21,7 @@ mod _string { format_spec: Option, preconversion_spec: Option, vm: &VirtualMachine, - ) -> PyResult { + ) -> PyObjectRef { let tuple = ( literal, field_name, @@ -51,7 +51,7 @@ mod _string { Some(format_spec), preconversion_spec, vm, - )?); + )); } FormatPart::Literal(text) => literal.push_str(&text), } @@ -63,7 +63,7 @@ mod _string { None, None, vm, - )?); + )); } Ok(result.into()) } @@ -77,17 +77,17 @@ mod _string { let first = match field_name.field_type { FieldType::Auto => vm.new_str("".to_owned()), - FieldType::Index(index) => index.into_pyobject(vm)?, - FieldType::Keyword(attribute) => attribute.into_pyobject(vm)?, + FieldType::Index(index) => index.into_pyobject(vm), + FieldType::Keyword(attribute) => attribute.into_pyobject(vm), }; let rest = field_name .parts .iter() .map(|p| match p { - FieldNamePart::Attribute(attribute) => (true, attribute).into_pyobject(vm).unwrap(), - FieldNamePart::StringIndex(index) => (false, index).into_pyobject(vm).unwrap(), - FieldNamePart::Index(index) => (false, *index).into_pyobject(vm).unwrap(), + FieldNamePart::Attribute(attribute) => (true, attribute).into_pyobject(vm), + FieldNamePart::StringIndex(index) => (false, index).into_pyobject(vm), + FieldNamePart::Index(index) => (false, *index).into_pyobject(vm), }) .collect(); diff --git a/vm/src/sysmodule.rs b/vm/src/sysmodule.rs index b9f74875d..590e91f65 100644 --- a/vm/src/sysmodule.rs +++ b/vm/src/sysmodule.rs @@ -576,12 +576,8 @@ settrace() -- set the global debug tracing function module_names.push("sys".to_owned()); module_names.push("builtins".to_owned()); module_names.sort(); - let builtin_module_names = ctx.new_tuple( - module_names - .iter() - .map(|v| v.into_pyobject(vm).unwrap()) - .collect(), - ); + let builtin_module_names = + ctx.new_tuple(module_names.iter().map(|v| v.into_pyobject(vm)).collect()); let modules = ctx.new_dict(); let prefix = option_env!("RUSTPYTHON_PREFIX").unwrap_or("/usr/local");