Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
migrate __bool__
  • Loading branch information
youknowone committed Dec 31, 2025
commit a798467930c7f0500577a7981b9aa2289387d50e
23 changes: 16 additions & 7 deletions crates/vm/src/builtins/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ use crate::{
class::PyClassImpl,
common::hash::PyHash,
function::{ArgIndex, FuncArgs, OptionalArg, PyComparisonValue},
protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods},
protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
types::{
AsMapping, AsSequence, Comparable, Hashable, IterNext, Iterable, PyComparisonOp,
AsMapping, AsNumber, AsSequence, Comparable, Hashable, IterNext, Iterable, PyComparisonOp,
Representable, SelfIter,
},
};
Expand Down Expand Up @@ -176,6 +176,7 @@ pub fn init(context: &Context) {
with(
Py,
AsMapping,
AsNumber,
AsSequence,
Hashable,
Comparable,
Expand Down Expand Up @@ -269,11 +270,6 @@ impl PyRange {
self.compute_length()
}

#[pymethod]
fn __bool__(&self) -> bool {
!self.is_empty()
}

#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef) {
let range_parameters: Vec<PyObjectRef> = [&self.start, &self.stop, &self.step]
Expand Down Expand Up @@ -426,6 +422,19 @@ impl AsSequence for PyRange {
}
}

impl AsNumber for PyRange {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
boolean: Some(|number, _vm| {
let zelf = number.obj.downcast_ref::<PyRange>().unwrap();
Ok(!zelf.is_empty())
}),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
}
}

impl Hashable for PyRange {
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
let length = zelf.compute_length();
Expand Down
30 changes: 15 additions & 15 deletions crates/vm/src/builtins/singletons.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,7 @@ impl Constructor for PyNone {
}

#[pyclass(with(Constructor, AsNumber, Representable))]
impl PyNone {
#[pymethod]
const fn __bool__(&self) -> bool {
false
}
}
impl PyNone {}

impl Representable for PyNone {
#[inline]
Expand Down Expand Up @@ -103,22 +98,27 @@ impl Constructor for PyNotImplemented {
}
}

#[pyclass(with(Constructor))]
#[pyclass(with(Constructor, AsNumber, Representable))]
impl PyNotImplemented {
// TODO: As per https://bugs.python.org/issue35712, using NotImplemented
// in boolean contexts will need to raise a DeprecationWarning in 3.9
// and, eventually, a TypeError.
#[pymethod]
const fn __bool__(&self) -> bool {
true
}

#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyStrRef {
vm.ctx.names.NotImplemented.to_owned()
}
}

impl AsNumber for PyNotImplemented {
fn as_number() -> &'static PyNumberMethods {
// TODO: As per https://bugs.python.org/issue35712, using NotImplemented
// in boolean contexts will need to raise a DeprecationWarning in 3.9
// and, eventually, a TypeError.
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
boolean: Some(|_number, _vm| Ok(true)),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
}
}

