Skip to content

Improve: binary ops with Number Protocol #4615

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 2 additions & 0 deletions Lib/test/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,8 @@ def __contains__(self, key):
d = c.new_child(b=20, c=30)
self.assertEqual(d.maps, [{'b': 20, 'c': 30}, {'a': 1, 'b': 2}])

# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_union_operators(self):
cm1 = ChainMap(dict(a=1, b=2), dict(c=3, d=4))
cm2 = ChainMap(dict(a=10, e=5), dict(b=20, d=4))
Expand Down
4 changes: 1 addition & 3 deletions Lib/test/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -2466,9 +2466,7 @@ class Color(StrMixin, AllMixin, Flag):
self.assertEqual(Color.ALL.value, 7)
self.assertEqual(str(Color.BLUE), 'blue')

# TODO: RUSTPYTHON
@unittest.expectedFailure
@unittest.skipIf(sys.platform == "win32", "TODO: RUSTPYTHON, inconsistent test result on Windows due to threading")
@unittest.skip("TODO: RUSTPYTHON, inconsistent test result on Windows due to threading")
@threading_helper.reap_threads
def test_unique_composite(self):
# override __eq__ to be identity only
Expand Down
2 changes: 0 additions & 2 deletions Lib/test/test_xml_dom_minicompat.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ def test_emptynodelist___add__(self):
node_list = EmptyNodeList() + NodeList()
self.assertEqual(node_list, NodeList())

