Rename members

This commit is contained in:
Jeong YunWon committed 2025-06-27 12:32:59 +09:00
1 parent ef3cf70e30
commit 993ea8923c
70 files changed
+1500 -1319

No files matched your search

+36 -3
View File
@@ -752,6 +752,13 @@ where
let raw = item_meta.raw()?;
let sig_doc = text_signature(func.sig(), &py_name);
// Add #[allow(non_snake_case)] for setter methods like set___name__
let method_name = ident.to_string();
if method_name.starts_with("set_") && method_name.contains("__") {
let allow_attr: Attribute = parse_quote!(#[allow(non_snake_case)]);
args.attrs.push(allow_attr);
}
let doc = args.attrs.doc().map(|doc| format_doc(&sig_doc, &doc));
args.context.method_items.add_item(MethodNurseryItem {
py_name,
@@ -780,6 +787,13 @@ where
let item_meta = GetSetItemMeta::from_attr(ident.clone(), &item_attr)?;
let (py_name, kind) = item_meta.getset_name()?;
// Add #[allow(non_snake_case)] for setter methods
if matches!(kind, GetSetItemKind::Set) {
let allow_attr: Attribute = parse_quote!(#[allow(non_snake_case)]);
args.attrs.push(allow_attr);
}
args.context
.getset_items
.add_item(py_name, args.cfgs.to_vec(), kind, ident.clone())?;
@@ -934,6 +948,12 @@ where
_ => MemberKind::ObjectEx,
};
// Add #[allow(non_snake_case)] for setter methods
if matches!(member_item_kind, MemberItemKind::Set) {
let allow_attr: Attribute = parse_quote!(#[allow(non_snake_case)]);
args.attrs.push(allow_attr);
}
args.context.member_items.add_item(
py_name,
member_item_kind,
@@ -1342,7 +1362,7 @@ impl ItemMeta for SlotItemMeta {
impl SlotItemMeta {
fn slot_name(&self) -> Result<Ident> {
let inner = self.inner();
let slot_name = if let Some((_, meta)) = inner.meta_map.get("name") {
let method_name = if let Some((_, meta)) = inner.meta_map.get("name") {
match meta {
Meta::Path(path) => path.get_ident().cloned(),
_ => None,
@@ -1356,12 +1376,25 @@ impl SlotItemMeta {
};
Some(name)
};
slot_name.ok_or_else(|| {
let method_name = method_name.ok_or_else(|| {
err_span!(
inner.meta_ident,
"#[pyslot] must be of the form #[pyslot] or #[pyslot(slot_name)]",
)
})
})?;
// Strip double underscores from slot names like __init__ -> init
let method_name_str = method_name.to_string();
let slot_name = if method_name_str.starts_with("__")
&& method_name_str.ends_with("__")
&& method_name_str.len() > 4
{
&method_name_str[2..method_name_str.len() - 2]
} else {
&method_name_str
};
Ok(proc_macro2::Ident::new(slot_name, slot_name.span()))
}
}
-11
View File
@@ -64,17 +64,6 @@ pub fn derive_from_args(input: TokenStream) -> TokenStream {
/// but so does any object that implements `PyValue`.
/// Consider using `OptionalArg` for optional arguments.
/// #### Arguments
/// - `magic`: marks the method as a magic method: the method name is surrounded with double underscores.
/// ```rust, ignore
/// #[pyclass]
/// impl MyStruct {
/// // This will be called as the `__add__` method in Python.
/// #[pymethod(magic)]
/// fn add(&self, other: &Self) -> PyResult<i32> {
/// ...
/// }
/// }
/// ```
/// - `name`: the name of the method in Python,
/// by default it is the same as the Rust method, or surrounded by double underscores if magic is present.
/// This overrides `magic` and the default name and cannot be used with `magic` to prevent ambiguity.
+56 -52
View File
@@ -907,7 +907,7 @@ mod array {
range: OptionalRangeArgs,
vm: &VirtualMachine,
) -> PyResult<usize> {
let (start, stop) = range.saturate(self.len(), vm)?;
let (start, stop) = range.saturate(self.__len__(), vm)?;
self.read().index(x, start, stop, vm)
}
@@ -976,29 +976,29 @@ mod array {
self.write().reverse()
}
#[pymethod(magic)]
fn copy(&self) -> PyArray {
#[pymethod]
fn __copy__(&self) -> PyArray {
self.array.read().clone().into()
}
#[pymethod(magic)]
fn deepcopy(&self, _memo: PyObjectRef) -> PyArray {
self.copy()
#[pymethod]
fn __deepcopy__(&self, _memo: PyObjectRef) -> PyArray {
self.__copy__()
}
fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult {
fn getitem_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult {
match SequenceIndex::try_from_borrowed_object(vm, needle, "array")? {
SequenceIndex::Int(i) => self.read().getitem_by_index(i, vm),
SequenceIndex::Slice(slice) => self.read().getitem_by_slice(slice, vm),
}
}
#[pymethod(magic)]
fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self._getitem(&needle, vm)
#[pymethod]
fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.getitem_inner(&needle, vm)
}
fn _setitem(
fn setitem_inner(
zelf: &Py<Self>,
needle: &PyObject,
value: PyObjectRef,
@@ -1035,30 +1035,30 @@ mod array {
}
}
#[pymethod(magic)]
fn setitem(
#[pymethod]
fn __setitem__(
zelf: &Py<Self>,
needle: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
Self::_setitem(zelf, &needle, value, vm)
Self::setitem_inner(zelf, &needle, value, vm)
}
fn _delitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
fn delitem_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
match SequenceIndex::try_from_borrowed_object(vm, needle, "array")? {
SequenceIndex::Int(i) => self.try_resizable(vm)?.delitem_by_index(i, vm),
SequenceIndex::Slice(slice) => self.try_resizable(vm)?.delitem_by_slice(slice, vm),
}
}
#[pymethod(magic)]
fn delitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self._delitem(&needle, vm)
#[pymethod]
fn __delitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.delitem_inner(&needle, vm)
}
#[pymethod(magic)]
fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
if let Some(other) = other.payload::<PyArray>() {
self.read()
.add(&other.read(), vm)
@@ -1071,8 +1071,8 @@ mod array {
}
}
#[pymethod(magic)]
fn iadd(
#[pymethod]
fn __iadd__(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -1091,28 +1091,28 @@ mod array {
}
#[pymethod(name = "__rmul__")]
#[pymethod(magic)]
fn mul(&self, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __mul__(&self, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
self.read()
.mul(value, vm)
.map(|x| Self::from(x).into_ref(&vm.ctx))
}
#[pymethod(magic)]
fn imul(zelf: PyRef<Self>, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __imul__(zelf: PyRef<Self>, value: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
zelf.try_resizable(vm)?.imul(value, vm)?;
Ok(zelf)
}
#[pymethod(magic)]
pub(crate) fn len(&self) -> usize {
#[pymethod]
pub(crate) fn __len__(&self) -> usize {
self.read().len()
}
fn array_eq(&self, other: &Self, vm: &VirtualMachine) -> PyResult<bool> {
// we cannot use zelf.is(other) for shortcut because if we contenting a
// float value NaN we always return False even they are the same object.
if self.len() != other.len() {
if self.__len__() != other.__len__() {
return Ok(false);
}
let array_a = self.read();
@@ -1133,14 +1133,14 @@ mod array {
Ok(true)
}
#[pymethod(magic)]
fn reduce_ex(
#[pymethod]
fn __reduce_ex__(
zelf: &Py<Self>,
proto: usize,
vm: &VirtualMachine,
) -> PyResult<(PyObjectRef, PyTupleRef, Option<PyDictRef>)> {
if proto < 3 {
return Self::reduce(zelf, vm);
return Self::__reduce__(zelf, vm);
}
let array = zelf.read();
let cls = zelf.class().to_owned();
@@ -1157,8 +1157,8 @@ mod array {
))
}
#[pymethod(magic)]
fn reduce(
#[pymethod]
fn __reduce__(
zelf: &Py<Self>,
vm: &VirtualMachine,
) -> PyResult<(PyObjectRef, PyTupleRef, Option<PyDictRef>)> {
@@ -1179,8 +1179,8 @@ mod array {
))
}
#[pymethod(magic)]
fn contains(&self, value: PyObjectRef, vm: &VirtualMachine) -> bool {
#[pymethod]
fn __contains__(&self, value: PyObjectRef, vm: &VirtualMachine) -> bool {
let array = self.array.read();
for element in array
.iter(vm)
@@ -1272,7 +1272,7 @@ mod array {
let class = zelf.class();
let class_name = class.name();
if zelf.read().typecode() == 'u' {
if zelf.len() == 0 {
if zelf.__len__() == 0 {
return Ok(format!("{class_name}('u')"));
}
let to_unicode = zelf.tounicode(vm)?;
@@ -1303,16 +1303,18 @@ mod array {
impl AsMapping for PyArray {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: atomic_func!(|mapping, _vm| Ok(PyArray::mapping_downcast(mapping).len())),
length: atomic_func!(|mapping, _vm| Ok(
PyArray::mapping_downcast(mapping).__len__()
)),
subscript: atomic_func!(|mapping, needle, vm| {
PyArray::mapping_downcast(mapping)._getitem(needle, vm)
PyArray::mapping_downcast(mapping).getitem_inner(needle, vm)
}),
ass_subscript: atomic_func!(|mapping, needle, value, vm| {
let zelf = PyArray::mapping_downcast(mapping);
if let Some(value) = value {
PyArray::_setitem(zelf, needle, value, vm)
PyArray::setitem_inner(zelf, needle, value, vm)
} else {
zelf._delitem(needle, vm)
zelf.delitem_inner(needle, vm)
}
}),
};
@@ -1323,13 +1325,15 @@ mod array {
impl AsSequence for PyArray {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: PySequenceMethods = PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyArray::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PyArray::sequence_downcast(seq).__len__())),
concat: atomic_func!(|seq, other, vm| {
let zelf = PyArray::sequence_downcast(seq);
PyArray::add(zelf, other.to_owned(), vm).map(|x| x.into())
PyArray::__add__(zelf, other.to_owned(), vm).map(|x| x.into())
}),
repeat: atomic_func!(|seq, n, vm| {
PyArray::sequence_downcast(seq).mul(n, vm).map(|x| x.into())
PyArray::sequence_downcast(seq)
.__mul__(n, vm)
.map(|x| x.into())
}),
item: atomic_func!(|seq, i, vm| {
PyArray::sequence_downcast(seq)
@@ -1346,15 +1350,15 @@ mod array {
}),
contains: atomic_func!(|seq, target, vm| {
let zelf = PyArray::sequence_downcast(seq);
Ok(zelf.contains(target.to_owned(), vm))
Ok(zelf.__contains__(target.to_owned(), vm))
}),
inplace_concat: atomic_func!(|seq, other, vm| {
let zelf = PyArray::sequence_downcast(seq).to_owned();
PyArray::iadd(zelf, other.to_owned(), vm).map(|x| x.into())
PyArray::__iadd__(zelf, other.to_owned(), vm).map(|x| x.into())
}),
inplace_repeat: atomic_func!(|seq, n, vm| {
let zelf = PyArray::sequence_downcast(seq).to_owned();
PyArray::imul(zelf, n, vm).map(|x| x.into())
PyArray::__imul__(zelf, n, vm).map(|x| x.into())
}),
};
&AS_SEQUENCE
@@ -1388,15 +1392,15 @@ mod array {
#[pyclass(with(IterNext, Iterable), flags(HAS_DICT))]
impl PyArrayIter {
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal
.lock()
.set_state(state, |obj, pos| pos.min(obj.len()), vm)
.set_state(state, |obj, pos| pos.min(obj.__len__()), vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.builtins_iter_reduce(|x| x.clone().into(), vm)
+19 -9
View File
@@ -197,8 +197,12 @@ mod _contextvars {
}
}
#[pymethod(magic)]
fn getitem(&self, var: PyRef<ContextVar>, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
#[pymethod]
fn __getitem__(
&self,
var: PyRef<ContextVar>,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
let vars = self.borrow_vars();
let item = vars
.get(&*var)
@@ -206,13 +210,13 @@ mod _contextvars {
Ok(item.to_owned())
}
#[pymethod(magic)]
fn len(&self) -> usize {
#[pymethod]
fn __len__(&self) -> usize {
self.borrow_vars().len()
}
#[pymethod(magic)]
fn iter(&self) -> PyResult {
#[pymethod]
fn __iter__(&self) -> PyResult {
unimplemented!("Context.__iter__ is currently under construction")
}
@@ -256,7 +260,9 @@ mod _contextvars {
impl AsMapping for PyContext {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: atomic_func!(|mapping, _vm| Ok(PyContext::mapping_downcast(mapping).len())),
length: atomic_func!(|mapping, _vm| Ok(
PyContext::mapping_downcast(mapping).__len__()
)),
subscript: atomic_func!(|mapping, needle, vm| {
let needle = needle.try_to_value(vm)?;
let found = PyContext::mapping_downcast(mapping).get_inner(needle);
@@ -470,8 +476,12 @@ mod _contextvars {
Ok(())
}
#[pyclassmethod(magic)]
fn class_getitem(_cls: PyTypeRef, _key: PyStrRef, _vm: &VirtualMachine) -> PyResult<()> {
#[pyclassmethod]
fn __class_getitem__(
_cls: PyTypeRef,
_key: PyStrRef,
_vm: &VirtualMachine,
) -> PyResult<()> {
unimplemented!("ContextVar.__class_getitem__() is currently under construction")
}
}
+37 -35
View File
@@ -416,7 +416,7 @@ mod mmap {
fn as_buffer(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyBuffer> {
let buf = PyBuffer::new(
zelf.to_owned().into(),
BufferDescriptor::simple(zelf.len(), true),
BufferDescriptor::simple(zelf.__len__(), true),
&BUFFER_METHODS,
);
@@ -427,14 +427,16 @@ mod mmap {
impl AsMapping for PyMmap {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: atomic_func!(|mapping, _vm| Ok(PyMmap::mapping_downcast(mapping).len())),
length: atomic_func!(
|mapping, _vm| Ok(PyMmap::mapping_downcast(mapping).__len__())
),
subscript: atomic_func!(|mapping, needle, vm| {
PyMmap::mapping_downcast(mapping)._getitem(needle, vm)
PyMmap::mapping_downcast(mapping).getitem_inner(needle, vm)
}),
ass_subscript: atomic_func!(|mapping, needle, value, vm| {
let zelf = PyMmap::mapping_downcast(mapping);
if let Some(value) = value {
PyMmap::_setitem(zelf, needle, value, vm)
PyMmap::setitem_inner(zelf, needle, value, vm)
} else {
Err(vm
.new_type_error("mmap object doesn't support item deletion".to_owned()))
@@ -449,7 +451,7 @@ mod mmap {
fn as_sequence() -> &'static PySequenceMethods {
use std::sync::LazyLock;
static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyMmap::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PyMmap::sequence_downcast(seq).__len__())),
item: atomic_func!(|seq, i, vm| {
let zelf = PyMmap::sequence_downcast(seq);
zelf.getitem_by_index(i, vm)
@@ -494,8 +496,8 @@ mod mmap {
.into()
}
#[pymethod(magic)]
fn len(&self) -> usize {
#[pymethod]
fn __len__(&self) -> usize {
self.size.load()
}
@@ -571,7 +573,7 @@ mod mmap {
}
fn get_find_range(&self, options: FindOptions) -> (usize, usize) {
let size = self.len();
let size = self.__len__();
let start = options
.start
.map(|start| start.saturated_at(size))
@@ -625,7 +627,7 @@ mod mmap {
#[pymethod]
fn flush(&self, options: FlushOptions, vm: &VirtualMachine) -> PyResult<()> {
let (offset, size) = options
.values(self.len())
.values(self.__len__())
.ok_or_else(|| vm.new_value_error("flush values out of range"))?;
if self.access == AccessMode::Read || self.access == AccessMode::Copy {
@@ -647,7 +649,7 @@ mod mmap {
#[allow(unused_assignments)]
#[pymethod]
fn madvise(&self, options: AdviseOptions, vm: &VirtualMachine) -> PyResult<()> {
let (option, _start, _length) = options.values(self.len(), vm)?;
let (option, _start, _length) = options.values(self.__len__(), vm)?;
let advice = advice_try_from_i32(vm, option)?;
//TODO: memmap2 doesn't support madvise range right now.
@@ -690,7 +692,7 @@ mod mmap {
Some((dest, src, cnt))
}
let size = self.len();
let size = self.__len__();
let (dest, src, cnt) = args(dest, src, cnt, size, vm)
.ok_or_else(|| vm.new_value_error("source, destination, or count out of range"))?;
@@ -722,7 +724,7 @@ mod mmap {
.flatten();
let mmap = self.check_valid(vm)?;
let pos = self.pos();
let remaining = self.len().saturating_sub(pos);
let remaining = self.__len__().saturating_sub(pos);
let num_bytes = num_bytes
.filter(|&n| n >= 0 && (n as usize) <= remaining)
.map(|n| n as usize)
@@ -744,7 +746,7 @@ mod mmap {
#[pymethod]
fn read_byte(&self, vm: &VirtualMachine) -> PyResult<PyIntRef> {
let pos = self.pos();
if pos >= self.len() {
if pos >= self.__len__() {
return Err(vm.new_value_error("read byte out of range"));
}
@@ -763,7 +765,7 @@ mod mmap {
let pos = self.pos();
let mmap = self.check_valid(vm)?;
let remaining = self.len().saturating_sub(pos);
let remaining = self.__len__().saturating_sub(pos);
if remaining == 0 {
return Ok(PyBytes::from(vec![]).into_ref(&vm.ctx));
}
@@ -778,7 +780,7 @@ mod mmap {
let end_pos = if let Some(i) = eof {
pos + i + 1
} else {
self.len()
self.__len__()
};
let bytes = match mmap.deref().as_ref().unwrap() {
@@ -808,7 +810,7 @@ mod mmap {
vm: &VirtualMachine,
) -> PyResult<()> {
let how = whence.unwrap_or(0);
let size = self.len();
let size = self.__len__();
let new_pos = match how {
0 => dist, // relative to start
@@ -855,7 +857,7 @@ mod mmap {
#[pymethod]
fn write(&self, bytes: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyIntRef> {
let pos = self.pos();
let size = self.len();
let size = self.__len__();
let data = bytes.borrow_buf();
@@ -880,7 +882,7 @@ mod mmap {
let b = value_from_object(vm, &byte)?;
let pos = self.pos();
let size = self.len();
let size = self.__len__();
if pos >= size {
return Err(vm.new_value_error("write byte out of range"));
@@ -895,29 +897,29 @@ mod mmap {
Ok(())
}
#[pymethod(magic)]
fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
self._getitem(&needle, vm)
#[pymethod]
fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
self.getitem_inner(&needle, vm)
}
#[pymethod(magic)]
fn setitem(
#[pymethod]
fn __setitem__(
zelf: &Py<Self>,
needle: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
Self::_setitem(zelf, &needle, value, vm)
Self::setitem_inner(zelf, &needle, value, vm)
}
#[pymethod(magic)]
fn enter(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __enter__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
let _m = zelf.check_valid(vm)?;
Ok(zelf.to_owned())
}
#[pymethod(magic)]
fn exit(zelf: &Py<Self>, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __exit__(zelf: &Py<Self>, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
zelf.close(vm)
}
}
@@ -925,7 +927,7 @@ mod mmap {
impl PyMmap {
fn getitem_by_index(&self, i: isize, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
let i = i
.wrapped_at(self.len())
.wrapped_at(self.__len__())
.ok_or_else(|| vm.new_index_error("mmap index out of range"))?;
let b = match self.check_valid(vm)?.deref().as_ref().unwrap() {
@@ -941,7 +943,7 @@ mod mmap {
slice: &SaturatedSlice,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
let (range, step, slice_len) = slice.adjust_indices(self.len());
let (range, step, slice_len) = slice.adjust_indices(self.__len__());
let mmap = self.check_valid(vm)?;
@@ -976,14 +978,14 @@ mod mmap {
Ok(PyBytes::from(result_buf).into_ref(&vm.ctx).into())
}
fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
fn getitem_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
match SequenceIndex::try_from_borrowed_object(vm, needle, "mmap")? {
SequenceIndex::Int(i) => self.getitem_by_index(i, vm),
SequenceIndex::Slice(slice) => self.getitem_by_slice(&slice, vm),
}
}
fn _setitem(
fn setitem_inner(
zelf: &Py<Self>,
needle: &PyObject,
value: PyObjectRef,
@@ -1002,7 +1004,7 @@ mod mmap {
vm: &VirtualMachine,
) -> PyResult<()> {
let i: usize = i
.wrapped_at(self.len())
.wrapped_at(self.__len__())
.ok_or_else(|| vm.new_index_error("mmap index out of range"))?;
let b = value_from_object(vm, &value)?;
@@ -1020,7 +1022,7 @@ mod mmap {
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
let (range, step, slice_len) = slice.adjust_indices(self.len());
let (range, step, slice_len) = slice.adjust_indices(self.__len__());
let bytes = bytes_from_object(vm, &value)?;
@@ -1079,7 +1081,7 @@ mod mmap {
let repr = format!(
"<mmap.mmap closed=False, access={}, length={}, pos={}, offset={}>",
access_str,
zelf.len(),
zelf.__len__(),
zelf.pos(),
zelf.offset
);
+2 -2
View File
@@ -191,8 +191,8 @@ pub(crate) mod _struct {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl UnpackIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
#[pymethod]
fn __length_hint__(&self) -> usize {
self.buffer.len().saturating_sub(self.offset.load()) / self.format_spec.size
}
}
+4 -4
View File
@@ -722,14 +722,14 @@ mod decl {
Ok(vm.ctx.new_list(ret))
}
#[pymethod(magic)]
fn enter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __enter__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
zelf.get_epoll(vm)?;
Ok(zelf)
}
#[pymethod(magic)]
fn exit(
#[pymethod]
fn __exit__(
&self,
_exc_type: OptionalArg,
_exc_value: OptionalArg,
+8 -8
View File
@@ -1317,13 +1317,13 @@ mod _sqlite {
self.db_lock(vm)?.limit(category, limit, vm)
}
#[pymethod(magic)]
fn enter(zelf: PyRef<Self>) -> PyRef<Self> {
#[pymethod]
fn __enter__(zelf: PyRef<Self>) -> PyRef<Self> {
zelf
}
#[pymethod(magic)]
fn exit(
#[pymethod]
fn __exit__(
&self,
cls: PyObjectRef,
exc: PyObjectRef,
@@ -2090,13 +2090,13 @@ mod _sqlite {
}
}
#[pymethod(magic)]
fn enter(zelf: PyRef<Self>) -> PyRef<Self> {
#[pymethod]
fn __enter__(zelf: PyRef<Self>) -> PyRef<Self> {
zelf
}
#[pymethod(magic)]
fn exit(&self, _args: FuncArgs) {
#[pymethod]
fn __exit__(&self, _args: FuncArgs) {
self.close()
}
+1 -1
View File
@@ -404,7 +404,7 @@ mod zlib {
// TODO: This is an optional feature of Compress
// #[pymethod]
// #[pymethod(magic)]
// #[pymethod(name = "__copy__")]
// #[pymethod(name = "__deepcopy__")]
// fn copy(&self) -> Self {
// todo!("<flate2::Compress as Clone>")
+10 -10
View File
@@ -39,13 +39,13 @@ impl PyAsyncGen {
}
}
#[pygetset(magic)]
fn name(&self) -> PyStrRef {
#[pygetset]
fn __name__(&self) -> PyStrRef {
self.inner.name()
}
#[pygetset(magic, setter)]
fn set_name(&self, name: PyStrRef) {
#[pygetset(setter)]
fn set___name__(&self, name: PyStrRef) {
self.inner.set_name(name)
}
@@ -66,21 +66,21 @@ impl PyAsyncGen {
self.inner.frame().code.clone()
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
#[pyclass]
impl PyRef<PyAsyncGen> {
#[pymethod(magic)]
fn aiter(self, _vm: &VirtualMachine) -> PyRef<PyAsyncGen> {
#[pymethod]
fn __aiter__(self, _vm: &VirtualMachine) -> PyRef<PyAsyncGen> {
self
}
#[pymethod(magic)]
fn anext(self, vm: &VirtualMachine) -> PyAsyncGenASend {
#[pymethod]
fn __anext__(self, vm: &VirtualMachine) -> PyAsyncGenASend {
Self::asend(self, vm.ctx.none(), vm)
}
+14 -14
View File
@@ -110,8 +110,8 @@ impl Constructor for PyBool {
#[pyclass(with(Constructor, AsNumber, Representable))]
impl PyBool {
#[pymethod(magic)]
fn format(obj: PyObjectRef, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
#[pymethod]
fn __format__(obj: PyObjectRef, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
let new_bool = obj.try_to_bool(vm)?;
FormatSpec::parse(spec.as_str())
.and_then(|format_spec| format_spec.format_bool(new_bool))
@@ -119,8 +119,8 @@ impl PyBool {
}
#[pymethod(name = "__ror__")]
#[pymethod(magic)]
fn or(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __or__(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if lhs.fast_isinstance(vm.ctx.types.bool_type)
&& rhs.fast_isinstance(vm.ctx.types.bool_type)
{
@@ -128,15 +128,15 @@ impl PyBool {
let rhs = get_value(&rhs);
(lhs || rhs).to_pyobject(vm)
} else if let Some(lhs) = lhs.payload::<PyInt>() {
lhs.or(rhs, vm).to_pyobject(vm)
lhs.__or__(rhs, vm).to_pyobject(vm)
} else {
vm.ctx.not_implemented()
}
}
#[pymethod(name = "__rand__")]
#[pymethod(magic)]
fn and(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __and__(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if lhs.fast_isinstance(vm.ctx.types.bool_type)
&& rhs.fast_isinstance(vm.ctx.types.bool_type)
{
@@ -144,15 +144,15 @@ impl PyBool {
let rhs = get_value(&rhs);
(lhs && rhs).to_pyobject(vm)
} else if let Some(lhs) = lhs.payload::<PyInt>() {
lhs.and(rhs, vm).to_pyobject(vm)
lhs.__and__(rhs, vm).to_pyobject(vm)
} else {
vm.ctx.not_implemented()
}
}
#[pymethod(name = "__rxor__")]
#[pymethod(magic)]
fn xor(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __xor__(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
if lhs.fast_isinstance(vm.ctx.types.bool_type)
&& rhs.fast_isinstance(vm.ctx.types.bool_type)
{
@@ -160,7 +160,7 @@ impl PyBool {
let rhs = get_value(&rhs);
(lhs ^ rhs).to_pyobject(vm)
} else if let Some(lhs) = lhs.payload::<PyInt>() {
lhs.xor(rhs, vm).to_pyobject(vm)
lhs.__xor__(rhs, vm).to_pyobject(vm)
} else {
vm.ctx.not_implemented()
}
@@ -170,9 +170,9 @@ impl PyBool {
impl AsNumber for PyBool {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
and: Some(|a, b, vm| PyBool::and(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)),
xor: Some(|a, b, vm| PyBool::xor(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)),
or: Some(|a, b, vm| PyBool::or(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)),
and: Some(|a, b, vm| PyBool::__and__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)),
xor: Some(|a, b, vm| PyBool::__xor__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)),
or: Some(|a, b, vm| PyBool::__or__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)),
..PyInt::AS_NUMBER
};
&AS_NUMBER
+21 -18
View File
@@ -75,16 +75,16 @@ impl Callable for PyNativeFunction {
#[pyclass(with(Callable, Unconstructible), flags(HAS_DICT))]
impl PyNativeFunction {
#[pygetset(magic)]
fn module(zelf: NativeFunctionOrMethod) -> Option<&'static PyStrInterned> {
#[pygetset]
fn __module__(zelf: NativeFunctionOrMethod) -> Option<&'static PyStrInterned> {
zelf.0.module
}
#[pygetset(magic)]
fn name(zelf: NativeFunctionOrMethod) -> &'static str {
#[pygetset]
fn __name__(zelf: NativeFunctionOrMethod) -> &'static str {
zelf.0.value.name
}
#[pygetset(magic)]
fn qualname(zelf: NativeFunctionOrMethod, vm: &VirtualMachine) -> PyResult<PyStrRef> {
#[pygetset]
fn __qualname__(zelf: NativeFunctionOrMethod, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let zelf = zelf.0;
let flags = zelf.value.flags;
// if flags.contains(PyMethodFlags::CLASS) || flags.contains(PyMethodFlags::STATIC) {
@@ -105,25 +105,25 @@ impl PyNativeFunction {
};
Ok(qualname)
}
#[pygetset(magic)]
fn doc(zelf: NativeFunctionOrMethod) -> Option<&'static str> {
#[pygetset]
fn __doc__(zelf: NativeFunctionOrMethod) -> Option<&'static str> {
zelf.0.value.doc
}
#[pygetset(name = "__self__")]
fn __self__(_zelf: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.none()
}
#[pymethod(magic)]
fn reduce(&self) -> &'static str {
#[pymethod]
fn __reduce__(&self) -> &'static str {
// TODO: return (getattr, (self.object, self.name)) if this is a method
self.value.name
}
#[pymethod(magic)]
fn reduce_ex(zelf: PyObjectRef, _ver: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reduce_ex__(zelf: PyObjectRef, _ver: PyObjectRef, vm: &VirtualMachine) -> PyResult {
vm.call_special_method(&zelf, identifier!(vm, __reduce__), ())
}
#[pygetset(magic)]
fn text_signature(zelf: NativeFunctionOrMethod) -> Option<&'static str> {
#[pygetset]
fn __text_signature__(zelf: NativeFunctionOrMethod) -> Option<&'static str> {
let doc = zelf.0.value.doc?;
let signature = type_::get_text_signature_from_internal_doc(zelf.0.value.name, doc)?;
Some(signature)
@@ -151,16 +151,19 @@ pub struct PyNativeMethod {
flags(HAS_DICT)
)]
impl PyNativeMethod {
#[pygetset(magic)]
fn qualname(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
#[pygetset]
fn __qualname__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let prefix = zelf.class.name().to_string();
Ok(vm
.ctx
.new_str(format!("{}.{}", prefix, &zelf.func.value.name)))
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyResult<(PyObjectRef, (PyObjectRef, &'static str))> {
#[pymethod]
fn __reduce__(
&self,
vm: &VirtualMachine,
) -> PyResult<(PyObjectRef, (PyObjectRef, &'static str))> {
// TODO: return (getattr, (self.object, self.name)) if this is a method
let getattr = vm.builtins.get_attr("getattr", vm)?;
let target = self
+51 -45
View File
@@ -200,28 +200,28 @@ impl PyByteArray {
self.inner.write()
}
#[pymethod(magic)]
fn alloc(&self) -> usize {
#[pymethod]
fn __alloc__(&self) -> usize {
self.inner().capacity()
}
#[pymethod(magic)]
fn len(&self) -> usize {
#[pymethod]
fn __len__(&self) -> usize {
self.borrow_buf().len()
}
#[pymethod(magic)]
fn sizeof(&self) -> usize {
#[pymethod]
fn __sizeof__(&self) -> usize {
size_of::<Self>() + self.borrow_buf().len() * size_of::<u8>()
}
#[pymethod(magic)]
fn add(&self, other: ArgBytesLike) -> Self {
#[pymethod]
fn __add__(&self, other: ArgBytesLike) -> Self {
self.inner().add(&other.borrow_buf()).into()
}
#[pymethod(magic)]
fn contains(
#[pymethod]
fn __contains__(
&self,
needle: Either<PyBytesInner, PyIntRef>,
vm: &VirtualMachine,
@@ -229,21 +229,25 @@ impl PyByteArray {
self.inner().contains(needle, vm)
}
#[pymethod(magic)]
fn iadd(zelf: PyRef<Self>, other: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __iadd__(
zelf: PyRef<Self>,
other: ArgBytesLike,
vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> {
zelf.try_resizable(vm)?
.elements
.extend(&*other.borrow_buf());
Ok(zelf)
}
#[pymethod(magic)]
fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self._getitem(&needle, vm)
}
#[pymethod(magic)]
pub fn delitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
pub fn __delitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self._delitem(&needle, vm)
}
@@ -541,13 +545,13 @@ impl PyByteArray {
}
#[pymethod(name = "__rmul__")]
#[pymethod(magic)]
fn mul(&self, value: ArgSize, vm: &VirtualMachine) -> PyResult<Self> {
#[pymethod]
fn __mul__(&self, value: ArgSize, vm: &VirtualMachine) -> PyResult<Self> {
self.repeat(value.into(), vm)
}
#[pymethod(magic)]
fn imul(zelf: PyRef<Self>, value: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __imul__(zelf: PyRef<Self>, value: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
Self::irepeat(&zelf, value.into(), vm)?;
Ok(zelf)
}
@@ -558,8 +562,8 @@ impl PyByteArray {
Ok(formatted.into())
}
#[pymethod(magic)]
fn rmod(&self, _values: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __rmod__(&self, _values: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
@@ -571,8 +575,8 @@ impl PyByteArray {
#[pyclass]
impl Py<PyByteArray> {
#[pymethod(magic)]
fn setitem(
#[pymethod]
fn __setitem__(
&self,
needle: PyObjectRef,
value: PyObjectRef,
@@ -634,17 +638,17 @@ impl Py<PyByteArray> {
Ok(())
}
#[pymethod(magic)]
fn reduce_ex(
#[pymethod]
fn __reduce_ex__(
&self,
_proto: usize,
vm: &VirtualMachine,
) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) {
Self::reduce(self, vm)
self.__reduce__(vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) {
let bytes = PyBytes::from(self.borrow_buf().to_vec()).to_pyobject(vm);
(
self.class().to_owned(),
@@ -749,7 +753,7 @@ impl AsBuffer for PyByteArray {
fn as_buffer(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyBuffer> {
Ok(PyBuffer::new(
zelf.to_owned().into(),
BufferDescriptor::simple(zelf.len(), false),
BufferDescriptor::simple(zelf.__len__(), false),
&BUFFER_METHODS,
))
}
@@ -767,16 +771,18 @@ impl BufferResizeGuard for PyByteArray {
impl AsMapping for PyByteArray {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: atomic_func!(|mapping, _vm| Ok(PyByteArray::mapping_downcast(mapping).len())),
length: atomic_func!(|mapping, _vm| Ok(
PyByteArray::mapping_downcast(mapping).__len__()
)),
subscript: atomic_func!(|mapping, needle, vm| {
PyByteArray::mapping_downcast(mapping).getitem(needle.to_owned(), vm)
PyByteArray::mapping_downcast(mapping).__getitem__(needle.to_owned(), vm)
}),
ass_subscript: atomic_func!(|mapping, needle, value, vm| {
let zelf = PyByteArray::mapping_downcast(mapping);
if let Some(value) = value {
Py::setitem(zelf, needle.to_owned(), value, vm)
zelf.__setitem__(needle.to_owned(), value, vm)
} else {
zelf.delitem(needle.to_owned(), vm)
zelf.__delitem__(needle.to_owned(), vm)
}
}),
};
@@ -787,7 +793,7 @@ impl AsMapping for PyByteArray {
impl AsSequence for PyByteArray {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: PySequenceMethods = PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyByteArray::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PyByteArray::sequence_downcast(seq).__len__())),
concat: atomic_func!(|seq, other, vm| {
PyByteArray::sequence_downcast(seq)
.inner()
@@ -816,12 +822,12 @@ impl AsSequence for PyByteArray {
contains: atomic_func!(|seq, other, vm| {
let other =
<Either<PyBytesInner, PyIntRef>>::try_from_object(vm, other.to_owned())?;
PyByteArray::sequence_downcast(seq).contains(other, vm)
PyByteArray::sequence_downcast(seq).__contains__(other, vm)
}),
inplace_concat: atomic_func!(|seq, other, vm| {
let other = ArgBytesLike::try_from_object(vm, other.to_owned())?;
let zelf = PyByteArray::sequence_downcast(seq).to_owned();
PyByteArray::iadd(zelf, other, vm).map(|x| x.into())
PyByteArray::__iadd__(zelf, other, vm).map(|x| x.into())
}),
inplace_repeat: atomic_func!(|seq, n, vm| {
let zelf = PyByteArray::sequence_downcast(seq).to_owned();
@@ -885,22 +891,22 @@ impl PyPayload for PyByteArrayIterator {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl PyByteArrayIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.len())
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.__len__())
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.builtins_iter_reduce(|x| x.clone().into(), vm)
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal
.lock()
.set_state(state, |obj, pos| pos.min(obj.len()), vm)
.set_state(state, |obj, pos| pos.min(obj.__len__()), vm)
}
}
+30 -30
View File
@@ -145,9 +145,9 @@ impl PyRef<PyBytes> {
)
)]
impl PyBytes {
#[pymethod(magic)]
#[inline]
pub fn len(&self) -> usize {
#[pymethod]
pub fn __len__(&self) -> usize {
self.inner.len()
}
@@ -161,18 +161,18 @@ impl PyBytes {
self.inner.as_bytes()
}
#[pymethod(magic)]
fn sizeof(&self) -> usize {
#[pymethod]
fn __sizeof__(&self) -> usize {
size_of::<Self>() + self.len() * size_of::<u8>()
}
#[pymethod(magic)]
fn add(&self, other: ArgBytesLike) -> Vec<u8> {
#[pymethod]
fn __add__(&self, other: ArgBytesLike) -> Vec<u8> {
self.inner.add(&other.borrow_buf())
}
#[pymethod(magic)]
fn contains(
#[pymethod]
fn __contains__(
&self,
needle: Either<PyBytesInner, PyIntRef>,
vm: &VirtualMachine,
@@ -185,8 +185,8 @@ impl PyBytes {
PyBytesInner::maketrans(from, to, vm)
}
#[pymethod(magic)]
fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self._getitem(&needle, vm)
}
@@ -459,8 +459,8 @@ impl PyBytes {
}
#[pymethod(name = "__rmul__")]
#[pymethod(magic)]
fn mul(zelf: PyRef<Self>, value: ArgIndex, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __mul__(zelf: PyRef<Self>, value: ArgIndex, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
zelf.repeat(value.try_to_primitive(vm)?, vm)
}
@@ -470,13 +470,13 @@ impl PyBytes {
Ok(formatted.into())
}
#[pymethod(magic)]
fn rmod(&self, _values: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __rmod__(&self, _values: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
#[pymethod(magic)]
fn getnewargs(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __getnewargs__(&self, vm: &VirtualMachine) -> PyTupleRef {
let param: Vec<PyObjectRef> = self.elements().map(|x| x.to_pyobject(vm)).collect();
PyTuple::new_ref(param, &vm.ctx)
}
@@ -484,17 +484,17 @@ impl PyBytes {
#[pyclass]
impl Py<PyBytes> {
#[pymethod(magic)]
fn reduce_ex(
#[pymethod]
fn __reduce_ex__(
&self,
_proto: usize,
vm: &VirtualMachine,
) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) {
Self::reduce(self, vm)
self.__reduce__(vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option<PyDictRef>) {
let bytes = PyBytes::from(self.to_vec()).to_pyobject(vm);
(
self.class().to_owned(),
@@ -506,8 +506,8 @@ impl Py<PyBytes> {
#[pyclass]
impl PyRef<PyBytes> {
#[pymethod(magic)]
fn bytes(self, vm: &VirtualMachine) -> PyRef<PyBytes> {
#[pymethod]
fn __bytes__(self, vm: &VirtualMachine) -> PyRef<PyBytes> {
if self.is(vm.ctx.types.bytes_type) {
self
} else {
@@ -604,7 +604,7 @@ impl AsSequence for PyBytes {
contains: atomic_func!(|seq, other, vm| {
let other =
<Either<PyBytesInner, PyIntRef>>::try_from_object(vm, other.to_owned())?;
PyBytes::sequence_downcast(seq).contains(other, vm)
PyBytes::sequence_downcast(seq).__contains__(other, vm)
}),
..PySequenceMethods::NOT_IMPLEMENTED
});
@@ -690,20 +690,20 @@ impl PyPayload for PyBytesIterator {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl PyBytesIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.len())
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.builtins_iter_reduce(|x| x.clone().into(), vm)
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal
.lock()
.set_state(state, |obj, pos| pos.min(obj.len()), vm)
+21 -18
View File
@@ -124,46 +124,46 @@ impl PyClassMethod {
flags(BASETYPE, HAS_DICT)
)]
impl PyClassMethod {
#[pygetset(magic)]
fn func(&self) -> PyObjectRef {
#[pygetset]
fn __func__(&self) -> PyObjectRef {
self.callable.lock().clone()
}
#[pygetset(magic)]
fn wrapped(&self) -> PyObjectRef {
#[pygetset]
fn __wrapped__(&self) -> PyObjectRef {
self.callable.lock().clone()
}
#[pygetset(magic)]
fn module(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __module__(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__module__", vm)
}
#[pygetset(magic)]
fn qualname(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __qualname__(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__qualname__", vm)
}
#[pygetset(magic)]
fn name(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __name__(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__name__", vm)
}
#[pygetset(magic)]
fn annotations(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __annotations__(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__annotations__", vm)
}
#[pygetset(magic)]
fn isabstractmethod(&self, vm: &VirtualMachine) -> PyObjectRef {
#[pygetset]
fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyObjectRef {
match vm.get_attribute_opt(self.callable.lock().clone(), "__isabstractmethod__") {
Ok(Some(is_abstract)) => is_abstract,
_ => vm.ctx.new_bool(false).into(),
}
}
#[pygetset(magic, setter)]
fn set_isabstractmethod(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pygetset(setter)]
fn set___isabstractmethod__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.callable
.lock()
.set_attr("__isabstractmethod__", value, vm)?;
@@ -179,10 +179,13 @@ impl Representable for PyClassMethod {
let repr = match (
class
.qualname(vm)
.__qualname__(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str()),
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
class
.__module__(vm)
.downcast_ref::<PyStr>()
.map(|m| m.as_str()),
) {
(None, _) => return Err(vm.new_type_error("Unknown qualified name")),
(Some(qualname), Some(module)) if module != "builtins" => {
+28 -28
View File
@@ -255,8 +255,8 @@ impl PyComplex {
self.value.im
}
#[pymethod(magic)]
fn abs(&self, vm: &VirtualMachine) -> PyResult<f64> {
#[pymethod]
fn __abs__(&self, vm: &VirtualMachine) -> PyResult<f64> {
let Complex64 { im, re } = self.value;
let is_finite = im.is_finite() && re.is_finite();
let abs_result = re.hypot(im);
@@ -284,8 +284,8 @@ impl PyComplex {
}
#[pymethod(name = "__radd__")]
#[pymethod(magic)]
fn add(
#[pymethod]
fn __add__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -293,8 +293,8 @@ impl PyComplex {
self.op(other, |a, b| Ok(a + b), vm)
}
#[pymethod(magic)]
fn sub(
#[pymethod]
fn __sub__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -302,8 +302,8 @@ impl PyComplex {
self.op(other, |a, b| Ok(a - b), vm)
}
#[pymethod(magic)]
fn rsub(
#[pymethod]
fn __rsub__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -317,8 +317,8 @@ impl PyComplex {
}
#[pymethod(name = "__rmul__")]
#[pymethod(magic)]
fn mul(
#[pymethod]
fn __mul__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -326,8 +326,8 @@ impl PyComplex {
self.op(other, |a, b| Ok(a * b), vm)
}
#[pymethod(magic)]
fn truediv(
#[pymethod]
fn __truediv__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -335,8 +335,8 @@ impl PyComplex {
self.op(other, |a, b| inner_div(a, b, vm), vm)
}
#[pymethod(magic)]
fn rtruediv(
#[pymethod]
fn __rtruediv__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -344,18 +344,18 @@ impl PyComplex {
self.op(other, |a, b| inner_div(b, a, vm), vm)
}
#[pymethod(magic)]
fn pos(&self) -> Complex64 {
#[pymethod]
fn __pos__(&self) -> Complex64 {
self.value
}
#[pymethod(magic)]
fn neg(&self) -> Complex64 {
#[pymethod]
fn __neg__(&self) -> Complex64 {
-self.value
}
#[pymethod(magic)]
fn pow(
#[pymethod]
fn __pow__(
&self,
other: PyObjectRef,
mod_val: OptionalOption<PyObjectRef>,
@@ -368,8 +368,8 @@ impl PyComplex {
}
}
#[pymethod(magic)]
fn rpow(
#[pymethod]
fn __rpow__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -377,13 +377,13 @@ impl PyComplex {
self.op(other, |a, b| inner_pow(b, a, vm), vm)
}
#[pymethod(magic)]
fn bool(&self) -> bool {
#[pymethod]
fn __bool__(&self) -> bool {
!Complex64::is_zero(&self.value)
}
#[pymethod(magic)]
fn getnewargs(&self) -> (f64, f64) {
#[pymethod]
fn __getnewargs__(&self) -> (f64, f64) {
let Complex64 { re, im } = self.value;
(re, im)
}
@@ -391,8 +391,8 @@ impl PyComplex {
#[pyclass]
impl PyRef<PyComplex> {
#[pymethod(magic)]
fn complex(self, vm: &VirtualMachine) -> PyRef<PyComplex> {
#[pymethod]
fn __complex__(self, vm: &VirtualMachine) -> PyRef<PyComplex> {
if self.is(vm.ctx.types.complex_type) {
self
} else {
+4 -4
View File
@@ -34,13 +34,13 @@ impl PyCoroutine {
}
}
#[pygetset(magic)]
fn name(&self) -> PyStrRef {
#[pygetset]
fn __name__(&self) -> PyStrRef {
self.inner.name()
}
#[pygetset(magic, setter)]
fn set_name(&self, name: PyStrRef) {
#[pygetset(setter)]
fn set___name__(&self, name: PyStrRef) {
self.inner.set_name(name)
}
+16 -16
View File
@@ -109,31 +109,31 @@ impl PyMethodDescriptor {
flags(METHOD_DESCRIPTOR)
)]
impl PyMethodDescriptor {
#[pygetset(magic)]
fn name(&self) -> &'static PyStrInterned {
#[pygetset]
fn __name__(&self) -> &'static PyStrInterned {
self.common.name
}
#[pygetset(magic)]
fn qualname(&self) -> String {
#[pygetset]
fn __qualname__(&self) -> String {
format!("{}.{}", self.common.typ.name(), &self.common.name)
}
#[pygetset(magic)]
fn doc(&self) -> Option<&'static str> {
#[pygetset]
fn __doc__(&self) -> Option<&'static str> {
self.method.doc
}
#[pygetset(magic)]
fn text_signature(&self) -> Option<String> {
#[pygetset]
fn __text_signature__(&self) -> Option<String> {
self.method.doc.and_then(|doc| {
type_::get_text_signature_from_internal_doc(self.method.name, doc)
.map(|signature| signature.to_string())
})
}
#[pygetset(magic)]
fn objclass(&self) -> PyTypeRef {
#[pygetset]
fn __objclass__(&self) -> PyTypeRef {
self.objclass.to_owned()
}
#[pymethod(magic)]
fn reduce(
#[pymethod]
fn __reduce__(
&self,
vm: &VirtualMachine,
) -> (Option<PyObjectRef>, (Option<PyObjectRef>, &'static str)) {
@@ -243,13 +243,13 @@ fn calculate_qualname(descr: &PyDescriptorOwned, vm: &VirtualMachine) -> PyResul
#[pyclass(with(GetDescriptor, Unconstructible, Representable), flags(BASETYPE))]
impl PyMemberDescriptor {
#[pygetset(magic)]
fn doc(&self) -> Option<String> {
#[pygetset]
fn __doc__(&self) -> Option<String> {
self.member.doc.to_owned()
}
#[pygetset(magic)]
fn qualname(&self, vm: &VirtualMachine) -> PyResult<Option<String>> {
#[pygetset]
fn __qualname__(&self, vm: &VirtualMachine) -> PyResult<Option<String>> {
let qualname = self.common.qualname.read();
Ok(if qualname.is_none() {
drop(qualname);
+71 -64
View File
@@ -189,7 +189,7 @@ impl PyDict {
match d.downcast_exact::<PyDict>(vm) {
Ok(pydict) => {
for key in iterable.iter(vm)? {
pydict.setitem(key?, value.clone(), vm)?;
pydict.__setitem__(key?, value.clone(), vm)?;
}
Ok(pydict.into_pyref().into())
}
@@ -202,23 +202,23 @@ impl PyDict {
}
}
#[pymethod(magic)]
pub fn len(&self) -> usize {
#[pymethod]
pub fn __len__(&self) -> usize {
self.entries.len()
}
#[pymethod(magic)]
fn sizeof(&self) -> usize {
#[pymethod]
fn __sizeof__(&self) -> usize {
std::mem::size_of::<Self>() + self.entries.sizeof()
}
#[pymethod(magic)]
fn contains(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __contains__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
self.entries.contains(vm, &*key)
}
#[pymethod(magic)]
fn delitem(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __delitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.inner_delitem(&*key, vm)
}
@@ -227,8 +227,13 @@ impl PyDict {
self.entries.clear()
}
#[pymethod(magic)]
fn setitem(&self, key: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setitem__(
&self,
key: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
self.inner_setitem(&*key, value, vm)
}
@@ -279,8 +284,8 @@ impl PyDict {
Ok(())
}
#[pymethod(magic)]
fn or(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let other_dict: Result<PyDictRef, _> = other.downcast();
if let Ok(other) = other_dict {
let self_cp = self.copy();
@@ -315,8 +320,8 @@ impl PyDict {
Ok((key, value))
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
@@ -334,10 +339,10 @@ impl Py<PyDict> {
return Self::inner_cmp(self, other, PyComparisonOp::Eq, item, vm)
.map(|x| x.map(|eq| !eq));
}
if !op.eval_ord(self.len().cmp(&other.len())) {
if !op.eval_ord(self.__len__().cmp(&other.__len__())) {
return Ok(Implemented(false));
}
let (superset, subset) = if self.len() < other.len() {
let (superset, subset) = if self.__len__() < other.__len__() {
(other, self)
} else {
(self, other)
@@ -360,9 +365,9 @@ impl Py<PyDict> {
Ok(Implemented(true))
}
#[pymethod(magic)]
#[pymethod]
#[cfg_attr(feature = "flame-it", flame("PyDictRef"))]
fn getitem(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult {
fn __getitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.inner_getitem(&*key, vm)
}
}
@@ -384,19 +389,19 @@ impl PyRef<PyDict> {
PyDictItems::new(self)
}
#[pymethod(magic)]
fn reversed(self) -> PyDictReverseKeyIterator {
#[pymethod]
fn __reversed__(self) -> PyDictReverseKeyIterator {
PyDictReverseKeyIterator::new(self)
}
#[pymethod(magic)]
fn ior(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
#[pymethod]
fn __ior__(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
self.merge_object(other, vm)?;
Ok(self)
}
#[pymethod(magic)]
fn ror(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __ror__(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let other_dict: Result<PyDictRef, _> = other.downcast();
if let Ok(other) = other_dict {
let other_cp = other.copy();
@@ -424,7 +429,7 @@ impl Initializer for PyDict {
impl AsMapping for PyDict {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: atomic_func!(|mapping, _vm| Ok(PyDict::mapping_downcast(mapping).len())),
length: atomic_func!(|mapping, _vm| Ok(PyDict::mapping_downcast(mapping).__len__())),
subscript: atomic_func!(|mapping, needle, vm| {
PyDict::mapping_downcast(mapping).inner_getitem(needle, vm)
}),
@@ -458,14 +463,16 @@ impl AsNumber for PyDict {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
or: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PyDict>() {
PyDict::or(a, b.to_pyobject(vm), vm)
PyDict::__or__(a, b.to_pyobject(vm), vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
inplace_or: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PyDict>() {
a.to_owned().ior(b.to_pyobject(vm), vm).map(|d| d.into())
a.to_owned()
.__ior__(b.to_pyobject(vm), vm)
.map(|d| d.into())
} else {
Ok(vm.ctx.not_implemented())
}
@@ -500,7 +507,7 @@ impl Representable for PyDict {
#[inline]
fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let s = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
let mut str_parts = Vec::with_capacity(zelf.len());
let mut str_parts = Vec::with_capacity(zelf.__len__());
for (key, value) in zelf {
let key_repr = &key.repr(vm)?;
let value_repr = value.repr(vm)?;
@@ -733,13 +740,13 @@ trait DictView: PyPayload + PyClassDef + Iterable + Representable {
fn dict(&self) -> &PyDictRef;
fn item(vm: &VirtualMachine, key: PyObjectRef, value: PyObjectRef) -> PyObjectRef;
#[pymethod(magic)]
fn len(&self) -> usize {
self.dict().len()
#[pymethod]
fn __len__(&self) -> usize {
self.dict().__len__()
}
#[pymethod(magic)]
fn reversed(&self) -> Self::ReverseIter;
#[pymethod]
fn __reversed__(&self) -> Self::ReverseIter;
}
macro_rules! dict_view {
@@ -768,7 +775,7 @@ macro_rules! dict_view {
#[allow(clippy::redundant_closure_call)]
$result_fn(vm, key, value)
}
fn reversed(&self) -> Self::ReverseIter {
fn __reversed__(&self) -> Self::ReverseIter {
$reverse_iter_name::new(self.dict.clone())
}
}
@@ -789,7 +796,7 @@ macro_rules! dict_view {
#[inline]
fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let s = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
let mut str_parts = Vec::with_capacity(zelf.len());
let mut str_parts = Vec::with_capacity(zelf.__len__());
for (key, value) in zelf.dict().clone() {
let s = &Self::item(vm, key, value).repr(vm)?;
str_parts.push(s.as_str().to_owned());
@@ -830,14 +837,14 @@ macro_rules! dict_view {
}
}
#[pymethod(magic)]
fn length_hint(&self) -> usize {
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal.lock().length_hint(|_| self.size.entries_size)
}
#[allow(clippy::redundant_closure_call)]
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
let iter = builtins_iter(vm).to_owned();
let internal = self.internal.lock();
let entries = match &internal.status {
@@ -906,8 +913,8 @@ macro_rules! dict_view {
}
#[allow(clippy::redundant_closure_call)]
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
let iter = builtins_reversed(vm).to_owned();
let internal = self.internal.lock();
// TODO: entries must be reversed too
@@ -921,8 +928,8 @@ macro_rules! dict_view {
vm.new_tuple((iter, (vm.ctx.new_list(entries),)))
}
#[pymethod(magic)]
fn length_hint(&self) -> usize {
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal
.lock()
.rev_length_hint(|_| self.size.entries_size)
@@ -1009,45 +1016,45 @@ dict_view! {
#[pyclass]
trait ViewSetOps: DictView {
fn to_set(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PySetInner> {
let len = zelf.dict().len();
let len = zelf.dict().__len__();
let zelf: PyObjectRef = Self::iter(zelf, vm)?;
let iter = PyIterIter::new(vm, zelf, Some(len));
PySetInner::from_iter(iter, vm)
}
#[pymethod(name = "__rxor__")]
#[pymethod(magic)]
fn xor(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> {
#[pymethod]
fn __xor__(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> {
let zelf = Self::to_set(zelf, vm)?;
let inner = zelf.symmetric_difference(other, vm)?;
Ok(PySet { inner })
}
#[pymethod(name = "__rand__")]
#[pymethod(magic)]
fn and(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> {
#[pymethod]
fn __and__(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> {
let zelf = Self::to_set(zelf, vm)?;
let inner = zelf.intersection(other, vm)?;
Ok(PySet { inner })
}
#[pymethod(name = "__ror__")]
#[pymethod(magic)]
fn or(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> {
#[pymethod]
fn __or__(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> {
let zelf = Self::to_set(zelf, vm)?;
let inner = zelf.union(other, vm)?;
Ok(PySet { inner })
}
#[pymethod(magic)]
fn sub(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> {
#[pymethod]
fn __sub__(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> {
let zelf = Self::to_set(zelf, vm)?;
let inner = zelf.difference(other, vm)?;
Ok(PySet { inner })
}
#[pymethod(magic)]
fn rsub(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> {
#[pymethod]
fn __rsub__(zelf: PyRef<Self>, other: ArgIterable, vm: &VirtualMachine) -> PyResult<PySet> {
let left = PySetInner::from_iter(other.iter(vm)?, vm)?;
let right = ArgIterable::try_from_object(vm, Self::iter(zelf, vm)?)?;
let inner = left.difference(right, vm)?;
@@ -1108,8 +1115,8 @@ impl ViewSetOps for PyDictKeys {}
Representable
))]
impl PyDictKeys {
#[pymethod(magic)]
fn contains(zelf: PyObjectRef, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __contains__(zelf: PyObjectRef, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
zelf.to_sequence().contains(&key, vm)
}
@@ -1134,7 +1141,7 @@ impl Comparable for PyDictKeys {
impl AsSequence for PyDictKeys {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyDictKeys::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PyDictKeys::sequence_downcast(seq).__len__())),
contains: atomic_func!(|seq, target, vm| {
PyDictKeys::sequence_downcast(seq)
.dict
@@ -1172,8 +1179,8 @@ impl ViewSetOps for PyDictItems {}
Representable
))]
impl PyDictItems {
#[pymethod(magic)]
fn contains(zelf: PyObjectRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __contains__(zelf: PyObjectRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
zelf.to_sequence().contains(&needle, vm)
}
#[pygetset]
@@ -1197,7 +1204,7 @@ impl Comparable for PyDictItems {
impl AsSequence for PyDictItems {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyDictItems::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PyDictItems::sequence_downcast(seq).__len__())),
contains: atomic_func!(|seq, target, vm| {
let needle: &Py<PyTuple> = match target.downcast_ref() {
Some(needle) => needle,
@@ -1209,11 +1216,11 @@ impl AsSequence for PyDictItems {
let zelf = PyDictItems::sequence_downcast(seq);
let key = needle.fast_getitem(0);
if !zelf.dict.contains(key.clone(), vm)? {
if !zelf.dict.__contains__(key.clone(), vm)? {
return Ok(false);
}
let value = needle.fast_getitem(1);
let found = zelf.dict().getitem(key, vm)?;
let found = zelf.dict().__getitem__(key, vm)?;
vm.identical_or_equal(&found, &value)
}),
..PySequenceMethods::NOT_IMPLEMENTED
@@ -1247,7 +1254,7 @@ impl Unconstructible for PyDictValues {}
impl AsSequence for PyDictValues {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyDictValues::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PyDictValues::sequence_downcast(seq).__len__())),
..PySequenceMethods::NOT_IMPLEMENTED
});
&AS_SEQUENCE
+10 -10
View File
@@ -54,16 +54,16 @@ impl Constructor for PyEnumerate {
#[pyclass(with(Py, IterNext, Iterable, Constructor), flags(BASETYPE))]
impl PyEnumerate {
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
#[pyclass]
impl Py<PyEnumerate> {
#[pymethod(magic)]
fn reduce(&self) -> (PyTypeRef, (PyIter, BigInt)) {
#[pymethod]
fn __reduce__(&self) -> (PyTypeRef, (PyIter, BigInt)) {
(
self.class().to_owned(),
(self.iterator.clone(), self.counter.read().clone()),
@@ -106,8 +106,8 @@ impl PyReverseSequenceIterator {
}
}
#[pymethod(magic)]
fn length_hint(&self, vm: &VirtualMachine) -> PyResult<usize> {
#[pymethod]
fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult<usize> {
let internal = self.internal.lock();
if let IterStatus::Active(obj) = &internal.status {
if internal.position <= obj.length(vm)? {
@@ -117,13 +117,13 @@ impl PyReverseSequenceIterator {
Ok(0)
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal.lock().set_state(state, |_, pos| pos, vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.builtins_reversed_reduce(|x| x.clone(), vm)
+2 -2
View File
@@ -34,8 +34,8 @@ impl Constructor for PyFilter {
#[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))]
impl PyFilter {
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> (PyTypeRef, (PyObjectRef, PyIter)) {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, (PyObjectRef, PyIter)) {
(
vm.ctx.types.filter_type.to_owned(),
(self.predicate.clone(), self.iterator.clone()),
+65 -53
View File
@@ -204,15 +204,15 @@ fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult<f64> {
with(Comparable, Hashable, Constructor, AsNumber, Representable)
)]
impl PyFloat {
#[pymethod(magic)]
fn format(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
#[pymethod]
fn __format__(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
FormatSpec::parse(spec.as_str())
.and_then(|format_spec| format_spec.format_float(self.value))
.map_err(|err| err.into_pyexception(vm))
}
#[pystaticmethod(magic)]
fn getformat(spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
#[pystaticmethod]
fn __getformat__(spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
if !matches!(spec.as_str(), "double" | "float") {
return Err(
vm.new_value_error("__getformat__() argument 1 must be 'double' or 'float'")
@@ -229,8 +229,8 @@ impl PyFloat {
.to_owned())
}
#[pymethod(magic)]
fn abs(&self) -> f64 {
#[pymethod]
fn __abs__(&self) -> f64 {
self.value.abs()
}
@@ -278,18 +278,18 @@ impl PyFloat {
}
#[pymethod(name = "__radd__")]
#[pymethod(magic)]
fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> {
#[pymethod]
fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> {
self.simple_op(other, |a, b| Ok(a + b), vm)
}
#[pymethod(magic)]
fn bool(&self) -> bool {
#[pymethod]
fn __bool__(&self) -> bool {
self.value != 0.0
}
#[pymethod(magic)]
fn divmod(
#[pymethod]
fn __divmod__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -297,8 +297,8 @@ impl PyFloat {
self.tuple_op(other, |a, b| inner_divmod(a, b, vm), vm)
}
#[pymethod(magic)]
fn rdivmod(
#[pymethod]
fn __rdivmod__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -306,8 +306,8 @@ impl PyFloat {
self.tuple_op(other, |a, b| inner_divmod(b, a, vm), vm)
}
#[pymethod(magic)]
fn floordiv(
#[pymethod]
fn __floordiv__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -315,8 +315,8 @@ impl PyFloat {
self.simple_op(other, |a, b| inner_floordiv(a, b, vm), vm)
}
#[pymethod(magic)]
fn rfloordiv(
#[pymethod]
fn __rfloordiv__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -329,23 +329,27 @@ impl PyFloat {
self.simple_op(other, |a, b| inner_mod(a, b, vm), vm)
}
#[pymethod(magic)]
fn rmod(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> {
#[pymethod]
fn __rmod__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyArithmeticValue<f64>> {
self.simple_op(other, |a, b| inner_mod(b, a, vm), vm)
}
#[pymethod(magic)]
fn pos(&self) -> f64 {
#[pymethod]
fn __pos__(&self) -> f64 {
self.value
}
#[pymethod(magic)]
fn neg(&self) -> f64 {
#[pymethod]
fn __neg__(&self) -> f64 {
-self.value
}
#[pymethod(magic)]
fn pow(
#[pymethod]
fn __pow__(
&self,
other: PyObjectRef,
mod_val: OptionalOption<PyObjectRef>,
@@ -358,28 +362,36 @@ impl PyFloat {
}
}
#[pymethod(magic)]
fn rpow(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __rpow__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.complex_op(other, |a, b| float_pow(b, a, vm), vm)
}
#[pymethod(magic)]
fn sub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> {
#[pymethod]
fn __sub__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> {
self.simple_op(other, |a, b| Ok(a - b), vm)
}
#[pymethod(magic)]
fn rsub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> {
#[pymethod]
fn __rsub__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyArithmeticValue<f64>> {
self.simple_op(other, |a, b| Ok(b - a), vm)
}
#[pymethod(magic)]
fn truediv(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> {
#[pymethod]
fn __truediv__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyArithmeticValue<f64>> {
self.simple_op(other, |a, b| inner_div(a, b, vm), vm)
}
#[pymethod(magic)]
fn rtruediv(
#[pymethod]
fn __rtruediv__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -388,28 +400,28 @@ impl PyFloat {
}
#[pymethod(name = "__rmul__")]
#[pymethod(magic)]
fn mul(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> {
#[pymethod]
fn __mul__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<f64>> {
self.simple_op(other, |a, b| Ok(a * b), vm)
}
#[pymethod(magic)]
fn trunc(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
#[pymethod]
fn __trunc__(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
try_to_bigint(self.value, vm)
}
#[pymethod(magic)]
fn floor(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
#[pymethod]
fn __floor__(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
try_to_bigint(self.value.floor(), vm)
}
#[pymethod(magic)]
fn ceil(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
#[pymethod]
fn __ceil__(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
try_to_bigint(self.value.ceil(), vm)
}
#[pymethod(magic)]
fn round(&self, ndigits: OptionalOption<PyIntRef>, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __round__(&self, ndigits: OptionalOption<PyIntRef>, vm: &VirtualMachine) -> PyResult {
let ndigits = ndigits.flatten();
let value = if let Some(ndigits) = ndigits {
let ndigits = ndigits.as_bigint();
@@ -438,13 +450,13 @@ impl PyFloat {
Ok(value)
}
#[pymethod(magic)]
fn int(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
self.trunc(vm)
#[pymethod]
fn __int__(&self, vm: &VirtualMachine) -> PyResult<BigInt> {
self.__trunc__(vm)
}
#[pymethod(magic)]
fn float(zelf: PyRef<Self>) -> PyRef<Self> {
#[pymethod]
fn __float__(zelf: PyRef<Self>) -> PyRef<Self> {
zelf
}
@@ -497,8 +509,8 @@ impl PyFloat {
crate::literal::float::to_hex(self.value)
}
#[pymethod(magic)]
fn getnewargs(&self, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __getnewargs__(&self, vm: &VirtualMachine) -> PyObjectRef {
(self.value,).to_pyobject(vm)
}
}
+61 -61
View File
@@ -145,7 +145,7 @@ impl PyFunction {
if nargs > n_expected_args {
return Err(vm.new_type_error(format!(
"{}() takes {} positional arguments but {} were given",
self.qualname(),
self.__qualname__(),
n_expected_args,
nargs
)));
@@ -180,7 +180,7 @@ impl PyFunction {
if slot.is_some() {
return Err(vm.new_type_error(format!(
"{}() got multiple values for argument '{}'",
self.qualname(),
self.__qualname__(),
name
)));
}
@@ -192,7 +192,7 @@ impl PyFunction {
} else {
return Err(vm.new_type_error(format!(
"{}() got an unexpected keyword argument '{}'",
self.qualname(),
self.__qualname__(),
name
)));
}
@@ -200,7 +200,7 @@ impl PyFunction {
if !posonly_passed_as_kwarg.is_empty() {
return Err(vm.new_type_error(format!(
"{}() got some positional-only arguments passed as keyword arguments: '{}'",
self.qualname(),
self.__qualname__(),
posonly_passed_as_kwarg.into_iter().format(", "),
)));
}
@@ -257,7 +257,7 @@ impl PyFunction {
return Err(vm.new_type_error(format!(
"{}() missing {} required positional argument{}: '{}{}{}'",
self.qualname(),
self.__qualname__(),
missing_args_len,
if missing_args_len == 1 { "" } else { "s" },
missing.iter().join("', '"),
@@ -362,9 +362,9 @@ impl PyFunction {
let is_gen = code.flags.contains(bytecode::CodeFlags::IS_GENERATOR);
let is_coro = code.flags.contains(bytecode::CodeFlags::IS_COROUTINE);
match (is_gen, is_coro) {
(true, false) => Ok(PyGenerator::new(frame, self.name()).into_pyobject(vm)),
(false, true) => Ok(PyCoroutine::new(frame, self.name()).into_pyobject(vm)),
(true, true) => Ok(PyAsyncGen::new(frame, self.name()).into_pyobject(vm)),
(true, false) => Ok(PyGenerator::new(frame, self.__name__()).into_pyobject(vm)),
(false, true) => Ok(PyCoroutine::new(frame, self.__name__()).into_pyobject(vm)),
(true, true) => Ok(PyAsyncGen::new(frame, self.__name__()).into_pyobject(vm)),
(false, false) => vm.run_frame(frame),
}
}
@@ -386,26 +386,26 @@ impl PyPayload for PyFunction {
flags(HAS_DICT, METHOD_DESCRIPTOR)
)]
impl PyFunction {
#[pygetset(magic)]
fn code(&self) -> PyRef<PyCode> {
#[pygetset]
fn __code__(&self) -> PyRef<PyCode> {
self.code.clone()
}
#[pygetset(magic)]
fn defaults(&self) -> Option<PyTupleRef> {
#[pygetset]
fn __defaults__(&self) -> Option<PyTupleRef> {
self.defaults_and_kwdefaults.lock().0.clone()
}
#[pygetset(magic, setter)]
fn set_defaults(&self, defaults: Option<PyTupleRef>) {
#[pygetset(setter)]
fn set___defaults__(&self, defaults: Option<PyTupleRef>) {
self.defaults_and_kwdefaults.lock().0 = defaults
}
#[pygetset(magic)]
fn kwdefaults(&self) -> Option<PyDictRef> {
#[pygetset]
fn __kwdefaults__(&self) -> Option<PyDictRef> {
self.defaults_and_kwdefaults.lock().1.clone()
}
#[pygetset(magic, setter)]
fn set_kwdefaults(&self, kwdefaults: Option<PyDictRef>) {
#[pygetset(setter)]
fn set___kwdefaults__(&self, kwdefaults: Option<PyDictRef>) {
self.defaults_and_kwdefaults.lock().1 = kwdefaults
}
@@ -414,36 +414,36 @@ impl PyFunction {
// {"__globals__", T_OBJECT, OFF(func_globals), READONLY},
// {"__module__", T_OBJECT, OFF(func_module), 0},
// {"__builtins__", T_OBJECT, OFF(func_builtins), READONLY},
#[pymember(magic)]
fn globals(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult {
#[pymember]
fn __globals__(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult {
let zelf = Self::_as_pyref(&zelf, vm)?;
Ok(zelf.globals.clone().into())
}
#[pymember(magic)]
fn closure(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult {
#[pymember]
fn __closure__(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult {
let zelf = Self::_as_pyref(&zelf, vm)?;
Ok(vm.unwrap_or_none(zelf.closure.clone().map(|x| x.to_pyobject(vm))))
}
#[pymember(magic)]
fn builtins(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult {
#[pymember]
fn __builtins__(vm: &VirtualMachine, zelf: PyObjectRef) -> PyResult {
let zelf = Self::_as_pyref(&zelf, vm)?;
Ok(zelf.builtins.clone())
}
#[pygetset(magic)]
fn name(&self) -> PyStrRef {
#[pygetset]
fn __name__(&self) -> PyStrRef {
self.name.lock().clone()
}
#[pygetset(magic, setter)]
fn set_name(&self, name: PyStrRef) {
#[pygetset(setter)]
fn set___name__(&self, name: PyStrRef) {
*self.name.lock() = name;
}
#[pymember(magic)]
fn doc(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult {
#[pymember]
fn __doc__(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult {
// When accessed from instance, obj is the PyFunction instance
if let Ok(func) = obj.downcast::<PyFunction>() {
let doc = func.doc.lock();
@@ -454,41 +454,41 @@ impl PyFunction {
}
}
#[pymember(magic, setter)]
fn set_doc(vm: &VirtualMachine, zelf: PyObjectRef, value: PySetterValue) -> PyResult<()> {
#[pymember(setter)]
fn set___doc__(vm: &VirtualMachine, zelf: PyObjectRef, value: PySetterValue) -> PyResult<()> {
let zelf: PyRef<PyFunction> = zelf.downcast().unwrap_or_else(|_| unreachable!());
let value = value.unwrap_or_none(vm);
*zelf.doc.lock() = value;
Ok(())
}
#[pygetset(magic)]
fn module(&self) -> PyObjectRef {
#[pygetset]
fn __module__(&self) -> PyObjectRef {
self.module.lock().clone()
}
#[pygetset(magic, setter)]
fn set_module(&self, module: PySetterValue<PyObjectRef>, vm: &VirtualMachine) {
#[pygetset(setter)]
fn set___module__(&self, module: PySetterValue<PyObjectRef>, vm: &VirtualMachine) {
*self.module.lock() = module.unwrap_or_none(vm);
}
#[pygetset(magic)]
fn annotations(&self) -> PyDictRef {
#[pygetset]
fn __annotations__(&self) -> PyDictRef {
self.annotations.lock().clone()
}
#[pygetset(magic, setter)]
fn set_annotations(&self, annotations: PyDictRef) {
#[pygetset(setter)]
fn set___annotations__(&self, annotations: PyDictRef) {
*self.annotations.lock() = annotations
}
#[pygetset(magic)]
fn qualname(&self) -> PyStrRef {
#[pygetset]
fn __qualname__(&self) -> PyStrRef {
self.qualname.lock().clone()
}
#[pygetset(magic, setter)]
fn set_qualname(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
#[pygetset(setter)]
fn set___qualname__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
match value {
PySetterValue::Assign(value) => {
let Ok(qualname) = value.downcast::<PyStr>() else {
@@ -503,13 +503,13 @@ impl PyFunction {
Ok(())
}
#[pygetset(magic)]
fn type_params(&self) -> PyTupleRef {
#[pygetset]
fn __type_params__(&self) -> PyTupleRef {
self.type_params.lock().clone()
}
#[pygetset(magic, setter)]
fn set_type_params(
#[pygetset(setter)]
fn set___type_params__(
&self,
value: PySetterValue<PyTupleRef>,
vm: &VirtualMachine,
@@ -526,8 +526,8 @@ impl PyFunction {
}
#[cfg(feature = "jit")]
#[pymethod(magic)]
fn jit(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __jit__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<()> {
zelf.jitted_code
.get_or_try_init(|| {
let arg_types = jitfunc::get_jit_arg_types(&zelf, vm)?;
@@ -569,7 +569,7 @@ impl Representable for PyFunction {
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(format!(
"<function {} at {:#x}>",
zelf.qualname(),
zelf.__qualname__(),
zelf.get_id()
))
}
@@ -736,8 +736,8 @@ impl PyBoundMethod {
flags(HAS_DICT)
)]
impl PyBoundMethod {
#[pymethod(magic)]
fn reduce(
#[pymethod]
fn __reduce__(
&self,
vm: &VirtualMachine,
) -> (Option<PyObjectRef>, (PyObjectRef, Option<PyObjectRef>)) {
@@ -747,13 +747,13 @@ impl PyBoundMethod {
(builtins_getattr, (func_self, func_name))
}
#[pygetset(magic)]
fn doc(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __doc__(&self, vm: &VirtualMachine) -> PyResult {
self.function.get_attr("__doc__", vm)
}
#[pygetset(magic)]
fn func(&self) -> PyObjectRef {
#[pygetset]
fn __func__(&self) -> PyObjectRef {
self.function.clone()
}
@@ -762,13 +762,13 @@ impl PyBoundMethod {
self.object.clone()
}
#[pygetset(magic)]
fn module(&self, vm: &VirtualMachine) -> Option<PyObjectRef> {
#[pygetset]
fn __module__(&self, vm: &VirtualMachine) -> Option<PyObjectRef> {
self.function.get_attr("__module__", vm).ok()
}
#[pygetset(magic)]
fn qualname(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __qualname__(&self, vm: &VirtualMachine) -> PyResult {
if self
.function
.fast_isinstance(vm.ctx.types.builtin_function_or_method_type)
+4 -4
View File
@@ -37,13 +37,13 @@ impl PyGenerator {
}
}
#[pygetset(magic)]
fn name(&self) -> PyStrRef {
#[pygetset]
fn __name__(&self) -> PyStrRef {
self.inner.name()
}
#[pygetset(magic, setter)]
fn set_name(&self, name: PyStrRef) {
#[pygetset(setter)]
fn set___name__(&self, name: PyStrRef) {
self.inner.set_name(name)
}
+37 -36
View File
@@ -143,28 +143,28 @@ impl PyGenericAlias {
))
}
#[pygetset(magic)]
fn parameters(&self) -> PyObjectRef {
#[pygetset]
fn __parameters__(&self) -> PyObjectRef {
self.parameters.clone().into()
}
#[pygetset(magic)]
fn args(&self) -> PyObjectRef {
#[pygetset]
fn __args__(&self) -> PyObjectRef {
self.args.clone().into()
}
#[pygetset(magic)]
fn origin(&self) -> PyObjectRef {
#[pygetset]
fn __origin__(&self) -> PyObjectRef {
self.origin.clone().into()
}
#[pygetset(magic)]
fn unpacked(&self) -> bool {
#[pygetset]
fn __unpacked__(&self) -> bool {
self.starred
}
#[pymethod(magic)]
fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let new_args = subs_parameters(
|vm| self.repr(vm),
self.args.clone(),
@@ -179,47 +179,47 @@ impl PyGenericAlias {
)
}
#[pymethod(magic)]
fn dir(&self, vm: &VirtualMachine) -> PyResult<PyList> {
let dir = vm.dir(Some(self.origin()))?;
#[pymethod]
fn __dir__(&self, vm: &VirtualMachine) -> PyResult<PyList> {
let dir = vm.dir(Some(self.__origin__()))?;
for exc in &ATTR_EXCEPTIONS {
if !dir.contains((*exc).to_pyobject(vm), vm)? {
if !dir.__contains__((*exc).to_pyobject(vm), vm)? {
dir.append((*exc).to_pyobject(vm));
}
}
Ok(dir)
}
#[pymethod(magic)]
fn reduce(zelf: &Py<Self>, vm: &VirtualMachine) -> (PyTypeRef, (PyTypeRef, PyTupleRef)) {
#[pymethod]
fn __reduce__(zelf: &Py<Self>, vm: &VirtualMachine) -> (PyTypeRef, (PyTypeRef, PyTupleRef)) {
(
vm.ctx.types.generic_alias_type.to_owned(),
(zelf.origin.clone(), zelf.args.clone()),
)
}
#[pymethod(magic)]
fn mro_entries(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyTupleRef {
PyTuple::new_ref(vec![self.origin()], &vm.ctx)
#[pymethod]
fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyTupleRef {
PyTuple::new_ref(vec![self.__origin__()], &vm.ctx)
}
#[pymethod(magic)]
fn instancecheck(_zelf: PyRef<Self>, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __instancecheck__(_zelf: PyRef<Self>, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("isinstance() argument 2 cannot be a parameterized generic"))
}
#[pymethod(magic)]
fn subclasscheck(_zelf: PyRef<Self>, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __subclasscheck__(_zelf: PyRef<Self>, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("issubclass() argument 2 cannot be a parameterized generic"))
}
#[pymethod(magic)]
fn ror(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __ror__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
type_::or_(other, zelf, vm)
}
#[pymethod(magic)]
fn or(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __or__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
type_::or_(zelf, other, vm)
}
}
@@ -404,7 +404,7 @@ impl AsMapping for PyGenericAlias {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: LazyLock<PyMappingMethods> = LazyLock::new(|| PyMappingMethods {
subscript: atomic_func!(|mapping, needle, vm| {
PyGenericAlias::mapping_downcast(mapping).getitem(needle.to_owned(), vm)
PyGenericAlias::mapping_downcast(mapping).__getitem__(needle.to_owned(), vm)
}),
..PyMappingMethods::NOT_IMPLEMENTED
});
@@ -415,7 +415,7 @@ impl AsMapping for PyGenericAlias {
impl AsNumber for PyGenericAlias {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
or: Some(|a, b, vm| Ok(PyGenericAlias::or(a.to_owned(), b.to_owned(), vm))),
or: Some(|a, b, vm| Ok(PyGenericAlias::__or__(a.to_owned(), b.to_owned(), vm))),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
@@ -448,14 +448,15 @@ impl Comparable for PyGenericAlias {
op.eq_only(|| {
let other = class_or_notimplemented!(Self, other);
Ok(PyComparisonValue::Implemented(
if !zelf
.origin()
.rich_compare_bool(&other.origin(), PyComparisonOp::Eq, vm)?
{
if !zelf.__origin__().rich_compare_bool(
&other.__origin__(),
PyComparisonOp::Eq,
vm,
)? {
false
} else {
zelf.args()
.rich_compare_bool(&other.args(), PyComparisonOp::Eq, vm)?
zelf.__args__()
.rich_compare_bool(&other.__args__(), PyComparisonOp::Eq, vm)?
},
))
})
@@ -476,7 +477,7 @@ impl GetAttr for PyGenericAlias {
return zelf.as_object().generic_getattr(attr, vm);
}
}
zelf.origin().get_attr(attr, vm)
zelf.__origin__().get_attr(attr, vm)
}
}
+6 -6
View File
@@ -130,18 +130,18 @@ impl PyGetSet {
Self::descr_set(&zelf, obj, PySetterValue::Delete, vm)
}
#[pygetset(magic)]
fn name(&self) -> String {
#[pygetset]
fn __name__(&self) -> String {
self.name.clone()
}
#[pygetset(magic)]
fn qualname(&self) -> String {
#[pygetset]
fn __qualname__(&self) -> String {
format!("{}.{}", self.class.slot_name(), self.name.clone())
}
#[pygetset(magic)]
fn objclass(&self) -> PyTypeRef {
#[pygetset]
fn __objclass__(&self) -> PyTypeRef {
self.class.to_owned()
}
}
+77 -77
View File
@@ -321,82 +321,82 @@ impl PyInt {
)]
impl PyInt {
#[pymethod(name = "__radd__")]
#[pymethod(magic)]
fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
#[pymethod]
fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
self.int_op(other, |a, b| a + b, vm)
}
#[pymethod(magic)]
fn sub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
#[pymethod]
fn __sub__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
self.int_op(other, |a, b| a - b, vm)
}
#[pymethod(magic)]
fn rsub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
#[pymethod]
fn __rsub__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
self.int_op(other, |a, b| b - a, vm)
}
#[pymethod(name = "__rmul__")]
#[pymethod(magic)]
fn mul(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
#[pymethod]
fn __mul__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
self.int_op(other, |a, b| a * b, vm)
}
#[pymethod(magic)]
fn truediv(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __truediv__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_truediv(a, b, vm), vm)
}
#[pymethod(magic)]
fn rtruediv(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __rtruediv__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_truediv(b, a, vm), vm)
}
#[pymethod(magic)]
fn floordiv(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __floordiv__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_floordiv(a, b, vm), vm)
}
#[pymethod(magic)]
fn rfloordiv(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __rfloordiv__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_floordiv(b, a, vm), vm)
}
#[pymethod(magic)]
fn lshift(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __lshift__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_lshift(a, b, vm), vm)
}
#[pymethod(magic)]
fn rlshift(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __rlshift__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_lshift(b, a, vm), vm)
}
#[pymethod(magic)]
fn rshift(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __rshift__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_rshift(a, b, vm), vm)
}
#[pymethod(magic)]
fn rrshift(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __rrshift__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_rshift(b, a, vm), vm)
}
#[pymethod(name = "__rxor__")]
#[pymethod(magic)]
pub fn xor(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
#[pymethod]
pub fn __xor__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
self.int_op(other, |a, b| a ^ b, vm)
}
#[pymethod(name = "__ror__")]
#[pymethod(magic)]
pub fn or(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
#[pymethod]
pub fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
self.int_op(other, |a, b| a | b, vm)
}
#[pymethod(name = "__rand__")]
#[pymethod(magic)]
pub fn and(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
#[pymethod]
pub fn __and__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue<BigInt> {
self.int_op(other, |a, b| a & b, vm)
}
@@ -442,8 +442,8 @@ impl PyInt {
)
}
#[pymethod(magic)]
fn pow(
#[pymethod]
fn __pow__(
&self,
other: PyObjectRef,
r#mod: OptionalOption<PyObjectRef>,
@@ -455,8 +455,8 @@ impl PyInt {
}
}
#[pymethod(magic)]
fn rpow(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __rpow__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_pow(b, a, vm), vm)
}
@@ -465,33 +465,33 @@ impl PyInt {
self.general_op(other, |a, b| inner_mod(a, b, vm), vm)
}
#[pymethod(magic)]
fn rmod(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __rmod__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_mod(b, a, vm), vm)
}
#[pymethod(magic)]
fn divmod(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __divmod__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_divmod(a, b, vm), vm)
}
#[pymethod(magic)]
fn rdivmod(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __rdivmod__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.general_op(other, |a, b| inner_divmod(b, a, vm), vm)
}
#[pymethod(magic)]
fn neg(&self) -> BigInt {
#[pymethod]
fn __neg__(&self) -> BigInt {
-(&self.value)
}
#[pymethod(magic)]
fn abs(&self) -> BigInt {
#[pymethod]
fn __abs__(&self) -> BigInt {
self.value.abs()
}
#[pymethod(magic)]
fn round(
#[pymethod]
fn __round__(
zelf: PyRef<Self>,
ndigits: OptionalArg<PyIntRef>,
vm: &VirtualMachine,
@@ -533,55 +533,55 @@ impl PyInt {
Ok(zelf)
}
#[pymethod(magic)]
fn pos(&self) -> BigInt {
#[pymethod]
fn __pos__(&self) -> BigInt {
self.value.clone()
}
#[pymethod(magic)]
fn float(&self, vm: &VirtualMachine) -> PyResult<f64> {
#[pymethod]
fn __float__(&self, vm: &VirtualMachine) -> PyResult<f64> {
try_to_float(&self.value, vm)
}
#[pymethod(magic)]
fn trunc(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.int(vm)
#[pymethod]
fn __trunc__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.__int__(vm)
}
#[pymethod(magic)]
fn floor(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.int(vm)
#[pymethod]
fn __floor__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.__int__(vm)
}
#[pymethod(magic)]
fn ceil(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.int(vm)
#[pymethod]
fn __ceil__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.__int__(vm)
}
#[pymethod(magic)]
fn index(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.int(vm)
#[pymethod]
fn __index__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.__int__(vm)
}
#[pymethod(magic)]
fn invert(&self) -> BigInt {
#[pymethod]
fn __invert__(&self) -> BigInt {
!(&self.value)
}
#[pymethod(magic)]
fn format(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
#[pymethod]
fn __format__(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
FormatSpec::parse(spec.as_str())
.and_then(|format_spec| format_spec.format_int(&self.value))
.map_err(|err| err.into_pyexception(vm))
}
#[pymethod(magic)]
fn bool(&self) -> bool {
#[pymethod]
fn __bool__(&self) -> bool {
!self.value.is_zero()
}
#[pymethod(magic)]
fn sizeof(&self) -> usize {
#[pymethod]
fn __sizeof__(&self) -> usize {
std::mem::size_of::<Self>() + (((self.value.bits() + 7) & !7) / 8) as usize
}
@@ -597,7 +597,7 @@ impl PyInt {
#[pymethod]
fn conjugate(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.int(vm)
zelf.__int__(vm)
}
#[pyclassmethod]
@@ -666,7 +666,7 @@ impl PyInt {
#[pygetset]
fn real(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.int(vm)
zelf.__int__(vm)
}
#[pygetset]
@@ -676,7 +676,7 @@ impl PyInt {
#[pygetset]
fn numerator(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRefExact<Self> {
zelf.int(vm)
zelf.__int__(vm)
}
#[pygetset]
@@ -691,16 +691,16 @@ impl PyInt {
self.value.iter_u32_digits().map(|n| n.count_ones()).sum()
}
#[pymethod(magic)]
fn getnewargs(&self, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __getnewargs__(&self, vm: &VirtualMachine) -> PyObjectRef {
(self.value.clone(),).to_pyobject(vm)
}
}
#[pyclass]
impl PyRef<PyInt> {
#[pymethod(magic)]
fn int(self, vm: &VirtualMachine) -> PyRefExact<PyInt> {
#[pymethod]
fn __int__(self, vm: &VirtualMachine) -> PyRefExact<PyInt> {
self.into_exact_or(&vm.ctx, |zelf| unsafe {
// TODO: this is actually safe. we need better interface
PyRefExact::new_unchecked(vm.ctx.new_bigint(&zelf.value))
+6 -6
View File
@@ -199,8 +199,8 @@ impl PySequenceIterator {
})
}
#[pymethod(magic)]
fn length_hint(&self, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __length_hint__(&self, vm: &VirtualMachine) -> PyObjectRef {
let internal = self.internal.lock();
if let IterStatus::Active(obj) = &internal.status {
let seq = PySequence {
@@ -215,13 +215,13 @@ impl PySequenceIterator {
}
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal.lock().builtins_iter_reduce(|x| x.clone(), vm)
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal.lock().set_state(state, |_, pos| pos, vm)
}
}
+49 -45
View File
@@ -142,8 +142,8 @@ impl PyList {
Ok(Self::new_ref(elements, &vm.ctx))
}
#[pymethod(magic)]
fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
self.concat(&other, vm)
}
@@ -157,8 +157,12 @@ impl PyList {
Ok(zelf.to_owned().into())
}
#[pymethod(magic)]
fn iadd(zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __iadd__(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> {
let mut seq = extract_cloned(&other, Ok, vm)?;
zelf.borrow_vec_mut().append(&mut seq);
Ok(zelf)
@@ -175,13 +179,13 @@ impl PyList {
}
#[allow(clippy::len_without_is_empty)]
#[pymethod(magic)]
pub fn len(&self) -> usize {
#[pymethod]
pub fn __len__(&self) -> usize {
self.borrow_vec().len()
}
#[pymethod(magic)]
fn sizeof(&self) -> usize {
#[pymethod]
fn __sizeof__(&self) -> usize {
std::mem::size_of::<Self>()
+ self.elements.read().capacity() * std::mem::size_of::<PyObjectRef>()
}
@@ -191,9 +195,9 @@ impl PyList {
self.borrow_vec_mut().reverse();
}
#[pymethod(magic)]
fn reversed(zelf: PyRef<Self>) -> PyListReverseIterator {
let position = zelf.len().saturating_sub(1);
#[pymethod]
fn __reversed__(zelf: PyRef<Self>) -> PyListReverseIterator {
let position = zelf.__len__().saturating_sub(1);
PyListReverseIterator {
internal: PyMutex::new(PositionIterInternal::new(zelf, position)),
}
@@ -209,8 +213,8 @@ impl PyList {
}
}
#[pymethod(magic)]
fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self._getitem(&needle, vm)
}
@@ -224,8 +228,8 @@ impl PyList {
}
}
#[pymethod(magic)]
fn setitem(
#[pymethod]
fn __setitem__(
&self,
needle: PyObjectRef,
value: PyObjectRef,
@@ -234,14 +238,14 @@ impl PyList {
self._setitem(&needle, value, vm)
}
#[pymethod(magic)]
#[pymethod]
#[pymethod(name = "__rmul__")]
fn mul(&self, n: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
fn __mul__(&self, n: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
self.repeat(n.into(), vm)
}
#[pymethod(magic)]
fn imul(zelf: PyRef<Self>, n: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __imul__(zelf: PyRef<Self>, n: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
Self::irepeat(zelf, n.into(), vm)
}
@@ -250,8 +254,8 @@ impl PyList {
self.mut_count(vm, &needle)
}
#[pymethod(magic)]
pub(crate) fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
pub(crate) fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
self.mut_contains(vm, &needle)
}
@@ -262,7 +266,7 @@ impl PyList {
range: OptionalRangeArgs,
vm: &VirtualMachine,
) -> PyResult<usize> {
let (start, stop) = range.saturate(self.len(), vm)?;
let (start, stop) = range.saturate(self.__len__(), vm)?;
let index = self.mut_index_range(vm, &needle, start..stop)?;
if let Some(index) = index.into() {
Ok(index)
@@ -308,8 +312,8 @@ impl PyList {
}
}
#[pymethod(magic)]
fn delitem(&self, subscript: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __delitem__(&self, subscript: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self._delitem(&subscript, vm)
}
@@ -330,8 +334,8 @@ impl PyList {
Ok(())
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
@@ -397,7 +401,7 @@ impl Initializer for PyList {
impl AsMapping for PyList {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: atomic_func!(|mapping, _vm| Ok(PyList::mapping_downcast(mapping).len())),
length: atomic_func!(|mapping, _vm| Ok(PyList::mapping_downcast(mapping).__len__())),
subscript: atomic_func!(
|mapping, needle, vm| PyList::mapping_downcast(mapping)._getitem(needle, vm)
),
@@ -417,7 +421,7 @@ impl AsMapping for PyList {
impl AsSequence for PyList {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: PySequenceMethods = PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyList::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PyList::sequence_downcast(seq).__len__())),
concat: atomic_func!(|seq, other, vm| {
PyList::sequence_downcast(seq)
.concat(other, vm)
@@ -489,7 +493,7 @@ impl Comparable for PyList {
impl Representable for PyList {
#[inline]
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let s = if zelf.len() == 0 {
let s = if zelf.__len__() == 0 {
"[]".to_owned()
} else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
collection_repr(None, "[", "]", zelf.borrow_vec().iter(), vm)?
@@ -541,20 +545,20 @@ impl PyPayload for PyListIterator {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl PyListIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.len())
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.__len__())
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal
.lock()
.set_state(state, |obj, pos| pos.min(obj.len()), vm)
.set_state(state, |obj, pos| pos.min(obj.__len__()), vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.builtins_iter_reduce(|x| x.clone().into(), vm)
@@ -586,20 +590,20 @@ impl PyPayload for PyListReverseIterator {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl PyListReverseIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
self.internal.lock().rev_length_hint(|obj| obj.len())
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal.lock().rev_length_hint(|obj| obj.__len__())
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal
.lock()
.set_state(state, |obj, pos| pos.min(obj.len()), vm)
.set_state(state, |obj, pos| pos.min(obj.__len__()), vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.builtins_reversed_reduce(|x| x.clone().into(), vm)
+4 -4
View File
@@ -34,8 +34,8 @@ impl Constructor for PyMap {
#[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))]
impl PyMap {
#[pymethod(magic)]
fn length_hint(&self, vm: &VirtualMachine) -> PyResult<usize> {
#[pymethod]
fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult<usize> {
self.iterators.iter().try_fold(0, |prev, cur| {
let cur = cur.as_ref().to_owned().length_hint(0, vm)?;
let max = std::cmp::max(prev, cur);
@@ -43,8 +43,8 @@ impl PyMap {
})
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef) {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef) {
let mut vec = vec![self.mapper.clone()];
vec.extend(self.iterators.iter().map(|o| o.clone().into()));
(vm.ctx.types.map_type.to_owned(), vm.new_tuple(vec))
+20 -18
View File
@@ -116,8 +116,8 @@ impl PyMappingProxy {
)?))
}
#[pymethod(magic)]
pub fn getitem(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
pub fn __getitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self.get_inner(key.clone(), vm)?
.ok_or_else(|| vm.new_key_error(key))
}
@@ -131,8 +131,8 @@ impl PyMappingProxy {
}
}
#[pymethod(magic)]
pub fn contains(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
pub fn __contains__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
self._contains(&key, vm)
}
@@ -170,19 +170,19 @@ impl PyMappingProxy {
}
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
#[pymethod(magic)]
fn len(&self, vm: &VirtualMachine) -> PyResult<usize> {
#[pymethod]
fn __len__(&self, vm: &VirtualMachine) -> PyResult<usize> {
let obj = self.to_object(vm)?;
obj.length(vm)
}
#[pymethod(magic)]
fn reversed(&self, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reversed__(&self, vm: &VirtualMachine) -> PyResult {
vm.call_method(
self.to_object(vm)?.as_object(),
identifier!(vm, __reversed__).as_str(),
@@ -190,8 +190,8 @@ impl PyMappingProxy {
)
}
#[pymethod(magic)]
fn ior(&self, _args: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __ior__(&self, _args: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error(format!(
"\"'|=' is not supported by {}; use '|' instead\"",
Self::class(&vm.ctx)
@@ -199,8 +199,8 @@ impl PyMappingProxy {
}
#[pymethod(name = "__ror__")]
#[pymethod(magic)]
fn or(&self, args: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __or__(&self, args: PyObjectRef, vm: &VirtualMachine) -> PyResult {
vm._or(self.copy(vm)?.as_ref(), args.as_ref())
}
}
@@ -222,9 +222,11 @@ impl Comparable for PyMappingProxy {
impl AsMapping for PyMappingProxy {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: LazyLock<PyMappingMethods> = LazyLock::new(|| PyMappingMethods {
length: atomic_func!(|mapping, vm| PyMappingProxy::mapping_downcast(mapping).len(vm)),
length: atomic_func!(
|mapping, vm| PyMappingProxy::mapping_downcast(mapping).__len__(vm)
),
subscript: atomic_func!(|mapping, needle, vm| {
PyMappingProxy::mapping_downcast(mapping).getitem(needle.to_owned(), vm)
PyMappingProxy::mapping_downcast(mapping).__getitem__(needle.to_owned(), vm)
}),
..PyMappingMethods::NOT_IMPLEMENTED
});
@@ -249,14 +251,14 @@ impl AsNumber for PyMappingProxy {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
or: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PyMappingProxy>() {
a.or(b.to_pyobject(vm), vm)
a.__or__(b.to_pyobject(vm), vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
inplace_or: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PyMappingProxy>() {
a.ior(b.to_pyobject(vm), vm)
a.__ior__(b.to_pyobject(vm), vm)
} else {
Ok(vm.ctx.not_implemented())
}
+24 -24
View File
@@ -641,18 +641,18 @@ impl PyMemoryView {
.map(|_| self.desc.ndim() <= 1 && self.desc.is_contiguous())
}
#[pymethod(magic)]
fn enter(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __enter__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
zelf.try_not_released(vm).map(|_| zelf)
}
#[pymethod(magic)]
fn exit(&self, _args: FuncArgs) {
#[pymethod]
fn __exit__(&self, _args: FuncArgs) {
self.release();
}
#[pymethod(magic)]
fn getitem(zelf: PyRef<Self>, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getitem__(zelf: PyRef<Self>, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
zelf.try_not_released(vm)?;
if zelf.desc.ndim() == 0 {
// 0-d memoryview can be referenced using mv[...] or mv[()] only
@@ -674,16 +674,16 @@ impl PyMemoryView {
}
}
#[pymethod(magic)]
fn delitem(&self, _needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __delitem__(&self, _needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if self.desc.readonly {
return Err(vm.new_type_error("cannot modify read-only memory"));
}
Err(vm.new_type_error("cannot delete memory"))
}
#[pymethod(magic)]
fn len(&self, vm: &VirtualMachine) -> PyResult<usize> {
#[pymethod]
fn __len__(&self, vm: &VirtualMachine) -> PyResult<usize> {
self.try_not_released(vm)?;
Ok(if self.desc.ndim() == 0 {
1
@@ -839,8 +839,8 @@ impl PyMemoryView {
#[pyclass]
impl Py<PyMemoryView> {
#[pymethod(magic)]
fn setitem(
#[pymethod]
fn __setitem__(
&self,
needle: PyObjectRef,
value: PyObjectRef,
@@ -872,13 +872,13 @@ impl Py<PyMemoryView> {
}
}
#[pymethod(magic)]
fn reduce_ex(&self, _proto: usize, vm: &VirtualMachine) -> PyResult {
self.reduce(vm)
#[pymethod]
fn __reduce_ex__(&self, _proto: usize, vm: &VirtualMachine) -> PyResult {
self.__reduce__(vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("cannot pickle 'memoryview' object"))
}
}
@@ -963,15 +963,15 @@ impl Drop for PyMemoryView {
impl AsMapping for PyMemoryView {
fn as_mapping() -> &'static PyMappingMethods {
static AS_MAPPING: PyMappingMethods = PyMappingMethods {
length: atomic_func!(|mapping, vm| PyMemoryView::mapping_downcast(mapping).len(vm)),
length: atomic_func!(|mapping, vm| PyMemoryView::mapping_downcast(mapping).__len__(vm)),
subscript: atomic_func!(|mapping, needle, vm| {
let zelf = PyMemoryView::mapping_downcast(mapping);
PyMemoryView::getitem(zelf.to_owned(), needle.to_owned(), vm)
PyMemoryView::__getitem__(zelf.to_owned(), needle.to_owned(), vm)
}),
ass_subscript: atomic_func!(|mapping, needle, value, vm| {
let zelf = PyMemoryView::mapping_downcast(mapping);
if let Some(value) = value {
zelf.setitem(needle.to_owned(), value, vm)
zelf.__setitem__(needle.to_owned(), value, vm)
} else {
Err(vm.new_type_error("cannot delete memory".to_owned()))
}
@@ -987,7 +987,7 @@ impl AsSequence for PyMemoryView {
length: atomic_func!(|seq, vm| {
let zelf = PyMemoryView::sequence_downcast(seq);
zelf.try_not_released(vm)?;
zelf.len(vm)
zelf.__len__(vm)
}),
item: atomic_func!(|seq, i, vm| {
let zelf = PyMemoryView::sequence_downcast(seq);
@@ -1124,8 +1124,8 @@ impl PyPayload for PyMemoryViewIterator {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl PyMemoryViewIterator {
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.builtins_iter_reduce(|x| x.clone().into(), vm)
@@ -1137,7 +1137,7 @@ impl SelfIter for PyMemoryViewIterator {}
impl IterNext for PyMemoryViewIterator {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().next(|mv, pos| {
let len = mv.len(vm)?;
let len = mv.__len__(vm)?;
Ok(if pos >= len {
PyIterReturn::StopIteration(None)
} else {
+2 -2
View File
@@ -168,8 +168,8 @@ impl PyModule {
PyModule::new().into_ref_with_type(vm, cls).map(Into::into)
}
#[pymethod(magic)]
fn dir(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
#[pymethod]
fn __dir__(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
// First check if __dict__ attribute exists and is actually a dictionary
let dict_attr = zelf.as_object().get_attr(identifier!(vm, __dict__), vm)?;
let dict = dict_attr
+3 -3
View File
@@ -40,8 +40,8 @@ impl PyNamespace {
with(Constructor, Initializer, Comparable, Representable)
)]
impl PyNamespace {
#[pymethod(magic)]
fn reduce(zelf: PyObjectRef, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyTupleRef {
let dict = zelf.as_object().dict().unwrap();
let obj = zelf.as_object().to_owned();
let result: (PyObjectRef, PyObjectRef, PyObjectRef) = (
@@ -96,7 +96,7 @@ impl Representable for PyNamespace {
let repr = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
let dict = zelf.as_object().dict().unwrap();
let mut parts = Vec::with_capacity(dict.len());
let mut parts = Vec::with_capacity(dict.__len__());
for (key, value) in dict {
let k = &key.repr(vm)?;
let key_str = k.as_str();
+47 -40
View File
@@ -135,7 +135,7 @@ fn object_getstate_default(obj: &PyObject, required: bool, vm: &VirtualMachine)
// basicsize += std::mem::size_of::<PyObjectRef>();
// }
if let Some(ref slot_names) = slot_names {
basicsize += std::mem::size_of::<PyObjectRef>() * slot_names.len();
basicsize += std::mem::size_of::<PyObjectRef>() * slot_names.__len__();
}
if obj.class().slots.basicsize > basicsize {
return Err(
@@ -145,7 +145,7 @@ fn object_getstate_default(obj: &PyObject, required: bool, vm: &VirtualMachine)
}
if let Some(slot_names) = slot_names {
let slot_names_len = slot_names.len();
let slot_names_len = slot_names.__len__();
if slot_names_len > 0 {
let slots = vm.ctx.new_dict();
for i in 0..slot_names_len {
@@ -247,8 +247,8 @@ impl PyBaseObject {
}
/// Return self==value.
#[pymethod(magic)]
fn eq(
#[pymethod]
fn __eq__(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
@@ -257,8 +257,8 @@ impl PyBaseObject {
}
/// Return self!=value.
#[pymethod(magic)]
fn ne(
#[pymethod]
fn __ne__(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
@@ -267,8 +267,8 @@ impl PyBaseObject {
}
/// Return self<value.
#[pymethod(magic)]
fn lt(
#[pymethod]
fn __lt__(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
@@ -277,8 +277,8 @@ impl PyBaseObject {
}
/// Return self<=value.
#[pymethod(magic)]
fn le(
#[pymethod]
fn __le__(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
@@ -287,8 +287,8 @@ impl PyBaseObject {
}
/// Return self>=value.
#[pymethod(magic)]
fn ge(
#[pymethod]
fn __ge__(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
@@ -297,8 +297,8 @@ impl PyBaseObject {
}
/// Return self>value.
#[pymethod(magic)]
fn gt(
#[pymethod]
fn __gt__(
zelf: PyObjectRef,
value: PyObjectRef,
vm: &VirtualMachine,
@@ -334,8 +334,8 @@ impl PyBaseObject {
}
/// Return str(self).
#[pymethod(magic)]
fn str(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
#[pymethod]
fn __str__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
// FIXME: try tp_repr first and fallback to object.__repr__
zelf.repr(vm)
}
@@ -345,10 +345,13 @@ impl PyBaseObject {
let class = zelf.class();
match (
class
.qualname(vm)
.__qualname__(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str()),
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
class
.__module__(vm)
.downcast_ref::<PyStr>()
.map(|m| m.as_str()),
) {
(None, _) => Err(vm.new_type_error("Unknown qualified name")),
(Some(qualname), Some(module)) if module != "builtins" => Ok(PyStr::from(format!(
@@ -368,26 +371,30 @@ impl PyBaseObject {
}
/// Return repr(self).
#[pymethod(magic)]
fn repr(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
#[pymethod]
fn __repr__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Self::slot_repr(&zelf, vm)
}
#[pyclassmethod(magic)]
fn subclasshook(_args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef {
#[pyclassmethod]
fn __subclasshook__(_args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
#[pyclassmethod(magic)]
fn init_subclass(_cls: PyTypeRef) {}
#[pyclassmethod]
fn __init_subclass__(_cls: PyTypeRef) {}
#[pymethod(magic)]
pub fn dir(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyList> {
#[pymethod]
pub fn __dir__(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyList> {
obj.dir(vm)
}
#[pymethod(magic)]
fn format(obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
#[pymethod]
fn __format__(
obj: PyObjectRef,
format_spec: PyStrRef,
vm: &VirtualMachine,
) -> PyResult<PyStrRef> {
if !format_spec.is_empty() {
return Err(vm.new_type_error(format!(
"unsupported format string passed to {}.__format__",
@@ -398,8 +405,8 @@ impl PyBaseObject {
}
#[pyslot]
#[pymethod(magic)]
fn init(_zelf: PyObjectRef, _args: FuncArgs, _vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __init__(_zelf: PyObjectRef, _args: FuncArgs, _vm: &VirtualMachine) -> PyResult<()> {
Ok(())
}
@@ -447,18 +454,18 @@ impl PyBaseObject {
obj.as_object().generic_getattr(name, vm)
}
#[pymethod(magic)]
fn getattribute(obj: PyObjectRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getattribute__(obj: PyObjectRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
Self::getattro(&obj, &name, vm)
}
#[pymethod(magic)]
fn reduce(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reduce__(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
common_reduce(obj, 0, vm)
}
#[pymethod(magic)]
fn reduce_ex(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reduce_ex__(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult {
let __reduce__ = identifier!(vm, __reduce__);
if let Some(reduce) = vm.get_attribute_opt(obj.clone(), __reduce__)? {
let object_reduce = vm.ctx.types.object_type.get_attr(__reduce__).unwrap();
@@ -477,13 +484,13 @@ impl PyBaseObject {
}
/// Return hash(self).
#[pymethod(magic)]
fn hash(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyHash> {
#[pymethod]
fn __hash__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyHash> {
Self::slot_hash(&zelf, vm)
}
#[pymethod(magic)]
fn sizeof(zelf: PyObjectRef) -> usize {
#[pymethod]
fn __sizeof__(zelf: PyObjectRef) -> usize {
zelf.class().slots.basicsize
}
}
+7 -7
View File
@@ -149,8 +149,8 @@ impl PyProperty {
*self.doc.write() = value;
}
#[pymethod(magic)]
fn set_name(&self, args: PosArgs, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __set_name__(&self, args: PosArgs, vm: &VirtualMachine) -> PyResult<()> {
let func_args = args.into_args(vm);
let func_args_len = func_args.args.len();
let (_owner, name): (PyObjectRef, PyObjectRef) = func_args.bind(vm).map_err(|_e| {
@@ -237,8 +237,8 @@ impl PyProperty {
Self::clone_property_with(zelf, None, None, deleter, vm)
}
#[pygetset(magic)]
fn isabstractmethod(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyResult {
// Helper to check if a method is abstract
let is_abstract = |method: &PyObjectRef| -> PyResult<bool> {
match method.get_attr("__isabstractmethod__", vm) {
@@ -271,8 +271,8 @@ impl PyProperty {
Ok(vm.ctx.new_bool(false).into())
}
#[pygetset(magic, setter)]
fn set_isabstractmethod(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pygetset(setter)]
fn set___isabstractmethod__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if let Some(getter) = self.getter.read().to_owned() {
getter.set_attr("__isabstractmethod__", value, vm)?;
}
@@ -289,7 +289,7 @@ impl PyProperty {
) -> PyResult<String> {
let prop_name = self.get_property_name(vm);
let obj_type = obj.class();
let qualname = obj_type.qualname(vm);
let qualname = obj_type.__qualname__(vm);
match prop_name {
Some(name) => Ok(format!(
+28 -28
View File
@@ -225,13 +225,13 @@ impl PyRange {
self.step.clone()
}
#[pymethod(magic)]
fn reversed(&self, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reversed__(&self, vm: &VirtualMachine) -> PyResult {
let start = self.start.as_bigint();
let step = self.step.as_bigint();
// Use CPython calculation for this:
let length = self.len();
let length = self.__len__();
let new_stop = start - step;
let start = &new_stop + length.clone() * step;
let step = -step;
@@ -261,18 +261,18 @@ impl PyRange {
)
}
#[pymethod(magic)]
fn len(&self) -> BigInt {
#[pymethod]
fn __len__(&self) -> BigInt {
self.compute_length()
}
#[pymethod(magic)]
fn bool(&self) -> bool {
#[pymethod]
fn __bool__(&self) -> bool {
!self.is_empty()
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef) {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef) {
let range_parameters: Vec<PyObjectRef> = [&self.start, &self.stop, &self.step]
.iter()
.map(|x| x.as_object().to_owned())
@@ -281,8 +281,8 @@ impl PyRange {
(vm.ctx.types.range_type.to_owned(), range_parameters_tuple)
}
#[pymethod(magic)]
fn getitem(&self, subscript: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getitem__(&self, subscript: PyObjectRef, vm: &VirtualMachine) -> PyResult {
match RangeIndex::try_from_object(vm, subscript)? {
RangeIndex::Slice(slice) => {
let (mut sub_start, mut sub_stop, mut sub_step) =
@@ -337,8 +337,8 @@ impl Py<PyRange> {
}
}
#[pymethod(magic)]
fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> bool {
#[pymethod]
fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> bool {
self.contains_inner(&needle, vm)
}
@@ -377,7 +377,7 @@ impl Py<PyRange> {
impl PyRange {
fn protocol_length(&self, vm: &VirtualMachine) -> PyResult<usize> {
PyInt::from(self.len())
PyInt::from(self.__len__())
.try_to_primitive::<isize>(vm)
.map(|x| x as usize)
}
@@ -390,7 +390,7 @@ impl AsMapping for PyRange {
|mapping, vm| PyRange::mapping_downcast(mapping).protocol_length(vm)
),
subscript: atomic_func!(|mapping, needle, vm| {
PyRange::mapping_downcast(mapping).getitem(needle.to_owned(), vm)
PyRange::mapping_downcast(mapping).__getitem__(needle.to_owned(), vm)
}),
..PyMappingMethods::NOT_IMPLEMENTED
});
@@ -474,7 +474,7 @@ impl Iterable for PyRange {
zelf.start.as_bigint(),
zelf.stop.as_bigint(),
zelf.step.as_bigint(),
zelf.len(),
zelf.__len__(),
);
if let (Some(start), Some(step), Some(_), Some(_)) = (
start.to_isize(),
@@ -540,8 +540,8 @@ impl PyPayload for PyLongRangeIterator {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl PyLongRangeIterator {
#[pymethod(magic)]
fn length_hint(&self) -> BigInt {
#[pymethod]
fn __length_hint__(&self) -> BigInt {
let index = BigInt::from(self.index.load());
if index < self.length {
self.length.clone() - index
@@ -550,14 +550,14 @@ impl PyLongRangeIterator {
}
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.index.store(range_state(&self.length, state, vm)?);
Ok(())
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
range_iter_reduce(
self.start.clone(),
self.length.clone(),
@@ -605,21 +605,21 @@ impl PyPayload for PyRangeIterator {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl PyRangeIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
#[pymethod]
fn __length_hint__(&self) -> usize {
let index = self.index.load();
self.length.saturating_sub(index)
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.index
.store(range_state(&BigInt::from(self.length), state, vm)?);
Ok(())
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
range_iter_reduce(
BigInt::from(self.start),
BigInt::from(self.length),
+93 -66
View File
@@ -542,13 +542,13 @@ fn reduce_set(
flags(BASETYPE)
)]
impl PySet {
#[pymethod(magic)]
fn len(&self) -> usize {
#[pymethod]
fn __len__(&self) -> usize {
self.inner.len()
}
#[pymethod(magic)]
fn sizeof(&self) -> usize {
#[pymethod]
fn __sizeof__(&self) -> usize {
std::mem::size_of::<Self>() + self.inner.sizeof()
}
@@ -559,8 +559,8 @@ impl PySet {
}
}
#[pymethod(magic)]
fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
self.inner.contains(&needle, vm)
}
@@ -604,8 +604,8 @@ impl PySet {
}
#[pymethod(name = "__ror__")]
#[pymethod(magic)]
fn or(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> {
#[pymethod]
fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> {
if let Ok(other) = AnySet::try_from_object(vm, other) {
Ok(PyArithmeticValue::Implemented(self.op(
other,
@@ -618,8 +618,12 @@ impl PySet {
}
#[pymethod(name = "__rand__")]
#[pymethod(magic)]
fn and(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> {
#[pymethod]
fn __and__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyArithmeticValue<Self>> {
if let Ok(other) = AnySet::try_from_object(vm, other) {
Ok(PyArithmeticValue::Implemented(self.op(
other,
@@ -631,8 +635,12 @@ impl PySet {
}
}
#[pymethod(magic)]
fn sub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> {
#[pymethod]
fn __sub__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyArithmeticValue<Self>> {
if let Ok(other) = AnySet::try_from_object(vm, other) {
Ok(PyArithmeticValue::Implemented(self.op(
other,
@@ -644,8 +652,8 @@ impl PySet {
}
}
#[pymethod(magic)]
fn rsub(
#[pymethod]
fn __rsub__(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -662,8 +670,12 @@ impl PySet {
}
#[pymethod(name = "__rxor__")]
#[pymethod(magic)]
fn xor(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> {
#[pymethod]
fn __xor__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyArithmeticValue<Self>> {
if let Ok(other) = AnySet::try_from_object(vm, other) {
Ok(PyArithmeticValue::Implemented(self.op(
other,
@@ -702,8 +714,8 @@ impl PySet {
self.inner.pop(vm)
}
#[pymethod(magic)]
fn ior(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __ior__(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
zelf.inner.update(set.into_iterable_iter(vm)?, vm)?;
Ok(zelf)
}
@@ -726,8 +738,8 @@ impl PySet {
Ok(())
}
#[pymethod(magic)]
fn iand(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __iand__(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
zelf.inner
.intersection_update(std::iter::once(set.into_iterable(vm)?), vm)?;
Ok(zelf)
@@ -739,8 +751,8 @@ impl PySet {
Ok(())
}
#[pymethod(magic)]
fn isub(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __isub__(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
zelf.inner
.difference_update(set.into_iterable_iter(vm)?, vm)?;
Ok(zelf)
@@ -757,23 +769,23 @@ impl PySet {
Ok(())
}
#[pymethod(magic)]
fn ixor(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __ixor__(zelf: PyRef<Self>, set: AnySet, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
zelf.inner
.symmetric_difference_update(set.into_iterable_iter(vm)?, vm)?;
Ok(zelf)
}
#[pymethod(magic)]
fn reduce(
#[pymethod]
fn __reduce__(
zelf: PyRef<Self>,
vm: &VirtualMachine,
) -> PyResult<(PyTypeRef, PyTupleRef, Option<PyDictRef>)> {
reduce_set(zelf.as_ref(), vm)
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
@@ -795,7 +807,7 @@ impl Initializer for PySet {
impl AsSequence for PySet {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PySet::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PySet::sequence_downcast(seq).__len__())),
contains: atomic_func!(|seq, needle, vm| PySet::sequence_downcast(seq)
.inner
.contains(needle, vm)),
@@ -829,35 +841,35 @@ impl AsNumber for PySet {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
subtract: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PySet>() {
a.sub(b.to_owned(), vm).to_pyresult(vm)
a.__sub__(b.to_owned(), vm).to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
and: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PySet>() {
a.and(b.to_owned(), vm).to_pyresult(vm)
a.__and__(b.to_owned(), vm).to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
xor: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PySet>() {
a.xor(b.to_owned(), vm).to_pyresult(vm)
a.__xor__(b.to_owned(), vm).to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
or: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PySet>() {
a.or(b.to_owned(), vm).to_pyresult(vm)
a.__or__(b.to_owned(), vm).to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
inplace_subtract: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PySet>() {
PySet::isub(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm)
PySet::__isub__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm)
.to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
@@ -865,7 +877,7 @@ impl AsNumber for PySet {
}),
inplace_and: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PySet>() {
PySet::iand(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm)
PySet::__iand__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm)
.to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
@@ -873,7 +885,7 @@ impl AsNumber for PySet {
}),
inplace_xor: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PySet>() {
PySet::ixor(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm)
PySet::__ixor__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm)
.to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
@@ -881,7 +893,7 @@ impl AsNumber for PySet {
}),
inplace_or: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PySet>() {
PySet::ior(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm)
PySet::__ior__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm)
.to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
@@ -956,13 +968,13 @@ impl Constructor for PyFrozenSet {
)
)]
impl PyFrozenSet {
#[pymethod(magic)]
fn len(&self) -> usize {
#[pymethod]
fn __len__(&self) -> usize {
self.inner.len()
}
#[pymethod(magic)]
fn sizeof(&self) -> usize {
#[pymethod]
fn __sizeof__(&self) -> usize {
std::mem::size_of::<Self>() + self.inner.sizeof()
}
@@ -979,8 +991,8 @@ impl PyFrozenSet {
}
}
#[pymethod(magic)]
fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
self.inner.contains(&needle, vm)
}
@@ -1024,8 +1036,8 @@ impl PyFrozenSet {
}
#[pymethod(name = "__ror__")]
#[pymethod(magic)]
fn or(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> {
#[pymethod]
fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> {
if let Ok(set) = AnySet::try_from_object(vm, other) {
Ok(PyArithmeticValue::Implemented(self.op(
set,
@@ -1038,8 +1050,12 @@ impl PyFrozenSet {
}
#[pymethod(name = "__rand__")]
#[pymethod(magic)]
fn and(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> {
#[pymethod]
fn __and__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyArithmeticValue<Self>> {
if let Ok(other) = AnySet::try_from_object(vm, other) {
Ok(PyArithmeticValue::Implemented(self.op(
other,
@@ -1051,8 +1067,12 @@ impl PyFrozenSet {
}
}
#[pymethod(magic)]
fn sub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> {
#[pymethod]
fn __sub__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyArithmeticValue<Self>> {
if let Ok(other) = AnySet::try_from_object(vm, other) {
Ok(PyArithmeticValue::Implemented(self.op(
other,
@@ -1064,8 +1084,8 @@ impl PyFrozenSet {
}
}
#[pymethod(magic)]
fn rsub(
#[pymethod]
fn __rsub__(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -1083,8 +1103,12 @@ impl PyFrozenSet {
}
#[pymethod(name = "__rxor__")]
#[pymethod(magic)]
fn xor(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyArithmeticValue<Self>> {
#[pymethod]
fn __xor__(
&self,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyArithmeticValue<Self>> {
if let Ok(other) = AnySet::try_from_object(vm, other) {
Ok(PyArithmeticValue::Implemented(self.op(
other,
@@ -1096,16 +1120,16 @@ impl PyFrozenSet {
}
}
#[pymethod(magic)]
fn reduce(
#[pymethod]
fn __reduce__(
zelf: PyRef<Self>,
vm: &VirtualMachine,
) -> PyResult<(PyTypeRef, PyTupleRef, Option<PyDictRef>)> {
reduce_set(zelf.as_ref(), vm)
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
@@ -1113,7 +1137,7 @@ impl PyFrozenSet {
impl AsSequence for PyFrozenSet {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyFrozenSet::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PyFrozenSet::sequence_downcast(seq).__len__())),
contains: atomic_func!(|seq, needle, vm| PyFrozenSet::sequence_downcast(seq)
.inner
.contains(needle, vm)),
@@ -1170,28 +1194,28 @@ impl AsNumber for PyFrozenSet {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
subtract: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PyFrozenSet>() {
a.sub(b.to_owned(), vm).to_pyresult(vm)
a.__sub__(b.to_owned(), vm).to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
and: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PyFrozenSet>() {
a.and(b.to_owned(), vm).to_pyresult(vm)
a.__and__(b.to_owned(), vm).to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
xor: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PyFrozenSet>() {
a.xor(b.to_owned(), vm).to_pyresult(vm)
a.__xor__(b.to_owned(), vm).to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
}
}),
or: Some(|a, b, vm| {
if let Some(a) = a.downcast_ref::<PyFrozenSet>() {
a.or(b.to_owned(), vm).to_pyresult(vm)
a.__or__(b.to_owned(), vm).to_pyresult(vm)
} else {
Ok(vm.ctx.not_implemented())
}
@@ -1278,13 +1302,16 @@ impl PyPayload for PySetIterator {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl PySetIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal.lock().length_hint(|_| self.size.entries_size)
}
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<(PyObjectRef, (PyObjectRef,))> {
#[pymethod]
fn __reduce__(
zelf: PyRef<Self>,
vm: &VirtualMachine,
) -> PyResult<(PyObjectRef, (PyObjectRef,))> {
let internal = zelf.internal.lock();
Ok((
builtins_iter(vm).to_owned(),
+6 -6
View File
@@ -44,8 +44,8 @@ impl Constructor for PyNone {
#[pyclass(with(Constructor, AsNumber, Representable))]
impl PyNone {
#[pymethod(magic)]
fn bool(&self) -> bool {
#[pymethod]
fn __bool__(&self) -> bool {
false
}
}
@@ -95,13 +95,13 @@ 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(magic)]
fn bool(&self) -> bool {
#[pymethod]
fn __bool__(&self) -> bool {
true
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyStrRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyStrRef {
vm.ctx.names.NotImplemented.to_owned()
}
}
+4 -4
View File
@@ -182,8 +182,8 @@ impl PySlice {
}
#[allow(clippy::type_complexity)]
#[pymethod(magic)]
fn reduce(
#[pymethod]
fn __reduce__(
zelf: PyRef<Self>,
) -> PyResult<(
PyTypeRef,
@@ -317,8 +317,8 @@ impl Constructor for PyEllipsis {
#[pyclass(with(Constructor, Representable))]
impl PyEllipsis {
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyStrRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyStrRef {
vm.ctx.names.Ellipsis.to_owned()
}
}
+21 -18
View File
@@ -85,46 +85,46 @@ impl Initializer for PyStaticMethod {
flags(BASETYPE, HAS_DICT)
)]
impl PyStaticMethod {
#[pygetset(magic)]
fn func(&self) -> PyObjectRef {
#[pygetset]
fn __func__(&self) -> PyObjectRef {
self.callable.lock().clone()
}
#[pygetset(magic)]
fn wrapped(&self) -> PyObjectRef {
#[pygetset]
fn __wrapped__(&self) -> PyObjectRef {
self.callable.lock().clone()
}
#[pygetset(magic)]
fn module(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __module__(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__module__", vm)
}
#[pygetset(magic)]
fn qualname(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __qualname__(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__qualname__", vm)
}
#[pygetset(magic)]
fn name(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __name__(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__name__", vm)
}
#[pygetset(magic)]
fn annotations(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __annotations__(&self, vm: &VirtualMachine) -> PyResult {
self.callable.lock().get_attr("__annotations__", vm)
}
#[pygetset(magic)]
fn isabstractmethod(&self, vm: &VirtualMachine) -> PyObjectRef {
#[pygetset]
fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyObjectRef {
match vm.get_attribute_opt(self.callable.lock().clone(), "__isabstractmethod__") {
Ok(Some(is_abstract)) => is_abstract,
_ => vm.ctx.new_bool(false).into(),
}
}
#[pygetset(magic, setter)]
fn set_isabstractmethod(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pygetset(setter)]
fn set___isabstractmethod__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.callable
.lock()
.set_attr("__isabstractmethod__", value, vm)?;
@@ -148,10 +148,13 @@ impl Representable for PyStaticMethod {
match (
class
.qualname(vm)
.__qualname__(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str()),
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
class
.__module__(vm)
.downcast_ref::<PyStr>()
.map(|m| m.as_str()),
) {
(None, _) => Err(vm.new_type_error("Unknown qualified name")),
(Some(qualname), Some(module)) if module != "builtins" => {
+23 -23
View File
@@ -283,13 +283,13 @@ impl PyPayload for PyStrIterator {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl PyStrIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal.lock().0.length_hint(|obj| obj.char_len())
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let mut internal = self.internal.lock();
internal.1 = usize::MAX;
internal
@@ -297,8 +297,8 @@ impl PyStrIterator {
.set_state(state, |obj, pos| pos.min(obj.char_len()), vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.0
@@ -513,8 +513,8 @@ impl PyStr {
)
)]
impl PyStr {
#[pymethod(magic)]
fn add(zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __add__(zelf: PyRef<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if let Some(other) = other.payload::<PyStr>() {
let bytes = zelf.as_wtf8().py_add(other.as_wtf8());
Ok(unsafe {
@@ -545,8 +545,8 @@ impl PyStr {
}
}
#[pymethod(magic)]
fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
self._contains(&needle, vm)
}
@@ -558,8 +558,8 @@ impl PyStr {
Ok(item)
}
#[pymethod(magic)]
fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self._getitem(&needle, vm)
}
@@ -602,14 +602,14 @@ impl PyStr {
matches!(self.kind(), StrKind::Ascii)
}
#[pymethod(magic)]
fn sizeof(&self) -> usize {
#[pymethod]
fn __sizeof__(&self) -> usize {
std::mem::size_of::<Self>() + self.byte_len() * std::mem::size_of::<u8>()
}
#[pymethod(name = "__rmul__")]
#[pymethod(magic)]
fn mul(zelf: PyRef<Self>, value: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __mul__(zelf: PyRef<Self>, value: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
Self::repeat(zelf, value.into(), vm)
}
@@ -920,8 +920,8 @@ impl PyStr {
cformat_string(vm, self.as_wtf8(), values)
}
#[pymethod(magic)]
fn rmod(&self, _values: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __rmod__(&self, _values: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
@@ -1431,8 +1431,8 @@ impl PyStr {
encode_string(zelf, args.encoding, args.errors, vm)
}
#[pymethod(magic)]
fn getnewargs(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __getnewargs__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyObjectRef {
(zelf.as_str(),).to_pyobject(vm)
}
}
@@ -1453,8 +1453,8 @@ impl crate::common::format::CharLen for CharLenStr<'_> {
#[pyclass]
impl PyRef<PyStr> {
#[pymethod(magic)]
fn str(self, vm: &VirtualMachine) -> PyRefExact<PyStr> {
#[pymethod]
fn __str__(self, vm: &VirtualMachine) -> PyRefExact<PyStr> {
self.into_exact_or(&vm.ctx, |zelf| {
PyStr::from(zelf.data.clone()).into_exact_ref(&vm.ctx)
})
@@ -1551,7 +1551,7 @@ impl AsSequence for PyStr {
length: atomic_func!(|seq, _vm| Ok(PyStr::sequence_downcast(seq).len())),
concat: atomic_func!(|seq, other, vm| {
let zelf = PyStr::sequence_downcast(seq);
PyStr::add(zelf.to_owned(), other.to_owned(), vm)
PyStr::__add__(zelf.to_owned(), other.to_owned(), vm)
}),
repeat: atomic_func!(|seq, n, vm| {
let zelf = PyStr::sequence_downcast(seq);
+4 -4
View File
@@ -135,13 +135,13 @@ impl Initializer for PySuper {
#[pyclass(with(GetAttr, GetDescriptor, Constructor, Initializer, Representable))]
impl PySuper {
#[pygetset(magic)]
fn thisclass(&self) -> PyTypeRef {
#[pygetset]
fn __thisclass__(&self) -> PyTypeRef {
self.inner.read().typ.clone()
}
#[pygetset(magic)]
fn self_class(&self) -> Option<PyTypeRef> {
#[pygetset]
fn __self_class__(&self) -> Option<PyTypeRef> {
Some(self.inner.read().obj.as_ref()?.1.clone())
}
+24 -24
View File
@@ -228,8 +228,8 @@ impl PyTuple {
)
)]
impl PyTuple {
#[pymethod(magic)]
fn add(
#[pymethod]
fn __add__(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -251,8 +251,8 @@ impl PyTuple {
PyArithmeticValue::from_option(added.ok())
}
#[pymethod(magic)]
fn bool(&self) -> bool {
#[pymethod]
fn __bool__(&self) -> bool {
!self.elements.is_empty()
}
@@ -267,9 +267,9 @@ impl PyTuple {
Ok(count)
}
#[pymethod(magic)]
#[inline]
pub fn len(&self) -> usize {
#[pymethod]
pub fn __len__(&self) -> usize {
self.elements.len()
}
@@ -279,8 +279,8 @@ impl PyTuple {
}
#[pymethod(name = "__rmul__")]
#[pymethod(magic)]
fn mul(zelf: PyRef<Self>, value: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __mul__(zelf: PyRef<Self>, value: ArgSize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
Self::repeat(zelf, value.into(), vm)
}
@@ -294,8 +294,8 @@ impl PyTuple {
}
}
#[pymethod(magic)]
fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult {
self._getitem(&needle, vm)
}
@@ -324,13 +324,13 @@ impl PyTuple {
Ok(false)
}
#[pymethod(magic)]
fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
self._contains(&needle, vm)
}
#[pymethod(magic)]
fn getnewargs(zelf: PyRef<Self>, vm: &VirtualMachine) -> (PyTupleRef,) {
#[pymethod]
fn __getnewargs__(zelf: PyRef<Self>, vm: &VirtualMachine) -> (PyTupleRef,) {
// the arguments to pass to tuple() is just one tuple - so we'll be doing tuple(tup), which
// should just return tup, or tuple_subclass(tup), which'll copy/validate (e.g. for a
// structseq)
@@ -342,8 +342,8 @@ impl PyTuple {
(tup_arg,)
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
@@ -364,10 +364,10 @@ impl AsMapping for PyTuple {
impl AsSequence for PyTuple {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyTuple::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PyTuple::sequence_downcast(seq).__len__())),
concat: atomic_func!(|seq, other, vm| {
let zelf = PyTuple::sequence_downcast(seq);
match PyTuple::add(zelf.to_owned(), other.to_owned(), vm) {
match PyTuple::__add__(zelf.to_owned(), other.to_owned(), vm) {
PyArithmeticValue::Implemented(tuple) => Ok(tuple.into()),
PyArithmeticValue::NotImplemented => Err(vm.new_type_error(format!(
"can only concatenate tuple (not '{}') to tuple",
@@ -464,20 +464,20 @@ impl PyPayload for PyTupleIterator {
#[pyclass(with(Unconstructible, IterNext, Iterable))]
impl PyTupleIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.len())
}
#[pymethod(magic)]
fn setstate(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.internal
.lock()
.set_state(state, |obj, pos| pos.min(obj.len()), vm)
}
#[pymethod(magic)]
fn reduce(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef {
self.internal
.lock()
.builtins_iter_reduce(|x| x.clone().into(), vm)
+52 -52
View File
@@ -476,8 +476,8 @@ impl Py<PyType> {
flags(BASETYPE)
)]
impl PyType {
#[pygetset(magic)]
fn bases(&self, vm: &VirtualMachine) -> PyTupleRef {
#[pygetset]
fn __bases__(&self, vm: &VirtualMachine) -> PyTupleRef {
vm.ctx.new_tuple(
self.bases
.read()
@@ -541,18 +541,18 @@ impl PyType {
Ok(())
}
#[pygetset(magic)]
fn base(&self) -> Option<PyTypeRef> {
#[pygetset]
fn __base__(&self) -> Option<PyTypeRef> {
self.base.clone()
}
#[pygetset(magic)]
fn flags(&self) -> u64 {
#[pygetset]
fn __flags__(&self) -> u64 {
self.slots.flags.bits()
}
#[pygetset(magic)]
fn basicsize(&self) -> usize {
#[pygetset]
fn __basicsize__(&self) -> usize {
self.slots.basicsize
}
@@ -574,8 +574,8 @@ impl PyType {
)
}
#[pygetset(magic)]
pub fn qualname(&self, vm: &VirtualMachine) -> PyObjectRef {
#[pygetset]
pub fn __qualname__(&self, vm: &VirtualMachine) -> PyObjectRef {
self.attributes
.read()
.get(identifier!(vm, __qualname__))
@@ -591,8 +591,8 @@ impl PyType {
.unwrap_or_else(|| vm.ctx.new_str(self.name().deref()).into())
}
#[pygetset(magic, setter)]
fn set_qualname(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
#[pygetset(setter)]
fn set___qualname__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
// TODO: we should replace heaptype flag check to immutable flag check
if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
return Err(vm.new_type_error(format!(
@@ -619,8 +619,8 @@ impl PyType {
Ok(())
}
#[pygetset(magic)]
fn annotations(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
#[pygetset]
fn __annotations__(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
return Err(vm.new_attribute_error(format!(
"type object '{}' has no attribute '__annotations__'",
@@ -645,8 +645,8 @@ impl PyType {
Ok(annotations)
}
#[pygetset(magic, setter)]
fn set_annotations(&self, value: Option<PyObjectRef>, vm: &VirtualMachine) -> PyResult<()> {
#[pygetset(setter)]
fn set___annotations__(&self, value: Option<PyObjectRef>, vm: &VirtualMachine) -> PyResult<()> {
if self.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
return Err(vm.new_type_error(format!(
"cannot set '__annotations__' attribute of immutable type '{}'",
@@ -673,8 +673,8 @@ impl PyType {
Ok(())
}
#[pygetset(magic)]
pub fn module(&self, vm: &VirtualMachine) -> PyObjectRef {
#[pygetset]
pub fn __module__(&self, vm: &VirtualMachine) -> PyObjectRef {
self.attributes
.read()
.get(identifier!(vm, __module__))
@@ -690,15 +690,15 @@ impl PyType {
.unwrap_or_else(|| vm.ctx.new_str(ascii!("builtins")).into())
}
#[pygetset(magic, setter)]
fn set_module(&self, value: PyObjectRef, vm: &VirtualMachine) {
#[pygetset(setter)]
fn set___module__(&self, value: PyObjectRef, vm: &VirtualMachine) {
self.attributes
.write()
.insert(identifier!(vm, __module__), value);
}
#[pyclassmethod(magic)]
fn prepare(
#[pyclassmethod]
fn __prepare__(
_cls: PyTypeRef,
_name: OptionalArg<PyObjectRef>,
_bases: OptionalArg<PyObjectRef>,
@@ -708,8 +708,8 @@ impl PyType {
vm.ctx.new_dict()
}
#[pymethod(magic)]
fn subclasses(&self) -> PyList {
#[pymethod]
fn __subclasses__(&self) -> PyList {
let mut subclasses = self.subclasses.write();
subclasses.retain(|x| x.upgrade().is_some());
PyList::from(
@@ -720,23 +720,23 @@ impl PyType {
)
}
#[pymethod(magic)]
pub fn ror(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
pub fn __ror__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
or_(other, zelf, vm)
}
#[pymethod(magic)]
pub fn or(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
pub fn __or__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
or_(zelf, other, vm)
}
#[pygetset(magic)]
fn dict(zelf: PyRef<Self>) -> PyMappingProxy {
#[pygetset]
fn __dict__(zelf: PyRef<Self>) -> PyMappingProxy {
PyMappingProxy::from(zelf)
}
#[pygetset(magic, setter)]
fn set_dict(&self, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pygetset(setter)]
fn set___dict__(&self, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
Err(vm.new_not_implemented_error(
"Setting __dict__ attribute on a type isn't yet implemented",
))
@@ -758,8 +758,8 @@ impl PyType {
Ok(())
}
#[pygetset(magic, setter)]
fn set_name(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pygetset(setter)]
fn set___name__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.check_set_special_type_attr(&value, identifier!(vm, __name__), vm)?;
let name = value.downcast::<PyStr>().map_err(|value| {
vm.new_type_error(format!(
@@ -777,8 +777,8 @@ impl PyType {
Ok(())
}
#[pygetset(magic)]
fn text_signature(&self) -> Option<String> {
#[pygetset]
fn __text_signature__(&self) -> Option<String> {
self.slots
.doc
.and_then(|doc| get_text_signature_from_internal_doc(&self.name(), doc))
@@ -1026,7 +1026,7 @@ impl Constructor for PyType {
name,
typ.name()
));
err.set_cause(Some(e));
err.set___cause__(Some(e));
err
})?;
}
@@ -1137,8 +1137,8 @@ impl Py<PyType> {
PyTuple::new_unchecked(elements.into_boxed_slice())
}
#[pygetset(magic)]
fn doc(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __doc__(&self, vm: &VirtualMachine) -> PyResult {
// Similar to CPython's type_get_doc
// For non-heap types (static types), check if there's an internal doc
if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) {
@@ -1165,8 +1165,8 @@ impl Py<PyType> {
}
}
#[pygetset(magic, setter)]
fn set_doc(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
#[pygetset(setter)]
fn set___doc__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> {
// Similar to CPython's type_set_doc
let value = value.ok_or_else(|| {
vm.new_type_error(format!(
@@ -1186,8 +1186,8 @@ impl Py<PyType> {
Ok(())
}
#[pymethod(magic)]
fn dir(&self) -> PyList {
#[pymethod]
fn __dir__(&self) -> PyList {
let attributes: Vec<PyObjectRef> = self
.get_attributes()
.into_iter()
@@ -1196,18 +1196,18 @@ impl Py<PyType> {
PyList::from(attributes)
}
#[pymethod(magic)]
fn instancecheck(&self, obj: PyObjectRef) -> bool {
#[pymethod]
fn __instancecheck__(&self, obj: PyObjectRef) -> bool {
obj.fast_isinstance(self)
}
#[pymethod(magic)]
fn subclasscheck(&self, subclass: PyTypeRef) -> bool {
#[pymethod]
fn __subclasscheck__(&self, subclass: PyTypeRef) -> bool {
subclass.fast_issubclass(self)
}
#[pyclassmethod(magic)]
fn subclasshook(_args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef {
#[pyclassmethod]
fn __subclasshook__(_args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.not_implemented()
}
@@ -1289,7 +1289,7 @@ impl AsNumber for PyType {
impl Representable for PyType {
#[inline]
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let module = zelf.module(vm);
let module = zelf.__module__(vm);
let module = module.downcast_ref::<PyStr>().map(|m| m.as_str());
let repr = match module {
@@ -1298,7 +1298,7 @@ impl Representable for PyType {
format!(
"<class '{}.{}'>",
module,
zelf.qualname(vm)
zelf.__qualname__(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str())
.unwrap_or_else(|| &name)
@@ -1476,7 +1476,7 @@ fn solid_base<'a>(typ: &'a Py<PyType>, vm: &VirtualMachine) -> &'a Py<PyType> {
};
// TODO: requires itemsize comparison too
if typ.basicsize() != base.basicsize() {
if typ.__basicsize__() != base.__basicsize__() {
typ
} else {
base
+21 -13
View File
@@ -84,18 +84,22 @@ impl PyUnion {
with(Hashable, Comparable, AsMapping, AsNumber, Representable)
)]
impl PyUnion {
#[pygetset(magic)]
fn parameters(&self) -> PyObjectRef {
#[pygetset]
fn __parameters__(&self) -> PyObjectRef {
self.parameters.clone().into()
}
#[pygetset(magic)]
fn args(&self) -> PyObjectRef {
#[pygetset]
fn __args__(&self) -> PyObjectRef {
self.args.clone().into()
}
#[pymethod(magic)]
fn instancecheck(zelf: PyRef<Self>, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __instancecheck__(
zelf: PyRef<Self>,
obj: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<bool> {
if zelf
.args
.iter()
@@ -103,12 +107,16 @@ impl PyUnion {
{
Err(vm.new_type_error("isinstance() argument 2 cannot be a parameterized generic"))
} else {
obj.is_instance(zelf.args().as_object(), vm)
obj.is_instance(zelf.__args__().as_object(), vm)
}
}
#[pymethod(magic)]
fn subclasscheck(zelf: PyRef<Self>, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __subclasscheck__(
zelf: PyRef<Self>,
obj: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<bool> {
if zelf
.args
.iter()
@@ -116,13 +124,13 @@ impl PyUnion {
{
Err(vm.new_type_error("issubclass() argument 2 cannot be a parameterized generic"))
} else {
obj.is_subclass(zelf.args().as_object(), vm)
obj.is_subclass(zelf.__args__().as_object(), vm)
}
}
#[pymethod(name = "__ror__")]
#[pymethod(magic)]
fn or(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __or__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef {
type_::or_(zelf, other, vm)
}
}
@@ -228,7 +236,7 @@ impl AsMapping for PyUnion {
impl AsNumber for PyUnion {
fn as_number() -> &'static PyNumberMethods {
static AS_NUMBER: PyNumberMethods = PyNumberMethods {
or: Some(|a, b, vm| PyUnion::or(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)),
or: Some(|a, b, vm| PyUnion::__or__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)),
..PyNumberMethods::NOT_IMPLEMENTED
};
&AS_NUMBER
+11 -11
View File
@@ -79,8 +79,8 @@ impl PyWeakProxy {
self.weak.upgrade().ok_or_else(|| new_reference_error(vm))
}
#[pymethod(magic)]
fn str(&self, vm: &VirtualMachine) -> PyResult<PyStrRef> {
#[pymethod]
fn __str__(&self, vm: &VirtualMachine) -> PyResult<PyStrRef> {
self.try_upgrade(vm)?.str(vm)
}
@@ -88,23 +88,23 @@ impl PyWeakProxy {
self.try_upgrade(vm)?.length(vm)
}
#[pymethod(magic)]
fn bool(&self, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __bool__(&self, vm: &VirtualMachine) -> PyResult<bool> {
self.try_upgrade(vm)?.is_true(vm)
}
#[pymethod(magic)]
fn bytes(&self, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __bytes__(&self, vm: &VirtualMachine) -> PyResult {
self.try_upgrade(vm)?.bytes(vm)
}
#[pymethod(magic)]
fn reversed(&self, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reversed__(&self, vm: &VirtualMachine) -> PyResult {
let obj = self.try_upgrade(vm)?;
reversed(obj, vm)
}
#[pymethod(magic)]
fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
self.try_upgrade(vm)?.to_sequence().contains(&needle, vm)
}
@@ -189,7 +189,7 @@ impl AsSequence for PyWeakProxy {
static AS_SEQUENCE: LazyLock<PySequenceMethods> = LazyLock::new(|| PySequenceMethods {
length: atomic_func!(|seq, vm| PyWeakProxy::sequence_downcast(seq).len(vm)),
contains: atomic_func!(|seq, needle, vm| {
PyWeakProxy::sequence_downcast(seq).contains(needle.to_owned(), vm)
PyWeakProxy::sequence_downcast(seq).__contains__(needle.to_owned(), vm)
}),
..PySequenceMethods::NOT_IMPLEMENTED
});
+2 -2
View File
@@ -52,8 +52,8 @@ impl Constructor for PyWeak {
flags(BASETYPE)
)]
impl PyWeak {
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
+4 -4
View File
@@ -43,8 +43,8 @@ impl Constructor for PyZip {
#[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))]
impl PyZip {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
let cls = zelf.class().to_owned();
let iterators = zelf
.iterators
@@ -59,8 +59,8 @@ impl PyZip {
})
}
#[pymethod(magic)]
fn setstate(zelf: PyRef<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(zelf: PyRef<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if let Ok(obj) = ArgIntoBool::try_from_object(vm, state) {
zelf.strict.store(obj.into(), atomic::Ordering::Release);
}
+2 -2
View File
@@ -115,13 +115,13 @@ impl Coro {
if e.fast_isinstance(vm.ctx.exceptions.stop_iteration) {
let err =
vm.new_runtime_error(format!("{} raised StopIteration", gen_name(jen, vm)));
err.set_cause(Some(e));
err.set___cause__(Some(e));
Err(err)
} else if jen.class().is(vm.ctx.types.async_generator)
&& e.fast_isinstance(vm.ctx.exceptions.stop_async_iteration)
{
let err = vm.new_runtime_error("async generator raised StopAsyncIteration");
err.set_cause(Some(e));
err.set___cause__(Some(e));
Err(err)
} else {
Err(e)
+43 -43
View File
@@ -94,14 +94,14 @@ impl VirtualMachine {
seen.insert(exc.get_id());
#[allow(clippy::manual_map)]
if let Some((cause_or_context, msg)) = if let Some(cause) = exc.cause() {
if let Some((cause_or_context, msg)) = if let Some(cause) = exc.__cause__() {
// This can be a special case: `raise e from e`,
// we just ignore it and treat like `raise e` without any extra steps.
Some((
cause,
"\nThe above exception was the direct cause of the following exception:\n",
))
} else if let Some(context) = exc.context() {
} else if let Some(context) = exc.__context__() {
// This can be a special case:
// e = ValueError('e')
// e.__context__ = e
@@ -310,7 +310,7 @@ impl VirtualMachine {
&self,
exc: PyBaseExceptionRef,
) -> (PyObjectRef, PyObjectRef, PyObjectRef) {
let tb = exc.traceback().to_pyobject(self);
let tb = exc.__traceback__().to_pyobject(self);
let class = exc.class().to_owned();
(class.into(), exc.into(), tb)
}
@@ -578,13 +578,13 @@ impl PyBaseException {
Ok(())
}
#[pygetset(magic)]
pub fn traceback(&self) -> Option<PyTracebackRef> {
#[pygetset]
pub fn __traceback__(&self) -> Option<PyTracebackRef> {
self.traceback.read().clone()
}
#[pygetset(magic, setter)]
pub fn set_traceback(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pygetset(setter)]
pub fn set___traceback__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let traceback = if vm.is_none(&value) {
None
} else {
@@ -604,25 +604,25 @@ impl PyBaseException {
*self.traceback.write() = traceback;
}
#[pygetset(magic)]
pub fn cause(&self) -> Option<PyRef<Self>> {
#[pygetset]
pub fn __cause__(&self) -> Option<PyRef<Self>> {
self.cause.read().clone()
}
#[pygetset(magic, setter)]
pub fn set_cause(&self, cause: Option<PyRef<Self>>) {
#[pygetset(setter)]
pub fn set___cause__(&self, cause: Option<PyRef<Self>>) {
let mut c = self.cause.write();
self.set_suppress_context(true);
*c = cause;
}
#[pygetset(magic)]
pub fn context(&self) -> Option<PyRef<Self>> {
#[pygetset]
pub fn __context__(&self) -> Option<PyRef<Self>> {
self.context.read().clone()
}
#[pygetset(magic, setter)]
pub fn set_context(&self, context: Option<PyRef<Self>>) {
#[pygetset(setter)]
pub fn set___context__(&self, context: Option<PyRef<Self>>) {
*self.context.write() = context;
}
@@ -636,8 +636,8 @@ impl PyBaseException {
self.suppress_context.store(suppress_context);
}
#[pymethod(magic)]
pub(super) fn str(&self, vm: &VirtualMachine) -> PyStrRef {
#[pymethod]
pub(super) fn __str__(&self, vm: &VirtualMachine) -> PyStrRef {
let str_args = vm.exception_args_as_string(self.args(), true);
match str_args.into_iter().exactly_one() {
Err(i) if i.len() == 0 => vm.ctx.empty_str.to_owned(),
@@ -655,8 +655,8 @@ impl PyRef<PyBaseException> {
Ok(self)
}
#[pymethod(magic)]
fn reduce(self, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(self, vm: &VirtualMachine) -> PyTupleRef {
if let Some(dict) = self.as_object().dict().filter(|x| !x.is_empty()) {
vm.new_tuple((self.class().to_owned(), self.args(), dict))
} else {
@@ -664,8 +664,8 @@ impl PyRef<PyBaseException> {
}
}
#[pymethod(magic)]
fn setstate(self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
#[pymethod]
fn __setstate__(self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
if !vm.is_none(&state) {
let dict = state
.downcast::<crate::builtins::PyDict>()
@@ -1098,21 +1098,21 @@ impl serde::Serialize for SerializeException<'_, '_> {
s.end()
}
}
self.exc.traceback().map(Tracebacks)
self.exc.__traceback__().map(Tracebacks)
};
struc.serialize_field("traceback", &tbs)?;
struc.serialize_field(
"cause",
&self
.exc
.cause()
.__cause__()
.map(|exc| SerializeExceptionOwned { vm: self.vm, exc }),
)?;
struc.serialize_field(
"context",
&self
.exc
.context()
.__context__()
.map(|exc| SerializeExceptionOwned { vm: self.vm, exc }),
)?;
struc.serialize_field("suppress_context", &self.exc.get_suppress_context())?;
@@ -1358,8 +1358,8 @@ pub(super) mod types {
zelf.set_attr("path", vm.unwrap_or_none(path), vm)?;
PyBaseException::slot_init(zelf, args, vm)
}
#[pymethod(magic)]
fn reduce(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyTupleRef {
let obj = exc.as_object().to_owned();
let mut result: Vec<PyObjectRef> = vec![
obj.class().to_owned().into(),
@@ -1392,8 +1392,8 @@ pub(super) mod types {
#[pyexception]
impl PyKeyError {
#[pymethod(magic)]
fn str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyStrRef {
#[pymethod]
fn __str__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyStrRef {
let args = exc.args();
if args.len() == 1 {
vm.exception_args_as_string(args, false)
@@ -1401,7 +1401,7 @@ pub(super) mod types {
.exactly_one()
.unwrap()
} else {
exc.str(vm)
exc.__str__(vm)
}
}
}
@@ -1479,8 +1479,8 @@ pub(super) mod types {
PyBaseException::slot_init(zelf, new_args, vm)
}
#[pymethod(magic)]
fn str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
#[pymethod]
fn __str__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let args = exc.args();
let obj = exc.as_object().to_owned();
@@ -1506,12 +1506,12 @@ pub(super) mod types {
};
Ok(vm.ctx.new_str(s))
} else {
Ok(exc.str(vm))
Ok(exc.__str__(vm))
}
}
#[pymethod(magic)]
fn reduce(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyTupleRef {
let args = exc.args();
let obj = exc.as_object().to_owned();
let mut result: Vec<PyObjectRef> = vec![obj.class().to_owned().into()];
@@ -1677,8 +1677,8 @@ pub(super) mod types {
PyBaseException::slot_init(zelf, new_args, vm)
}
#[pymethod(magic)]
fn str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyStrRef {
#[pymethod]
fn __str__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyStrRef {
fn basename(filename: &str) -> &str {
let splitted = if cfg!(windows) {
filename.rsplit(&['/', '\\']).next()
@@ -1705,7 +1705,7 @@ pub(super) mod types {
.exactly_one()
.unwrap()
} else {
return exc.str(vm);
return exc.__str__(vm);
};
let msg_with_location_info: String = match (maybe_lineno, maybe_filename) {
@@ -1795,8 +1795,8 @@ pub(super) mod types {
Ok(())
}
#[pymethod(magic)]
fn str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult<String> {
#[pymethod]
fn __str__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult<String> {
let Ok(object) = exc.as_object().get_attr("object", vm) else {
return Ok("".to_owned());
};
@@ -1845,8 +1845,8 @@ pub(super) mod types {
Ok(())
}
#[pymethod(magic)]
fn str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult<String> {
#[pymethod]
fn __str__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult<String> {
let Ok(object) = exc.as_object().get_attr("object", vm) else {
return Ok("".to_owned());
};
@@ -1895,8 +1895,8 @@ pub(super) mod types {
Ok(())
}
#[pymethod(magic)]
fn str(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult<String> {
#[pymethod]
fn __str__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult<String> {
let Ok(object) = exc.as_object().get_attr("object", vm) else {
return Ok("".to_owned());
};
+2 -2
View File
@@ -386,7 +386,7 @@ impl ExecutingFrame<'_> {
// 3. Unwind block stack till appropriate handler is found.
let loc = frame.code.locations[idx].clone();
let next = exception.traceback();
let next = exception.__traceback__();
let new_traceback =
PyTraceback::new(next, frame.object.to_owned(), frame.lasti(), loc.row);
vm_trace!("Adding to traceback: {:?} {:?}", new_traceback, loc.row);
@@ -1711,7 +1711,7 @@ impl ExecutingFrame<'_> {
#[cfg(debug_assertions)]
debug!("Exception raised: {exception:?} with cause: {cause:?}");
if let Some(cause) = cause {
exception.set_cause(cause);
exception.set___cause__(cause);
}
Err(exception)
}
+1 -1
View File
@@ -211,7 +211,7 @@ pub fn remove_importlib_frames(vm: &VirtualMachine, exc: &PyBaseExceptionRef) {
let always_trim = exc.fast_isinstance(vm.ctx.exceptions.import_error);
if let Some(tb) = exc.traceback() {
if let Some(tb) = exc.__traceback__() {
let trimmed_tb = remove_importlib_frames_inner(vm, Some(tb), always_trim).0;
exc.set_traceback_typed(trimmed_tb);
}
+2 -2
View File
@@ -15,8 +15,8 @@ pub(crate) mod _ast {
#[pyclass(flags(BASETYPE, HAS_DICT))]
impl NodeAst {
#[pyslot]
#[pymethod(magic)]
fn init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __init__(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let fields = zelf.get_attr("_fields", vm)?;
let fields: Vec<PyStrRef> = fields.try_to_value(vm)?;
let n_args = args.args.len();
+50 -46
View File
@@ -93,7 +93,7 @@ mod _collections {
self.borrow_deque_mut().clear()
}
#[pymethod(magic)]
#[pymethod(name = "__copy__")]
#[pymethod]
fn copy(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
Self {
@@ -170,7 +170,7 @@ mod _collections {
) -> PyResult<usize> {
let start_state = self.state.load();
let (start, stop) = range.saturate(self.len(), vm)?;
let (start, stop) = range.saturate(self.__len__(), vm)?;
let index = self.mut_index_range(vm, &needle, start..stop)?;
if start_state != self.state.load() {
Err(vm.new_runtime_error("deque mutated during iteration"))
@@ -250,8 +250,8 @@ mod _collections {
*self.borrow_deque_mut() = rev;
}
#[pymethod(magic)]
fn reversed(zelf: PyRef<Self>) -> PyResult<PyReverseDequeIterator> {
#[pymethod]
fn __reversed__(zelf: PyRef<Self>) -> PyResult<PyReverseDequeIterator> {
Ok(PyReverseDequeIterator {
state: zelf.state.load(),
internal: PyMutex::new(PositionIterInternal::new(zelf, 0)),
@@ -277,16 +277,16 @@ mod _collections {
self.maxlen
}
#[pymethod(magic)]
fn getitem(&self, idx: isize, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getitem__(&self, idx: isize, vm: &VirtualMachine) -> PyResult {
let deque = self.borrow_deque();
idx.wrapped_at(deque.len())
.and_then(|i| deque.get(i).cloned())
.ok_or_else(|| vm.new_index_error("deque index out of range"))
}
#[pymethod(magic)]
fn setitem(&self, idx: isize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setitem__(&self, idx: isize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let mut deque = self.borrow_deque_mut();
idx.wrapped_at(deque.len())
.and_then(|i| deque.get_mut(i))
@@ -294,16 +294,16 @@ mod _collections {
.ok_or_else(|| vm.new_index_error("deque index out of range"))
}
#[pymethod(magic)]
fn delitem(&self, idx: isize, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __delitem__(&self, idx: isize, vm: &VirtualMachine) -> PyResult<()> {
let mut deque = self.borrow_deque_mut();
idx.wrapped_at(deque.len())
.and_then(|i| deque.remove(i).map(drop))
.ok_or_else(|| vm.new_index_error("deque index out of range"))
}
#[pymethod(magic)]
fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
#[pymethod]
fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
self._contains(&needle, vm)
}
@@ -331,9 +331,9 @@ mod _collections {
Ok(deque)
}
#[pymethod(magic)]
#[pymethod]
#[pymethod(name = "__rmul__")]
fn mul(&self, n: isize, vm: &VirtualMachine) -> PyResult<Self> {
fn __mul__(&self, n: isize, vm: &VirtualMachine) -> PyResult<Self> {
let deque = self._mul(n, vm)?;
Ok(PyDeque {
deque: PyRwLock::new(deque),
@@ -342,25 +342,25 @@ mod _collections {
})
}
#[pymethod(magic)]
fn imul(zelf: PyRef<Self>, n: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
#[pymethod]
fn __imul__(zelf: PyRef<Self>, n: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
let mul_deque = zelf._mul(n, vm)?;
*zelf.borrow_deque_mut() = mul_deque;
Ok(zelf)
}
#[pymethod(magic)]
fn len(&self) -> usize {
#[pymethod]
fn __len__(&self) -> usize {
self.borrow_deque().len()
}
#[pymethod(magic)]
fn bool(&self) -> bool {
#[pymethod]
fn __bool__(&self) -> bool {
!self.borrow_deque().is_empty()
}
#[pymethod(magic)]
fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
#[pymethod]
fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
self.concat(&other, vm)
}
@@ -389,8 +389,8 @@ mod _collections {
}
}
#[pymethod(magic)]
fn iadd(
#[pymethod]
fn __iadd__(
zelf: PyRef<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
@@ -399,8 +399,8 @@ mod _collections {
Ok(zelf)
}
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult {
let cls = zelf.class().to_owned();
let value = match zelf.maxlen {
Some(v) => vm.new_pyobj((vm.ctx.empty_tuple.clone(), v)),
@@ -409,8 +409,12 @@ mod _collections {
Ok(vm.new_pyobj((cls, value, vm.ctx.none(), PyDequeIterator::new(zelf))))
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(
cls: PyTypeRef,
args: PyObjectRef,
vm: &VirtualMachine,
) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
@@ -495,7 +499,7 @@ mod _collections {
impl AsSequence for PyDeque {
fn as_sequence() -> &'static PySequenceMethods {
static AS_SEQUENCE: PySequenceMethods = PySequenceMethods {
length: atomic_func!(|seq, _vm| Ok(PyDeque::sequence_downcast(seq).len())),
length: atomic_func!(|seq, _vm| Ok(PyDeque::sequence_downcast(seq).__len__())),
concat: atomic_func!(|seq, other, vm| {
PyDeque::sequence_downcast(seq)
.concat(other, vm)
@@ -503,16 +507,16 @@ mod _collections {
}),
repeat: atomic_func!(|seq, n, vm| {
PyDeque::sequence_downcast(seq)
.mul(n, vm)
.__mul__(n, vm)
.map(|x| x.into_ref(&vm.ctx).into())
}),
item: atomic_func!(|seq, i, vm| PyDeque::sequence_downcast(seq).getitem(i, vm)),
item: atomic_func!(|seq, i, vm| PyDeque::sequence_downcast(seq).__getitem__(i, vm)),
ass_item: atomic_func!(|seq, i, value, vm| {
let zelf = PyDeque::sequence_downcast(seq);
if let Some(value) = value {
zelf.setitem(i, value, vm)
zelf.__setitem__(i, value, vm)
} else {
zelf.delitem(i, vm)
zelf.__delitem__(i, vm)
}
}),
contains: atomic_func!(
@@ -525,7 +529,7 @@ mod _collections {
}),
inplace_repeat: atomic_func!(|seq, n, vm| {
let zelf = PyDeque::sequence_downcast(seq);
PyDeque::imul(zelf.to_owned(), n, vm).map(|x| x.into())
PyDeque::__imul__(zelf.to_owned(), n, vm).map(|x| x.into())
}),
};
@@ -569,7 +573,7 @@ mod _collections {
.map(|maxlen| format!("], maxlen={maxlen}"))
.unwrap_or_else(|| "]".to_owned());
let s = if zelf.len() == 0 {
let s = if zelf.__len__() == 0 {
format!("{class_name}([{closing_part})")
} else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
collection_repr(Some(&class_name), "[", &closing_part, deque.iter(), vm)?
@@ -624,13 +628,13 @@ mod _collections {
}
}
#[pymethod(magic)]
fn length_hint(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.len())
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.__len__())
}
#[pymethod(magic)]
fn reduce(
#[pymethod]
fn __reduce__(
zelf: PyRef<Self>,
vm: &VirtualMachine,
) -> (PyTypeRef, (PyDequeRef, PyObjectRef)) {
@@ -679,7 +683,7 @@ mod _collections {
(DequeIterArgs { deque, index }, _kwargs): Self::Args,
vm: &VirtualMachine,
) -> PyResult {
let iter = PyDeque::reversed(deque)?;
let iter = PyDeque::__reversed__(deque)?;
if let OptionalArg::Present(index) = index {
let index = max(index, 0) as usize;
iter.internal.lock().position = index;
@@ -690,13 +694,13 @@ mod _collections {
#[pyclass(with(IterNext, Iterable, Constructor))]
impl PyReverseDequeIterator {
#[pymethod(magic)]
fn length_hint(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.len())
#[pymethod]
fn __length_hint__(&self) -> usize {
self.internal.lock().length_hint(|obj| obj.__len__())
}
#[pymethod(magic)]
fn reduce(
#[pymethod]
fn __reduce__(
zelf: PyRef<Self>,
vm: &VirtualMachine,
) -> PyResult<(PyTypeRef, (PyDequeRef, PyObjectRef))> {
+2 -2
View File
@@ -261,8 +261,8 @@ impl PyCSimple {
.to_pyobject(vm))
}
#[pyclassmethod(magic)]
fn mul(cls: PyTypeRef, n: isize, vm: &VirtualMachine) -> PyResult {
#[pyclassmethod]
fn __mul__(cls: PyTypeRef, n: isize, vm: &VirtualMachine) -> PyResult {
PyCSimple::repeat(cls, n, vm)
}
}
+4 -4
View File
@@ -199,13 +199,13 @@ impl Callable for PyCFuncPtr {
#[pyclass(flags(BASETYPE), with(Callable, Constructor))]
impl PyCFuncPtr {
#[pygetset(magic)]
fn name(&self) -> String {
#[pygetset]
fn __name__(&self) -> String {
self.name.read().clone()
}
#[pygetset(setter, magic)]
fn set_name(&self, name: String) {
#[pygetset(setter)]
fn set___name__(&self, name: String) {
*self.name.write() = name;
}
+3 -3
View File
@@ -100,8 +100,8 @@ mod _functools {
.into())
}
#[pymethod(magic)]
fn setstate(zelf: &Py<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(zelf: &Py<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let state_tuple = state
.downcast::<PyTuple>()
.map_err(|_| vm.new_type_error("argument to __setstate__ must be a tuple"))?;
@@ -293,7 +293,7 @@ mod _functools {
}
let class_name = zelf.class().name();
let module = zelf.class().module(vm);
let module = zelf.class().__module__(vm);
let qualified_name = if zelf.class().is(PyPartial::class(&vm.ctx)) {
// For the base partial class, always use functools.partial
+14 -14
View File
@@ -425,14 +425,14 @@ mod _io {
ctx.new_bool(false)
}
#[pymethod(magic)]
fn enter(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __enter__(instance: PyObjectRef, vm: &VirtualMachine) -> PyResult {
check_closed(&instance, vm)?;
Ok(instance)
}
#[pymethod(magic)]
fn exit(instance: PyObjectRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __exit__(instance: PyObjectRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
vm.call_method(&instance, "close", ())?;
Ok(())
}
@@ -1410,7 +1410,7 @@ mod _io {
fn __init__(&self, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let (raw, BufferSize { buffer_size }): (PyObjectRef, _) =
args.bind(vm).map_err(|e| {
let msg = format!("{}() {}", Self::CLASS_NAME, *e.str(vm));
let msg = format!("{}() {}", Self::CLASS_NAME, *e.__str__(vm));
vm.new_exception_msg(e.class().to_owned(), msg)
})?;
self.init(raw, BufferSize { buffer_size }, vm)
@@ -1559,8 +1559,8 @@ mod _io {
Ok(vm.ctx.new_str(repr))
}
#[pymethod(magic)]
fn repr(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
#[pymethod]
fn __repr__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Self::slot_repr(&zelf, vm)
}
@@ -1601,8 +1601,8 @@ mod _io {
}
// TODO: this should be the default for an equivalent of _PyObject_GetState
#[pymethod(magic)]
fn reduce(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reduce__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error(format!("cannot pickle '{}' object", zelf.class().name())))
}
}
@@ -1680,7 +1680,7 @@ mod _io {
fn exception_chain<T>(e1: PyResult<()>, e2: PyResult<T>) -> PyResult<T> {
match (e1, e2) {
(Err(e1), Err(e)) => {
e.set_context(Some(e1));
e.set___context__(Some(e1));
Err(e)
}
(Err(e), Ok(_)) | (Ok(()), Err(e)) => Err(e),
@@ -2994,8 +2994,8 @@ mod _io {
Ok(self.lock(vm)?.buffer.clone())
}
#[pymethod(magic)]
fn reduce(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reduce__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error(format!("cannot pickle '{}' object", zelf.class().name())))
}
}
@@ -4503,8 +4503,8 @@ mod fileio {
Ok(os::isatty(fd))
}
#[pymethod(magic)]
fn reduce(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __reduce__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error(format!("cannot pickle '{}' object", zelf.class().name())))
}
}
+68 -48
View File
@@ -62,13 +62,17 @@ mod decl {
.into_ref_with_type(vm, cls)
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(
cls: PyTypeRef,
args: PyObjectRef,
vm: &VirtualMachine,
) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
let source = zelf.source.read().clone();
let active = zelf.active.read().clone();
let cls = zelf.class().to_owned();
@@ -83,8 +87,8 @@ mod decl {
Ok(reduced)
}
#[pymethod(magic)]
fn setstate(zelf: PyRef<Self>, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(zelf: PyRef<Self>, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> {
let args = state.as_slice();
if args.is_empty() {
let msg = String::from("function takes at least 1 arguments (0 given)");
@@ -197,8 +201,8 @@ mod decl {
#[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))]
impl PyItertoolsCompress {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyIter, PyIter)) {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>) -> (PyTypeRef, (PyIter, PyIter)) {
(
zelf.class().to_owned(),
(zelf.data.clone(), zelf.selectors.clone()),
@@ -270,8 +274,8 @@ mod decl {
// TODO: Implement this
// if (lz->cnt == PY_SSIZE_T_MAX)
// return Py_BuildValue("0(00)", Py_TYPE(lz), lz->long_cnt, lz->long_step);
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef,)) {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef,)) {
(zelf.class().to_owned(), (zelf.cur.read().clone(),))
}
}
@@ -391,8 +395,8 @@ mod decl {
#[pyclass(with(IterNext, Iterable, Constructor, Representable), flags(BASETYPE))]
impl PyItertoolsRepeat {
#[pymethod(magic)]
fn length_hint(&self, vm: &VirtualMachine) -> PyResult<usize> {
#[pymethod]
fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult<usize> {
// Return TypeError, length_hint picks this up and returns the default.
let times = self
.times
@@ -401,8 +405,8 @@ mod decl {
Ok(*times.read())
}
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
let cls = zelf.class().to_owned();
Ok(match zelf.times {
Some(ref times) => vm.new_tuple((cls, (zelf.object.clone(), *times.read()))),
@@ -470,8 +474,8 @@ mod decl {
#[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))]
impl PyItertoolsStarmap {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter)) {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter)) {
(
zelf.class().to_owned(),
(zelf.function.clone(), zelf.iterable.clone()),
@@ -535,16 +539,20 @@ mod decl {
#[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))]
impl PyItertoolsTakewhile {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter), u32) {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter), u32) {
(
zelf.class().to_owned(),
(zelf.predicate.clone(), zelf.iterable.clone()),
zelf.stop_flag.load() as _,
)
}
#[pymethod(magic)]
fn setstate(zelf: PyRef<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(
zelf: PyRef<Self>,
state: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
if let Ok(obj) = ArgIntoBool::try_from_object(vm, state) {
zelf.stop_flag.store(*obj);
}
@@ -618,16 +626,20 @@ mod decl {
#[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))]
impl PyItertoolsDropwhile {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter), u32) {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter), u32) {
(
zelf.class().to_owned(),
(zelf.predicate.clone().into(), zelf.iterable.clone()),
(zelf.start_flag.load() as _),
)
}
#[pymethod(magic)]
fn setstate(zelf: PyRef<Self>, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(
zelf: PyRef<Self>,
state: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
if let Ok(obj) = ArgIntoBool::try_from_object(vm, state) {
zelf.start_flag.store(*obj);
}
@@ -951,8 +963,8 @@ mod decl {
.map(Into::into)
}
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
let cls = zelf.class().to_owned();
let itr = zelf.iterable.clone();
let cur = zelf.cur.take();
@@ -964,8 +976,8 @@ mod decl {
}
}
#[pymethod(magic)]
fn setstate(zelf: PyRef<Self>, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(zelf: PyRef<Self>, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> {
let args = state.as_slice();
if args.len() != 1 {
let msg = format!("function takes exactly 1 argument ({} given)", args.len());
@@ -1048,8 +1060,8 @@ mod decl {
#[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))]
impl PyItertoolsFilterFalse {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter)) {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>) -> (PyTypeRef, (PyObjectRef, PyIter)) {
(
zelf.class().to_owned(),
(zelf.predicate.clone(), zelf.iterable.clone()),
@@ -1118,14 +1130,18 @@ mod decl {
#[pyclass(with(IterNext, Iterable, Constructor))]
impl PyItertoolsAccumulate {
#[pymethod(magic)]
fn setstate(zelf: PyRef<Self>, state: PyObjectRef, _vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(
zelf: PyRef<Self>,
state: PyObjectRef,
_vm: &VirtualMachine,
) -> PyResult<()> {
*zelf.acc_value.write() = Some(state);
Ok(())
}
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyTupleRef {
let class = zelf.class().to_owned();
let bin_op = zelf.bin_op.clone();
let it = zelf.iterable.clone();
@@ -1287,8 +1303,8 @@ mod decl {
.into())
}
#[pymethod(magic)]
fn copy(&self) -> Self {
#[pymethod]
fn __copy__(&self) -> Self {
Self {
tee_data: PyRc::clone(&self.tee_data),
index: AtomicCell::new(self.index.load()),
@@ -1374,8 +1390,8 @@ mod decl {
}
}
#[pymethod(magic)]
fn setstate(zelf: PyRef<Self>, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(zelf: PyRef<Self>, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> {
let args = state.as_slice();
if args.len() != zelf.pools.len() {
let msg = "Invalid number of arguments".to_string();
@@ -1400,8 +1416,8 @@ mod decl {
Ok(())
}
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyTupleRef {
let class = zelf.class().to_owned();
if zelf.stop.load() {
@@ -1509,8 +1525,8 @@ mod decl {
#[pyclass(with(IterNext, Iterable, Constructor))]
impl PyItertoolsCombinations {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyTupleRef {
let r = zelf.r.load();
let class = zelf.class().to_owned();
@@ -1750,8 +1766,8 @@ mod decl {
#[pyclass(with(IterNext, Iterable, Constructor))]
impl PyItertoolsPermutations {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRef<PyTuple> {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyRef<PyTuple> {
vm.new_tuple((
zelf.class().to_owned(),
vm.new_tuple((zelf.pool.clone(), vm.ctx.new_int(zelf.r.load()))),
@@ -1863,8 +1879,8 @@ mod decl {
#[pyclass(with(IterNext, Iterable, Constructor))]
impl PyItertoolsZipLongest {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
let args: Vec<PyObjectRef> = zelf
.iterators
.iter()
@@ -1877,8 +1893,12 @@ mod decl {
)))
}
#[pymethod(magic)]
fn setstate(zelf: PyRef<Self>, state: PyObjectRef, _vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __setstate__(
zelf: PyRef<Self>,
state: PyObjectRef,
_vm: &VirtualMachine,
) -> PyResult<()> {
*zelf.fillvalue.write() = state;
Ok(())
}
+6 -6
View File
@@ -356,8 +356,8 @@ mod _operator {
#[pyclass(with(Callable, Constructor, Representable))]
impl PyAttrGetter {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<(PyTypeRef, PyTupleRef)> {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<(PyTypeRef, PyTupleRef)> {
let attrs = vm
.ctx
.new_tuple(zelf.attrs.iter().map(|v| v.clone().into()).collect());
@@ -455,8 +455,8 @@ mod _operator {
#[pyclass(with(Callable, Constructor, Representable))]
impl PyItemGetter {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyObjectRef {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyObjectRef {
let items = vm.ctx.new_tuple(zelf.items.to_vec());
vm.new_pyobj((zelf.class().to_owned(), items))
}
@@ -526,8 +526,8 @@ mod _operator {
#[pyclass(with(Callable, Constructor, Representable))]
impl PyMethodCaller {
#[pymethod(magic)]
fn reduce(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
#[pymethod]
fn __reduce__(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
// With no kwargs, return (type(obj), (name, *args)) tuple.
if zelf.args.kwargs.is_empty() {
let mut py_args = vec![zelf.name.as_object().to_owned()];
+12 -8
View File
@@ -581,13 +581,17 @@ pub(super) mod _os {
Ok(junction::exists(self.pathval.clone()).unwrap_or(false))
}
#[pymethod(magic)]
fn fspath(&self, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __fspath__(&self, vm: &VirtualMachine) -> PyResult {
self.path(vm)
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(
cls: PyTypeRef,
args: PyObjectRef,
vm: &VirtualMachine,
) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
@@ -637,13 +641,13 @@ pub(super) mod _os {
let _dropped = entryref.take();
}
#[pymethod(magic)]
fn enter(zelf: PyRef<Self>) -> PyRef<Self> {
#[pymethod]
fn __enter__(zelf: PyRef<Self>) -> PyRef<Self> {
zelf
}
#[pymethod(magic)]
fn exit(zelf: PyRef<Self>, _args: FuncArgs) {
#[pymethod]
fn __exit__(zelf: PyRef<Self>, _args: FuncArgs) {
zelf.close()
}
}
+15 -7
View File
@@ -496,8 +496,12 @@ mod _sre {
})
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(
cls: PyTypeRef,
args: PyObjectRef,
vm: &VirtualMachine,
) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
@@ -717,8 +721,8 @@ mod _sre {
})
}
#[pymethod(magic)]
fn getitem(
#[pymethod]
fn __getitem__(
&self,
group: PyObjectRef,
vm: &VirtualMachine,
@@ -806,8 +810,12 @@ mod _sre {
Some(str_drive.slice(start as usize, end as usize, vm))
}
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
#[pyclassmethod]
fn __class_getitem__(
cls: PyTypeRef,
args: PyObjectRef,
vm: &VirtualMachine,
) -> PyGenericAlias {
PyGenericAlias::new(cls, args, vm)
}
}
@@ -818,7 +826,7 @@ mod _sre {
std::sync::LazyLock::new(|| PyMappingMethods {
subscript: atomic_func!(|mapping, needle, vm| {
Match::mapping_downcast(mapping)
.getitem(needle.to_owned(), vm)
.__getitem__(needle.to_owned(), vm)
.map(|x| x.to_pyobject(vm))
}),
..PyMappingMethods::NOT_IMPLEMENTED
+4 -4
View File
@@ -158,8 +158,8 @@ pub(crate) mod _thread {
Ok(())
}
#[pymethod(magic)]
fn exit(&self, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __exit__(&self, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
self.release(vm)
}
@@ -244,8 +244,8 @@ pub(crate) mod _thread {
self.mu.is_owned_by_current_thread()
}
#[pymethod(magic)]
fn exit(&self, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __exit__(&self, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
self.release(vm)
}
}
+66 -66
View File
@@ -69,18 +69,18 @@ pub(crate) mod decl {
}
#[pyclass(flags(HAS_DICT), with(AsNumber, Constructor, Representable))]
impl TypeVar {
#[pymethod(magic)]
fn mro_entries(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("Cannot subclass an instance of TypeVar"))
}
#[pygetset(magic)]
fn name(&self) -> PyObjectRef {
#[pygetset]
fn __name__(&self) -> PyObjectRef {
self.name.clone()
}
#[pygetset(magic)]
fn constraints(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __constraints__(&self, vm: &VirtualMachine) -> PyResult {
let mut constraints = self.constraints.lock();
if !vm.is_none(&constraints) {
return Ok(constraints.clone());
@@ -94,8 +94,8 @@ pub(crate) mod decl {
Ok(r)
}
#[pygetset(magic)]
fn bound(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __bound__(&self, vm: &VirtualMachine) -> PyResult {
let mut bound = self.bound.lock();
if !vm.is_none(&bound) {
return Ok(bound.clone());
@@ -109,23 +109,23 @@ pub(crate) mod decl {
Ok(r)
}
#[pygetset(magic)]
fn covariant(&self) -> bool {
#[pygetset]
fn __covariant__(&self) -> bool {
self.covariant
}
#[pygetset(magic)]
fn contravariant(&self) -> bool {
#[pygetset]
fn __contravariant__(&self) -> bool {
self.contravariant
}
#[pygetset(magic)]
fn infer_variance(&self) -> bool {
#[pygetset]
fn __infer_variance__(&self) -> bool {
self.infer_variance
}
#[pygetset(magic)]
fn default(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __default__(&self, vm: &VirtualMachine) -> PyResult {
let mut default_value = self.default_value.lock();
// Check if default_value is NoDefault (not just None)
if !default_value.is(&vm.ctx.typing_no_default) {
@@ -140,8 +140,8 @@ pub(crate) mod decl {
}
}
#[pymethod(magic)]
fn typing_subst(
#[pymethod]
fn __typing_subst__(
zelf: crate::PyRef<Self>,
arg: PyObjectRef,
vm: &VirtualMachine,
@@ -150,8 +150,8 @@ pub(crate) mod decl {
_call_typing_func_object(vm, "_typevar_subst", (self_obj, arg))
}
#[pymethod(magic)]
fn reduce(&self) -> PyObjectRef {
#[pymethod]
fn __reduce__(&self) -> PyObjectRef {
self.name.clone()
}
@@ -344,13 +344,13 @@ pub(crate) mod decl {
#[pyclass(flags(HAS_DICT), with(AsNumber, Constructor))]
impl ParamSpec {
#[pymethod(magic)]
fn mro_entries(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("Cannot subclass an instance of ParamSpec"))
}
#[pygetset(magic)]
fn name(&self) -> PyObjectRef {
#[pygetset]
fn __name__(&self) -> PyObjectRef {
self.name.clone()
}
@@ -372,31 +372,31 @@ pub(crate) mod decl {
Ok(psk.into_ref(&vm.ctx).into())
}
#[pygetset(magic)]
fn bound(&self, vm: &VirtualMachine) -> PyObjectRef {
#[pygetset]
fn __bound__(&self, vm: &VirtualMachine) -> PyObjectRef {
if let Some(bound) = self.bound.clone() {
return bound;
}
vm.ctx.none()
}
#[pygetset(magic)]
fn covariant(&self) -> bool {
#[pygetset]
fn __covariant__(&self) -> bool {
self.covariant
}
#[pygetset(magic)]
fn contravariant(&self) -> bool {
#[pygetset]
fn __contravariant__(&self) -> bool {
self.contravariant
}
#[pygetset(magic)]
fn infer_variance(&self) -> bool {
#[pygetset]
fn __infer_variance__(&self) -> bool {
self.infer_variance
}
#[pygetset(magic)]
fn default(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __default__(&self, vm: &VirtualMachine) -> PyResult {
if let Some(ref default_value) = self.default_value {
// Check if default_value is NoDefault (not just None)
if !default_value.is(&vm.ctx.typing_no_default) {
@@ -420,8 +420,8 @@ pub(crate) mod decl {
vm.ctx.none()
}
#[pymethod(magic)]
fn reduce(&self) -> PyResult {
#[pymethod]
fn __reduce__(&self) -> PyResult {
Ok(self.name.clone())
}
@@ -438,8 +438,8 @@ pub(crate) mod decl {
}
}
#[pymethod(magic)]
fn typing_subst(
#[pymethod]
fn __typing_subst__(
zelf: crate::PyRef<Self>,
arg: PyObjectRef,
vm: &VirtualMachine,
@@ -448,8 +448,8 @@ pub(crate) mod decl {
_call_typing_func_object(vm, "_paramspec_subst", (self_obj, arg))
}
#[pymethod(magic)]
fn typing_prepare_subst(
#[pymethod]
fn __typing_prepare_subst__(
zelf: crate::PyRef<Self>,
alias: PyObjectRef,
args: PyTupleRef,
@@ -572,8 +572,8 @@ pub(crate) mod decl {
#[pyclass(with(Constructor, Representable), flags(BASETYPE))]
impl NoDefault {
#[pymethod(magic)]
fn reduce(&self, _vm: &VirtualMachine) -> String {
#[pymethod]
fn __reduce__(&self, _vm: &VirtualMachine) -> String {
"NoDefault".to_owned()
}
}
@@ -609,13 +609,13 @@ pub(crate) mod decl {
}
#[pyclass(flags(HAS_DICT), with(Constructor, Representable, Iterable))]
impl TypeVarTuple {
#[pygetset(magic)]
fn name(&self) -> PyObjectRef {
#[pygetset]
fn __name__(&self) -> PyObjectRef {
self.name.clone()
}
#[pygetset(magic)]
fn default(&self, vm: &VirtualMachine) -> PyResult {
#[pygetset]
fn __default__(&self, vm: &VirtualMachine) -> PyResult {
let mut default_value = self.default_value.lock();
// Check if default_value is NoDefault (not just None)
if !default_value.is(&vm.ctx.typing_no_default) {
@@ -640,23 +640,23 @@ pub(crate) mod decl {
!default_value.is(&vm.ctx.typing_no_default)
}
#[pymethod(magic)]
fn reduce(&self) -> PyObjectRef {
#[pymethod]
fn __reduce__(&self) -> PyObjectRef {
self.name.clone()
}
#[pymethod(magic)]
fn mro_entries(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("Cannot subclass an instance of TypeVarTuple"))
}
#[pymethod(magic)]
fn typing_subst(&self, _arg: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __typing_subst__(&self, _arg: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("Substitution of bare TypeVarTuple is not supported"))
}
#[pymethod(magic)]
fn typing_prepare_subst(
#[pymethod]
fn __typing_prepare_subst__(
zelf: crate::PyRef<Self>,
alias: PyObjectRef,
args: PyObjectRef,
@@ -759,13 +759,13 @@ pub(crate) mod decl {
}
#[pyclass(with(Constructor, Representable, Comparable))]
impl ParamSpecArgs {
#[pymethod(magic)]
fn mro_entries(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("Cannot subclass an instance of ParamSpecArgs"))
}
#[pygetset(magic)]
fn origin(&self) -> PyObjectRef {
#[pygetset]
fn __origin__(&self) -> PyObjectRef {
self.__origin__.clone()
}
}
@@ -838,13 +838,13 @@ pub(crate) mod decl {
}
#[pyclass(with(Constructor, Representable, Comparable))]
impl ParamSpecKwargs {
#[pymethod(magic)]
fn mro_entries(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __mro_entries__(&self, _bases: PyObjectRef, vm: &VirtualMachine) -> PyResult {
Err(vm.new_type_error("Cannot subclass an instance of ParamSpecKwargs"))
}
#[pygetset(magic)]
fn origin(&self) -> PyObjectRef {
#[pygetset]
fn __origin__(&self) -> PyObjectRef {
self.__origin__.clone()
}
}
@@ -967,8 +967,8 @@ pub(crate) mod decl {
// #[pyclass(with(AsMapping), flags(BASETYPE))]
#[pyclass(flags(BASETYPE))]
impl Generic {
#[pyclassmethod(magic)]
fn class_getitem(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyResult {
#[pyclassmethod]
fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyResult {
// Convert single arg to FuncArgs
let func_args = FuncArgs {
args: vec![args],
@@ -977,8 +977,8 @@ pub(crate) mod decl {
call_typing_args_kwargs("_generic_class_getitem", cls, func_args, vm)
}
#[pyclassmethod(magic)]
fn init_subclass(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
#[pyclassmethod]
fn __init_subclass__(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
call_typing_args_kwargs("_generic_init_subclass", cls, args, vm)
}
}
+6 -6
View File
@@ -101,16 +101,16 @@ mod winreg {
handle as usize
}
#[pymethod(magic)]
fn bool(&self) -> bool {
#[pymethod]
fn __bool__(&self) -> bool {
!self.key().raw_handle().is_null()
}
#[pymethod(magic)]
fn enter(zelf: PyRef<Self>) -> PyRef<Self> {
#[pymethod]
fn __enter__(zelf: PyRef<Self>) -> PyRef<Self> {
zelf
}
#[pymethod(magic)]
fn exit(&self, _cls: PyObjectRef, _exc: PyObjectRef, _tb: PyObjectRef) {
#[pymethod]
fn __exit__(&self, _cls: PyObjectRef, _exc: PyObjectRef, _tb: PyObjectRef) {
self.Close();
}
}
+1 -1
View File
@@ -55,7 +55,7 @@ pub fn offer_suggestions(exc: &PyBaseExceptionRef, vm: &VirtualMachine) -> Optio
calculate_suggestions(vm.dir(Some(obj)).ok()?.borrow_vec().iter(), &name)
} else if exc.class().is(vm.ctx.exceptions.name_error) {
let name = exc.as_object().get_attr("name", vm).unwrap();
let tb = exc.traceback()?;
let tb = exc.__traceback__()?;
let tb = tb.iter().last().unwrap_or(tb);
let varnames = tb.frame.code.clone().co_varnames(vm);
+44 -20
View File
@@ -896,8 +896,8 @@ pub trait GetDescriptor: PyPayload {
) -> PyResult;
#[inline]
#[pymethod(magic)]
fn get(
#[pymethod]
fn __get__(
zelf: PyObjectRef,
obj: PyObjectRef,
cls: OptionalArg<PyObjectRef>,
@@ -1022,33 +1022,57 @@ pub trait Comparable: PyPayload {
) -> PyResult<PyComparisonValue>;
#[inline]
#[pymethod(magic)]
fn eq(zelf: &Py<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyComparisonValue> {
#[pymethod]
fn __eq__(
zelf: &Py<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(zelf, &other, PyComparisonOp::Eq, vm)
}
#[inline]
#[pymethod(magic)]
fn ne(zelf: &Py<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyComparisonValue> {
#[pymethod]
fn __ne__(
zelf: &Py<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(zelf, &other, PyComparisonOp::Ne, vm)
}
#[inline]
#[pymethod(magic)]
fn lt(zelf: &Py<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyComparisonValue> {
#[pymethod]
fn __lt__(
zelf: &Py<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(zelf, &other, PyComparisonOp::Lt, vm)
}
#[inline]
#[pymethod(magic)]
fn le(zelf: &Py<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyComparisonValue> {
#[pymethod]
fn __le__(
zelf: &Py<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(zelf, &other, PyComparisonOp::Le, vm)
}
#[inline]
#[pymethod(magic)]
fn ge(zelf: &Py<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyComparisonValue> {
#[pymethod]
fn __ge__(
zelf: &Py<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(zelf, &other, PyComparisonOp::Ge, vm)
}
#[inline]
#[pymethod(magic)]
fn gt(zelf: &Py<Self>, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyComparisonValue> {
#[pymethod]
fn __gt__(
zelf: &Py<Self>,
other: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
Self::cmp(zelf, &other, PyComparisonOp::Gt, vm)
}
}
@@ -1164,8 +1188,8 @@ pub trait GetAttr: PyPayload {
fn getattro(zelf: &Py<Self>, name: &Py<PyStr>, vm: &VirtualMachine) -> PyResult;
#[inline]
#[pymethod(magic)]
fn getattribute(zelf: PyRef<Self>, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
#[pymethod]
fn __getattribute__(zelf: PyRef<Self>, name: PyStrRef, vm: &VirtualMachine) -> PyResult {
Self::getattro(&zelf, &name, vm)
}
}
@@ -1194,8 +1218,8 @@ pub trait SetAttr: PyPayload {
) -> PyResult<()>;
#[inline]
#[pymethod(magic)]
fn setattr(
#[pymethod]
fn __setattr__(
zelf: PyRef<Self>,
name: PyStrRef,
value: PyObjectRef,
@@ -1205,8 +1229,8 @@ pub trait SetAttr: PyPayload {
}
#[inline]
#[pymethod(magic)]
fn delattr(zelf: PyRef<Self>, name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
#[pymethod]
fn __delattr__(zelf: PyRef<Self>, name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
Self::setattro(&zelf, &name, PySetterValue::Delete, vm)
}
}
+4 -4
View File
@@ -47,8 +47,8 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static {
Ok(seq)
}
#[pymethod(magic)]
fn repr(zelf: PyRef<PyTuple>, vm: &VirtualMachine) -> PyResult<String> {
#[pymethod]
fn __repr__(zelf: PyRef<PyTuple>, vm: &VirtualMachine) -> PyResult<String> {
let format_field = |(value, name): (&PyObjectRef, _)| {
let s = value.repr(vm)?;
Ok(format!("{name}={s}"))
@@ -74,8 +74,8 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static {
Ok(format!("{}({}{})", Self::TP_NAME, body, suffix))
}
#[pymethod(magic)]
fn reduce(zelf: PyRef<PyTuple>, vm: &VirtualMachine) -> PyTupleRef {
#[pymethod]
fn __reduce__(zelf: PyRef<PyTuple>, vm: &VirtualMachine) -> PyTupleRef {
vm.new_tuple((zelf.class().to_owned(), (vm.ctx.new_tuple(zelf.to_vec()),)))
}
+5 -5
View File
@@ -257,7 +257,7 @@ impl VirtualMachine {
}
let err = self.new_runtime_error(msg);
err.set_cause(Some(import_err));
err.set___cause__(Some(import_err));
err
})?;
Ok(())
@@ -459,7 +459,7 @@ impl VirtualMachine {
let unraisablehook = sys_module.get_attr("unraisablehook", self).unwrap();
let exc_type = e.class().to_owned();
let exc_traceback = e.traceback().to_pyobject(self); // TODO: actual traceback
let exc_traceback = e.__traceback__().to_pyobject(self); // TODO: actual traceback
let exc_value = e.into();
let args = stdlib::sys::UnraisableHookArgs {
exc_type,
@@ -829,14 +829,14 @@ impl VirtualMachine {
if let Some(context_exc) = self.topmost_exception() {
if !context_exc.is(exception) {
let mut o = context_exc.clone();
while let Some(context) = o.context() {
while let Some(context) = o.__context__() {
if context.is(exception) {
o.set_context(None);
o.set___context__(None);
break;
}
o = context;
}
exception.set_context(Some(context_exc))
exception.set___context__(Some(context_exc))
}
}
}