From 4378a61c8b0bb8888f78549607db3c0d5bfd29f3 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Fri, 27 Jun 2025 12:32:35 +0900 Subject: [PATCH 1/4] Fix 1.80 build --- example_projects/barebone/Cargo.toml | 3 +++ example_projects/frozen_stdlib/Cargo.toml | 3 +++ 2 files changed, 6 insertions(+) diff --git a/example_projects/barebone/Cargo.toml b/example_projects/barebone/Cargo.toml index ffae04e4ba..a993277f31 100644 --- a/example_projects/barebone/Cargo.toml +++ b/example_projects/barebone/Cargo.toml @@ -7,3 +7,6 @@ edition = "2021" rustpython-vm = { path = "../../vm", default-features = false } [workspace] + +[patch.crates-io] +radium = { version = "1.1.0", git = "https://github.com/youknowone/ferrilab", branch = "fix-nightly" } diff --git a/example_projects/frozen_stdlib/Cargo.toml b/example_projects/frozen_stdlib/Cargo.toml index 12e9e5902d..be1b1eb16c 100644 --- a/example_projects/frozen_stdlib/Cargo.toml +++ b/example_projects/frozen_stdlib/Cargo.toml @@ -9,3 +9,6 @@ rustpython-vm = { path = "../../vm", default-features = false, features = ["free rustpython-pylib = { path = "../../pylib", default-features = false, features = ["freeze-stdlib"] } [workspace] + +[patch.crates-io] +radium = { version = "1.1.0", git = "https://github.com/youknowone/ferrilab", branch = "fix-nightly" } From ef3cf70e3050fd18a114fa1ae172f51033665861 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Thu, 26 Jun 2025 22:34:41 +0900 Subject: [PATCH 2/4] Remove magic from macro --- derive-impl/src/pyclass.rs | 26 +++++++------------------- 1 file changed, 7 insertions(+), 19 deletions(-) diff --git a/derive-impl/src/pyclass.rs b/derive-impl/src/pyclass.rs index b704e083c6..645e896d6c 100644 --- a/derive-impl/src/pyclass.rs +++ b/derive-impl/src/pyclass.rs @@ -1208,7 +1208,7 @@ impl ToTokens for MemberNursery { struct MethodItemMeta(ItemMetaInner); impl ItemMeta for MethodItemMeta { - const ALLOWED_NAMES: &'static [&'static str] = &["name", "magic", "raw"]; + const ALLOWED_NAMES: &'static [&'static str] = &["name", "raw"]; fn from_inner(inner: ItemMetaInner) -> Self { Self(inner) @@ -1225,19 +1225,10 @@ impl MethodItemMeta { fn method_name(&self) -> Result { let inner = self.inner(); let name = inner._optional_str("name")?; - let magic = inner._bool("magic")?; - if magic && name.is_some() { - bail_span!( - &inner.meta_ident, - "A #[{}] method cannot be magic and have a specified name, choose one.", - inner.meta_name() - ); - } Ok(if let Some(name) = name { name } else { - let name = inner.item_name(); - if magic { format!("__{name}__") } else { name } + inner.item_name() }) } } @@ -1245,7 +1236,7 @@ impl MethodItemMeta { struct GetSetItemMeta(ItemMetaInner); impl ItemMeta for GetSetItemMeta { - const ALLOWED_NAMES: &'static [&'static str] = &["name", "magic", "setter", "deleter"]; + const ALLOWED_NAMES: &'static [&'static str] = &["name", "setter", "deleter"]; fn from_inner(inner: ItemMetaInner) -> Self { Self(inner) @@ -1258,7 +1249,6 @@ impl ItemMeta for GetSetItemMeta { impl GetSetItemMeta { fn getset_name(&self) -> Result<(String, GetSetItemKind)> { let inner = self.inner(); - let magic = inner._bool("magic")?; let kind = match (inner._bool("setter")?, inner._bool("deleter")?) { (false, false) => GetSetItemKind::Get, (true, false) => GetSetItemKind::Set, @@ -1299,12 +1289,11 @@ impl GetSetItemMeta { )) } }; - let name = match kind { + match kind { GetSetItemKind::Get => sig_name, GetSetItemKind::Set => extract_prefix_name("set_", "setter")?, GetSetItemKind::Delete => extract_prefix_name("del_", "deleter")?, - }; - if magic { format!("__{name}__") } else { name } + } }; Ok((py_name, kind)) } @@ -1379,7 +1368,7 @@ impl SlotItemMeta { struct MemberItemMeta(ItemMetaInner); impl ItemMeta for MemberItemMeta { - const ALLOWED_NAMES: &'static [&'static str] = &["magic", "type", "setter"]; + const ALLOWED_NAMES: &'static [&'static str] = &["type", "setter"]; fn from_inner(inner: ItemMetaInner) -> Self { Self(inner) @@ -1416,7 +1405,6 @@ impl MemberItemMeta { )) } }; - let magic = inner._bool("magic")?; let kind = if inner._bool("setter")? { MemberItemKind::Set } else { @@ -1426,7 +1414,7 @@ impl MemberItemMeta { MemberItemKind::Get => sig_name, MemberItemKind::Set => extract_prefix_name("set_", "setter")?, }; - Ok((if magic { format!("__{name}__") } else { name }, kind)) + Ok((name, kind)) } fn member_kind(&self) -> Result> { From 993ea8923c9fb149fa6a8c97d14e888bfbd941d2 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Thu, 26 Jun 2025 23:52:43 +0900 Subject: [PATCH 3/4] Rename members --- derive-impl/src/pyclass.rs | 39 +++++++- derive/src/lib.rs | 11 --- stdlib/src/array.rs | 108 ++++++++++---------- stdlib/src/contextvars.rs | 28 ++++-- stdlib/src/mmap.rs | 72 +++++++------- stdlib/src/pystruct.rs | 4 +- stdlib/src/select.rs | 8 +- stdlib/src/sqlite.rs | 16 +-- stdlib/src/zlib.rs | 2 +- vm/src/builtins/asyncgenerator.rs | 20 ++-- vm/src/builtins/bool.rs | 28 +++--- vm/src/builtins/builtin_func.rs | 39 ++++---- vm/src/builtins/bytearray.rs | 96 +++++++++--------- vm/src/builtins/bytes.rs | 60 +++++------ vm/src/builtins/classmethod.rs | 39 ++++---- vm/src/builtins/complex.rs | 56 +++++------ vm/src/builtins/coroutine.rs | 8 +- vm/src/builtins/descriptor.rs | 32 +++--- vm/src/builtins/dict.rs | 135 +++++++++++++------------ vm/src/builtins/enumerate.rs | 20 ++-- vm/src/builtins/filter.rs | 4 +- vm/src/builtins/float.rs | 118 ++++++++++++---------- vm/src/builtins/function.rs | 122 +++++++++++------------ vm/src/builtins/generator.rs | 8 +- vm/src/builtins/genericalias.rs | 73 +++++++------- vm/src/builtins/getset.rs | 12 +-- vm/src/builtins/int.rs | 154 ++++++++++++++--------------- vm/src/builtins/iter.rs | 12 +-- vm/src/builtins/list.rs | 94 +++++++++--------- vm/src/builtins/map.rs | 8 +- vm/src/builtins/mappingproxy.rs | 38 +++---- vm/src/builtins/memory.rs | 48 ++++----- vm/src/builtins/module.rs | 4 +- vm/src/builtins/namespace.rs | 6 +- vm/src/builtins/object.rs | 87 ++++++++-------- vm/src/builtins/property.rs | 14 +-- vm/src/builtins/range.rs | 56 +++++------ vm/src/builtins/set.rs | 159 +++++++++++++++++------------- vm/src/builtins/singletons.rs | 12 +-- vm/src/builtins/slice.rs | 8 +- vm/src/builtins/staticmethod.rs | 39 ++++---- vm/src/builtins/str.rs | 46 ++++----- vm/src/builtins/super.rs | 8 +- vm/src/builtins/tuple.rs | 48 ++++----- vm/src/builtins/type.rs | 104 +++++++++---------- vm/src/builtins/union.rs | 34 ++++--- vm/src/builtins/weakproxy.rs | 22 ++--- vm/src/builtins/weakref.rs | 4 +- vm/src/builtins/zip.rs | 8 +- vm/src/coroutine.rs | 4 +- vm/src/exceptions.rs | 86 ++++++++-------- vm/src/frame.rs | 4 +- vm/src/import.rs | 2 +- vm/src/stdlib/ast/python.rs | 4 +- vm/src/stdlib/collections.rs | 96 +++++++++--------- vm/src/stdlib/ctypes/base.rs | 4 +- vm/src/stdlib/ctypes/function.rs | 8 +- vm/src/stdlib/functools.rs | 6 +- vm/src/stdlib/io.rs | 28 +++--- vm/src/stdlib/itertools.rs | 116 +++++++++++++--------- vm/src/stdlib/operator.rs | 12 +-- vm/src/stdlib/os.rs | 20 ++-- vm/src/stdlib/sre.rs | 22 +++-- vm/src/stdlib/thread.rs | 8 +- vm/src/stdlib/typing.rs | 132 ++++++++++++------------- vm/src/stdlib/winreg.rs | 12 +-- vm/src/suggestion.rs | 2 +- vm/src/types/slot.rs | 64 ++++++++---- vm/src/types/structseq.rs | 8 +- vm/src/vm/mod.rs | 10 +- 70 files changed, 1500 insertions(+), 1319 deletions(-) diff --git a/derive-impl/src/pyclass.rs b/derive-impl/src/pyclass.rs index 645e896d6c..3ff493bbc1 100644 --- a/derive-impl/src/pyclass.rs +++ b/derive-impl/src/pyclass.rs @@ -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 { 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())) } } diff --git a/derive/src/lib.rs b/derive/src/lib.rs index 2a7b3d68fc..3b95c594a1 100644 --- a/derive/src/lib.rs +++ b/derive/src/lib.rs @@ -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 { -/// ... -/// } -/// } -/// ``` /// - `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. diff --git a/stdlib/src/array.rs b/stdlib/src/array.rs index a1a401943d..0bdbb67af5 100644 --- a/stdlib/src/array.rs +++ b/stdlib/src/array.rs @@ -907,7 +907,7 @@ mod array { range: OptionalRangeArgs, vm: &VirtualMachine, ) -> PyResult { - 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, needle: &PyObject, value: PyObjectRef, @@ -1035,30 +1035,30 @@ mod array { } } - #[pymethod(magic)] - fn setitem( + #[pymethod] + fn __setitem__( zelf: &Py, 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> { + #[pymethod] + fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { if let Some(other) = other.payload::() { self.read() .add(&other.read(), vm) @@ -1071,8 +1071,8 @@ mod array { } } - #[pymethod(magic)] - fn iadd( + #[pymethod] + fn __iadd__( zelf: PyRef, other: PyObjectRef, vm: &VirtualMachine, @@ -1091,28 +1091,28 @@ mod array { } #[pymethod(name = "__rmul__")] - #[pymethod(magic)] - fn mul(&self, value: isize, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __mul__(&self, value: isize, vm: &VirtualMachine) -> PyResult> { self.read() .mul(value, vm) .map(|x| Self::from(x).into_ref(&vm.ctx)) } - #[pymethod(magic)] - fn imul(zelf: PyRef, value: isize, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __imul__(zelf: PyRef, value: isize, vm: &VirtualMachine) -> PyResult> { 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 { // 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, proto: usize, vm: &VirtualMachine, ) -> PyResult<(PyObjectRef, PyTupleRef, Option)> { 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, vm: &VirtualMachine, ) -> PyResult<(PyObjectRef, PyTupleRef, Option)> { @@ -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) diff --git a/stdlib/src/contextvars.rs b/stdlib/src/contextvars.rs index 64986be0fd..d1b8457e28 100644 --- a/stdlib/src/contextvars.rs +++ b/stdlib/src/contextvars.rs @@ -197,8 +197,12 @@ mod _contextvars { } } - #[pymethod(magic)] - fn getitem(&self, var: PyRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __getitem__( + &self, + var: PyRef, + vm: &VirtualMachine, + ) -> PyResult { 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") } } diff --git a/stdlib/src/mmap.rs b/stdlib/src/mmap.rs index f3a2fc9a06..6589699d3f 100644 --- a/stdlib/src/mmap.rs +++ b/stdlib/src/mmap.rs @@ -416,7 +416,7 @@ mod mmap { fn as_buffer(zelf: &Py, _vm: &VirtualMachine) -> PyResult { 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 = 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 { 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 { 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 { - self._getitem(&needle, vm) + #[pymethod] + fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + self.getitem_inner(&needle, vm) } - #[pymethod(magic)] - fn setitem( + #[pymethod] + fn __setitem__( zelf: &Py, 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, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __enter__(zelf: &Py, vm: &VirtualMachine) -> PyResult> { let _m = zelf.check_valid(vm)?; Ok(zelf.to_owned()) } - #[pymethod(magic)] - fn exit(zelf: &Py, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __exit__(zelf: &Py, _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 { 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 { - 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 { + fn getitem_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { 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, 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!( "", access_str, - zelf.len(), + zelf.__len__(), zelf.pos(), zelf.offset ); diff --git a/stdlib/src/pystruct.rs b/stdlib/src/pystruct.rs index 15e949dc9f..0243b56e03 100644 --- a/stdlib/src/pystruct.rs +++ b/stdlib/src/pystruct.rs @@ -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 } } diff --git a/stdlib/src/select.rs b/stdlib/src/select.rs index d91c229419..905358f686 100644 --- a/stdlib/src/select.rs +++ b/stdlib/src/select.rs @@ -722,14 +722,14 @@ mod decl { Ok(vm.ctx.new_list(ret)) } - #[pymethod(magic)] - fn enter(zelf: PyRef, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __enter__(zelf: PyRef, vm: &VirtualMachine) -> PyResult> { zelf.get_epoll(vm)?; Ok(zelf) } - #[pymethod(magic)] - fn exit( + #[pymethod] + fn __exit__( &self, _exc_type: OptionalArg, _exc_value: OptionalArg, diff --git a/stdlib/src/sqlite.rs b/stdlib/src/sqlite.rs index f9b30a7b07..ed3f739917 100644 --- a/stdlib/src/sqlite.rs +++ b/stdlib/src/sqlite.rs @@ -1317,13 +1317,13 @@ mod _sqlite { self.db_lock(vm)?.limit(category, limit, vm) } - #[pymethod(magic)] - fn enter(zelf: PyRef) -> PyRef { + #[pymethod] + fn __enter__(zelf: PyRef) -> PyRef { 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) -> PyRef { + #[pymethod] + fn __enter__(zelf: PyRef) -> PyRef { zelf } - #[pymethod(magic)] - fn exit(&self, _args: FuncArgs) { + #[pymethod] + fn __exit__(&self, _args: FuncArgs) { self.close() } diff --git a/stdlib/src/zlib.rs b/stdlib/src/zlib.rs index 867c94b671..8a86582a59 100644 --- a/stdlib/src/zlib.rs +++ b/stdlib/src/zlib.rs @@ -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!("") diff --git a/vm/src/builtins/asyncgenerator.rs b/vm/src/builtins/asyncgenerator.rs index 38cb81434d..1172d1d255 100644 --- a/vm/src/builtins/asyncgenerator.rs +++ b/vm/src/builtins/asyncgenerator.rs @@ -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 { - #[pymethod(magic)] - fn aiter(self, _vm: &VirtualMachine) -> PyRef { + #[pymethod] + fn __aiter__(self, _vm: &VirtualMachine) -> PyRef { self } - #[pymethod(magic)] - fn anext(self, vm: &VirtualMachine) -> PyAsyncGenASend { + #[pymethod] + fn __anext__(self, vm: &VirtualMachine) -> PyAsyncGenASend { Self::asend(self, vm.ctx.none(), vm) } diff --git a/vm/src/builtins/bool.rs b/vm/src/builtins/bool.rs index a909e3eb5c..c7e4395091 100644 --- a/vm/src/builtins/bool.rs +++ b/vm/src/builtins/bool.rs @@ -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 { + #[pymethod] + fn __format__(obj: PyObjectRef, spec: PyStrRef, vm: &VirtualMachine) -> PyResult { 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::() { - 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::() { - 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::() { - 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 diff --git a/vm/src/builtins/builtin_func.rs b/vm/src/builtins/builtin_func.rs index ff3ef38d3a..4b3dd47b76 100644 --- a/vm/src/builtins/builtin_func.rs +++ b/vm/src/builtins/builtin_func.rs @@ -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 { + #[pygetset] + fn __qualname__(zelf: NativeFunctionOrMethod, vm: &VirtualMachine) -> PyResult { 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, vm: &VirtualMachine) -> PyResult { + #[pygetset] + fn __qualname__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { 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 diff --git a/vm/src/builtins/bytearray.rs b/vm/src/builtins/bytearray.rs index d66dba44d7..c238190fdc 100644 --- a/vm/src/builtins/bytearray.rs +++ b/vm/src/builtins/bytearray.rs @@ -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.borrow_buf().len() * size_of::() } - #[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, vm: &VirtualMachine, @@ -229,21 +229,25 @@ impl PyByteArray { self.inner().contains(needle, vm) } - #[pymethod(magic)] - fn iadd(zelf: PyRef, other: ArgBytesLike, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __iadd__( + zelf: PyRef, + other: ArgBytesLike, + vm: &VirtualMachine, + ) -> PyResult> { 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 { + #[pymethod] + fn __mul__(&self, value: ArgSize, vm: &VirtualMachine) -> PyResult { self.repeat(value.into(), vm) } - #[pymethod(magic)] - fn imul(zelf: PyRef, value: ArgSize, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __imul__(zelf: PyRef, value: ArgSize, vm: &VirtualMachine) -> PyResult> { 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 { - #[pymethod(magic)] - fn setitem( + #[pymethod] + fn __setitem__( &self, needle: PyObjectRef, value: PyObjectRef, @@ -634,17 +638,17 @@ impl Py { Ok(()) } - #[pymethod(magic)] - fn reduce_ex( + #[pymethod] + fn __reduce_ex__( &self, _proto: usize, vm: &VirtualMachine, ) -> (PyTypeRef, PyTupleRef, Option) { - Self::reduce(self, vm) + self.__reduce__(vm) } - #[pymethod(magic)] - fn reduce(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option) { + #[pymethod] + fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option) { 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, _vm: &VirtualMachine) -> PyResult { 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 = >::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) } } diff --git a/vm/src/builtins/bytes.rs b/vm/src/builtins/bytes.rs index 86efaff6ce..10ccff37a4 100644 --- a/vm/src/builtins/bytes.rs +++ b/vm/src/builtins/bytes.rs @@ -145,9 +145,9 @@ impl PyRef { ) )] 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.len() * size_of::() } - #[pymethod(magic)] - fn add(&self, other: ArgBytesLike) -> Vec { + #[pymethod] + fn __add__(&self, other: ArgBytesLike) -> Vec { self.inner.add(&other.borrow_buf()) } - #[pymethod(magic)] - fn contains( + #[pymethod] + fn __contains__( &self, needle: Either, 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, value: ArgIndex, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __mul__(zelf: PyRef, value: ArgIndex, vm: &VirtualMachine) -> PyResult> { 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 = self.elements().map(|x| x.to_pyobject(vm)).collect(); PyTuple::new_ref(param, &vm.ctx) } @@ -484,17 +484,17 @@ impl PyBytes { #[pyclass] impl Py { - #[pymethod(magic)] - fn reduce_ex( + #[pymethod] + fn __reduce_ex__( &self, _proto: usize, vm: &VirtualMachine, ) -> (PyTypeRef, PyTupleRef, Option) { - Self::reduce(self, vm) + self.__reduce__(vm) } - #[pymethod(magic)] - fn reduce(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option) { + #[pymethod] + fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option) { let bytes = PyBytes::from(self.to_vec()).to_pyobject(vm); ( self.class().to_owned(), @@ -506,8 +506,8 @@ impl Py { #[pyclass] impl PyRef { - #[pymethod(magic)] - fn bytes(self, vm: &VirtualMachine) -> PyRef { + #[pymethod] + fn __bytes__(self, vm: &VirtualMachine) -> PyRef { 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 = >::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) diff --git a/vm/src/builtins/classmethod.rs b/vm/src/builtins/classmethod.rs index 4b5fe20f2e..f4cb1ba379 100644 --- a/vm/src/builtins/classmethod.rs +++ b/vm/src/builtins/classmethod.rs @@ -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::() .map(|n| n.as_str()), - class.module(vm).downcast_ref::().map(|m| m.as_str()), + class + .__module__(vm) + .downcast_ref::() + .map(|m| m.as_str()), ) { (None, _) => return Err(vm.new_type_error("Unknown qualified name")), (Some(qualname), Some(module)) if module != "builtins" => { diff --git a/vm/src/builtins/complex.rs b/vm/src/builtins/complex.rs index ced5e39863..9fb304e8b0 100644 --- a/vm/src/builtins/complex.rs +++ b/vm/src/builtins/complex.rs @@ -255,8 +255,8 @@ impl PyComplex { self.value.im } - #[pymethod(magic)] - fn abs(&self, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __abs__(&self, vm: &VirtualMachine) -> PyResult { 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, @@ -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 { - #[pymethod(magic)] - fn complex(self, vm: &VirtualMachine) -> PyRef { + #[pymethod] + fn __complex__(self, vm: &VirtualMachine) -> PyRef { if self.is(vm.ctx.types.complex_type) { self } else { diff --git a/vm/src/builtins/coroutine.rs b/vm/src/builtins/coroutine.rs index cca2db3293..0be0c83410 100644 --- a/vm/src/builtins/coroutine.rs +++ b/vm/src/builtins/coroutine.rs @@ -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) } diff --git a/vm/src/builtins/descriptor.rs b/vm/src/builtins/descriptor.rs index 5dbecbaa5f..4555583dc9 100644 --- a/vm/src/builtins/descriptor.rs +++ b/vm/src/builtins/descriptor.rs @@ -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 { + #[pygetset] + fn __text_signature__(&self) -> Option { 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, (Option, &'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 { + #[pygetset] + fn __doc__(&self) -> Option { self.member.doc.to_owned() } - #[pygetset(magic)] - fn qualname(&self, vm: &VirtualMachine) -> PyResult> { + #[pygetset] + fn __qualname__(&self, vm: &VirtualMachine) -> PyResult> { let qualname = self.common.qualname.read(); Ok(if qualname.is_none() { drop(qualname); diff --git a/vm/src/builtins/dict.rs b/vm/src/builtins/dict.rs index 2b1aa3ad04..6fc68a0e63 100644 --- a/vm/src/builtins/dict.rs +++ b/vm/src/builtins/dict.rs @@ -189,7 +189,7 @@ impl PyDict { match d.downcast_exact::(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.entries.sizeof() } - #[pymethod(magic)] - fn contains(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __contains__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { 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 = 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 { 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 { 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 { 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 { + #[pymethod] + fn __ior__(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { 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 = 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::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::() { - 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, vm: &VirtualMachine) -> PyResult { 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, vm: &VirtualMachine) -> PyResult { 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, vm: &VirtualMachine) -> PyResult { - 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, other: ArgIterable, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __xor__(zelf: PyRef, other: ArgIterable, vm: &VirtualMachine) -> PyResult { 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, other: ArgIterable, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __and__(zelf: PyRef, other: ArgIterable, vm: &VirtualMachine) -> PyResult { 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, other: ArgIterable, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __or__(zelf: PyRef, other: ArgIterable, vm: &VirtualMachine) -> PyResult { let zelf = Self::to_set(zelf, vm)?; let inner = zelf.union(other, vm)?; Ok(PySet { inner }) } - #[pymethod(magic)] - fn sub(zelf: PyRef, other: ArgIterable, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __sub__(zelf: PyRef, other: ArgIterable, vm: &VirtualMachine) -> PyResult { let zelf = Self::to_set(zelf, vm)?; let inner = zelf.difference(other, vm)?; Ok(PySet { inner }) } - #[pymethod(magic)] - fn rsub(zelf: PyRef, other: ArgIterable, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __rsub__(zelf: PyRef, other: ArgIterable, vm: &VirtualMachine) -> PyResult { 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 { + #[pymethod] + fn __contains__(zelf: PyObjectRef, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { 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 = 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 { + #[pymethod] + fn __contains__(zelf: PyObjectRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { 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 = 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 = 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 = 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 diff --git a/vm/src/builtins/enumerate.rs b/vm/src/builtins/enumerate.rs index aa84115074..b28f1888cd 100644 --- a/vm/src/builtins/enumerate.rs +++ b/vm/src/builtins/enumerate.rs @@ -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 { - #[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 { + #[pymethod] + fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult { 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) diff --git a/vm/src/builtins/filter.rs b/vm/src/builtins/filter.rs index 009a1b3eab..bc8e12fc2f 100644 --- a/vm/src/builtins/filter.rs +++ b/vm/src/builtins/filter.rs @@ -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()), diff --git a/vm/src/builtins/float.rs b/vm/src/builtins/float.rs index cecb1f2d14..c7cf8a10a5 100644 --- a/vm/src/builtins/float.rs +++ b/vm/src/builtins/float.rs @@ -204,15 +204,15 @@ fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult { with(Comparable, Hashable, Constructor, AsNumber, Representable) )] impl PyFloat { - #[pymethod(magic)] - fn format(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __format__(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult { 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 { + #[pystaticmethod] + fn __getformat__(spec: PyStrRef, vm: &VirtualMachine) -> PyResult { 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> { + #[pymethod] + fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { 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> { + #[pymethod] + fn __rmod__( + &self, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult> { 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, @@ -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> { + #[pymethod] + fn __sub__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { self.simple_op(other, |a, b| Ok(a - b), vm) } - #[pymethod(magic)] - fn rsub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __rsub__( + &self, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult> { self.simple_op(other, |a, b| Ok(b - a), vm) } - #[pymethod(magic)] - fn truediv(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __truediv__( + &self, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult> { 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> { + #[pymethod] + fn __mul__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { self.simple_op(other, |a, b| Ok(a * b), vm) } - #[pymethod(magic)] - fn trunc(&self, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __trunc__(&self, vm: &VirtualMachine) -> PyResult { try_to_bigint(self.value, vm) } - #[pymethod(magic)] - fn floor(&self, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __floor__(&self, vm: &VirtualMachine) -> PyResult { try_to_bigint(self.value.floor(), vm) } - #[pymethod(magic)] - fn ceil(&self, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __ceil__(&self, vm: &VirtualMachine) -> PyResult { try_to_bigint(self.value.ceil(), vm) } - #[pymethod(magic)] - fn round(&self, ndigits: OptionalOption, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __round__(&self, ndigits: OptionalOption, 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 { - self.trunc(vm) + #[pymethod] + fn __int__(&self, vm: &VirtualMachine) -> PyResult { + self.__trunc__(vm) } - #[pymethod(magic)] - fn float(zelf: PyRef) -> PyRef { + #[pymethod] + fn __float__(zelf: PyRef) -> PyRef { 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) } } diff --git a/vm/src/builtins/function.rs b/vm/src/builtins/function.rs index 77ba46fc9e..dc97fce41d 100644 --- a/vm/src/builtins/function.rs +++ b/vm/src/builtins/function.rs @@ -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 { + #[pygetset] + fn __code__(&self) -> PyRef { self.code.clone() } - #[pygetset(magic)] - fn defaults(&self) -> Option { + #[pygetset] + fn __defaults__(&self) -> Option { self.defaults_and_kwdefaults.lock().0.clone() } - #[pygetset(magic, setter)] - fn set_defaults(&self, defaults: Option) { + #[pygetset(setter)] + fn set___defaults__(&self, defaults: Option) { self.defaults_and_kwdefaults.lock().0 = defaults } - #[pygetset(magic)] - fn kwdefaults(&self) -> Option { + #[pygetset] + fn __kwdefaults__(&self) -> Option { self.defaults_and_kwdefaults.lock().1.clone() } - #[pygetset(magic, setter)] - fn set_kwdefaults(&self, kwdefaults: Option) { + #[pygetset(setter)] + fn set___kwdefaults__(&self, kwdefaults: Option) { 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::() { 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 = 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, vm: &VirtualMachine) { + #[pygetset(setter)] + fn set___module__(&self, module: PySetterValue, 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::() 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, vm: &VirtualMachine, @@ -526,8 +526,8 @@ impl PyFunction { } #[cfg(feature = "jit")] - #[pymethod(magic)] - fn jit(zelf: PyRef, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __jit__(zelf: PyRef, 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, _vm: &VirtualMachine) -> PyResult { Ok(format!( "", - 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, Option)) { @@ -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 { + #[pygetset] + fn __module__(&self, vm: &VirtualMachine) -> Option { 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) diff --git a/vm/src/builtins/generator.rs b/vm/src/builtins/generator.rs index db9c263cb2..5235202b47 100644 --- a/vm/src/builtins/generator.rs +++ b/vm/src/builtins/generator.rs @@ -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) } diff --git a/vm/src/builtins/genericalias.rs b/vm/src/builtins/genericalias.rs index 6b6bdc29ac..f0196f7463 100644 --- a/vm/src/builtins/genericalias.rs +++ b/vm/src/builtins/genericalias.rs @@ -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 { - let dir = vm.dir(Some(self.origin()))?; + #[pymethod] + fn __dir__(&self, vm: &VirtualMachine) -> PyResult { + 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, vm: &VirtualMachine) -> (PyTypeRef, (PyTypeRef, PyTupleRef)) { + #[pymethod] + fn __reduce__(zelf: &Py, 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, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __instancecheck__(_zelf: PyRef, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { Err(vm.new_type_error("isinstance() argument 2 cannot be a parameterized generic")) } - #[pymethod(magic)] - fn subclasscheck(_zelf: PyRef, _obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __subclasscheck__(_zelf: PyRef, _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 = 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) } } diff --git a/vm/src/builtins/getset.rs b/vm/src/builtins/getset.rs index c2e11b770a..ac67a4b7af 100644 --- a/vm/src/builtins/getset.rs +++ b/vm/src/builtins/getset.rs @@ -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() } } diff --git a/vm/src/builtins/int.rs b/vm/src/builtins/int.rs index 93df88b968..9e8d8c34e3 100644 --- a/vm/src/builtins/int.rs +++ b/vm/src/builtins/int.rs @@ -321,82 +321,82 @@ impl PyInt { )] impl PyInt { #[pymethod(name = "__radd__")] - #[pymethod(magic)] - fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { + #[pymethod] + fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { self.int_op(other, |a, b| a + b, vm) } - #[pymethod(magic)] - fn sub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { + #[pymethod] + fn __sub__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { self.int_op(other, |a, b| a - b, vm) } - #[pymethod(magic)] - fn rsub(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { + #[pymethod] + fn __rsub__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { self.int_op(other, |a, b| b - a, vm) } #[pymethod(name = "__rmul__")] - #[pymethod(magic)] - fn mul(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { + #[pymethod] + fn __mul__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { 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 { + #[pymethod] + pub fn __xor__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { self.int_op(other, |a, b| a ^ b, vm) } #[pymethod(name = "__ror__")] - #[pymethod(magic)] - pub fn or(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { + #[pymethod] + pub fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { self.int_op(other, |a, b| a | b, vm) } #[pymethod(name = "__rand__")] - #[pymethod(magic)] - pub fn and(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { + #[pymethod] + pub fn __and__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyArithmeticValue { 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, @@ -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, ndigits: OptionalArg, 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 { + #[pymethod] + fn __float__(&self, vm: &VirtualMachine) -> PyResult { try_to_float(&self.value, vm) } - #[pymethod(magic)] - fn trunc(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { - zelf.int(vm) + #[pymethod] + fn __trunc__(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { + zelf.__int__(vm) } - #[pymethod(magic)] - fn floor(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { - zelf.int(vm) + #[pymethod] + fn __floor__(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { + zelf.__int__(vm) } - #[pymethod(magic)] - fn ceil(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { - zelf.int(vm) + #[pymethod] + fn __ceil__(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { + zelf.__int__(vm) } - #[pymethod(magic)] - fn index(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { - zelf.int(vm) + #[pymethod] + fn __index__(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { + 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 { + #[pymethod] + fn __format__(&self, spec: PyStrRef, vm: &VirtualMachine) -> PyResult { 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.value.bits() + 7) & !7) / 8) as usize } @@ -597,7 +597,7 @@ impl PyInt { #[pymethod] fn conjugate(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { - zelf.int(vm) + zelf.__int__(vm) } #[pyclassmethod] @@ -666,7 +666,7 @@ impl PyInt { #[pygetset] fn real(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { - zelf.int(vm) + zelf.__int__(vm) } #[pygetset] @@ -676,7 +676,7 @@ impl PyInt { #[pygetset] fn numerator(zelf: PyRef, vm: &VirtualMachine) -> PyRefExact { - 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 { - #[pymethod(magic)] - fn int(self, vm: &VirtualMachine) -> PyRefExact { + #[pymethod] + fn __int__(self, vm: &VirtualMachine) -> PyRefExact { 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)) diff --git a/vm/src/builtins/iter.rs b/vm/src/builtins/iter.rs index 31062b5c14..c0aaa85279 100644 --- a/vm/src/builtins/iter.rs +++ b/vm/src/builtins/iter.rs @@ -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) } } diff --git a/vm/src/builtins/list.rs b/vm/src/builtins/list.rs index a5b7f78f8f..1c19ea0665 100644 --- a/vm/src/builtins/list.rs +++ b/vm/src/builtins/list.rs @@ -142,8 +142,8 @@ impl PyList { Ok(Self::new_ref(elements, &vm.ctx)) } - #[pymethod(magic)] - fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { self.concat(&other, vm) } @@ -157,8 +157,12 @@ impl PyList { Ok(zelf.to_owned().into()) } - #[pymethod(magic)] - fn iadd(zelf: PyRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __iadd__( + zelf: PyRef, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult> { 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.elements.read().capacity() * std::mem::size_of::() } @@ -191,9 +195,9 @@ impl PyList { self.borrow_vec_mut().reverse(); } - #[pymethod(magic)] - fn reversed(zelf: PyRef) -> PyListReverseIterator { - let position = zelf.len().saturating_sub(1); + #[pymethod] + fn __reversed__(zelf: PyRef) -> 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> { + fn __mul__(&self, n: ArgSize, vm: &VirtualMachine) -> PyResult> { self.repeat(n.into(), vm) } - #[pymethod(magic)] - fn imul(zelf: PyRef, n: ArgSize, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __imul__(zelf: PyRef, n: ArgSize, vm: &VirtualMachine) -> PyResult> { 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 { + #[pymethod] + pub(crate) fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.mut_contains(vm, &needle) } @@ -262,7 +266,7 @@ impl PyList { range: OptionalRangeArgs, vm: &VirtualMachine, ) -> PyResult { - 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, vm: &VirtualMachine) -> PyResult { - 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) diff --git a/vm/src/builtins/map.rs b/vm/src/builtins/map.rs index 555e38c8b9..e62817a9a8 100644 --- a/vm/src/builtins/map.rs +++ b/vm/src/builtins/map.rs @@ -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 { + #[pymethod] + fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult { 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)) diff --git a/vm/src/builtins/mappingproxy.rs b/vm/src/builtins/mappingproxy.rs index 5dd31500fb..5a06459fa2 100644 --- a/vm/src/builtins/mappingproxy.rs +++ b/vm/src/builtins/mappingproxy.rs @@ -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 { + #[pymethod] + pub fn __contains__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { 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 { + #[pymethod] + fn __len__(&self, vm: &VirtualMachine) -> PyResult { 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 = 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::() { - 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::() { - a.ior(b.to_pyobject(vm), vm) + a.__ior__(b.to_pyobject(vm), vm) } else { Ok(vm.ctx.not_implemented()) } diff --git a/vm/src/builtins/memory.rs b/vm/src/builtins/memory.rs index ac6991f940..54e82bbd15 100644 --- a/vm/src/builtins/memory.rs +++ b/vm/src/builtins/memory.rs @@ -641,18 +641,18 @@ impl PyMemoryView { .map(|_| self.desc.ndim() <= 1 && self.desc.is_contiguous()) } - #[pymethod(magic)] - fn enter(zelf: PyRef, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __enter__(zelf: PyRef, vm: &VirtualMachine) -> PyResult> { 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, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __getitem__(zelf: PyRef, 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 { + #[pymethod] + fn __len__(&self, vm: &VirtualMachine) -> PyResult { self.try_not_released(vm)?; Ok(if self.desc.ndim() == 0 { 1 @@ -839,8 +839,8 @@ impl PyMemoryView { #[pyclass] impl Py { - #[pymethod(magic)] - fn setitem( + #[pymethod] + fn __setitem__( &self, needle: PyObjectRef, value: PyObjectRef, @@ -872,13 +872,13 @@ impl Py { } } - #[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, vm: &VirtualMachine) -> PyResult { zelf.internal.lock().next(|mv, pos| { - let len = mv.len(vm)?; + let len = mv.__len__(vm)?; Ok(if pos >= len { PyIterReturn::StopIteration(None) } else { diff --git a/vm/src/builtins/module.rs b/vm/src/builtins/module.rs index 0abf38415e..8107390f59 100644 --- a/vm/src/builtins/module.rs +++ b/vm/src/builtins/module.rs @@ -168,8 +168,8 @@ impl PyModule { PyModule::new().into_ref_with_type(vm, cls).map(Into::into) } - #[pymethod(magic)] - fn dir(zelf: &Py, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __dir__(zelf: &Py, vm: &VirtualMachine) -> PyResult> { // 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 diff --git a/vm/src/builtins/namespace.rs b/vm/src/builtins/namespace.rs index 90f42651dc..1284203e68 100644 --- a/vm/src/builtins/namespace.rs +++ b/vm/src/builtins/namespace.rs @@ -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(); diff --git a/vm/src/builtins/object.rs b/vm/src/builtins/object.rs index 7214b8f15e..f0679cbe29 100644 --- a/vm/src/builtins/object.rs +++ b/vm/src/builtins/object.rs @@ -135,7 +135,7 @@ fn object_getstate_default(obj: &PyObject, required: bool, vm: &VirtualMachine) // basicsize += std::mem::size_of::(); // } if let Some(ref slot_names) = slot_names { - basicsize += std::mem::size_of::() * slot_names.len(); + basicsize += std::mem::size_of::() * 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 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 { + #[pymethod] + fn __str__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { // 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::() .map(|n| n.as_str()), - class.module(vm).downcast_ref::().map(|m| m.as_str()), + class + .__module__(vm) + .downcast_ref::() + .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 { + #[pymethod] + fn __repr__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { 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 { + #[pymethod] + pub fn __dir__(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { obj.dir(vm) } - #[pymethod(magic)] - fn format(obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __format__( + obj: PyObjectRef, + format_spec: PyStrRef, + vm: &VirtualMachine, + ) -> PyResult { 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 { + #[pymethod] + fn __hash__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { Self::slot_hash(&zelf, vm) } - #[pymethod(magic)] - fn sizeof(zelf: PyObjectRef) -> usize { + #[pymethod] + fn __sizeof__(zelf: PyObjectRef) -> usize { zelf.class().slots.basicsize } } diff --git a/vm/src/builtins/property.rs b/vm/src/builtins/property.rs index a5e8f12587..30d5d3d904 100644 --- a/vm/src/builtins/property.rs +++ b/vm/src/builtins/property.rs @@ -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 { 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 { 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!( diff --git a/vm/src/builtins/range.rs b/vm/src/builtins/range.rs index 55dad35cc2..7596571e3f 100644 --- a/vm/src/builtins/range.rs +++ b/vm/src/builtins/range.rs @@ -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 = [&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 { } } - #[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 { impl PyRange { fn protocol_length(&self, vm: &VirtualMachine) -> PyResult { - PyInt::from(self.len()) + PyInt::from(self.__len__()) .try_to_primitive::(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 { + #[pymethod] + fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { 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 { + #[pymethod] + fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { range_iter_reduce( BigInt::from(self.start), BigInt::from(self.length), diff --git a/vm/src/builtins/set.rs b/vm/src/builtins/set.rs index 25444f14dd..f873867352 100644 --- a/vm/src/builtins/set.rs +++ b/vm/src/builtins/set.rs @@ -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.inner.sizeof() } @@ -559,8 +559,8 @@ impl PySet { } } - #[pymethod(magic)] - fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.inner.contains(&needle, vm) } @@ -604,8 +604,8 @@ impl PySet { } #[pymethod(name = "__ror__")] - #[pymethod(magic)] - fn or(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { 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> { + #[pymethod] + fn __and__( + &self, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult> { 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> { + #[pymethod] + fn __sub__( + &self, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult> { 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, other: PyObjectRef, vm: &VirtualMachine, @@ -662,8 +670,12 @@ impl PySet { } #[pymethod(name = "__rxor__")] - #[pymethod(magic)] - fn xor(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __xor__( + &self, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult> { 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, set: AnySet, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __ior__(zelf: PyRef, set: AnySet, vm: &VirtualMachine) -> PyResult> { zelf.inner.update(set.into_iterable_iter(vm)?, vm)?; Ok(zelf) } @@ -726,8 +738,8 @@ impl PySet { Ok(()) } - #[pymethod(magic)] - fn iand(zelf: PyRef, set: AnySet, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __iand__(zelf: PyRef, set: AnySet, vm: &VirtualMachine) -> PyResult> { 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, set: AnySet, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __isub__(zelf: PyRef, set: AnySet, vm: &VirtualMachine) -> PyResult> { 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, set: AnySet, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __ixor__(zelf: PyRef, set: AnySet, vm: &VirtualMachine) -> PyResult> { zelf.inner .symmetric_difference_update(set.into_iterable_iter(vm)?, vm)?; Ok(zelf) } - #[pymethod(magic)] - fn reduce( + #[pymethod] + fn __reduce__( zelf: PyRef, vm: &VirtualMachine, ) -> PyResult<(PyTypeRef, PyTupleRef, Option)> { 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 = 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::() { - 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::() { - 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::() { - 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::() { - 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::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::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::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::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.inner.sizeof() } @@ -979,8 +991,8 @@ impl PyFrozenSet { } } - #[pymethod(magic)] - fn contains(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.inner.contains(&needle, vm) } @@ -1024,8 +1036,8 @@ impl PyFrozenSet { } #[pymethod(name = "__ror__")] - #[pymethod(magic)] - fn or(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { 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> { + #[pymethod] + fn __and__( + &self, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult> { 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> { + #[pymethod] + fn __sub__( + &self, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult> { 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, other: PyObjectRef, vm: &VirtualMachine, @@ -1083,8 +1103,12 @@ impl PyFrozenSet { } #[pymethod(name = "__rxor__")] - #[pymethod(magic)] - fn xor(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __xor__( + &self, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult> { 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, vm: &VirtualMachine, ) -> PyResult<(PyTypeRef, PyTupleRef, Option)> { 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 = 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::() { - 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::() { - 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::() { - 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::() { - 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, vm: &VirtualMachine) -> PyResult<(PyObjectRef, (PyObjectRef,))> { + #[pymethod] + fn __reduce__( + zelf: PyRef, + vm: &VirtualMachine, + ) -> PyResult<(PyObjectRef, (PyObjectRef,))> { let internal = zelf.internal.lock(); Ok(( builtins_iter(vm).to_owned(), diff --git a/vm/src/builtins/singletons.rs b/vm/src/builtins/singletons.rs index da0c718c46..75738f96fe 100644 --- a/vm/src/builtins/singletons.rs +++ b/vm/src/builtins/singletons.rs @@ -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() } } diff --git a/vm/src/builtins/slice.rs b/vm/src/builtins/slice.rs index 9143fcedb5..6cbac09566 100644 --- a/vm/src/builtins/slice.rs +++ b/vm/src/builtins/slice.rs @@ -182,8 +182,8 @@ impl PySlice { } #[allow(clippy::type_complexity)] - #[pymethod(magic)] - fn reduce( + #[pymethod] + fn __reduce__( zelf: PyRef, ) -> 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() } } diff --git a/vm/src/builtins/staticmethod.rs b/vm/src/builtins/staticmethod.rs index 1e16cfd8ab..80db5a2fc7 100644 --- a/vm/src/builtins/staticmethod.rs +++ b/vm/src/builtins/staticmethod.rs @@ -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::() .map(|n| n.as_str()), - class.module(vm).downcast_ref::().map(|m| m.as_str()), + class + .__module__(vm) + .downcast_ref::() + .map(|m| m.as_str()), ) { (None, _) => Err(vm.new_type_error("Unknown qualified name")), (Some(qualname), Some(module)) if module != "builtins" => { diff --git a/vm/src/builtins/str.rs b/vm/src/builtins/str.rs index bf51c146a7..0af9bd3c61 100644 --- a/vm/src/builtins/str.rs +++ b/vm/src/builtins/str.rs @@ -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, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __add__(zelf: PyRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if let Some(other) = other.payload::() { 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 { + #[pymethod] + fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { 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.byte_len() * std::mem::size_of::() } #[pymethod(name = "__rmul__")] - #[pymethod(magic)] - fn mul(zelf: PyRef, value: ArgSize, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __mul__(zelf: PyRef, value: ArgSize, vm: &VirtualMachine) -> PyResult> { 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, vm: &VirtualMachine) -> PyObjectRef { + #[pymethod] + fn __getnewargs__(zelf: PyRef, vm: &VirtualMachine) -> PyObjectRef { (zelf.as_str(),).to_pyobject(vm) } } @@ -1453,8 +1453,8 @@ impl crate::common::format::CharLen for CharLenStr<'_> { #[pyclass] impl PyRef { - #[pymethod(magic)] - fn str(self, vm: &VirtualMachine) -> PyRefExact { + #[pymethod] + fn __str__(self, vm: &VirtualMachine) -> PyRefExact { 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); diff --git a/vm/src/builtins/super.rs b/vm/src/builtins/super.rs index 97adb33a41..ed2bf6767d 100644 --- a/vm/src/builtins/super.rs +++ b/vm/src/builtins/super.rs @@ -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 { + #[pygetset] + fn __self_class__(&self) -> Option { Some(self.inner.read().obj.as_ref()?.1.clone()) } diff --git a/vm/src/builtins/tuple.rs b/vm/src/builtins/tuple.rs index a6ae9a5a46..2c99e30d87 100644 --- a/vm/src/builtins/tuple.rs +++ b/vm/src/builtins/tuple.rs @@ -228,8 +228,8 @@ impl PyTuple { ) )] impl PyTuple { - #[pymethod(magic)] - fn add( + #[pymethod] + fn __add__( zelf: PyRef, 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, value: ArgSize, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __mul__(zelf: PyRef, value: ArgSize, vm: &VirtualMachine) -> PyResult> { 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 { + #[pymethod] + fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self._contains(&needle, vm) } - #[pymethod(magic)] - fn getnewargs(zelf: PyRef, vm: &VirtualMachine) -> (PyTupleRef,) { + #[pymethod] + fn __getnewargs__(zelf: PyRef, 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 = 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) diff --git a/vm/src/builtins/type.rs b/vm/src/builtins/type.rs index 4de069d796..8373082c8a 100644 --- a/vm/src/builtins/type.rs +++ b/vm/src/builtins/type.rs @@ -476,8 +476,8 @@ impl Py { 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 { + #[pygetset] + fn __base__(&self) -> Option { 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 { + #[pygetset] + fn __annotations__(&self, vm: &VirtualMachine) -> PyResult { 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, vm: &VirtualMachine) -> PyResult<()> { + #[pygetset(setter)] + fn set___annotations__(&self, value: Option, 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, _bases: OptionalArg, @@ -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) -> PyMappingProxy { + #[pygetset] + fn __dict__(zelf: PyRef) -> 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::().map_err(|value| { vm.new_type_error(format!( @@ -777,8 +777,8 @@ impl PyType { Ok(()) } - #[pygetset(magic)] - fn text_signature(&self) -> Option { + #[pygetset] + fn __text_signature__(&self) -> Option { 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 { 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 { } } - #[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 { Ok(()) } - #[pymethod(magic)] - fn dir(&self) -> PyList { + #[pymethod] + fn __dir__(&self) -> PyList { let attributes: Vec = self .get_attributes() .into_iter() @@ -1196,18 +1196,18 @@ impl Py { 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, vm: &VirtualMachine) -> PyResult { - let module = zelf.module(vm); + let module = zelf.__module__(vm); let module = module.downcast_ref::().map(|m| m.as_str()); let repr = match module { @@ -1298,7 +1298,7 @@ impl Representable for PyType { format!( "", module, - zelf.qualname(vm) + zelf.__qualname__(vm) .downcast_ref::() .map(|n| n.as_str()) .unwrap_or_else(|| &name) @@ -1476,7 +1476,7 @@ fn solid_base<'a>(typ: &'a Py, vm: &VirtualMachine) -> &'a Py { }; // TODO: requires itemsize comparison too - if typ.basicsize() != base.basicsize() { + if typ.__basicsize__() != base.__basicsize__() { typ } else { base diff --git a/vm/src/builtins/union.rs b/vm/src/builtins/union.rs index b83e97c80d..7b39cdb0f8 100644 --- a/vm/src/builtins/union.rs +++ b/vm/src/builtins/union.rs @@ -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, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __instancecheck__( + zelf: PyRef, + obj: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { 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, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __subclasscheck__( + zelf: PyRef, + obj: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { 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 diff --git a/vm/src/builtins/weakproxy.rs b/vm/src/builtins/weakproxy.rs index 49e38d2d66..381bbf4ae4 100644 --- a/vm/src/builtins/weakproxy.rs +++ b/vm/src/builtins/weakproxy.rs @@ -79,8 +79,8 @@ impl PyWeakProxy { self.weak.upgrade().ok_or_else(|| new_reference_error(vm)) } - #[pymethod(magic)] - fn str(&self, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __str__(&self, vm: &VirtualMachine) -> PyResult { 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 { + #[pymethod] + fn __bool__(&self, vm: &VirtualMachine) -> PyResult { 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 { + #[pymethod] + fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.try_upgrade(vm)?.to_sequence().contains(&needle, vm) } @@ -189,7 +189,7 @@ impl AsSequence for PyWeakProxy { static AS_SEQUENCE: LazyLock = 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 }); diff --git a/vm/src/builtins/weakref.rs b/vm/src/builtins/weakref.rs index b8de184fb3..5e10bdd30b 100644 --- a/vm/src/builtins/weakref.rs +++ b/vm/src/builtins/weakref.rs @@ -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) } } diff --git a/vm/src/builtins/zip.rs b/vm/src/builtins/zip.rs index abd82b3ccb..c78cc3f6f2 100644 --- a/vm/src/builtins/zip.rs +++ b/vm/src/builtins/zip.rs @@ -43,8 +43,8 @@ impl Constructor for PyZip { #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyZip { - #[pymethod(magic)] - fn reduce(zelf: PyRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { let cls = zelf.class().to_owned(); let iterators = zelf .iterators @@ -59,8 +59,8 @@ impl PyZip { }) } - #[pymethod(magic)] - fn setstate(zelf: PyRef, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __setstate__(zelf: PyRef, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if let Ok(obj) = ArgIntoBool::try_from_object(vm, state) { zelf.strict.store(obj.into(), atomic::Ordering::Release); } diff --git a/vm/src/coroutine.rs b/vm/src/coroutine.rs index 75c58744ff..5ff4202db6 100644 --- a/vm/src/coroutine.rs +++ b/vm/src/coroutine.rs @@ -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) diff --git a/vm/src/exceptions.rs b/vm/src/exceptions.rs index 928b1576b2..ff24334f7e 100644 --- a/vm/src/exceptions.rs +++ b/vm/src/exceptions.rs @@ -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 { + #[pygetset] + pub fn __traceback__(&self) -> Option { 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> { + #[pygetset] + pub fn __cause__(&self) -> Option> { self.cause.read().clone() } - #[pygetset(magic, setter)] - pub fn set_cause(&self, cause: Option>) { + #[pygetset(setter)] + pub fn set___cause__(&self, cause: Option>) { let mut c = self.cause.write(); self.set_suppress_context(true); *c = cause; } - #[pygetset(magic)] - pub fn context(&self) -> Option> { + #[pygetset] + pub fn __context__(&self) -> Option> { self.context.read().clone() } - #[pygetset(magic, setter)] - pub fn set_context(&self, context: Option>) { + #[pygetset(setter)] + pub fn set___context__(&self, context: Option>) { *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 { 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 { } } - #[pymethod(magic)] - fn setstate(self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __setstate__(self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult { if !vm.is_none(&state) { let dict = state .downcast::() @@ -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 = 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 { + #[pymethod] + fn __str__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult { 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 = 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 { + #[pymethod] + fn __str__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult { 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 { + #[pymethod] + fn __str__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult { 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 { + #[pymethod] + fn __str__(exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyResult { let Ok(object) = exc.as_object().get_attr("object", vm) else { return Ok("".to_owned()); }; diff --git a/vm/src/frame.rs b/vm/src/frame.rs index 5d5f3e8141..478e3c21b9 100644 --- a/vm/src/frame.rs +++ b/vm/src/frame.rs @@ -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) } diff --git a/vm/src/import.rs b/vm/src/import.rs index 69c8396c07..c119405fe1 100644 --- a/vm/src/import.rs +++ b/vm/src/import.rs @@ -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); } diff --git a/vm/src/stdlib/ast/python.rs b/vm/src/stdlib/ast/python.rs index 74c4db888a..0ce2843a4d 100644 --- a/vm/src/stdlib/ast/python.rs +++ b/vm/src/stdlib/ast/python.rs @@ -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 = fields.try_to_value(vm)?; let n_args = args.args.len(); diff --git a/vm/src/stdlib/collections.rs b/vm/src/stdlib/collections.rs index d5880869aa..57e3335ac4 100644 --- a/vm/src/stdlib/collections.rs +++ b/vm/src/stdlib/collections.rs @@ -93,7 +93,7 @@ mod _collections { self.borrow_deque_mut().clear() } - #[pymethod(magic)] + #[pymethod(name = "__copy__")] #[pymethod] fn copy(zelf: PyRef, vm: &VirtualMachine) -> PyResult> { Self { @@ -170,7 +170,7 @@ mod _collections { ) -> PyResult { 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) -> PyResult { + #[pymethod] + fn __reversed__(zelf: PyRef) -> PyResult { 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 { + #[pymethod] + fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { 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 { + fn __mul__(&self, n: isize, vm: &VirtualMachine) -> PyResult { let deque = self._mul(n, vm)?; Ok(PyDeque { deque: PyRwLock::new(deque), @@ -342,25 +342,25 @@ mod _collections { }) } - #[pymethod(magic)] - fn imul(zelf: PyRef, n: isize, vm: &VirtualMachine) -> PyResult> { + #[pymethod] + fn __imul__(zelf: PyRef, n: isize, vm: &VirtualMachine) -> PyResult> { 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 { + #[pymethod] + fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.concat(&other, vm) } @@ -389,8 +389,8 @@ mod _collections { } } - #[pymethod(magic)] - fn iadd( + #[pymethod] + fn __iadd__( zelf: PyRef, other: PyObjectRef, vm: &VirtualMachine, @@ -399,8 +399,8 @@ mod _collections { Ok(zelf) } - #[pymethod(magic)] - fn reduce(zelf: PyRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __reduce__(zelf: PyRef, 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, 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, vm: &VirtualMachine, ) -> PyResult<(PyTypeRef, (PyDequeRef, PyObjectRef))> { diff --git a/vm/src/stdlib/ctypes/base.rs b/vm/src/stdlib/ctypes/base.rs index 4d47eef6f6..2fcac469b9 100644 --- a/vm/src/stdlib/ctypes/base.rs +++ b/vm/src/stdlib/ctypes/base.rs @@ -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) } } diff --git a/vm/src/stdlib/ctypes/function.rs b/vm/src/stdlib/ctypes/function.rs index b32666d67f..66103a3dea 100644 --- a/vm/src/stdlib/ctypes/function.rs +++ b/vm/src/stdlib/ctypes/function.rs @@ -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; } diff --git a/vm/src/stdlib/functools.rs b/vm/src/stdlib/functools.rs index f27a1ac143..2cca5a807c 100644 --- a/vm/src/stdlib/functools.rs +++ b/vm/src/stdlib/functools.rs @@ -100,8 +100,8 @@ mod _functools { .into()) } - #[pymethod(magic)] - fn setstate(zelf: &Py, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __setstate__(zelf: &Py, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let state_tuple = state .downcast::() .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 diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index ee6a846bdd..e1ac84025d 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -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 { + #[pymethod] + fn __repr__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { 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(e1: PyResult<()>, e2: PyResult) -> PyResult { 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()))) } } diff --git a/vm/src/stdlib/itertools.rs b/vm/src/stdlib/itertools.rs index 353a11dfcb..ac106fe162 100644 --- a/vm/src/stdlib/itertools.rs +++ b/vm/src/stdlib/itertools.rs @@ -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, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { 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, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __setstate__(zelf: PyRef, 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) -> (PyTypeRef, (PyIter, PyIter)) { + #[pymethod] + fn __reduce__(zelf: PyRef) -> (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) -> (PyTypeRef, (PyObjectRef,)) { + #[pymethod] + fn __reduce__(zelf: PyRef) -> (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 { + #[pymethod] + fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult { // 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, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { 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) -> (PyTypeRef, (PyObjectRef, PyIter)) { + #[pymethod] + fn __reduce__(zelf: PyRef) -> (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) -> (PyTypeRef, (PyObjectRef, PyIter), u32) { + #[pymethod] + fn __reduce__(zelf: PyRef) -> (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, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __setstate__( + zelf: PyRef, + 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) -> (PyTypeRef, (PyObjectRef, PyIter), u32) { + #[pymethod] + fn __reduce__(zelf: PyRef) -> (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, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __setstate__( + zelf: PyRef, + 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, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { 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, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __setstate__(zelf: PyRef, 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) -> (PyTypeRef, (PyObjectRef, PyIter)) { + #[pymethod] + fn __reduce__(zelf: PyRef) -> (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, state: PyObjectRef, _vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __setstate__( + zelf: PyRef, + state: PyObjectRef, + _vm: &VirtualMachine, + ) -> PyResult<()> { *zelf.acc_value.write() = Some(state); Ok(()) } - #[pymethod(magic)] - fn reduce(zelf: PyRef, vm: &VirtualMachine) -> PyTupleRef { + #[pymethod] + fn __reduce__(zelf: PyRef, 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, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __setstate__(zelf: PyRef, 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, vm: &VirtualMachine) -> PyTupleRef { + #[pymethod] + fn __reduce__(zelf: PyRef, 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, vm: &VirtualMachine) -> PyTupleRef { + #[pymethod] + fn __reduce__(zelf: PyRef, 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, vm: &VirtualMachine) -> PyRef { + #[pymethod] + fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyRef { 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, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { let args: Vec = zelf .iterators .iter() @@ -1877,8 +1893,12 @@ mod decl { ))) } - #[pymethod(magic)] - fn setstate(zelf: PyRef, state: PyObjectRef, _vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __setstate__( + zelf: PyRef, + state: PyObjectRef, + _vm: &VirtualMachine, + ) -> PyResult<()> { *zelf.fillvalue.write() = state; Ok(()) } diff --git a/vm/src/stdlib/operator.rs b/vm/src/stdlib/operator.rs index ab06407815..5a2a50ff78 100644 --- a/vm/src/stdlib/operator.rs +++ b/vm/src/stdlib/operator.rs @@ -356,8 +356,8 @@ mod _operator { #[pyclass(with(Callable, Constructor, Representable))] impl PyAttrGetter { - #[pymethod(magic)] - fn reduce(zelf: PyRef, vm: &VirtualMachine) -> PyResult<(PyTypeRef, PyTupleRef)> { + #[pymethod] + fn __reduce__(zelf: PyRef, 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, vm: &VirtualMachine) -> PyObjectRef { + #[pymethod] + fn __reduce__(zelf: PyRef, 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, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { // 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()]; diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index 40250d969c..35a9aa1b3d 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -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) -> PyRef { + #[pymethod] + fn __enter__(zelf: PyRef) -> PyRef { zelf } - #[pymethod(magic)] - fn exit(zelf: PyRef, _args: FuncArgs) { + #[pymethod] + fn __exit__(zelf: PyRef, _args: FuncArgs) { zelf.close() } } diff --git a/vm/src/stdlib/sre.rs b/vm/src/stdlib/sre.rs index 34a83c2559..39d3ebaf6e 100644 --- a/vm/src/stdlib/sre.rs +++ b/vm/src/stdlib/sre.rs @@ -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 diff --git a/vm/src/stdlib/thread.rs b/vm/src/stdlib/thread.rs index a0b559421a..cdcdee95a9 100644 --- a/vm/src/stdlib/thread.rs +++ b/vm/src/stdlib/thread.rs @@ -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) } } diff --git a/vm/src/stdlib/typing.rs b/vm/src/stdlib/typing.rs index 1105183350..2bb27642e4 100644 --- a/vm/src/stdlib/typing.rs +++ b/vm/src/stdlib/typing.rs @@ -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, 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, 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, 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, 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) } } diff --git a/vm/src/stdlib/winreg.rs b/vm/src/stdlib/winreg.rs index d5b768e872..bc671114d4 100644 --- a/vm/src/stdlib/winreg.rs +++ b/vm/src/stdlib/winreg.rs @@ -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) -> PyRef { + #[pymethod] + fn __enter__(zelf: PyRef) -> PyRef { zelf } - #[pymethod(magic)] - fn exit(&self, _cls: PyObjectRef, _exc: PyObjectRef, _tb: PyObjectRef) { + #[pymethod] + fn __exit__(&self, _cls: PyObjectRef, _exc: PyObjectRef, _tb: PyObjectRef) { self.Close(); } } diff --git a/vm/src/suggestion.rs b/vm/src/suggestion.rs index 3d075ee3bb..32d4b623b4 100644 --- a/vm/src/suggestion.rs +++ b/vm/src/suggestion.rs @@ -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); diff --git a/vm/src/types/slot.rs b/vm/src/types/slot.rs index b57ec6e132..7f36a8baf0 100644 --- a/vm/src/types/slot.rs +++ b/vm/src/types/slot.rs @@ -896,8 +896,8 @@ pub trait GetDescriptor: PyPayload { ) -> PyResult; #[inline] - #[pymethod(magic)] - fn get( + #[pymethod] + fn __get__( zelf: PyObjectRef, obj: PyObjectRef, cls: OptionalArg, @@ -1022,33 +1022,57 @@ pub trait Comparable: PyPayload { ) -> PyResult; #[inline] - #[pymethod(magic)] - fn eq(zelf: &Py, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __eq__( + zelf: &Py, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { Self::cmp(zelf, &other, PyComparisonOp::Eq, vm) } #[inline] - #[pymethod(magic)] - fn ne(zelf: &Py, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __ne__( + zelf: &Py, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { Self::cmp(zelf, &other, PyComparisonOp::Ne, vm) } #[inline] - #[pymethod(magic)] - fn lt(zelf: &Py, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __lt__( + zelf: &Py, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { Self::cmp(zelf, &other, PyComparisonOp::Lt, vm) } #[inline] - #[pymethod(magic)] - fn le(zelf: &Py, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __le__( + zelf: &Py, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { Self::cmp(zelf, &other, PyComparisonOp::Le, vm) } #[inline] - #[pymethod(magic)] - fn ge(zelf: &Py, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __ge__( + zelf: &Py, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { Self::cmp(zelf, &other, PyComparisonOp::Ge, vm) } #[inline] - #[pymethod(magic)] - fn gt(zelf: &Py, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __gt__( + zelf: &Py, + other: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { Self::cmp(zelf, &other, PyComparisonOp::Gt, vm) } } @@ -1164,8 +1188,8 @@ pub trait GetAttr: PyPayload { fn getattro(zelf: &Py, name: &Py, vm: &VirtualMachine) -> PyResult; #[inline] - #[pymethod(magic)] - fn getattribute(zelf: PyRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __getattribute__(zelf: PyRef, 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, name: PyStrRef, value: PyObjectRef, @@ -1205,8 +1229,8 @@ pub trait SetAttr: PyPayload { } #[inline] - #[pymethod(magic)] - fn delattr(zelf: PyRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __delattr__(zelf: PyRef, name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> { Self::setattro(&zelf, &name, PySetterValue::Delete, vm) } } diff --git a/vm/src/types/structseq.rs b/vm/src/types/structseq.rs index 7b7f5fb9b5..625398caf0 100644 --- a/vm/src/types/structseq.rs +++ b/vm/src/types/structseq.rs @@ -47,8 +47,8 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static { Ok(seq) } - #[pymethod(magic)] - fn repr(zelf: PyRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __repr__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { 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, vm: &VirtualMachine) -> PyTupleRef { + #[pymethod] + fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyTupleRef { vm.new_tuple((zelf.class().to_owned(), (vm.ctx.new_tuple(zelf.to_vec()),))) } diff --git a/vm/src/vm/mod.rs b/vm/src/vm/mod.rs index 5829361a83..20c8161004 100644 --- a/vm/src/vm/mod.rs +++ b/vm/src/vm/mod.rs @@ -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)) } } } From 3673372d3d781cafcc51d5cab763fbfb85732671 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Fri, 27 Jun 2025 11:11:29 +0900 Subject: [PATCH 4/4] Fix cspell warnings --- .cspell.dict/cpython.txt | 2 ++ .cspell.dict/python-more.txt | 6 +++++ .cspell.dict/rust-more.txt | 4 +++ .cspell.json | 3 +++ common/src/str.rs | 3 ++- compiler/codegen/src/compile.rs | 26 +++++++++---------- compiler/src/lib.rs | 2 +- example_projects/frozen_stdlib/src/main.rs | 1 + examples/parse_folder.rs | 2 +- jit/tests/common.rs | 4 +-- jit/tests/float_tests.rs | 4 +-- src/lib.rs | 1 + stdlib/build.rs | 2 ++ stdlib/src/gc.rs | 2 +- stdlib/src/lzma.rs | 12 ++++----- vm/src/builtins/descriptor.rs | 2 +- vm/src/builtins/function.rs | 10 +++---- .../builtins/function/{jitfunc.rs => jit.rs} | 0 vm/src/builtins/genericalias.rs | 1 + vm/src/builtins/module.rs | 4 +-- vm/src/builtins/object.rs | 4 +-- vm/src/builtins/str.rs | 5 ++++ vm/src/function/argument.rs | 8 +++--- vm/src/function/builtin.rs | 2 +- vm/src/object/traverse_object.rs | 4 +-- vm/src/stdlib/builtins.rs | 2 +- vm/src/stdlib/ctypes/library.rs | 8 +++--- vm/src/stdlib/typing.rs | 1 + vm/src/vm/setting.rs | 2 ++ vm/sre_engine/benches/benches.rs | 2 +- 30 files changed, 79 insertions(+), 50 deletions(-) rename vm/src/builtins/function/{jitfunc.rs => jit.rs} (100%) diff --git a/.cspell.dict/cpython.txt b/.cspell.dict/cpython.txt index d28a4bb8c5..48059cf4e4 100644 --- a/.cspell.dict/cpython.txt +++ b/.cspell.dict/cpython.txt @@ -45,7 +45,9 @@ SA_ONSTACK stackdepth stringlib structseq +subparams tok_oldval +tvars unaryop unparse unparser diff --git a/.cspell.dict/python-more.txt b/.cspell.dict/python-more.txt index 531283e6a1..90789b1818 100644 --- a/.cspell.dict/python-more.txt +++ b/.cspell.dict/python-more.txt @@ -84,6 +84,7 @@ getrandom getrecursionlimit getrefcount getsizeof +getswitchinterval getweakrefcount getweakrefs getwindowsversion @@ -167,13 +168,17 @@ pycs pyexpat PYTHONBREAKPOINT PYTHONDEBUG +PYTHONDONTWRITEBYTECODE PYTHONHASHSEED PYTHONHOME PYTHONINSPECT +PYTHONINTMAXSTRDIGITS +PYTHONNOUSERSITE PYTHONOPTIMIZE PYTHONPATH PYTHONPATH PYTHONSAFEPATH +PYTHONUNBUFFERED PYTHONVERBOSE PYTHONWARNDEFAULTENCODING PYTHONWARNINGS @@ -206,6 +211,7 @@ seennl setattro setcomp setrecursionlimit +setswitchinterval showwarnmsg signum slotnames diff --git a/.cspell.dict/rust-more.txt b/.cspell.dict/rust-more.txt index 6a98daa9db..6f89fdfafe 100644 --- a/.cspell.dict/rust-more.txt +++ b/.cspell.dict/rust-more.txt @@ -3,8 +3,10 @@ arrayvec bidi biguint bindgen +bitand bitflags bitor +bitxor bstr byteorder byteset @@ -15,6 +17,7 @@ cranelift cstring datelike deserializer +deserializers fdiv flamescope flate2 @@ -31,6 +34,7 @@ keccak lalrpop lexopt libc +libcall libloading libz longlong diff --git a/.cspell.json b/.cspell.json index 98a03180fe..00062d1f79 100644 --- a/.cspell.json +++ b/.cspell.json @@ -67,6 +67,8 @@ "GetSet", "groupref", "internable", + "jitted", + "jitting", "lossily", "makeunicodedata", "miri", @@ -85,6 +87,7 @@ "pygetset", "pyimpl", "pylib", + "pymath", "pymember", "PyMethod", "PyModule", diff --git a/common/src/str.rs b/common/src/str.rs index ca5e0d117f..574c86a9f4 100644 --- a/common/src/str.rs +++ b/common/src/str.rs @@ -1,3 +1,4 @@ +// cspell:ignore uncomputed use crate::atomic::{PyAtomic, Radium}; use crate::format::CharLen; use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf}; @@ -424,7 +425,7 @@ pub fn zfill(bytes: &[u8], width: usize) -> Vec { } } -/// Convert a string to ascii compatible, escaping unicodes into escape +/// Convert a string to ascii compatible, escaping unicode-s into escape /// sequences. pub fn to_ascii(value: &str) -> AsciiString { let mut ascii = Vec::new(); diff --git a/compiler/codegen/src/compile.rs b/compiler/codegen/src/compile.rs index d6d4cc16b3..f74d8b33d4 100644 --- a/compiler/codegen/src/compile.rs +++ b/compiler/codegen/src/compile.rs @@ -2361,7 +2361,7 @@ impl Compiler<'_> { // self.jump_to_fail_pop(pc, JumpOp::PopJumpIfFalse)?; // } - // // Check that the number of subpatterns is not absurd. + // // Check that the number of sub-patterns is not absurd. // if size.saturating_sub(1) > (i32::MAX as usize) { // panic!("too many sub-patterns in mapping pattern"); // // return self.compiler_error("too many sub-patterns in mapping pattern"); @@ -2469,27 +2469,27 @@ impl Compiler<'_> { emit!(self, Instruction::CopyItem { index: 1_u32 }); self.compile_pattern(alt, pc)?; - let nstores = pc.stores.len(); + let n_stores = pc.stores.len(); if i == 0 { // Save the captured names from the first alternative. control = Some(pc.stores.clone()); } else { let control_vec = control.as_ref().unwrap(); - if nstores != control_vec.len() { + if n_stores != control_vec.len() { return Err(self.error(CodegenErrorType::ConflictingNameBindPattern)); - } else if nstores > 0 { + } else if n_stores > 0 { // Check that the names occur in the same order. - for icontrol in (0..nstores).rev() { - let name = &control_vec[icontrol]; + for i_control in (0..n_stores).rev() { + let name = &control_vec[i_control]; // Find the index of `name` in the current stores. - let istores = + let i_stores = pc.stores.iter().position(|n| n == name).ok_or_else(|| { self.error(CodegenErrorType::ConflictingNameBindPattern) })?; - if icontrol != istores { + if i_control != i_stores { // The orders differ; we must reorder. - assert!(istores < icontrol, "expected istores < icontrol"); - let rotations = istores + 1; + assert!(i_stores < i_control, "expected i_stores < i_control"); + let rotations = i_stores + 1; // Rotate pc.stores: take a slice of the first `rotations` items... let rotated = pc.stores[0..rotations].to_vec(); // Remove those elements. @@ -2497,13 +2497,13 @@ impl Compiler<'_> { pc.stores.remove(0); } // Insert the rotated slice at the appropriate index. - let insert_pos = icontrol - istores; + let insert_pos = i_control - i_stores; for (j, elem) in rotated.into_iter().enumerate() { pc.stores.insert(insert_pos + j, elem); } // Also perform the same rotation on the evaluation stack. - for _ in 0..(istores + 1) { - self.pattern_helper_rotate(icontrol + 1)?; + for _ in 0..(i_stores + 1) { + self.pattern_helper_rotate(i_control + 1)?; } } } diff --git a/compiler/src/lib.rs b/compiler/src/lib.rs index 7647e19348..fde8e96e8a 100644 --- a/compiler/src/lib.rs +++ b/compiler/src/lib.rs @@ -93,7 +93,7 @@ pub fn compile( source_path: &str, opts: CompileOpts, ) -> Result { - // TODO: do this less hackily; ruff's parser should translate a CRLF line + // TODO: do this less hacky; ruff's parser should translate a CRLF line // break in a multiline string into just an LF in the parsed value #[cfg(windows)] let source = &source.replace("\r\n", "\n"); diff --git a/example_projects/frozen_stdlib/src/main.rs b/example_projects/frozen_stdlib/src/main.rs index dd6cfc3b35..a49a4d2736 100644 --- a/example_projects/frozen_stdlib/src/main.rs +++ b/example_projects/frozen_stdlib/src/main.rs @@ -1,3 +1,4 @@ +// cspell:ignore aheui /// Setting up a project with a frozen stdlib can be done *either* by using `rustpython::InterpreterConfig` or `rustpython_vm::Interpreter::with_init`. /// See each function for example. /// diff --git a/examples/parse_folder.rs b/examples/parse_folder.rs index 462fd29256..440bcdb9b5 100644 --- a/examples/parse_folder.rs +++ b/examples/parse_folder.rs @@ -56,7 +56,7 @@ fn parse_folder(path: &Path) -> std::io::Result> { let parsed_file = parse_python_file(&path); match &parsed_file.result { Ok(_) => {} - Err(y) => error!("Erreur in file {path:?} {y:?}"), + Err(y) => error!("Error in file {path:?} {y:?}"), } res.push(parsed_file); diff --git a/jit/tests/common.rs b/jit/tests/common.rs index 78318bc406..16a4fded46 100644 --- a/jit/tests/common.rs +++ b/jit/tests/common.rs @@ -77,9 +77,9 @@ impl StackMachine { } pub fn run(&mut self, code: CodeObject) { - let mut oparg_state = OpArgState::default(); + let mut op_arg_state = OpArgState::default(); let _ = code.instructions.iter().try_for_each(|&word| { - let (instruction, arg) = oparg_state.get(word); + let (instruction, arg) = op_arg_state.get(word); self.process_instruction(instruction, arg, &code.constants, &code.names) }); } diff --git a/jit/tests/float_tests.rs b/jit/tests/float_tests.rs index 384d7b9468..b5fcba9fc6 100644 --- a/jit/tests/float_tests.rs +++ b/jit/tests/float_tests.rs @@ -168,7 +168,7 @@ fn test_power() { assert_approx_eq!(pow(-4.5, 4.0), Ok(410.0625)); assert_approx_eq!(pow(-2.5, 3.0), Ok(-15.625)); assert_approx_eq!(pow(-2.5, 4.0), Ok(39.0625)); - // Test positive float base, positive float exponent with nonintegral exponents + // Test positive float base, positive float exponent with non-integral exponents assert_approx_eq!(pow(2.0, 2.5), Ok(5.656854249492381)); assert_approx_eq!(pow(3.0, 3.5), Ok(46.76537180435969)); assert_approx_eq!(pow(4.0, 4.5), Ok(512.0)); @@ -187,7 +187,7 @@ fn test_power() { assert_approx_eq!(pow(-2.0, -3.0), Ok(-0.125)); assert_approx_eq!(pow(-2.0, -4.0), Ok(0.0625)); - // Currently negative float base with nonintegral exponent is not supported: + // Currently negative float base with non-integral exponent is not supported: // assert_approx_eq!(pow(-2.0, 2.5), Ok(5.656854249492381)); // assert_approx_eq!(pow(-3.0, 3.5), Ok(-46.76537180435969)); // assert_approx_eq!(pow(-4.0, 4.5), Ok(512.0)); diff --git a/src/lib.rs b/src/lib.rs index 69b612d932..bb2b390655 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -242,6 +242,7 @@ fn write_profile(settings: &Settings) -> Result<(), Box> Some("html") => ProfileFormat::Html, Some("text") => ProfileFormat::Text, None if profile_output == Some("-".as_ref()) => ProfileFormat::Text, + // cspell:ignore speedscope Some("speedscope") | None => ProfileFormat::SpeedScope, Some(other) => { error!("Unknown profile format {}", other); diff --git a/stdlib/build.rs b/stdlib/build.rs index 3eb8a2d6b6..864ca0b041 100644 --- a/stdlib/build.rs +++ b/stdlib/build.rs @@ -1,3 +1,5 @@ +// cspell:ignore ossl osslconf + fn main() { println!(r#"cargo::rustc-check-cfg=cfg(osslconf, values("OPENSSL_NO_COMP"))"#); println!(r#"cargo::rustc-check-cfg=cfg(openssl_vendored)"#); diff --git a/stdlib/src/gc.rs b/stdlib/src/gc.rs index 0059e2424f..5fc96a302f 100644 --- a/stdlib/src/gc.rs +++ b/stdlib/src/gc.rs @@ -40,7 +40,7 @@ mod gc { } #[pyfunction] - fn get_refererts(_args: FuncArgs, vm: &VirtualMachine) -> PyResult { + fn get_referents(_args: FuncArgs, vm: &VirtualMachine) -> PyResult { Err(vm.new_not_implemented_error("")) } diff --git a/stdlib/src/lzma.rs b/stdlib/src/lzma.rs index 79fef0be38..c2dd912577 100644 --- a/stdlib/src/lzma.rs +++ b/stdlib/src/lzma.rs @@ -140,7 +140,7 @@ mod _lzma { #[pyarg(any, default = FORMAT_AUTO)] format: i32, #[pyarg(any, optional)] - memlimit: Option, + mem_limit: Option, #[pyarg(any, optional)] filters: Option, } @@ -149,15 +149,15 @@ mod _lzma { type Args = LZMADecompressorConstructorArgs; fn py_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult { - if args.format == FORMAT_RAW && args.memlimit.is_some() { + if args.format == FORMAT_RAW && args.mem_limit.is_some() { return Err(vm.new_value_error("Cannot specify memory limit with FORMAT_RAW")); } - let memlimit = args.memlimit.unwrap_or(u64::MAX); + let mem_limit = args.mem_limit.unwrap_or(u64::MAX); let filters = args.filters.unwrap_or(0); let stream_result = match args.format { - FORMAT_AUTO => Stream::new_auto_decoder(memlimit, filters), - FORMAT_XZ => Stream::new_stream_decoder(memlimit, filters), - FORMAT_ALONE => Stream::new_lzma_decoder(memlimit), + FORMAT_AUTO => Stream::new_auto_decoder(mem_limit, filters), + FORMAT_XZ => Stream::new_stream_decoder(mem_limit, filters), + FORMAT_ALONE => Stream::new_lzma_decoder(mem_limit), // TODO: FORMAT_RAW _ => return Err(new_lzma_error("Invalid format", vm)), }; diff --git a/vm/src/builtins/descriptor.rs b/vm/src/builtins/descriptor.rs index 4555583dc9..9e8ef982d1 100644 --- a/vm/src/builtins/descriptor.rs +++ b/vm/src/builtins/descriptor.rs @@ -26,7 +26,7 @@ pub struct PyDescriptorOwned { pub struct PyMethodDescriptor { pub common: PyDescriptor, pub method: &'static PyMethodDef, - // vectorcall: vectorcallfunc, + // vectorcall: vector_call_func, pub objclass: &'static Py, // TODO: move to tp_members } diff --git a/vm/src/builtins/function.rs b/vm/src/builtins/function.rs index dc97fce41d..53aa537e20 100644 --- a/vm/src/builtins/function.rs +++ b/vm/src/builtins/function.rs @@ -1,5 +1,5 @@ #[cfg(feature = "jit")] -mod jitfunc; +mod jit; use super::{ PyAsyncGen, PyCode, PyCoroutine, PyDictRef, PyGenerator, PyStr, PyStrRef, PyTupleRef, PyType, @@ -324,7 +324,7 @@ impl PyFunction { ) -> PyResult { #[cfg(feature = "jit")] if let Some(jitted_code) = self.jitted_code.get() { - match jitfunc::get_jit_args(self, &func_args, jitted_code, vm) { + match jit::get_jit_args(self, &func_args, jitted_code, vm) { Ok(args) => { return Ok(args.invoke().to_pyobject(vm)); } @@ -530,10 +530,10 @@ impl PyFunction { fn __jit__(zelf: PyRef, vm: &VirtualMachine) -> PyResult<()> { zelf.jitted_code .get_or_try_init(|| { - let arg_types = jitfunc::get_jit_arg_types(&zelf, vm)?; - let ret_type = jitfunc::jit_ret_type(&zelf, vm)?; + let arg_types = jit::get_jit_arg_types(&zelf, vm)?; + let ret_type = jit::jit_ret_type(&zelf, vm)?; rustpython_jit::compile(&zelf.code.code, &arg_types, ret_type) - .map_err(|err| jitfunc::new_jit_error(err.to_string(), vm)) + .map_err(|err| jit::new_jit_error(err.to_string(), vm)) }) .map(drop) } diff --git a/vm/src/builtins/function/jitfunc.rs b/vm/src/builtins/function/jit.rs similarity index 100% rename from vm/src/builtins/function/jitfunc.rs rename to vm/src/builtins/function/jit.rs diff --git a/vm/src/builtins/genericalias.rs b/vm/src/builtins/genericalias.rs index f0196f7463..7ef98098ee 100644 --- a/vm/src/builtins/genericalias.rs +++ b/vm/src/builtins/genericalias.rs @@ -1,3 +1,4 @@ +// cspell:ignore iparam use std::sync::LazyLock; use super::type_; diff --git a/vm/src/builtins/module.rs b/vm/src/builtins/module.rs index 8107390f59..ccf44712e3 100644 --- a/vm/src/builtins/module.rs +++ b/vm/src/builtins/module.rs @@ -17,9 +17,9 @@ pub struct PyModuleDef { // pub size: isize, pub methods: &'static [PyMethodDef], pub slots: PyModuleSlots, - // traverse: traverseproc + // traverse: traverse_proc // clear: inquiry - // free: freefunc + // free: free_func } pub type ModuleCreate = diff --git a/vm/src/builtins/object.rs b/vm/src/builtins/object.rs index f0679cbe29..0afdb8a961 100644 --- a/vm/src/builtins/object.rs +++ b/vm/src/builtins/object.rs @@ -126,12 +126,12 @@ fn object_getstate_default(obj: &PyObject, required: bool, vm: &VirtualMachine) if required { let mut basicsize = obj.class().slots.basicsize; - // if obj.class().slots.dictoffset > 0 + // if obj.class().slots.dict_offset > 0 // && !obj.class().slots.flags.has_feature(PyTypeFlags::MANAGED_DICT) // { // basicsize += std::mem::size_of::(); // } - // if obj.class().slots.weaklistoffset > 0 { + // if obj.class().slots.weaklist_offset > 0 { // basicsize += std::mem::size_of::(); // } if let Some(ref slot_names) = slot_names { diff --git a/vm/src/builtins/str.rs b/vm/src/builtins/str.rs index 0af9bd3c61..d99467826a 100644 --- a/vm/src/builtins/str.rs +++ b/vm/src/builtins/str.rs @@ -575,6 +575,7 @@ impl PyStr { fn _compute_hash(&self, vm: &VirtualMachine) -> hash::PyHash { let hash_val = vm.state.hash_secret.hash_bytes(self.as_bytes()); debug_assert_ne!(hash_val, hash::SENTINEL); + // cspell:ignore cmpxchg // like with char_len, we don't need a cmpxchg loop, since it'll always be the same value self.hash.store(hash_val, atomic::Ordering::Relaxed); hash_val @@ -2259,7 +2260,9 @@ mod tests { ("Format This As Title String", "fOrMaT thIs aS titLe String"), ("Format,This-As*Title;String", "fOrMaT,thIs-aS*titLe;String"), ("Getint", "getInt"), + // cspell:disable-next-line ("Greek Ωppercases ...", "greek ωppercases ..."), + // cspell:disable-next-line ("Greek ῼitlecases ...", "greek ῳitlecases ..."), ]; for (title, input) in tests { @@ -2274,7 +2277,9 @@ mod tests { "A Titlecased Line", "A\nTitlecased Line", "A Titlecased, Line", + // cspell:disable-next-line "Greek Ωppercases ...", + // cspell:disable-next-line "Greek ῼitlecases ...", ]; diff --git a/vm/src/function/argument.rs b/vm/src/function/argument.rs index cf9d035bb4..b4ba3bd578 100644 --- a/vm/src/function/argument.rs +++ b/vm/src/function/argument.rs @@ -118,15 +118,15 @@ impl FuncArgs { { // last `kwarg_names.len()` elements of args in order of appearance in the call signature let total_argc = args.len(); - let kwargc = kwarg_names.len(); - let posargc = total_argc - kwargc; + let kwarg_count = kwarg_names.len(); + let pos_arg_count = total_argc - kwarg_count; - let posargs = args.by_ref().take(posargc).collect(); + let pos_args = args.by_ref().take(pos_arg_count).collect(); let kwargs = kwarg_names.zip_eq(args).collect::>(); FuncArgs { - args: posargs, + args: pos_args, kwargs, } } diff --git a/vm/src/function/builtin.rs b/vm/src/function/builtin.rs index 186dc7aeb8..1a91e4344b 100644 --- a/vm/src/function/builtin.rs +++ b/vm/src/function/builtin.rs @@ -66,7 +66,7 @@ const fn zst_ref_out_of_thin_air(x: T) -> &'static T { } /// Get the STATIC_FUNC of the passed function. The same -/// requirements of zero-sizedness apply, see that documentation for details. +/// requirements of zero-sized-ness apply, see that documentation for details. /// /// Equivalent to [`IntoPyNativeFn::into_func()`], but usable in a const context. This is only /// valid if the function is zero-sized, i.e. that `std::mem::size_of::() == 0`. If you call diff --git a/vm/src/object/traverse_object.rs b/vm/src/object/traverse_object.rs index 2cf4fba2d3..55204080bc 100644 --- a/vm/src/object/traverse_object.rs +++ b/vm/src/object/traverse_object.rs @@ -44,7 +44,7 @@ unsafe impl Traverse for PyInner { // 2. call vtable's trace function to trace payload // self.typ.trace(tracer_fn); self.dict.traverse(tracer_fn); - // weak_list keeps a *pointer* to a struct for maintaince weak ref, so no ownership, no trace + // weak_list keeps a *pointer* to a struct for maintenance of weak ref, so no ownership, no trace self.slots.traverse(tracer_fn); if let Some(f) = self.vtable.trace { @@ -64,7 +64,7 @@ unsafe impl Traverse for PyInner { // (No need to call vtable's trace function because we already know the type) // self.typ.trace(tracer_fn); self.dict.traverse(tracer_fn); - // weak_list keeps a *pointer* to a struct for maintaince weak ref, so no ownership, no trace + // weak_list keeps a *pointer* to a struct for maintenance of weak ref, so no ownership, no trace self.slots.traverse(tracer_fn); T::try_traverse(&self.payload, tracer_fn); } diff --git a/vm/src/stdlib/builtins.rs b/vm/src/stdlib/builtins.rs index bf8b5285c6..7d3afe04d9 100644 --- a/vm/src/stdlib/builtins.rs +++ b/vm/src/stdlib/builtins.rs @@ -443,7 +443,7 @@ mod builtins { .is_ok_and(|fd| fd == expected) }; - // everything is normalish, we can just rely on rustyline to use stdin/stdout + // everything is normal, we can just rely on rustyline to use stdin/stdout if fd_matches(&stdin, 0) && fd_matches(&stdout, 1) && std::io::stdin().is_terminal() { let prompt = prompt.as_ref().map_or("", |s| s.as_str()); let mut readline = Readline::new(()); diff --git a/vm/src/stdlib/ctypes/library.rs b/vm/src/stdlib/ctypes/library.rs index 74a601a488..e918470b6c 100644 --- a/vm/src/stdlib/ctypes/library.rs +++ b/vm/src/stdlib/ctypes/library.rs @@ -69,17 +69,17 @@ impl ExternalLibs { library_path: &str, _vm: &VirtualMachine, ) -> Result<(usize, &SharedLibrary), libloading::Error> { - let nlib = SharedLibrary::new(library_path)?; - let key = nlib.get_pointer(); + let new_lib = SharedLibrary::new(library_path)?; + let key = new_lib.get_pointer(); match self.libraries.get(&key) { Some(l) => { if l.is_closed() { - self.libraries.insert(key, nlib); + self.libraries.insert(key, new_lib); } } _ => { - self.libraries.insert(key, nlib); + self.libraries.insert(key, new_lib); } }; diff --git a/vm/src/stdlib/typing.rs b/vm/src/stdlib/typing.rs index 2bb27642e4..25a26015a4 100644 --- a/vm/src/stdlib/typing.rs +++ b/vm/src/stdlib/typing.rs @@ -1,3 +1,4 @@ +// cspell:ignore typevarobject funcobj use crate::{PyRef, VirtualMachine, stdlib::PyModule}; pub(crate) use decl::*; diff --git a/vm/src/vm/setting.rs b/vm/src/vm/setting.rs index 1abd26cf4c..725bc272ae 100644 --- a/vm/src/vm/setting.rs +++ b/vm/src/vm/setting.rs @@ -36,9 +36,11 @@ pub struct Settings { /// sys.argv pub argv: Vec, + // cspell:ignore Xfoo /// -Xfoo[=bar] pub xoptions: Vec<(String, Option)>, + // cspell:ignore Wfoo /// -Wfoo pub warnoptions: Vec, diff --git a/vm/sre_engine/benches/benches.rs b/vm/sre_engine/benches/benches.rs index e2372d783e..127f72e274 100644 --- a/vm/sre_engine/benches/benches.rs +++ b/vm/sre_engine/benches/benches.rs @@ -45,7 +45,7 @@ fn basic(c: &mut Criterion) { // START GENERATED by generate_tests.py #[rustfmt::skip] let p5 = Pattern { pattern: "(Python)\\1", code: &[14, 18, 1, 12, 12, 6, 0, 80, 121, 116, 104, 111, 110, 0, 0, 0, 0, 0, 0, 17, 0, 16, 80, 16, 121, 16, 116, 16, 104, 16, 111, 16, 110, 17, 1, 11, 0, 1] }; // END GENERATED - // pattern p6 = re.compile('([0a-z][a-z0-9]*,)+') #, 'a5,b7,c9,'), # Disable the fastmap optimization + // pattern p6 = re.compile('([0a-z][a-z0-9]*,)+') #, 'a5,b7,c9,'), # Disable the fast map optimization // START GENERATED by generate_tests.py #[rustfmt::skip] let p6 = Pattern { pattern: "([0a-z][a-z0-9]*,)+", code: &[14, 4, 0, 2, 4294967295, 23, 31, 1, 4294967295, 17, 0, 13, 7, 16, 48, 22, 97, 122, 0, 24, 13, 0, 4294967295, 13, 8, 22, 97, 122, 22, 48, 57, 0, 1, 16, 44, 17, 1, 18, 1] }; // END GENERATED