Skip to content

Commit bc2bb10

Browse files
committed
try to types utility functions to PyObjectRef methods
1 parent 3a0c2bb commit bc2bb10

10 files changed

Lines changed: 96 additions & 82 deletions

File tree

vm/src/builtins/complex.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ fn try_complex(obj: &PyObjectRef, vm: &VirtualMachine) -> PyResult<Option<(Compl
446446
if let Some(complex) = obj.payload_if_subclass::<PyComplex>(vm) {
447447
return Ok(Some((complex.value, true)));
448448
}
449-
if let Some(float) = float::try_float_opt(obj, vm)? {
449+
if let Some(float) = obj.try_to_f64(vm)? {
450450
return Ok(Some((Complex64::new(float, 0.0), false)));
451451
}
452452
Ok(None)

vm/src/builtins/float.rs

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{int, PyBytes, PyInt, PyIntRef, PyStr, PyStrRef, PyTypeRef};
1+
use super::{try_bigint_to_f64, PyBytes, PyInt, PyIntRef, PyStr, PyStrRef, PyTypeRef};
22
use crate::common::{float_ops, hash};
33
use crate::format::FormatSpec;
44
use crate::function::{OptionalArg, OptionalOption};
@@ -51,29 +51,31 @@ impl From<f64> for PyFloat {
5151
}
5252
}
5353

54-
pub fn try_float_opt(obj: &PyObjectRef, vm: &VirtualMachine) -> PyResult<Option<f64>> {
55-
if let Some(float) = obj.payload_if_exact::<PyFloat>(vm) {
56-
return Ok(Some(float.value));
57-
}
58-
if let Some(method) = vm.get_method(obj.clone(), "__float__") {
59-
let result = vm.invoke(&method?, ())?;
60-
// TODO: returning strict subclasses of float in __float__ is deprecated
61-
return match result.payload::<PyFloat>() {
62-
Some(float_obj) => Ok(Some(float_obj.value)),
63-
None => Err(vm.new_type_error(format!(
64-
"__float__ returned non-float (type '{}')",
65-
result.class().name()
66-
))),
67-
};
68-
}
69-
if let Some(r) = vm.to_index_opt(obj.clone()).transpose()? {
70-
return Ok(Some(int::to_float(r.as_bigint(), vm)?));
54+
impl PyObjectRef {
55+
pub fn try_to_f64(&self, vm: &VirtualMachine) -> PyResult<Option<f64>> {
56+
if let Some(float) = self.payload_if_exact::<PyFloat>(vm) {
57+
return Ok(Some(float.value));
58+
}
59+
if let Some(method) = vm.get_method(self.clone(), "__float__") {
60+
let result = vm.invoke(&method?, ())?;
61+
// TODO: returning strict subclasses of float in __float__ is deprecated
62+
return match result.payload::<PyFloat>() {
63+
Some(float_obj) => Ok(Some(float_obj.value)),
64+
None => Err(vm.new_type_error(format!(
65+
"__float__ returned non-float (type '{}')",
66+
result.class().name()
67+
))),
68+
};
69+
}
70+
if let Some(r) = vm.to_index_opt(self.clone()).transpose()? {
71+
return Ok(Some(try_bigint_to_f64(r.as_bigint(), vm)?));
72+
}
73+
Ok(None)
7174
}
72-
Ok(None)
7375
}
7476

7577
pub fn try_float(obj: &PyObjectRef, vm: &VirtualMachine) -> PyResult<f64> {
76-
try_float_opt(obj, vm)?.ok_or_else(|| {
78+
obj.try_to_f64(vm)?.ok_or_else(|| {
7779
vm.new_type_error(format!("must be real number, not {}", obj.class().name()))
7880
})
7981
}
@@ -82,7 +84,7 @@ pub(crate) fn to_op_float(obj: &PyObjectRef, vm: &VirtualMachine) -> PyResult<Op
8284
let v = if let Some(float) = obj.payload_if_subclass::<PyFloat>(vm) {
8385
Some(float.value)
8486
} else if let Some(int) = obj.payload_if_subclass::<PyInt>(vm) {
85-
Some(int::to_float(int.as_bigint(), vm)?)
87+
Some(try_bigint_to_f64(int.as_bigint(), vm)?)
8688
} else {
8789
None
8890
};
@@ -111,7 +113,7 @@ fn inner_mod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<f64> {
111113
.ok_or_else(|| vm.new_zero_division_error("float mod by zero".to_owned()))
112114
}
113115

114-
pub fn try_bigint(value: f64, vm: &VirtualMachine) -> PyResult<BigInt> {
116+
pub fn try_to_bigint(value: f64, vm: &VirtualMachine) -> PyResult<BigInt> {
115117
match value.to_bigint() {
116118
Some(int) => Ok(int),
117119
None => {
@@ -171,7 +173,7 @@ impl SlotConstructor for PyFloat {
171173
val
172174
};
173175

174-
if let Some(f) = try_float_opt(&val, vm)? {
176+
if let Some(f) = val.try_to_f64(vm)? {
175177
f
176178
} else if let Some(s) = val.payload_if_subclass::<PyStr>(vm) {
177179
float_ops::parse_str(s.as_str().trim()).ok_or_else(|| {
@@ -379,17 +381,17 @@ impl PyFloat {
379381

380382
#[pymethod(magic)]
381383
fn trunc(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
382-
try_bigint(self.value, vm)
384+
try_to_bigint(self.value, vm)
383385
}
384386

385387
#[pymethod(magic)]
386388
fn floor(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
387-
try_bigint(self.value.floor(), vm)
389+
try_to_bigint(self.value.floor(), vm)
388390
}
389391

390392
#[pymethod(magic)]
391393
fn ceil(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
392-
try_bigint(self.value.ceil(), vm)
394+
try_to_bigint(self.value.ceil(), vm)
393395
}
394396

395397
#[pymethod(magic)]
@@ -417,7 +419,7 @@ impl PyFloat {
417419
} else {
418420
self.value.round()
419421
};
420-
let int = try_bigint(value, vm)?;
422+
let int = try_to_bigint(value, vm)?;
421423
vm.ctx.new_int(int)
422424
};
423425
Ok(value)

vm/src/builtins/int.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
use super::{float, IntoPyBool, PyByteArray, PyBytes, PyStr, PyStrRef, PyTypeRef};
2+
use crate::bytesinner::PyBytesInner;
23
use crate::common::hash;
34
use crate::format::FormatSpec;
45
use crate::function::{OptionalArg, OptionalOption};
56
use crate::slots::{Comparable, Hashable, PyComparisonOp, SlotConstructor};
67
use crate::VirtualMachine;
7-
use crate::{bytesinner::PyBytesInner, byteslike::try_bytes_like};
88
use crate::{
99
try_value_from_borrowed_object, IdProtocol, IntoPyObject, IntoPyResult, PyArithmaticValue,
1010
PyClassImpl, PyComparisonValue, PyContext, PyObjectRef, PyRef, PyResult, PyValue,
@@ -142,8 +142,8 @@ pub fn bigint_unsigned_mask(v: &BigInt) -> u32 {
142142

143143
fn inner_pow(int1: &BigInt, int2: &BigInt, vm: &VirtualMachine) -> PyResult {
144144
if int2.is_negative() {
145-
let v1 = to_float(int1, vm)?;
146-
let v2 = to_float(int2, vm)?;
145+
let v1 = try_to_float(int1, vm)?;
146+
let v2 = try_to_float(int2, vm)?;
147147
float::float_pow(v1, v2, vm).into_pyresult(vm)
148148
} else {
149149
Ok(if let Some(v2) = int2.to_u64() {
@@ -541,7 +541,7 @@ impl PyInt {
541541

542542
#[pymethod(magic)]
543543
fn float(&self, vm: &VirtualMachine) -> PyResult<f64> {
544-
to_float(&self.value, vm)
544+
try_to_float(&self.value, vm)
545545
}
546546

547547
#[pymethod(magic)]
@@ -914,7 +914,7 @@ pub(crate) fn get_value(obj: &PyObjectRef) -> &BigInt {
914914
&obj.payload::<PyInt>().unwrap().value
915915
}
916916

917-
pub fn to_float(int: &BigInt, vm: &VirtualMachine) -> PyResult<f64> {
917+
pub fn try_to_float(int: &BigInt, vm: &VirtualMachine) -> PyResult<f64> {
918918
i2f(int).ok_or_else(|| vm.new_overflow_error("int too large to convert to float".to_owned()))
919919
}
920920
// num-bigint now returns Some(inf) for to_f64() in some cases, so just keep that the same for now
@@ -939,7 +939,7 @@ pub(crate) fn try_int(obj: &PyObjectRef, vm: &VirtualMachine) -> PyResult<BigInt
939939
if let Some(s) = obj.downcast_ref::<PyStr>() {
940940
return try_convert(obj, s.as_str().as_bytes(), vm);
941941
}
942-
if let Ok(r) = try_bytes_like(vm, obj, |x| try_convert(obj, x, vm)) {
942+
if let Ok(r) = obj.try_bytes_like(vm, |x| try_convert(obj, x, vm)) {
943943
return r;
944944
}
945945
// strict `int` check

vm/src/builtins/mod.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,5 +80,8 @@ pub(crate) mod zip;
8080
pub use zip::PyZip;
8181
pub(crate) mod genericalias;
8282

83+
pub use float::try_to_bigint as try_f64_to_bigint;
84+
pub use int::try_to_float as try_bigint_to_f64;
85+
8386
mod make_module;
8487
pub use make_module::{ascii, make_module, print};

vm/src/builtins/pybool.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,14 @@ impl TryFromBorrowedObject for bool {
2929
}
3030
}
3131

32+
impl PyObjectRef {
33+
pub fn try_into_bool(self, vm: &VirtualMachine) -> PyResult<bool> {
34+
boolval(vm, self)
35+
}
36+
}
37+
3238
/// Convert Python bool into Rust bool.
33-
pub fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<bool> {
39+
pub(crate) fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<bool> {
3440
if obj.is(&vm.ctx.true_value) {
3541
return Ok(true);
3642
}

vm/src/bytesinner.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use crate::builtins::bytes::{PyBytes, PyBytesRef};
44
use crate::builtins::int::{PyInt, PyIntRef};
55
use crate::builtins::pystr::{self, PyStr, PyStrRef};
66
use crate::builtins::PyTypeRef;
7-
use crate::byteslike::try_bytes_like;
87
use crate::cformat::CFormatBytes;
98
use crate::function::{OptionalArg, OptionalOption};
109
use crate::sliceable::PySliceableSequence;
@@ -320,10 +319,9 @@ impl PyBytesInner {
320319
// TODO: bytes can compare with any object implemented buffer protocol
321320
// but not memoryview, and not equal if compare with unicode str(PyStr)
322321
PyComparisonValue::from_option(
323-
try_bytes_like(vm, other, |other| {
324-
op.eval_ord(self.elements.as_slice().cmp(other))
325-
})
326-
.ok(),
322+
other
323+
.try_bytes_like(vm, |other| op.eval_ord(self.elements.as_slice().cmp(other)))
324+
.ok(),
327325
)
328326
}
329327

@@ -1238,7 +1236,7 @@ pub const fn is_py_ascii_whitespace(b: u8) -> bool {
12381236
}
12391237

12401238
pub fn bytes_from_object(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<Vec<u8>> {
1241-
if let Ok(elements) = try_bytes_like(vm, obj, |bytes| bytes.to_vec()) {
1239+
if let Ok(elements) = obj.try_bytes_like(vm, |bytes| bytes.to_vec()) {
12421240
return Ok(elements);
12431241
}
12441242

vm/src/byteslike.rs

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -77,27 +77,31 @@ impl TryFromBorrowedObject for ArgBytesLike {
7777
}
7878
}
7979

80-
pub fn try_bytes_like<R>(
81-
vm: &VirtualMachine,
82-
obj: &PyObjectRef,
83-
f: impl FnOnce(&[u8]) -> R,
84-
) -> PyResult<R> {
85-
let buffer = PyBuffer::try_from_borrowed_object(vm, obj)?;
86-
buffer.as_contiguous().map(|x| f(&*x)).ok_or_else(|| {
87-
vm.new_type_error("non-contiguous buffer is not a bytes-like object".to_owned())
88-
})
89-
}
90-
91-
pub fn try_rw_bytes_like<R>(
92-
vm: &VirtualMachine,
93-
obj: &PyObjectRef,
94-
f: impl FnOnce(&mut [u8]) -> R,
95-
) -> PyResult<R> {
96-
let buffer = PyBuffer::try_from_borrowed_object(vm, obj)?;
97-
buffer
98-
.as_contiguous_mut()
99-
.map(|mut x| f(&mut *x))
100-
.ok_or_else(|| vm.new_type_error("buffer is not a read-write bytes-like object".to_owned()))
80+
impl PyObjectRef {
81+
pub fn try_bytes_like<R>(
82+
&self,
83+
vm: &VirtualMachine,
84+
f: impl FnOnce(&[u8]) -> R,
85+
) -> PyResult<R> {
86+
let buffer = PyBuffer::try_from_borrowed_object(vm, self)?;
87+
buffer.as_contiguous().map(|x| f(&*x)).ok_or_else(|| {
88+
vm.new_type_error("non-contiguous buffer is not a bytes-like object".to_owned())
89+
})
90+
}
91+
92+
pub fn try_rw_bytes_like<R>(
93+
&self,
94+
vm: &VirtualMachine,
95+
f: impl FnOnce(&mut [u8]) -> R,
96+
) -> PyResult<R> {
97+
let buffer = PyBuffer::try_from_borrowed_object(vm, self)?;
98+
buffer
99+
.as_contiguous_mut()
100+
.map(|mut x| f(&mut *x))
101+
.ok_or_else(|| {
102+
vm.new_type_error("buffer is not a read-write bytes-like object".to_owned())
103+
})
104+
}
101105
}
102106

103107
impl ArgMemoryBuffer {

vm/src/cformat.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1+
//! Implementation of Printf-Style string formatting
2+
//! [https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting]
3+
14
use crate::buffer::PyBuffer;
2-
/// Implementation of Printf-Style string formatting
3-
/// [https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting]
4-
use crate::builtins::float::{try_bigint, IntoPyFloat, PyFloat};
5-
use crate::builtins::int::{self, PyInt};
6-
use crate::builtins::pystr::PyStr;
7-
use crate::builtins::{tuple, PyBytes};
5+
use crate::builtins::{
6+
float::IntoPyFloat, int, try_f64_to_bigint, tuple, PyBytes, PyFloat, PyInt, PyStr,
7+
};
88
use crate::common::float_ops;
9-
use crate::vm::VirtualMachine;
109
use crate::{
1110
ItemProtocol, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject, TypeProtocol,
11+
VirtualMachine,
1212
};
1313
use itertools::Itertools;
1414
use num_bigint::{BigInt, Sign};
@@ -403,7 +403,7 @@ impl CFormatSpec {
403403
}
404404
ref f @ PyFloat => {
405405
Ok(self
406-
.format_number(&try_bigint(f.to_f64(), vm)?)
406+
.format_number(&try_f64_to_bigint(f.to_f64(), vm)?)
407407
.into_bytes())
408408
}
409409
obj => {
@@ -477,7 +477,7 @@ impl CFormatSpec {
477477
Ok(self.format_number(i.as_bigint()))
478478
}
479479
ref f @ PyFloat => {
480-
Ok(self.format_number(&try_bigint(f.to_f64(), vm)?))
480+
Ok(self.format_number(&try_f64_to_bigint(f.to_f64(), vm)?))
481481
}
482482
obj => {
483483
if let Some(method) = vm.get_method(obj.clone(), "__int__") {

vm/src/stdlib/array.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ mod array {
1616
use crate::builtins::pytype::PyTypeRef;
1717
use crate::builtins::slice::PySliceRef;
1818
use crate::builtins::{PyByteArray, PyBytes, PyBytesRef, PyIntRef};
19-
use crate::byteslike::{try_bytes_like, ArgBytesLike};
19+
use crate::byteslike::ArgBytesLike;
2020
use crate::common::borrow::{BorrowedValue, BorrowedValueMut};
2121
use crate::common::lock::{
2222
PyMappedRwLockReadGuard, PyMappedRwLockWriteGuard, PyRwLock, PyRwLockReadGuard,
@@ -657,13 +657,13 @@ mod array {
657657
)));
658658
}
659659
} else if init.payload_is::<PyBytes>() || init.payload_is::<PyByteArray>() {
660-
try_bytes_like(vm, &init, |x| array.frombytes(x))?;
660+
init.try_bytes_like(vm, |x| array.frombytes(x))?;
661661
} else if let Ok(iter) = PyIterable::try_from_object(vm, init.clone()) {
662662
for obj in iter.iter(vm)? {
663663
array.push(obj?, vm)?;
664664
}
665665
} else {
666-
try_bytes_like(vm, &init, |x| array.frombytes(x))?;
666+
init.try_bytes_like(vm, |x| array.frombytes(x))?;
667667
}
668668
}
669669

vm/src/stdlib/math.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@ use num_bigint::BigInt;
77
use num_traits::{One, Signed, Zero};
88
use puruspe::{erf, erfc, gamma, ln_gamma};
99

10-
use crate::builtins::float::{self, IntoPyFloat, PyFloatRef};
11-
use crate::builtins::int::{self, PyInt, PyIntRef};
10+
use crate::builtins::{
11+
float::IntoPyFloat, try_bigint_to_f64, try_f64_to_bigint, PyFloatRef, PyInt, PyIntRef,
12+
};
1213
use crate::function::{Args, OptionalArg};
1314
use crate::utils::Either;
1415
use crate::vm::VirtualMachine;
@@ -359,8 +360,8 @@ fn math_trunc(value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
359360
fn math_ceil(value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
360361
let result_or_err = try_magic_method("__ceil__", vm, &value);
361362
if result_or_err.is_err() {
362-
if let Ok(Some(v)) = float::try_float_opt(&value, vm) {
363-
let v = float::try_bigint(v.ceil(), vm)?;
363+
if let Ok(Some(v)) = value.try_to_f64(vm) {
364+
let v = try_f64_to_bigint(v.ceil(), vm)?;
364365
return Ok(vm.ctx.new_int(v));
365366
}
366367
}
@@ -376,8 +377,8 @@ fn math_ceil(value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
376377
fn math_floor(value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
377378
let result_or_err = try_magic_method("__floor__", vm, &value);
378379
if result_or_err.is_err() {
379-
if let Ok(Some(v)) = float::try_float_opt(&value, vm) {
380-
let v = float::try_bigint(v.floor(), vm)?;
380+
if let Ok(Some(v)) = value.try_to_f64(vm) {
381+
let v = try_f64_to_bigint(v.floor(), vm)?;
381382
return Ok(vm.ctx.new_int(v));
382383
}
383384
}
@@ -401,14 +402,14 @@ fn math_ldexp(
401402
) -> PyResult<f64> {
402403
let value = match value {
403404
Either::A(f) => f.to_f64(),
404-
Either::B(z) => int::to_float(z.as_bigint(), vm)?,
405+
Either::B(z) => try_bigint_to_f64(z.as_bigint(), vm)?,
405406
};
406407

407408
if value == 0_f64 || !value.is_finite() {
408409
// NaNs, zeros and infinities are returned unchanged
409410
Ok(value)
410411
} else {
411-
let result = value * (2_f64).powf(int::to_float(i.as_bigint(), vm)?);
412+
let result = value * (2_f64).powf(try_bigint_to_f64(i.as_bigint(), vm)?);
412413
result_or_overflow(value, result, vm)
413414
}
414415
}

0 commit comments

Comments
 (0)