impl Representable for PyNotImplemented {
#[inline]
fn repr(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Expand Down
24 changes: 16 additions & 8 deletions crates/vm/src/builtins/tuple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ use crate::{
convert::{ToPyObject, TransmuteFromObject},
function::{ArgSize, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue},
iter::PyExactSizeIterator,
protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods},
protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
recursion::ReprGuard,
sequence::{OptionalRangeArgs, SequenceExt},
sliceable::{SequenceIndex, SliceableSequenceOp},
types::{
AsMapping, AsSequence, Comparable, Constructor, Hashable, IterNext, Iterable,
AsMapping, AsNumber, AsSequence, Comparable, Constructor, Hashable, IterNext, Iterable,
PyComparisonOp, Representable, SelfIter,
},
utils::collection_repr,
Expand Down Expand Up @@ -260,7 +260,7 @@ impl<T> PyTuple<PyRef<T>> {
#[pyclass(
itemsize = core::mem::size_of::<crate::PyObjectRef>(),
flags(BASETYPE, SEQUENCE, _MATCH_SELF),
with(AsMapping, AsSequence, Hashable, Comparable, Iterable, Constructor, Representable)
with(AsMapping, AsNumber, AsSequence, Hashable, Comparable, Iterable, Constructor, Representable)
)]
impl PyTuple {
#[pymethod]
Expand All @@ -286,11 +286,6 @@ impl PyTuple {
PyArithmeticValue::from_option(added.ok())
}

#[pymethod]
const fn __bool__(&self) -> bool {
!self.elements.is_empty()
}

#[pymethod]
fn count(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
let mut count: usize = 0;
Expand Down Expand Up @@ -423,6 +418,19 @@ impl AsSequence for PyTuple {
}
}

impl AsNumber for PyTuple {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
boolean: Some(|number, _vm| {
let zelf = number.obj.downcast_ref::<PyTuple>().unwrap();
Ok(!zelf.elements.is_empty())
}),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
}
}

impl Hashable for PyTuple {
#[inline]
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
Expand Down
25 changes: 17 additions & 8 deletions crates/vm/src/builtins/weakproxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ use crate::{
class::PyClassImpl,
common::hash::PyHash,
function::{OptionalArg, PyComparisonValue, PySetterValue},
protocol::{PyIter, PyIterReturn, PyMappingMethods, PySequenceMethods},
protocol::{PyIter, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
stdlib::builtins::reversed,
types::{
AsMapping, AsSequence, Comparable, Constructor, GetAttr, Hashable, IterNext, Iterable,
PyComparisonOp, Representable, SetAttr,
AsMapping, AsNumber, AsSequence, Comparable, Constructor, GetAttr, Hashable, IterNext,
Iterable, PyComparisonOp, Representable, SetAttr,
},
};
use std::sync::LazyLock;
Expand Down Expand Up @@ -68,6 +68,7 @@ crate::common::static_cell! {
SetAttr,
Constructor,
Comparable,
AsNumber,
AsSequence,
AsMapping,
Representable,
Expand All @@ -87,11 +88,6 @@ impl PyWeakProxy {
self.try_upgrade(vm)?.length(vm)
}

#[pymethod]
fn __bool__(&self, vm: &VirtualMachine) -> PyResult<bool> {
self.try_upgrade(vm)?.is_true(vm)
}

#[pymethod]
fn __bytes__(&self, vm: &VirtualMachine) -> PyResult {
self.try_upgrade(vm)?.bytes(vm)
Expand Down Expand Up @@ -171,6 +167,19 @@ impl SetAttr for PyWeakProxy {
}
}

impl AsNumber for PyWeakProxy {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: LazyLock<PyNumberMethods> = LazyLock::new(|| PyNumberMethods {
boolean: Some(|number, vm| {
let zelf = number.obj.downcast_ref::<PyWeakProxy>().unwrap();
zelf.try_upgrade(vm)?.is_true(vm)
}),
..PyNumberMethods::NOT_IMPLEMENTED
});
&AS_NUMBER
}
}

impl Comparable for PyWeakProxy {
fn cmp(
zelf: &Py<Self>,
Expand Down
25 changes: 17 additions & 8 deletions crates/vm/src/stdlib/collections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ mod _collections {
common::lock::{PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard},
function::{KwArgs, OptionalArg, PyComparisonValue},
iter::PyExactSizeIterator,
protocol::{PyIterReturn, PySequenceMethods},
protocol::{PyIterReturn, PyNumberMethods, PySequenceMethods},
recursion::ReprGuard,
sequence::{MutObjectSequenceOp, OptionalRangeArgs},
sliceable::SequenceIndexOp,
types::{
AsSequence, Comparable, Constructor, DefaultConstructor, Initializer, IterNext,
Iterable, PyComparisonOp, Representable, SelfIter,
AsNumber, AsSequence, Comparable, Constructor, DefaultConstructor, Initializer,
IterNext, Iterable, PyComparisonOp, Representable, SelfIter,
},
utils::collection_repr,
};
Expand Down Expand Up @@ -60,6 +60,7 @@ mod _collections {
with(
Constructor,
Initializer,
AsNumber,
AsSequence,
Comparable,
Iterable,
Expand Down Expand Up @@ -354,11 +355,6 @@ mod _collections {
self.borrow_deque().len()
}

#[pymethod]
fn __bool__(&self) -> bool {
!self.borrow_deque().is_empty()
}

#[pymethod]
fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
self.concat(&other, vm)
Expand Down Expand Up @@ -496,6 +492,19 @@ mod _collections {
}
}

impl AsNumber for PyDeque {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
boolean: Some(|number, _vm| {
let zelf = number.obj.downcast_ref::<PyDeque>().unwrap();
Ok(!zelf.borrow_deque().is_empty())
}),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
}
}

impl AsSequence for PyDeque {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: PySequenceMethods = PySequenceMethods {
Expand Down
24 changes: 17 additions & 7 deletions crates/vm/src/stdlib/ctypes/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ use crate::{
builtins::{PyBytes, PyDict, PyNone, PyStr, PyTuple, PyType, PyTypeRef},
class::StaticType,
function::FuncArgs,
protocol::{BufferDescriptor, PyBuffer},
types::{AsBuffer, Callable, Constructor, Initializer, Representable},
protocol::{BufferDescriptor, PyBuffer, PyNumberMethods},
types::{AsBuffer, AsNumber, Callable, Constructor, Initializer, Representable},
vm::thread::with_current_vm,
};
use alloc::borrow::Cow;
Expand Down Expand Up @@ -1772,7 +1772,10 @@ impl AsBuffer for PyCFuncPtr {
}
}

#[pyclass(flags(BASETYPE), with(Callable, Constructor, Representable, AsBuffer))]
#[pyclass(
flags(BASETYPE),
with(Callable, Constructor, AsNumber, Representable, AsBuffer)
)]
impl PyCFuncPtr {
// restype getter/setter
#[pygetset]
Expand Down Expand Up @@ -1848,11 +1851,18 @@ impl PyCFuncPtr {
.map(|stg| stg.flags.bits())
.unwrap_or(StgInfoFlags::empty().bits())
}
}

// bool conversion - check if function pointer is set
#[pymethod]
fn __bool__(&self) -> bool {
self.get_func_ptr() != 0
impl AsNumber for PyCFuncPtr {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
boolean: Some(|number, _vm| {
let zelf = number.obj.downcast_ref::<PyCFuncPtr>().unwrap();
Ok(zelf.get_func_ptr() != 0)
}),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
}
}

Expand Down
21 changes: 14 additions & 7 deletions crates/vm/src/stdlib/ctypes/pointer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ impl Initializer for PyCPointer {

#[pyclass(
flags(BASETYPE, IMMUTABLETYPE),
with(Constructor, Initializer, AsBuffer)
with(Constructor, Initializer, AsNumber, AsBuffer)
)]
impl PyCPointer {
/// Get the pointer value stored in buffer as usize
Expand All @@ -279,12 +279,6 @@ impl PyCPointer {
}
}

/// Pointer_bool: returns True if pointer is not NULL
#[pymethod]
fn __bool__(&self) -> bool {
self.get_ptr_value() != 0
}

/// contents getter - reads address from b_ptr and creates an instance of the pointed-to type
#[pygetset]
fn contents(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
Expand Down Expand Up @@ -779,6 +773,19 @@ impl PyCPointer {
}
}

impl AsNumber for PyCPointer {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
boolean: Some(|number, _vm| {
let zelf = number.obj.downcast_ref::<PyCPointer>().unwrap();
Ok(zelf.get_ptr_value() != 0)
}),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
}
}

impl AsBuffer for PyCPointer {
fn as_buffer(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyBuffer> {
let stg_info = zelf
Expand Down
8 changes: 0 additions & 8 deletions crates/vm/src/stdlib/ctypes/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1133,14 +1133,6 @@ impl PyCSimple {
self.0.base.read().clone()
}

/// return True if any byte in buffer is non-zero
#[pymethod]
fn __bool__(&self) -> bool {
let buffer = self.0.buffer.read();
// Simple_bool: memcmp(self->b_ptr, zeros, self->b_size)
buffer.iter().any(|&b| b != 0)
}

#[pygetset]
pub fn value(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
let zelf: &Py<Self> = instance
Expand Down
Loading
Loading