# TODO: RUSTPYTHON
@unittest.expectedFailure
def test_emptynodelist___radd__(self):
node_list = [1,2] + EmptyNodeList()
self.assertEqual(node_list, [1,2])
Expand Down
4 changes: 2 additions & 2 deletions common/src/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,10 @@ pub mod levenshtein {
if a == b {
return 0;
}
if (b'A'..=b'Z').contains(&a) {
if a.is_ascii_uppercase() {
a += b'a' - b'A';
}
if (b'A'..=b'Z').contains(&b) {
if b.is_ascii_uppercase() {
b += b'a' - b'A';
}
if a == b {
Expand Down
29 changes: 21 additions & 8 deletions derive-impl/src/pyclass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -548,14 +548,27 @@ where
other
),
};
quote_spanned! { ident.span() =>
class.set_str_attr(
#py_name,
ctx.make_funcdef(#py_name, Self::#ident)
#doc
#build_func,
ctx,
);
if py_name.starts_with("__") && py_name.ends_with("__") {
let name_ident = Ident::new(&py_name, ident.span());
quote_spanned! { ident.span() =>
class.set_attr(
ctx.names.#name_ident,
ctx.make_funcdef(#py_name, Self::#ident)
#doc
#build_func
.into(),
);
}
} else {
quote_spanned! { ident.span() =>
class.set_str_attr(
#py_name,
ctx.make_funcdef(#py_name, Self::#ident)
#doc
#build_func,
ctx,
);
}
}
};

Expand Down
1 change: 0 additions & 1 deletion rust-toolchain

This file was deleted.

2 changes: 2 additions & 0 deletions rust-toolchain.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[toolchain]
channel = "stable"
1 change: 1 addition & 0 deletions stdlib/src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub(crate) fn make_module(vm: &VirtualMachine) -> PyObjectRef {
let array = module
.get_attr("array", vm)
.expect("Expect array has array type.");
array.init_builtin_number_slots(&vm.ctx);

let collections_abc = vm
.import("collections.abc", None, 0)
Expand Down
27 changes: 25 additions & 2 deletions vm/src/builtins/bool.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
use super::{PyInt, PyStrRef, PyType, PyTypeRef};
use crate::{
class::PyClassImpl, convert::ToPyObject, function::OptionalArg, identifier, types::Constructor,
class::PyClassImpl,
convert::{ToPyObject, ToPyResult},
function::OptionalArg,
identifier,
protocol::PyNumberMethods,
types::{AsNumber, Constructor},
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromBorrowedObject,
VirtualMachine,
};
Expand Down Expand Up @@ -102,7 +107,7 @@ impl Constructor for PyBool {
}
}

#[pyclass(with(Constructor))]
#[pyclass(with(Constructor, AsNumber))]
impl PyBool {
#[pymethod(magic)]
fn repr(zelf: bool, vm: &VirtualMachine) -> PyStrRef {
Expand Down Expand Up @@ -166,6 +171,24 @@ impl PyBool {
}
}

impl AsNumber for PyBool {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
and: Some(|number, other, vm| {
PyBool::and(number.obj.to_owned(), other.to_owned(), vm).to_pyresult(vm)
}),
xor: Some(|number, other, vm| {
PyBool::xor(number.obj.to_owned(), other.to_owned(), vm).to_pyresult(vm)
}),
or: Some(|number, other, vm| {
PyBool::or(number.obj.to_owned(), other.to_owned(), vm).to_pyresult(vm)
}),
..PyInt::AS_NUMBER
};
&AS_NUMBER
}
}

pub(crate) fn init(context: &Context) {
PyBool::extend_class(context, context.types.bool_type);
}
Expand Down
15 changes: 8 additions & 7 deletions vm/src/builtins/bytearray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ use crate::{
VirtualMachine,
};
use bstr::ByteSlice;
use once_cell::sync::Lazy;
use std::mem::size_of;

#[pyclass(module = false, name = "bytearray", unhashable = true)]
Expand Down Expand Up @@ -859,14 +858,16 @@ impl AsSequence for PyByteArray {

impl AsNumber for PyByteArray {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: Lazy<PyNumberMethods> = Lazy::new(|| PyNumberMethods {
remainder: atomic_func!(|number, other, vm| {
PyByteArray::number_downcast(number)
.mod_(other.to_owned(), vm)
.to_pyresult(vm)
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
remainder: Some(|number, other, vm| {
if let Some(number) = number.obj.downcast_ref::<PyByteArray>() {
number.mod_(other.to_owned(), vm).to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
..PyNumberMethods::NOT_IMPLEMENTED
});
};
&AS_NUMBER
}
}
Expand Down
14 changes: 8 additions & 6 deletions vm/src/builtins/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -629,14 +629,16 @@ impl AsSequence for PyBytes {

impl AsNumber for PyBytes {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: Lazy<PyNumberMethods> = Lazy::new(|| PyNumberMethods {
remainder: atomic_func!(|number, other, vm| {
PyBytes::number_downcast(number)
.mod_(other.to_owned(), vm)
.to_pyresult(vm)
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
remainder: Some(|number, other, vm| {
if let Some(number) = number.obj.downcast_ref::<PyBytes>() {
number.mod_(other.to_owned(), vm).to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
..PyNumberMethods::NOT_IMPLEMENTED
});
};
&AS_NUMBER
}
}
Expand Down
32 changes: 13 additions & 19 deletions vm/src/builtins/complex.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use super::{float, PyStr, PyType, PyTypeRef};
use crate::{
atomic_func,
class::PyClassImpl,
convert::{ToPyObject, ToPyResult},
function::{
Expand All @@ -15,7 +14,6 @@ use crate::{
};
use num_complex::Complex64;
use num_traits::Zero;
use once_cell::sync::Lazy;
use rustpython_common::{float_ops, hash};
use std::num::Wrapping;

Expand Down Expand Up @@ -454,38 +452,34 @@ impl Hashable for PyComplex {

impl AsNumber for PyComplex {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: Lazy<PyNumberMethods> = Lazy::new(|| PyNumberMethods {
add: atomic_func!(|number, other, vm| {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
add: Some(|number, other, vm| {
PyComplex::number_op(number, other, |a, b, _vm| a + b, vm)
}),
subtract: atomic_func!(|number, other, vm| {
subtract: Some(|number, other, vm| {
PyComplex::number_op(number, other, |a, b, _vm| a - b, vm)
}),
multiply: atomic_func!(|number, other, vm| {
multiply: Some(|number, other, vm| {
PyComplex::number_op(number, other, |a, b, _vm| a * b, vm)
}),
power: atomic_func!(|number, other, vm| PyComplex::number_op(
number, other, inner_pow, vm
)),
negative: atomic_func!(|number, vm| {
power: Some(|number, other, vm| PyComplex::number_op(number, other, inner_pow, vm)),
negative: Some(|number, vm| {
let value = PyComplex::number_downcast(number).value;
(-value).to_pyresult(vm)
}),
positive: atomic_func!(
|number, vm| PyComplex::number_downcast_exact(number, vm).to_pyresult(vm)
),
absolute: atomic_func!(|number, vm| {
positive: Some(|number, vm| {
PyComplex::number_downcast_exact(number, vm).to_pyresult(vm)
}),
absolute: Some(|number, vm| {
let value = PyComplex::number_downcast(number).value;
value.norm().to_pyresult(vm)
}),
boolean: atomic_func!(|number, _vm| Ok(PyComplex::number_downcast(number)
.value
.is_zero())),
true_divide: atomic_func!(|number, other, vm| {
boolean: Some(|number, _vm| Ok(PyComplex::number_downcast(number).value.is_zero())),
true_divide: Some(|number, other, vm| {
PyComplex::number_op(number, other, inner_div, vm)
}),
..PyNumberMethods::NOT_IMPLEMENTED
});
};
&AS_NUMBER
}

Expand Down
Loading