Skip to content

Commit dd84cd8

Browse files
committed
pybool::boolval -> PyObjectRef::try_into_bool
1 parent 51e9fae commit dd84cd8

File tree

10 files changed

+76
-82
lines changed

10 files changed

+76
-82
lines changed

vm/src/builtins/filter.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use super::pybool;
21
use super::pytype::PyTypeRef;
32
use crate::iterator;
43
use crate::slots::{PyIter, SlotConstructor};
@@ -64,7 +63,7 @@ impl PyIter for PyFilter {
6463
// iteration
6564
vm.invoke(predicate, vec![next_obj.clone()])?
6665
};
67-
if pybool::boolval(vm, predicate_value)? {
66+
if predicate_value.try_into_bool(vm)? {
6867
return Ok(next_obj);
6968
}
7069
}

vm/src/builtins/object.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use super::dict::{PyDict, PyDictRef};
22
use super::list::PyList;
3-
use super::pybool;
43
use super::pystr::{PyStr, PyStrRef};
54
use super::pytype::PyTypeRef;
65
use crate::builtins::pytype::PyType;
@@ -77,7 +76,7 @@ impl PyBaseObject {
7776
.unwrap();
7877
let value = match cmp(zelf, other, PyComparisonOp::Eq, vm)? {
7978
Either::A(obj) => PyArithmaticValue::from_object(vm, obj)
80-
.map(|obj| pybool::boolval(vm, obj))
79+
.map(|obj| obj.try_into_bool(vm))
8180
.transpose()?,
8281
Either::B(value) => value,
8382
};

vm/src/builtins/pybool.rs

Lines changed: 38 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -30,54 +30,50 @@ impl TryFromBorrowedObject for bool {
3030
}
3131

3232
impl PyObjectRef {
33+
/// Convert Python bool into Rust bool.
3334
pub fn try_into_bool(self, vm: &VirtualMachine) -> PyResult<bool> {
34-
boolval(vm, self)
35-
}
36-
}
37-
38-
/// Convert Python bool into Rust bool.
39-
pub(crate) fn boolval(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<bool> {
40-
if obj.is(&vm.ctx.true_value) {
41-
return Ok(true);
42-
}
43-
if obj.is(&vm.ctx.false_value) {
44-
return Ok(false);
45-
}
46-
let rs_bool = match vm.get_method(obj.clone(), "__bool__") {
47-
Some(method_or_err) => {
48-
// If descriptor returns Error, propagate it further
49-
let method = method_or_err?;
50-
let bool_obj = vm.invoke(&method, ())?;
51-
if !bool_obj.isinstance(&vm.ctx.types.bool_type) {
52-
return Err(vm.new_type_error(format!(
53-
"__bool__ should return bool, returned type {}",
54-
bool_obj.class().name()
55-
)));
56-
}
57-
58-
get_value(&bool_obj)
35+
if self.is(&vm.ctx.true_value) {
36+
return Ok(true);
37+
}
38+
if self.is(&vm.ctx.false_value) {
39+
return Ok(false);
5940
}
60-
None => match vm.get_method(obj, "__len__") {
41+
let rs_bool = match vm.get_method(self.clone(), "__bool__") {
6142
Some(method_or_err) => {
43+
// If descriptor returns Error, propagate it further
6244
let method = method_or_err?;
6345
let bool_obj = vm.invoke(&method, ())?;
64-
let int_obj = bool_obj.payload::<PyInt>().ok_or_else(|| {
65-
vm.new_type_error(format!(
66-
"'{}' object cannot be interpreted as an integer",
46+
if !bool_obj.isinstance(&vm.ctx.types.bool_type) {
47+
return Err(vm.new_type_error(format!(
48+
"__bool__ should return bool, returned type {}",
6749
bool_obj.class().name()
68-
))
69-
})?;
70-
71-
let len_val = int_obj.as_bigint();
72-
if len_val.sign() == Sign::Minus {
73-
return Err(vm.new_value_error("__len__() should return >= 0".to_owned()));
50+
)));
7451
}
75-
!len_val.is_zero()
52+
53+
get_value(&bool_obj)
7654
}
77-
None => true,
78-
},
79-
};
80-
Ok(rs_bool)
55+
None => match vm.get_method(self, "__len__") {
56+
Some(method_or_err) => {
57+
let method = method_or_err?;
58+
let bool_obj = vm.invoke(&method, ())?;
59+
let int_obj = bool_obj.payload::<PyInt>().ok_or_else(|| {
60+
vm.new_type_error(format!(
61+
"'{}' object cannot be interpreted as an integer",
62+
bool_obj.class().name()
63+
))
64+
})?;
65+
66+
let len_val = int_obj.as_bigint();
67+
if len_val.sign() == Sign::Minus {
68+
return Err(vm.new_value_error("__len__() should return >= 0".to_owned()));
69+
}
70+
!len_val.is_zero()
71+
}
72+
None => true,
73+
},
74+
};
75+
Ok(rs_bool)
76+
}
8177
}
8278

8379
/// bool(x) -> bool
@@ -111,7 +107,7 @@ impl SlotConstructor for PyBool {
111107
actual_type
112108
)));
113109
}
114-
let val = x.map_or(Ok(false), |val| boolval(vm, val))?;
110+
let val = x.map_or(Ok(false), |val| val.try_into_bool(vm))?;
115111
Ok(vm.ctx.new_bool(val))
116112
}
117113
}
@@ -208,7 +204,7 @@ impl IntoPyBool {
208204
impl TryFromObject for IntoPyBool {
209205
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
210206
Ok(IntoPyBool {
211-
value: boolval(vm, obj)?,
207+
value: obj.try_into_bool(vm)?,
212208
})
213209
}
214210
}

