Skip to content

Commit 7a12d1e

Browse files
committed
Implement Number Protocol for PyType
1 parent 6e4c2fe commit 7a12d1e

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

vm/src/builtins/type.rs

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,8 @@ use super::{
22
mappingproxy::PyMappingProxy, object, union_, PyClassMethod, PyDictRef, PyList, PyStaticMethod,
33
PyStr, PyStrInterned, PyStrRef, PyTuple, PyTupleRef, PyWeak,
44
};
5-
use crate::common::{
6-
ascii,
7-
borrow::BorrowedValue,
8-
lock::{PyRwLock, PyRwLockReadGuard},
9-
};
105
use crate::{
6+
atomic_func,
117
builtins::{
128
descriptor::{
139
DescrObject, MemberDef, MemberDescrObject, MemberGetter, MemberKind, MemberSetter,
@@ -17,15 +13,22 @@ use crate::{
1713
PyBaseExceptionRef,
1814
},
1915
class::{PyClassImpl, StaticType},
20-
convert::ToPyObject,
16+
common::{
17+
ascii,
18+
borrow::BorrowedValue,
19+
lock::{PyRwLock, PyRwLockReadGuard},
20+
},
21+
convert::{ToPyObject, ToPyResult},
2122
function::{FuncArgs, KwArgs, OptionalArg, PySetterValue},
2223
identifier,
2324
protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
25+
types::AsNumber,
2426
types::{Callable, GetAttr, PyTypeFlags, PyTypeSlots, SetAttr},
2527
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
2628
};
2729
use indexmap::{map::Entry, IndexMap};
2830
use itertools::Itertools;
31+
use once_cell::sync::Lazy;
2932
use std::{borrow::Borrow, collections::HashSet, fmt, ops::Deref, pin::Pin, ptr::NonNull};
3033

3134
#[pyclass(module = false, name = "type")]
@@ -371,7 +374,7 @@ impl Py<PyType> {
371374
}
372375
}
373376

374-
#[pyclass(with(GetAttr, SetAttr, Callable), flags(BASETYPE))]
377+
#[pyclass(with(GetAttr, SetAttr, Callable, AsNumber), flags(BASETYPE))]
375378
impl PyType {
376379
// bound method for every type
377380
pub(crate) fn __new__(zelf: PyRef<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
@@ -1058,6 +1061,18 @@ impl Callable for PyType {
10581061
}
10591062
}
10601063

1064+
impl AsNumber for PyType {
1065+
fn as_number() -> &'static PyNumberMethods {
1066+
static AS_NUMBER: Lazy<PyNumberMethods> = Lazy::new(|| PyNumberMethods {
1067+
or: atomic_func!(|num, other, vm| {
1068+
or_(num.obj.to_owned(), other.to_owned(), vm).to_pyresult(vm)
1069+
}),
1070+
..PyNumberMethods::NOT_IMPLEMENTED
1071+
});
1072+
&AS_NUMBER
1073+
}
1074+
}
1075+
10611076
fn find_base_dict_descr(cls: &Py<PyType>, vm: &VirtualMachine) -> Option<PyObjectRef> {
10621077
cls.iter_base_chain().skip(1).find_map(|cls| {
10631078
// TODO: should actually be some translation of:

0 commit comments

Comments
 (0)