vm/src/codecs.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::borrow::Cow;
22
use std::collections::HashMap;
33
use std::ops::Range;
44

5-
use crate::builtins::{pybool, PyBytesRef, PyStr, PyStrRef, PyTuple, PyTupleRef};
5+
use crate::builtins::{PyBytesRef, PyStr, PyStrRef, PyTuple, PyTupleRef};
66
use crate::common::lock::PyRwLock;
77
use crate::exceptions::PyBaseExceptionRef;
88
use crate::VirtualMachine;
@@ -52,7 +52,7 @@ impl PyCodec {
5252

5353
pub fn is_text_codec(&self, vm: &VirtualMachine) -> PyResult<bool> {
5454
let is_text = vm.get_attribute_opt(self.0.clone().into_object(), "_is_text_encoding")?;
55-
is_text.map_or(Ok(true), |is_text| pybool::boolval(vm, is_text))
55+
is_text.map_or(Ok(true), |is_text| is_text.try_into_bool(vm))
5656
}
5757

5858
pub fn encode(

vm/src/frame.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use crate::builtins::pytype::PyTypeRef;
1717
use crate::builtins::slice::PySlice;
1818
use crate::builtins::traceback::PyTraceback;
1919
use crate::builtins::tuple::{PyTuple, PyTupleTyped};
20-
use crate::builtins::{list, pybool, set};
20+
use crate::builtins::{list, set};
2121
use crate::bytecode;
2222
use crate::common::boxvec::BoxVec;
2323
use crate::common::lock::PyMutex;
@@ -844,7 +844,7 @@ impl ExecutingFrame<'_> {
844844
_ => self.fatal("WithCleanupFinish expects a FinallyHandler block on stack"),
845845
};
846846

847-
let suppress_exception = pybool::boolval(vm, self.pop_value())?;
847+
let suppress_exception = self.pop_value().try_into_bool(vm)?;
848848

849849
vm.set_exception(prev_exc);
850850

@@ -957,7 +957,7 @@ impl ExecutingFrame<'_> {
957957
}
958958
bytecode::Instruction::JumpIfTrue { target } => {
959959
let obj = self.pop_value();
960-
let value = pybool::boolval(vm, obj)?;
960+
let value = obj.try_into_bool(vm)?;
961961
if value {
962962
self.jump(*target);
963963
}
@@ -966,7 +966,7 @@ impl ExecutingFrame<'_> {
966966

967967
bytecode::Instruction::JumpIfFalse { target } => {
968968
let obj = self.pop_value();
969-
let value = pybool::boolval(vm, obj)?;
969+
let value = obj.try_into_bool(vm)?;
970970
if !value {
971971
self.jump(*target);
972972
}
@@ -975,7 +975,7 @@ impl ExecutingFrame<'_> {
975975

976976
bytecode::Instruction::JumpIfTrueOrPop { target } => {
977977
let obj = self.last_value();
978-
let value = pybool::boolval(vm, obj)?;
978+
let value = obj.try_into_bool(vm)?;
979979
if value {
980980
self.jump(*target);
981981
} else {
@@ -986,7 +986,7 @@ impl ExecutingFrame<'_> {
986986

987987
bytecode::Instruction::JumpIfFalseOrPop { target } => {
988988
let obj = self.last_value();
989-
let value = pybool::boolval(vm, obj)?;
989+
let value = obj.try_into_bool(vm)?;
990990
if !value {
991991
self.jump(*target);
992992
} else {
@@ -1670,7 +1670,7 @@ impl ExecutingFrame<'_> {
16701670
bytecode::UnaryOperator::Plus => vm._pos(&a)?,
16711671
bytecode::UnaryOperator::Invert => vm._invert(&a)?,
16721672
bytecode::UnaryOperator::Not => {
1673-
let value = pybool::boolval(vm, a)?;
1673+
let value = a.try_into_bool(vm)?;
16741674
vm.ctx.new_bool(!value)
16751675
}
16761676
};
@@ -1689,7 +1689,7 @@ impl ExecutingFrame<'_> {
16891689
haystack: PyObjectRef,
16901690
) -> PyResult<bool> {
16911691
let found = vm._membership(haystack, needle)?;
1692-
pybool::boolval(vm, found)
1692+
found.try_into_bool(vm)
16931693
}
16941694

16951695
fn _not_in(
@@ -1699,7 +1699,7 @@ impl ExecutingFrame<'_> {
16991699
haystack: PyObjectRef,
17001700
) -> PyResult<bool> {
17011701
let found = vm._membership(haystack, needle)?;
1702-
Ok(!pybool::boolval(vm, found)?)
1702+
Ok(!found.try_into_bool(vm)?)
17031703
}
17041704

17051705
fn _is(&self, a: PyObjectRef, b: PyObjectRef) -> bool {

vm/src/stdlib/io.rs

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ mod _io {
8181
use crate::builtins::memory::PyMemoryView;
8282
use crate::builtins::{
8383
bytes::{PyBytes, PyBytesRef},
84-
pybool, pytype, PyByteArray, PyStr, PyStrRef, PyTypeRef,
84+
pytype, PyByteArray, PyStr, PyStrRef, PyTypeRef,
8585
};
8686
use crate::byteslike::{ArgBytesLike, ArgMemoryBuffer};
8787
use crate::common::borrow::{BorrowedValue, BorrowedValueMut};
@@ -113,7 +113,10 @@ mod _io {
113113
}
114114

115115
fn ensure_unclosed(file: &PyObjectRef, msg: &str, vm: &VirtualMachine) -> PyResult<()> {
116-
if pybool::boolval(vm, vm.get_attribute(file.clone(), "closed")?)? {
116+
if vm
117+
.get_attribute(file.clone(), "closed")?
118+
.try_into_bool(vm)?
119+
{
117120
Err(vm.new_value_error(msg.to_owned()))
118121
} else {
119122
Ok(())
@@ -288,7 +291,7 @@ mod _io {
288291
}
289292

290293
fn file_closed(file: &PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
291-
pybool::boolval(vm, vm.get_attribute(file.clone(), "closed")?)
294+
vm.get_attribute(file.clone(), "closed")?.try_into_bool(vm)
292295
}
293296
fn check_closed(file: &PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
294297
if file_closed(file, vm)? {
@@ -299,7 +302,7 @@ mod _io {
299302
}
300303

301304
fn check_readable(file: &PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
302-
if pybool::boolval(vm, vm.call_method(file, "readable", ())?)? {
305+
if vm.call_method(file, "readable", ())?.try_into_bool(vm)? {
303306
Ok(())
304307
} else {
305308
Err(new_unsupported_operation(
@@ -310,7 +313,7 @@ mod _io {
310313
}
311314

312315
fn check_writable(file: &PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
313-
if pybool::boolval(vm, vm.call_method(file, "writable", ())?)? {
316+
if vm.call_method(file, "writable", ())?.try_into_bool(vm)? {
314317
Ok(())
315318
} else {
316319
Err(new_unsupported_operation(
@@ -321,7 +324,7 @@ mod _io {
321324
}
322325

323326
fn check_seekable(file: &PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
324-
if pybool::boolval(vm, vm.call_method(file, "seekable", ())?)? {
327+
if vm.call_method(file, "seekable", ())?.try_into_bool(vm)? {
325328
Ok(())
326329
} else {
327330
Err(new_unsupported_operation(
@@ -520,7 +523,7 @@ mod _io {
520523
#[pyslot]
521524
fn tp_iternext(instance: &PyObjectRef, vm: &VirtualMachine) -> PyResult {
522525
let line = vm.call_method(instance, "readline", ())?;
523-
if !pybool::boolval(vm, line.clone())? {
526+
if !line.clone().try_into_bool(vm)? {
524527
Err(vm.new_stop_iteration())
525528
} else {
526529
Ok(line)
@@ -1812,7 +1815,7 @@ mod _io {
18121815
fn isatty(&self, vm: &VirtualMachine) -> PyResult {
18131816
// read.isatty() or write.isatty()
18141817
let res = self.read.isatty(vm)?;
1815-
if pybool::boolval(vm, res.clone())? {
1818+
if res.clone().try_into_bool(vm)? {
18161819
Ok(res)
18171820
} else {
18181821
self.write.isatty(vm)
@@ -2208,11 +2211,11 @@ mod _io {
22082211
let buffer = args.buffer;
22092212

22102213
let has_read1 = vm.get_attribute_opt(buffer.clone(), "read1")?.is_some();
2211-
let seekable = pybool::boolval(vm, vm.call_method(&buffer, "seekable", ())?)?;
2214+
let seekable = vm.call_method(&buffer, "seekable", ())?.try_into_bool(vm)?;
22122215

22132216
let codec = vm.state.codec_registry.lookup(encoding.as_str(), vm)?;
22142217

2215-
let encoder = if pybool::boolval(vm, vm.call_method(&buffer, "writable", ())?)? {
2218+
let encoder = if vm.call_method(&buffer, "writable", ())?.try_into_bool(vm)? {
22162219
let incremental_encoder =
22172220
codec.get_incremental_encoder(Some(errors.clone()), vm)?;
22182221
let encoding_name = vm.get_attribute_opt(incremental_encoder.clone(), "name")?;
@@ -2228,7 +2231,7 @@ mod _io {
22282231
None
22292232
};
22302233

2231-
let decoder = if pybool::boolval(vm, vm.call_method(&buffer, "readable", ())?)? {
2234+
let decoder = if vm.call_method(&buffer, "readable", ())?.try_into_bool(vm)? {
22322235
let incremental_decoder =
22332236
codec.get_incremental_decoder(Some(errors.clone()), vm)?;
22342237
// TODO: wrap in IncrementalNewlineDecoder if newlines == Universal | Passthrough

vm/src/stdlib/itertools.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ mod decl {
88
use std::fmt;
99

1010
use crate::builtins::int::{self, PyInt, PyIntRef};
11-
use crate::builtins::pybool;
1211
use crate::builtins::pytype::PyTypeRef;
1312
use crate::builtins::tuple::PyTupleRef;
1413
use crate::common::lock::{PyMutex, PyRwLock, PyRwLockWriteGuard};
@@ -136,7 +135,7 @@ mod decl {
136135
fn next(zelf: &PyRef<Self>, vm: &VirtualMachine) -> PyResult {
137136
loop {
138137
let sel_obj = call_next(vm, &zelf.selector)?;
139-
let verdict = pybool::boolval(vm, sel_obj.clone())?;
138+
let verdict = sel_obj.clone().try_into_bool(vm)?;
140139
let data_obj = call_next(vm, &zelf.data)?;
141140

142141
if verdict {
@@ -432,7 +431,7 @@ mod decl {
432431
let predicate = &zelf.predicate;
433432

434433
let verdict = vm.invoke(predicate, (obj.clone(),))?;
435-
let verdict = pybool::boolval(vm, verdict)?;
434+
let verdict = verdict.try_into_bool(vm)?;
436435
if verdict {
437436
Ok(obj)
438437
} else {
@@ -493,7 +492,7 @@ mod decl {
493492
let obj = call_next(vm, iterable)?;
494493
let pred = predicate.clone();
495494
let pred_value = vm.invoke(&pred.into_object(), (obj.clone(),))?;
496-
if !pybool::boolval(vm, pred_value)? {
495+
if !pred_value.try_into_bool(vm)? {
497496
zelf.start_flag.store(true);
498497
return Ok(obj);
499498
}
@@ -841,7 +840,7 @@ mod decl {
841840
vm.invoke(predicate, vec![obj.clone()])?
842841
};
843842

844-
if !pybool::boolval(vm, pred_value)? {
843+
if !pred_value.try_into_bool(vm)? {
845844
return Ok(obj);
846845
}
847846
}

vm/src/stdlib/json.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ mod machinery;
55
mod _json {
66
use super::*;
77
use crate::builtins::pystr::PyStrRef;
8-
use crate::builtins::{pybool, pytype::PyTypeRef};
8+
use crate::builtins::pytype::PyTypeRef;
99
use crate::exceptions::PyBaseExceptionRef;
1010
use crate::function::{FuncArgs, OptionalArg};
1111
use crate::iterator;
@@ -35,7 +35,7 @@ mod _json {
3535
type Args = PyObjectRef;
3636

3737
fn py_new(cls: PyTypeRef, ctx: Self::Args, vm: &VirtualMachine) -> PyResult {
38-
let strict = pybool::boolval(vm, vm.get_attribute(ctx.clone(), "strict")?)?;
38+
let strict = vm.get_attribute(ctx.clone(), "strict")?.try_into_bool(vm)?;
3939
let object_hook = vm.option_if_none(vm.get_attribute(ctx.clone(), "object_hook")?);
4040
let object_pairs_hook =
4141
vm.option_if_none(vm.get_attribute(ctx.clone(), "object_pairs_hook")?);

0 commit comments

Comments
 (0)