From b30c919b1b857bb2abbb3072a3e77c4148a757cb Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 00:57:36 +0300 Subject: [PATCH 01/16] vm --- vm/src/buffer.rs | 6 +++--- vm/src/builtins/asyncgenerator.rs | 10 +++++----- vm/src/builtins/builtin_func.rs | 6 +++--- vm/src/builtins/bytearray.rs | 2 +- vm/src/builtins/bytes.rs | 4 ++-- vm/src/builtins/code.rs | 12 ++++++------ vm/src/builtins/complex.rs | 12 ++++++------ vm/src/builtins/coroutine.rs | 6 +++--- vm/src/builtins/dict.rs | 8 ++++---- vm/src/builtins/enumerate.rs | 2 +- vm/src/builtins/float.rs | 2 +- vm/src/builtins/frame.rs | 2 +- vm/src/builtins/function.rs | 4 ++-- vm/src/builtins/iter.rs | 4 ++-- vm/src/builtins/set.rs | 2 +- vm/src/builtins/singletons.rs | 4 ++-- vm/src/builtins/str.rs | 10 +++++----- vm/src/builtins/traceback.rs | 6 +++--- vm/src/builtins/type.rs | 6 +++--- vm/src/builtins/union.rs | 2 +- vm/src/codecs.rs | 2 +- vm/src/function/protocol.rs | 2 +- vm/src/intern.rs | 4 ++-- vm/src/object/core.rs | 12 ++++++------ vm/src/object/ext.rs | 4 ++-- vm/src/protocol/iter.rs | 2 +- vm/src/protocol/sequence.rs | 2 +- vm/src/readline.rs | 2 +- vm/src/sliceable.rs | 4 ++-- vm/src/stdlib/ast.rs | 8 ++++---- vm/src/stdlib/collections.rs | 2 +- vm/src/stdlib/imp.rs | 8 ++++---- vm/src/stdlib/io.rs | 24 ++++++++++++------------ vm/src/stdlib/os.rs | 8 ++++---- vm/src/stdlib/posix.rs | 16 ++++++++-------- vm/src/stdlib/sre.rs | 2 +- vm/src/stdlib/stat.rs | 26 +++++++++++++------------- vm/src/stdlib/symtable.rs | 4 ++-- vm/src/stdlib/sys.rs | 10 +++++----- vm/src/stdlib/typevar.rs | 14 +++++++------- vm/src/stdlib/typing.rs | 2 +- vm/src/types/slot.rs | 10 +++++----- 42 files changed, 139 insertions(+), 139 deletions(-) diff --git a/vm/src/buffer.rs b/vm/src/buffer.rs index d6bff513720..13efe9aa424 100644 --- a/vm/src/buffer.rs +++ b/vm/src/buffer.rs @@ -201,7 +201,7 @@ pub(crate) struct FormatCode { } impl FormatCode { - pub fn arg_count(&self) -> usize { + pub const fn arg_count(&self) -> usize { match self.code { FormatType::Pad => 0, FormatType::Str | FormatType::Pascal => 1, @@ -286,7 +286,7 @@ impl FormatCode { } } -fn compensate_alignment(offset: usize, align: usize) -> Option { +const fn compensate_alignment(offset: usize, align: usize) -> Option { if align != 0 && offset != 0 { // a % b == a & (b-1) if b is a power of 2 (align - 1).checked_sub((offset - 1) & (align - 1)) @@ -444,7 +444,7 @@ impl FormatSpec { } #[inline] - pub fn size(&self) -> usize { + pub const fn size(&self) -> usize { self.size } } diff --git a/vm/src/builtins/asyncgenerator.rs b/vm/src/builtins/asyncgenerator.rs index a280495fda8..8eafcaf0323 100644 --- a/vm/src/builtins/asyncgenerator.rs +++ b/vm/src/builtins/asyncgenerator.rs @@ -29,7 +29,7 @@ impl PyPayload for PyAsyncGen { #[pyclass(with(PyRef, Unconstructible, Representable))] impl PyAsyncGen { - pub fn as_coro(&self) -> &Coro { + pub const fn as_coro(&self) -> &Coro { &self.inner } @@ -76,7 +76,7 @@ impl PyAsyncGen { #[pyclass] impl PyRef { #[pymethod] - fn __aiter__(self, _vm: &VirtualMachine) -> PyRef { + const fn __aiter__(self, _vm: &VirtualMachine) -> PyRef { self } @@ -86,7 +86,7 @@ impl PyRef { } #[pymethod] - fn asend(self, value: PyObjectRef, _vm: &VirtualMachine) -> PyAsyncGenASend { + const fn asend(self, value: PyObjectRef, _vm: &VirtualMachine) -> PyAsyncGenASend { PyAsyncGenASend { ag: self, state: AtomicCell::new(AwaitableState::Init), @@ -201,7 +201,7 @@ impl PyPayload for PyAsyncGenASend { #[pyclass(with(IterNext, Iterable))] impl PyAsyncGenASend { #[pymethod(name = "__await__")] - fn r#await(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { + const fn r#await(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { zelf } @@ -295,7 +295,7 @@ impl PyPayload for PyAsyncGenAThrow { #[pyclass(with(IterNext, Iterable))] impl PyAsyncGenAThrow { #[pymethod(name = "__await__")] - fn r#await(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { + const fn r#await(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { zelf } diff --git a/vm/src/builtins/builtin_func.rs b/vm/src/builtins/builtin_func.rs index 5e276b89767..a39b56fb88a 100644 --- a/vm/src/builtins/builtin_func.rs +++ b/vm/src/builtins/builtin_func.rs @@ -36,7 +36,7 @@ impl fmt::Debug for PyNativeFunction { } impl PyNativeFunction { - pub fn with_module(mut self, module: &'static PyStrInterned) -> Self { + pub const fn with_module(mut self, module: &'static PyStrInterned) -> Self { self.module = Some(module); self } @@ -50,7 +50,7 @@ impl PyNativeFunction { } // PyCFunction_GET_SELF - pub fn get_self(&self) -> Option<&PyObjectRef> { + pub const fn get_self(&self) -> Option<&PyObjectRef> { if self.value.flags.contains(PyMethodFlags::STATIC) { return None; } @@ -119,7 +119,7 @@ impl PyNativeFunction { } #[pymethod] - fn __reduce__(&self) -> &'static str { + const fn __reduce__(&self) -> &'static str { // TODO: return (getattr, (self.object, self.name)) if this is a method self.value.name } diff --git a/vm/src/builtins/bytearray.rs b/vm/src/builtins/bytearray.rs index f7f1d9da343..fefb095ecd4 100644 --- a/vm/src/builtins/bytearray.rs +++ b/vm/src/builtins/bytearray.rs @@ -77,7 +77,7 @@ impl PyByteArray { PyRef::new_ref(Self::from(data), ctx.types.bytearray_type.to_owned(), None) } - fn from_inner(inner: PyBytesInner) -> Self { + const fn from_inner(inner: PyBytesInner) -> Self { PyByteArray { inner: PyRwLock::new(inner), exports: AtomicUsize::new(0), diff --git a/vm/src/builtins/bytes.rs b/vm/src/builtins/bytes.rs index 67f910bef7d..8951444a8f3 100644 --- a/vm/src/builtins/bytes.rs +++ b/vm/src/builtins/bytes.rs @@ -149,12 +149,12 @@ impl PyRef { impl PyBytes { #[inline] #[pymethod] - pub fn __len__(&self) -> usize { + pub const fn __len__(&self) -> usize { self.inner.len() } #[inline] - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.inner.is_empty() } diff --git a/vm/src/builtins/code.rs b/vm/src/builtins/code.rs index 659a1ce7027..d490e8cfd8e 100644 --- a/vm/src/builtins/code.rs +++ b/vm/src/builtins/code.rs @@ -202,7 +202,7 @@ impl Deref for PyCode { } impl PyCode { - pub fn new(code: CodeObject) -> PyCode { + pub const fn new(code: CodeObject) -> PyCode { PyCode { code } } } @@ -242,17 +242,17 @@ impl PyCode { } #[pygetset] - fn co_posonlyargcount(&self) -> usize { + const fn co_posonlyargcount(&self) -> usize { self.code.posonlyarg_count as usize } #[pygetset] - fn co_argcount(&self) -> usize { + const fn co_argcount(&self) -> usize { self.code.arg_count as usize } #[pygetset] - fn co_stacksize(&self) -> u32 { + const fn co_stacksize(&self) -> u32 { self.code.max_stackdepth } @@ -284,7 +284,7 @@ impl PyCode { } #[pygetset] - fn co_kwonlyargcount(&self) -> usize { + const fn co_kwonlyargcount(&self) -> usize { self.code.kwonlyarg_count as usize } @@ -312,7 +312,7 @@ impl PyCode { } #[pygetset] - fn co_flags(&self) -> u16 { + const fn co_flags(&self) -> u16 { self.code.flags.bits() } diff --git a/vm/src/builtins/complex.rs b/vm/src/builtins/complex.rs index 752d9410613..338e0ff9392 100644 --- a/vm/src/builtins/complex.rs +++ b/vm/src/builtins/complex.rs @@ -28,7 +28,7 @@ pub struct PyComplex { } impl PyComplex { - pub fn to_complex64(self) -> Complex64 { + pub const fn to_complex64(self) -> Complex64 { self.value } } @@ -236,7 +236,7 @@ impl PyComplex { PyRef::new_ref(Self::from(value), ctx.types.complex_type.to_owned(), None) } - pub fn to_complex(&self) -> Complex64 { + pub const fn to_complex(&self) -> Complex64 { self.value } } @@ -247,12 +247,12 @@ impl PyComplex { )] impl PyComplex { #[pygetset] - fn real(&self) -> f64 { + const fn real(&self) -> f64 { self.value.re } #[pygetset] - fn imag(&self) -> f64 { + const fn imag(&self) -> f64 { self.value.im } @@ -346,7 +346,7 @@ impl PyComplex { } #[pymethod] - fn __pos__(&self) -> Complex64 { + const fn __pos__(&self) -> Complex64 { self.value } @@ -384,7 +384,7 @@ impl PyComplex { } #[pymethod] - fn __getnewargs__(&self) -> (f64, f64) { + const fn __getnewargs__(&self) -> (f64, f64) { let Complex64 { re, im } = self.value; (re, im) } diff --git a/vm/src/builtins/coroutine.rs b/vm/src/builtins/coroutine.rs index eea50a567b3..b98fbd1ba18 100644 --- a/vm/src/builtins/coroutine.rs +++ b/vm/src/builtins/coroutine.rs @@ -25,7 +25,7 @@ impl PyPayload for PyCoroutine { #[pyclass(with(Py, Unconstructible, IterNext, Representable))] impl PyCoroutine { - pub fn as_coro(&self) -> &Coro { + pub const fn as_coro(&self) -> &Coro { &self.inner } @@ -46,7 +46,7 @@ impl PyCoroutine { } #[pymethod(name = "__await__")] - fn r#await(zelf: PyRef) -> PyCoroutineWrapper { + const fn r#await(zelf: PyRef) -> PyCoroutineWrapper { PyCoroutineWrapper { coro: zelf } } @@ -69,7 +69,7 @@ impl PyCoroutine { // TODO: coroutine origin tracking: // https://docs.python.org/3/library/sys.html#sys.set_coroutine_origin_tracking_depth #[pygetset] - fn cr_origin(&self, _vm: &VirtualMachine) -> Option<(PyStrRef, usize, PyStrRef)> { + const fn cr_origin(&self, _vm: &VirtualMachine) -> Option<(PyStrRef, usize, PyStrRef)> { None } diff --git a/vm/src/builtins/dict.rs b/vm/src/builtins/dict.rs index f9610af5dcf..7c04781a710 100644 --- a/vm/src/builtins/dict.rs +++ b/vm/src/builtins/dict.rs @@ -57,7 +57,7 @@ impl PyDict { /// escape hatch to access the underlying data structure directly. prefer adding a method on /// PyDict instead of using this - pub(crate) fn _as_dict_inner(&self) -> &DictContentType { + pub(crate) const fn _as_dict_inner(&self) -> &DictContentType { &self.entries } @@ -376,17 +376,17 @@ impl Py { #[pyclass] impl PyRef { #[pymethod] - fn keys(self) -> PyDictKeys { + const fn keys(self) -> PyDictKeys { PyDictKeys::new(self) } #[pymethod] - fn values(self) -> PyDictValues { + const fn values(self) -> PyDictValues { PyDictValues::new(self) } #[pymethod] - fn items(self) -> PyDictItems { + const fn items(self) -> PyDictItems { PyDictItems::new(self) } diff --git a/vm/src/builtins/enumerate.rs b/vm/src/builtins/enumerate.rs index f0287a61933..05241691b4e 100644 --- a/vm/src/builtins/enumerate.rs +++ b/vm/src/builtins/enumerate.rs @@ -101,7 +101,7 @@ impl PyPayload for PyReverseSequenceIterator { #[pyclass(with(IterNext, Iterable))] impl PyReverseSequenceIterator { - pub fn new(obj: PyObjectRef, len: usize) -> Self { + pub const fn new(obj: PyObjectRef, len: usize) -> Self { let position = len.saturating_sub(1); Self { internal: PyMutex::new(PositionIterInternal::new(obj, position)), diff --git a/vm/src/builtins/float.rs b/vm/src/builtins/float.rs index 6c0ba28e557..d7d20dee793 100644 --- a/vm/src/builtins/float.rs +++ b/vm/src/builtins/float.rs @@ -231,7 +231,7 @@ impl PyFloat { } #[pymethod] - fn __abs__(&self) -> f64 { + const fn __abs__(&self) -> f64 { self.value.abs() } diff --git a/vm/src/builtins/frame.rs b/vm/src/builtins/frame.rs index 88337c14946..65ac3e798d7 100644 --- a/vm/src/builtins/frame.rs +++ b/vm/src/builtins/frame.rs @@ -34,7 +34,7 @@ impl Representable for Frame { #[pyclass(with(Unconstructible, Py))] impl Frame { #[pymethod] - fn clear(&self) { + const fn clear(&self) { // TODO } diff --git a/vm/src/builtins/function.rs b/vm/src/builtins/function.rs index 7bcd6bd7b03..720fad549d5 100644 --- a/vm/src/builtins/function.rs +++ b/vm/src/builtins/function.rs @@ -722,7 +722,7 @@ impl Constructor for PyBoundMethod { } impl PyBoundMethod { - pub fn new(object: PyObjectRef, function: PyObjectRef) -> Self { + pub const fn new(object: PyObjectRef, function: PyObjectRef) -> Self { PyBoundMethod { object, function } } @@ -846,7 +846,7 @@ impl Constructor for PyCell { #[pyclass(with(Constructor))] impl PyCell { - pub fn new(contents: Option) -> Self { + pub const fn new(contents: Option) -> Self { Self { contents: PyMutex::new(contents), } diff --git a/vm/src/builtins/iter.rs b/vm/src/builtins/iter.rs index 4250a86d717..8fc4e7d431d 100644 --- a/vm/src/builtins/iter.rs +++ b/vm/src/builtins/iter.rs @@ -47,7 +47,7 @@ unsafe impl Traverse for PositionIterInternal { } impl PositionIterInternal { - pub fn new(obj: T, position: usize) -> Self { + pub const fn new(obj: T, position: usize) -> Self { Self { status: IterStatus::Active(obj), position, @@ -256,7 +256,7 @@ impl PyPayload for PyCallableIterator { #[pyclass(with(IterNext, Iterable))] impl PyCallableIterator { - pub fn new(callable: ArgCallable, sentinel: PyObjectRef) -> Self { + pub const fn new(callable: ArgCallable, sentinel: PyObjectRef) -> Self { Self { sentinel, status: PyRwLock::new(IterStatus::Active(callable)), diff --git a/vm/src/builtins/set.rs b/vm/src/builtins/set.rs index 4ff5bed7b0c..c765b2884c7 100644 --- a/vm/src/builtins/set.rs +++ b/vm/src/builtins/set.rs @@ -454,7 +454,7 @@ impl PySetInner { // This is important because some use cases have many combinations of a // small number of elements with nearby hashes so that many distinct // combinations collapse to only a handful of distinct hash values. - fn _shuffle_bits(h: u64) -> u64 { + const fn _shuffle_bits(h: u64) -> u64 { ((h ^ 89869747) ^ (h.wrapping_shl(16))).wrapping_mul(3644798167) } // Factor in the number of active entries diff --git a/vm/src/builtins/singletons.rs b/vm/src/builtins/singletons.rs index b1b02d3124a..7b674cb35b1 100644 --- a/vm/src/builtins/singletons.rs +++ b/vm/src/builtins/singletons.rs @@ -46,7 +46,7 @@ impl Constructor for PyNone { #[pyclass(with(Constructor, AsNumber, Representable))] impl PyNone { #[pymethod] - fn __bool__(&self) -> bool { + const fn __bool__(&self) -> bool { false } } @@ -98,7 +98,7 @@ impl PyNotImplemented { // in boolean contexts will need to raise a DeprecationWarning in 3.9 // and, eventually, a TypeError. #[pymethod] - fn __bool__(&self) -> bool { + const fn __bool__(&self) -> bool { true } diff --git a/vm/src/builtins/str.rs b/vm/src/builtins/str.rs index feb2231e7d4..51d10b23fcb 100644 --- a/vm/src/builtins/str.rs +++ b/vm/src/builtins/str.rs @@ -414,11 +414,11 @@ impl PyStr { } #[inline] - pub fn as_wtf8(&self) -> &Wtf8 { + pub const fn as_wtf8(&self) -> &Wtf8 { self.data.as_wtf8() } - pub fn as_bytes(&self) -> &[u8] { + pub const fn as_bytes(&self) -> &[u8] { self.data.as_wtf8().as_bytes() } @@ -456,7 +456,7 @@ impl PyStr { .unwrap_or_else(|| self.as_wtf8().to_string_lossy()) } - pub fn kind(&self) -> StrKind { + pub const fn kind(&self) -> StrKind { self.data.kind() } @@ -465,7 +465,7 @@ impl PyStr { self.data.as_str_kind() } - pub fn is_utf8(&self) -> bool { + pub const fn is_utf8(&self) -> bool { self.kind().is_utf8() } @@ -601,7 +601,7 @@ impl PyStr { #[pymethod(name = "isascii")] #[inline(always)] - pub fn is_ascii(&self) -> bool { + pub const fn is_ascii(&self) -> bool { matches!(self.kind(), StrKind::Ascii) } diff --git a/vm/src/builtins/traceback.rs b/vm/src/builtins/traceback.rs index b0b9555e6e1..91add179175 100644 --- a/vm/src/builtins/traceback.rs +++ b/vm/src/builtins/traceback.rs @@ -27,7 +27,7 @@ impl PyPayload for PyTraceback { #[pyclass] impl PyTraceback { - pub fn new(next: Option>, frame: FrameRef, lasti: u32, lineno: LineNumber) -> Self { + pub const fn new(next: Option>, frame: FrameRef, lasti: u32, lineno: LineNumber) -> Self { PyTraceback { next: PyMutex::new(next), frame, @@ -42,12 +42,12 @@ impl PyTraceback { } #[pygetset] - fn tb_lasti(&self) -> u32 { + const fn tb_lasti(&self) -> u32 { self.lasti } #[pygetset] - fn tb_lineno(&self) -> usize { + const fn tb_lineno(&self) -> usize { self.lineno.get() } diff --git a/vm/src/builtins/type.rs b/vm/src/builtins/type.rs index 558653366e3..39b64892d0f 100644 --- a/vm/src/builtins/type.rs +++ b/vm/src/builtins/type.rs @@ -73,7 +73,7 @@ unsafe impl Sync for PointerSlot {} unsafe impl Send for PointerSlot {} impl PointerSlot { - pub unsafe fn borrow_static(&self) -> &'static T { + pub const unsafe fn borrow_static(&self) -> &'static T { unsafe { self.0.as_ref() } } } @@ -621,12 +621,12 @@ impl PyType { } #[pygetset] - fn __flags__(&self) -> u64 { + const fn __flags__(&self) -> u64 { self.slots.flags.bits() } #[pygetset] - fn __basicsize__(&self) -> usize { + const fn __basicsize__(&self) -> usize { self.slots.basicsize } diff --git a/vm/src/builtins/union.rs b/vm/src/builtins/union.rs index b5a604ec2a8..c7abd634ef5 100644 --- a/vm/src/builtins/union.rs +++ b/vm/src/builtins/union.rs @@ -42,7 +42,7 @@ impl PyUnion { /// Direct access to args field, matching CPython's _Py_union_args #[inline] - pub fn args(&self) -> &PyTupleRef { + pub const fn args(&self) -> &PyTupleRef { &self.args } diff --git a/vm/src/codecs.rs b/vm/src/codecs.rs index 0f55c438d62..ab7df098e90 100644 --- a/vm/src/codecs.rs +++ b/vm/src/codecs.rs @@ -52,7 +52,7 @@ impl PyCodec { self.0 } #[inline] - pub fn as_tuple(&self) -> &PyTupleRef { + pub const fn as_tuple(&self) -> &PyTupleRef { &self.0 } diff --git a/vm/src/function/protocol.rs b/vm/src/function/protocol.rs index 0f146fed95f..d50e3bb6d61 100644 --- a/vm/src/function/protocol.rs +++ b/vm/src/function/protocol.rs @@ -130,7 +130,7 @@ pub struct ArgMapping { impl ArgMapping { #[inline] - pub fn with_methods(obj: PyObjectRef, methods: &'static PyMappingMethods) -> Self { + pub const fn with_methods(obj: PyObjectRef, methods: &'static PyMappingMethods) -> Self { Self { obj, methods } } diff --git a/vm/src/intern.rs b/vm/src/intern.rs index 08e41bb5b50..680a9d2b222 100644 --- a/vm/src/intern.rs +++ b/vm/src/intern.rs @@ -118,7 +118,7 @@ impl CachedPyStrRef { /// # Safety /// the given cache must be alive while returned reference is alive #[inline] - unsafe fn as_interned_str(&self) -> &'static PyStrInterned { + const unsafe fn as_interned_str(&self) -> &'static PyStrInterned { unsafe { std::mem::transmute_copy(self) } } @@ -142,7 +142,7 @@ impl PyInterned { } #[inline] - fn as_ptr(&self) -> *const Py { + const fn as_ptr(&self) -> *const Py { self as *const _ as *const _ } diff --git a/vm/src/object/core.rs b/vm/src/object/core.rs index 253d8fda635..99b78bd903e 100644 --- a/vm/src/object/core.rs +++ b/vm/src/object/core.rs @@ -421,7 +421,7 @@ impl From for InstanceDict { impl InstanceDict { #[inline] - pub fn new(d: PyDictRef) -> Self { + pub const fn new(d: PyDictRef) -> Self { Self { d: PyRwLock::new(d), } @@ -512,7 +512,7 @@ impl ToOwned for PyObject { impl PyObjectRef { #[inline(always)] - pub fn into_raw(self) -> NonNull { + pub const fn into_raw(self) -> NonNull { let ptr = self.ptr; std::mem::forget(self); ptr @@ -524,7 +524,7 @@ impl PyObjectRef { /// dropped more than once due to mishandling the reference count by calling this function /// too many times. #[inline(always)] - pub unsafe fn from_raw(ptr: NonNull) -> Self { + pub const unsafe fn from_raw(ptr: NonNull) -> Self { Self { ptr } } @@ -663,7 +663,7 @@ impl PyObject { /// # Safety /// The actual payload type must be T. #[inline(always)] - pub unsafe fn payload_unchecked(&self) -> &T { + pub const unsafe fn payload_unchecked(&self) -> &T { // we cast to a PyInner first because we don't know T's exact offset because of // varying alignment, but once we get a PyInner the compiler can get it for us let inner = unsafe { &*(&self.0 as *const PyInner as *const PyInner) }; @@ -1026,7 +1026,7 @@ impl Clone for PyRef { impl PyRef { #[inline(always)] - pub(crate) unsafe fn from_raw(raw: *const Py) -> Self { + pub(crate) const unsafe fn from_raw(raw: *const Py) -> Self { Self { ptr: unsafe { NonNull::new_unchecked(raw as *mut _) }, } @@ -1050,7 +1050,7 @@ impl PyRef { } } - pub fn leak(pyref: Self) -> &'static Py { + pub const fn leak(pyref: Self) -> &'static Py { let ptr = pyref.ptr; std::mem::forget(pyref); unsafe { ptr.as_ref() } diff --git a/vm/src/object/ext.rs b/vm/src/object/ext.rs index 41443aa56ff..9712426ff90 100644 --- a/vm/src/object/ext.rs +++ b/vm/src/object/ext.rs @@ -66,7 +66,7 @@ impl PyExact { /// # Safety /// Given reference must be exact type of payload T #[inline(always)] - pub unsafe fn ref_unchecked(r: &Py) -> &Self { + pub const unsafe fn ref_unchecked(r: &Py) -> &Self { unsafe { &*(r as *const _ as *const Self) } } } @@ -141,7 +141,7 @@ pub struct PyRefExact { impl PyRefExact { /// # Safety /// obj must have exact type for the payload - pub unsafe fn new_unchecked(obj: PyRef) -> Self { + pub const unsafe fn new_unchecked(obj: PyRef) -> Self { Self { inner: obj } } diff --git a/vm/src/protocol/iter.rs b/vm/src/protocol/iter.rs index d05bd26a8a3..f5fe6a40eee 100644 --- a/vm/src/protocol/iter.rs +++ b/vm/src/protocol/iter.rs @@ -33,7 +33,7 @@ impl PyIter where O: Borrow, { - pub fn new(obj: O) -> Self { + pub const fn new(obj: O) -> Self { Self(obj) } pub fn next(&self, vm: &VirtualMachine) -> PyResult { diff --git a/vm/src/protocol/sequence.rs b/vm/src/protocol/sequence.rs index fbd8d634092..567c45f36ff 100644 --- a/vm/src/protocol/sequence.rs +++ b/vm/src/protocol/sequence.rs @@ -76,7 +76,7 @@ unsafe impl Traverse for PySequence<'_> { impl<'a> PySequence<'a> { #[inline] - pub fn with_methods(obj: &'a PyObject, methods: &'static PySequenceMethods) -> Self { + pub const fn with_methods(obj: &'a PyObject, methods: &'static PySequenceMethods) -> Self { Self { obj, methods } } diff --git a/vm/src/readline.rs b/vm/src/readline.rs index d37bbb74582..8a90a7ae40e 100644 --- a/vm/src/readline.rs +++ b/vm/src/readline.rs @@ -28,7 +28,7 @@ mod basic_readline { } impl Readline { - pub fn new(helper: H) -> Self { + pub const fn new(helper: H) -> Self { Self { helper } } diff --git a/vm/src/sliceable.rs b/vm/src/sliceable.rs index 13035fadc22..ebe16405c98 100644 --- a/vm/src/sliceable.rs +++ b/vm/src/sliceable.rs @@ -415,7 +415,7 @@ impl SaturatedSliceIter { Self::from_adjust_indices(range, step, len) } - pub fn from_adjust_indices(range: Range, step: isize, len: usize) -> Self { + pub const fn from_adjust_indices(range: Range, step: isize, len: usize) -> Self { let index = if step.is_negative() { range.end as isize - 1 } else { @@ -424,7 +424,7 @@ impl SaturatedSliceIter { Self { index, step, len } } - pub fn positive_order(mut self) -> Self { + pub const fn positive_order(mut self) -> Self { if self.step.is_negative() { self.index += self.step * self.len.saturating_sub(1) as isize; self.step = self.step.saturating_abs() diff --git a/vm/src/stdlib/ast.rs b/vm/src/stdlib/ast.rs index e815bc41596..f6679f18976 100644 --- a/vm/src/stdlib/ast.rs +++ b/vm/src/stdlib/ast.rs @@ -90,7 +90,7 @@ pub struct PySourceLocation { } impl PySourceLocation { - fn to_source_location(&self) -> SourceLocation { + const fn to_source_location(&self) -> SourceLocation { SourceLocation { row: self.row.get_one_indexed(), column: self.column.get_one_indexed(), @@ -103,7 +103,7 @@ impl PySourceLocation { struct Row(OneIndexed); impl Row { - fn get(self) -> usize { + const fn get(self) -> usize { self.0.get() } @@ -117,11 +117,11 @@ impl Row { struct Column(TextSize); impl Column { - fn get(self) -> usize { + const fn get(self) -> usize { self.0.to_usize() } - fn get_one_indexed(self) -> OneIndexed { + const fn get_one_indexed(self) -> OneIndexed { OneIndexed::from_zero_indexed(self.get()) } } diff --git a/vm/src/stdlib/collections.rs b/vm/src/stdlib/collections.rs index f24d3fb4e32..5f572b20cbc 100644 --- a/vm/src/stdlib/collections.rs +++ b/vm/src/stdlib/collections.rs @@ -273,7 +273,7 @@ mod _collections { } #[pygetset] - fn maxlen(&self) -> Option { + const fn maxlen(&self) -> Option { self.maxlen } diff --git a/vm/src/stdlib/imp.rs b/vm/src/stdlib/imp.rs index 378a1003641..596847776ff 100644 --- a/vm/src/stdlib/imp.rs +++ b/vm/src/stdlib/imp.rs @@ -35,11 +35,11 @@ mod lock { mod lock { use crate::vm::VirtualMachine; #[pyfunction] - pub(super) fn acquire_lock(_vm: &VirtualMachine) {} + pub(super) const fn acquire_lock(_vm: &VirtualMachine) {} #[pyfunction] - pub(super) fn release_lock(_vm: &VirtualMachine) {} + pub(super) const fn release_lock(_vm: &VirtualMachine) {} #[pyfunction] - pub(super) fn lock_held(_vm: &VirtualMachine) -> bool { + pub(super) const fn lock_held(_vm: &VirtualMachine) -> bool { false } } @@ -95,7 +95,7 @@ mod _imp { } #[pyfunction] - fn extension_suffixes() -> PyResult> { + const fn extension_suffixes() -> PyResult> { Ok(Vec::new()) } diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index bdce5ddcfc9..8efa317255a 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -289,7 +289,7 @@ mod _io { Some(b) } - fn tell(&self) -> u64 { + const fn tell(&self) -> u64 { self.cursor.position() } @@ -783,27 +783,27 @@ mod _io { } #[inline] - fn writable(&self) -> bool { + const fn writable(&self) -> bool { self.flags.contains(BufferedFlags::WRITABLE) } #[inline] - fn readable(&self) -> bool { + const fn readable(&self) -> bool { self.flags.contains(BufferedFlags::READABLE) } #[inline] - fn valid_read(&self) -> bool { + const fn valid_read(&self) -> bool { self.readable() && self.read_end != -1 } #[inline] - fn valid_write(&self) -> bool { + const fn valid_write(&self) -> bool { self.writable() && self.write_end != -1 } #[inline] - fn raw_offset(&self) -> Offset { + const fn raw_offset(&self) -> Offset { if (self.valid_read() || self.valid_write()) && self.raw_pos >= 0 { self.raw_pos - self.pos } else { @@ -812,7 +812,7 @@ mod _io { } #[inline] - fn readahead(&self) -> Offset { + const fn readahead(&self) -> Offset { if self.valid_read() { self.read_end - self.pos } else { @@ -820,11 +820,11 @@ mod _io { } } - fn reset_read(&mut self) { + const fn reset_read(&mut self) { self.read_end = -1; } - fn reset_write(&mut self) { + const fn reset_write(&mut self) { self.write_pos = 0; self.write_end = -1; } @@ -1278,7 +1278,7 @@ mod _io { } } - fn adjust_position(&mut self, new_pos: Offset) { + const fn adjust_position(&mut self, new_pos: Offset) { self.pos = new_pos; if self.valid_read() && self.read_end < self.pos { self.read_end = self.pos @@ -2096,7 +2096,7 @@ mod _io { // TODO: implement legit fast-paths for other encodings type EncodeFunc = fn(PyStrRef) -> PendingWrite; - fn textio_encode_utf8(s: PyStrRef) -> PendingWrite { + const fn textio_encode_utf8(s: PyStrRef) -> PendingWrite { PendingWrite::Utf8(s) } @@ -2264,7 +2264,7 @@ mod _io { } } - fn set_num_to_skip(&mut self, num: Utf8size) { + const fn set_num_to_skip(&mut self, num: Utf8size) { self.bytes_to_skip = num.bytes as i32; self.chars_to_skip = num.chars as i32; } diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index 0349307b279..6a257e415c5 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -85,7 +85,7 @@ impl DirFd<1> { } #[inline(always)] - pub(crate) fn fd(&self) -> Fd { + pub(crate) const fn fd(&self) -> Fd { self.0[0] } } @@ -571,7 +571,7 @@ pub(super) mod _os { #[cfg(not(windows))] #[pymethod] - fn is_junction(&self, _vm: &VirtualMachine) -> PyResult { + const fn is_junction(&self, _vm: &VirtualMachine) -> PyResult { Ok(false) } @@ -642,7 +642,7 @@ pub(super) mod _os { } #[pymethod] - fn __enter__(zelf: PyRef) -> PyRef { + const fn __enter__(zelf: PyRef) -> PyRef { zelf } @@ -1495,7 +1495,7 @@ pub(crate) struct SupportFunc { } impl SupportFunc { - pub(crate) fn new( + pub(crate) const fn new( name: &'static str, fd: Option, dir_fd: Option, diff --git a/vm/src/stdlib/posix.rs b/vm/src/stdlib/posix.rs index e7e6782b123..86b6284fe10 100644 --- a/vm/src/stdlib/posix.rs +++ b/vm/src/stdlib/posix.rs @@ -211,7 +211,7 @@ pub mod module { is_executable: bool, } - fn get_permissions(mode: u32) -> Permissions { + const fn get_permissions(mode: u32) -> Permissions { Permissions { is_readable: mode & 4 != 0, is_writable: mode & 2 != 0, @@ -1228,7 +1228,7 @@ pub mod module { } #[pyfunction] - fn sync() { + const fn sync() { #[cfg(not(any(target_os = "redox", target_os = "android")))] unsafe { libc::sync(); @@ -1603,32 +1603,32 @@ pub mod module { } #[pyfunction(name = "WIFSIGNALED")] - fn wifsignaled(status: i32) -> bool { + const fn wifsignaled(status: i32) -> bool { libc::WIFSIGNALED(status) } #[pyfunction(name = "WIFSTOPPED")] - fn wifstopped(status: i32) -> bool { + const fn wifstopped(status: i32) -> bool { libc::WIFSTOPPED(status) } #[pyfunction(name = "WIFEXITED")] - fn wifexited(status: i32) -> bool { + const fn wifexited(status: i32) -> bool { libc::WIFEXITED(status) } #[pyfunction(name = "WTERMSIG")] - fn wtermsig(status: i32) -> i32 { + const fn wtermsig(status: i32) -> i32 { libc::WTERMSIG(status) } #[pyfunction(name = "WSTOPSIG")] - fn wstopsig(status: i32) -> i32 { + const fn wstopsig(status: i32) -> i32 { libc::WSTOPSIG(status) } #[pyfunction(name = "WEXITSTATUS")] - fn wexitstatus(status: i32) -> i32 { + const fn wexitstatus(status: i32) -> i32 { libc::WEXITSTATUS(status) } diff --git a/vm/src/stdlib/sre.rs b/vm/src/stdlib/sre.rs index da72363e3a3..7ac4953ab89 100644 --- a/vm/src/stdlib/sre.rs +++ b/vm/src/stdlib/sre.rs @@ -396,7 +396,7 @@ mod _sre { } #[pygetset] - fn flags(&self) -> u16 { + const fn flags(&self) -> u16 { self.flags.bits() } diff --git a/vm/src/stdlib/stat.rs b/vm/src/stdlib/stat.rs index 7cfacf965c5..fdb88b37f08 100644 --- a/vm/src/stdlib/stat.rs +++ b/vm/src/stdlib/stat.rs @@ -246,82 +246,82 @@ mod stat { #[pyfunction] #[allow(non_snake_case)] - fn S_ISDIR(mode: Mode) -> bool { + const fn S_ISDIR(mode: Mode) -> bool { (mode & S_IFMT) == S_IFDIR } #[pyfunction] #[allow(non_snake_case)] - fn S_ISCHR(mode: Mode) -> bool { + const fn S_ISCHR(mode: Mode) -> bool { (mode & S_IFMT) == S_IFCHR } #[pyfunction] #[allow(non_snake_case)] - fn S_ISREG(mode: Mode) -> bool { + const fn S_ISREG(mode: Mode) -> bool { (mode & S_IFMT) == S_IFREG } #[pyfunction] #[allow(non_snake_case)] - fn S_ISBLK(mode: Mode) -> bool { + const fn S_ISBLK(mode: Mode) -> bool { (mode & S_IFMT) == S_IFBLK } #[pyfunction] #[allow(non_snake_case)] - fn S_ISFIFO(mode: Mode) -> bool { + const fn S_ISFIFO(mode: Mode) -> bool { (mode & S_IFMT) == S_IFIFO } #[pyfunction] #[allow(non_snake_case)] - fn S_ISLNK(mode: Mode) -> bool { + const fn S_ISLNK(mode: Mode) -> bool { (mode & S_IFMT) == S_IFLNK } #[pyfunction] #[allow(non_snake_case)] - fn S_ISSOCK(mode: Mode) -> bool { + const fn S_ISSOCK(mode: Mode) -> bool { (mode & S_IFMT) == S_IFSOCK } // TODO: RUSTPYTHON Support Solaris #[pyfunction] #[allow(non_snake_case)] - fn S_ISDOOR(_mode: Mode) -> bool { + const fn S_ISDOOR(_mode: Mode) -> bool { false } // TODO: RUSTPYTHON Support Solaris #[pyfunction] #[allow(non_snake_case)] - fn S_ISPORT(_mode: Mode) -> bool { + const fn S_ISPORT(_mode: Mode) -> bool { false } // TODO: RUSTPYTHON Support BSD #[pyfunction] #[allow(non_snake_case)] - fn S_ISWHT(_mode: Mode) -> bool { + const fn S_ISWHT(_mode: Mode) -> bool { false } #[pyfunction(name = "S_IMODE")] #[allow(non_snake_case)] - fn S_IMODE_method(mode: Mode) -> Mode { + const fn S_IMODE_method(mode: Mode) -> Mode { mode & S_IMODE } #[pyfunction(name = "S_IFMT")] #[allow(non_snake_case)] - fn S_IFMT_method(mode: Mode) -> Mode { + const fn S_IFMT_method(mode: Mode) -> Mode { // 0o170000 is from the S_IFMT definition in CPython include/fileutils.h mode & S_IFMT } #[pyfunction] - fn filetype(mode: Mode) -> char { + const fn filetype(mode: Mode) -> char { if S_ISREG(mode) { '-' } else if S_ISDIR(mode) { diff --git a/vm/src/stdlib/symtable.rs b/vm/src/stdlib/symtable.rs index a848de5dc47..6f6b02c0e08 100644 --- a/vm/src/stdlib/symtable.rs +++ b/vm/src/stdlib/symtable.rs @@ -29,7 +29,7 @@ mod symtable { Ok(py_symbol_table.into_ref(&vm.ctx)) } - fn to_py_symbol_table(symtable: SymbolTable) -> PySymbolTable { + const fn to_py_symbol_table(symtable: SymbolTable) -> PySymbolTable { PySymbolTable { symtable } } @@ -190,7 +190,7 @@ mod symtable { } #[pymethod] - fn is_nested(&self) -> bool { + const fn is_nested(&self) -> bool { // TODO false } diff --git a/vm/src/stdlib/sys.rs b/vm/src/stdlib/sys.rs index 3011c3b6c09..6c37a920ec7 100644 --- a/vm/src/stdlib/sys.rs +++ b/vm/src/stdlib/sys.rs @@ -95,7 +95,7 @@ mod sys { const DLLHANDLE: usize = 0; #[pyattr] - fn default_prefix(_vm: &VirtualMachine) -> &'static str { + const fn default_prefix(_vm: &VirtualMachine) -> &'static str { // TODO: the windows one doesn't really make sense if cfg!(windows) { "C:" } else { "/usr/local" } } @@ -238,7 +238,7 @@ mod sys { } #[pyattr] - fn meta_path(_vm: &VirtualMachine) -> Vec { + const fn meta_path(_vm: &VirtualMachine) -> Vec { Vec::new() } @@ -258,7 +258,7 @@ mod sys { } #[pyattr] - fn path_hooks(_vm: &VirtualMachine) -> Vec { + const fn path_hooks(_vm: &VirtualMachine) -> Vec { Vec::new() } @@ -454,7 +454,7 @@ mod sys { } #[pyfunction] - fn getdefaultencoding() -> &'static str { + const fn getdefaultencoding() -> &'static str { crate::codecs::DEFAULT_ENCODING } @@ -964,7 +964,7 @@ mod sys { #[pyclass(with(PyStructSequence))] impl Flags { - fn from_settings(settings: &Settings) -> Self { + const fn from_settings(settings: &Settings) -> Self { Self { debug: settings.debug, inspect: settings.inspect as u8, diff --git a/vm/src/stdlib/typevar.rs b/vm/src/stdlib/typevar.rs index 9617439a0ee..9f3f8739a93 100644 --- a/vm/src/stdlib/typevar.rs +++ b/vm/src/stdlib/typevar.rs @@ -124,17 +124,17 @@ impl TypeVar { } #[pygetset] - fn __covariant__(&self) -> bool { + const fn __covariant__(&self) -> bool { self.covariant } #[pygetset] - fn __contravariant__(&self) -> bool { + const fn __contravariant__(&self) -> bool { self.contravariant } #[pygetset] - fn __infer_variance__(&self) -> bool { + const fn __infer_variance__(&self) -> bool { self.infer_variance } @@ -445,17 +445,17 @@ impl ParamSpec { } #[pygetset] - fn __covariant__(&self) -> bool { + const fn __covariant__(&self) -> bool { self.covariant } #[pygetset] - fn __contravariant__(&self) -> bool { + const fn __contravariant__(&self) -> bool { self.contravariant } #[pygetset] - fn __infer_variance__(&self) -> bool { + const fn __infer_variance__(&self) -> bool { self.infer_variance } @@ -627,7 +627,7 @@ impl Representable for ParamSpec { } impl ParamSpec { - pub fn new(name: PyObjectRef) -> Self { + pub const fn new(name: PyObjectRef) -> Self { Self { name, bound: None, diff --git a/vm/src/stdlib/typing.rs b/vm/src/stdlib/typing.rs index adf261cc651..5ba8ff695f5 100644 --- a/vm/src/stdlib/typing.rs +++ b/vm/src/stdlib/typing.rs @@ -105,7 +105,7 @@ pub(crate) mod decl { } #[pyclass(flags(BASETYPE))] impl TypeAliasType { - pub fn new( + pub const fn new( name: PyObjectRef, type_params: PyTupleRef, value: PyObjectRef, diff --git a/vm/src/types/slot.rs b/vm/src/types/slot.rs index 7f36a8baf07..704ec3edf0f 100644 --- a/vm/src/types/slot.rs +++ b/vm/src/types/slot.rs @@ -149,12 +149,12 @@ impl PyTypeFlags { } } - pub fn has_feature(self, flag: Self) -> bool { + pub const fn has_feature(self, flag: Self) -> bool { self.contains(flag) } #[cfg(debug_assertions)] - pub fn is_created_with_flags(self) -> bool { + pub const fn is_created_with_flags(self) -> bool { self.contains(Self::_CREATED_WITH_FLAGS) } } @@ -325,7 +325,7 @@ fn iter_wrapper(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { } // PyObject_SelfIter in CPython -fn self_iter(zelf: PyObjectRef, _vm: &VirtualMachine) -> PyResult { +const fn self_iter(zelf: PyObjectRef, _vm: &VirtualMachine) -> PyResult { Ok(zelf) } @@ -1109,7 +1109,7 @@ impl PyComparisonOp { } } - pub fn eval_ord(self, ord: Ordering) -> bool { + pub const fn eval_ord(self, ord: Ordering) -> bool { let bit = match ord { Ordering::Less => Self::Lt, Ordering::Equal => Self::Eq, @@ -1118,7 +1118,7 @@ impl PyComparisonOp { self.0 as u8 & bit.0 as u8 != 0 } - pub fn swapped(self) -> Self { + pub const fn swapped(self) -> Self { match self { Self::Lt => Self::Gt, Self::Le => Self::Ge, From a18f0c2a412ab2b67d341b90107559df4a141a8c Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 00:59:10 +0300 Subject: [PATCH 02/16] compiler --- compiler/core/src/bytecode.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/compiler/core/src/bytecode.rs b/compiler/core/src/bytecode.rs index 8100146cc35..84a89dfcff5 100644 --- a/compiler/core/src/bytecode.rs +++ b/compiler/core/src/bytecode.rs @@ -174,7 +174,7 @@ impl OpArg { /// Returns how many CodeUnits a instruction with this op_arg will be encoded as #[inline] - pub fn instr_size(self) -> usize { + pub const fn instr_size(self) -> usize { (self.0 > 0xff) as usize + (self.0 > 0xff_ff) as usize + (self.0 > 0xff_ff_ff) as usize + 1 } @@ -214,7 +214,7 @@ impl OpArgState { OpArg(self.state) } #[inline(always)] - pub fn reset(&mut self) { + pub const fn reset(&mut self) { self.state = 0 } } @@ -280,7 +280,7 @@ pub struct Arg(PhantomData); impl Arg { #[inline] - pub fn marker() -> Self { + pub const fn marker() -> Self { Arg(PhantomData) } #[inline] @@ -660,7 +660,7 @@ pub struct CodeUnit { const _: () = assert!(mem::size_of::() == 2); impl CodeUnit { - pub fn new(op: Instruction, arg: OpArgByte) -> Self { + pub const fn new(op: Instruction, arg: OpArgByte) -> Self { Self { op, arg } } } @@ -1150,7 +1150,7 @@ impl fmt::Display for CodeObject { impl Instruction { /// Gets the label stored inside this instruction, if it exists #[inline] - pub fn label_arg(&self) -> Option> { + pub const fn label_arg(&self) -> Option> { match self { Jump { target: l } | JumpIfTrue { target: l } @@ -1177,7 +1177,7 @@ impl Instruction { /// let jump_inst = Instruction::Jump { target: Arg::marker() }; /// assert!(jump_inst.unconditional_branch()) /// ``` - pub fn unconditional_branch(&self) -> bool { + pub const fn unconditional_branch(&self) -> bool { matches!( self, Jump { .. } From fde322c3738917645c5c1ef4f4cdc1593539ef85 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 01:01:34 +0300 Subject: [PATCH 03/16] sre engine --- vm/sre_engine/src/engine.rs | 18 +++++++++--------- vm/sre_engine/src/string.rs | 8 ++++---- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/vm/sre_engine/src/engine.rs b/vm/sre_engine/src/engine.rs index 1e0b15fd010..316560f5a81 100644 --- a/vm/sre_engine/src/engine.rs +++ b/vm/sre_engine/src/engine.rs @@ -68,7 +68,7 @@ impl Marks { } } - pub fn last_index(&self) -> isize { + pub const fn last_index(&self) -> isize { self.last_index } @@ -1054,11 +1054,11 @@ impl MatchContext { &req.pattern_codes[self.code_position..] } - fn remaining_codes(&self, req: &Request<'_, S>) -> usize { + const fn remaining_codes(&self, req: &Request<'_, S>) -> usize { req.pattern_codes.len() - self.code_position } - fn remaining_chars(&self, req: &Request<'_, S>) -> usize { + const fn remaining_chars(&self, req: &Request<'_, S>) -> usize { req.end - self.cursor.position } @@ -1097,7 +1097,7 @@ impl MatchContext { self.peek_code(req, peek).try_into() } - fn skip_code(&mut self, skip: usize) { + const fn skip_code(&mut self, skip: usize) { self.code_position += skip; } @@ -1105,12 +1105,12 @@ impl MatchContext { self.skip_code(self.peek_code(req, peek) as usize + 1); } - fn at_beginning(&self) -> bool { + const fn at_beginning(&self) -> bool { // self.ctx().string_position == self.state().start self.cursor.position == 0 } - fn at_end(&self, req: &Request<'_, S>) -> bool { + const fn at_end(&self, req: &Request<'_, S>) -> bool { self.cursor.position == req.end } @@ -1144,7 +1144,7 @@ impl MatchContext { this == that } - fn can_success(&self, req: &Request<'_, S>) -> bool { + const fn can_success(&self, req: &Request<'_, S>) -> bool { if !self.toplevel { return true; } @@ -1163,12 +1163,12 @@ impl MatchContext { } #[must_use] - fn next_offset(&mut self, offset: usize, jump: Jump) -> Self { + const fn next_offset(&mut self, offset: usize, jump: Jump) -> Self { self.next_at(self.code_position + offset, jump) } #[must_use] - fn next_at(&mut self, code_position: usize, jump: Jump) -> Self { + const fn next_at(&mut self, code_position: usize, jump: Jump) -> Self { self.jump = jump; MatchContext { code_position, diff --git a/vm/sre_engine/src/string.rs b/vm/sre_engine/src/string.rs index 9ca97069f82..0d3325b6a1d 100644 --- a/vm/sre_engine/src/string.rs +++ b/vm/sre_engine/src/string.rs @@ -223,7 +223,7 @@ impl StrDrive for &Wtf8 { /// /// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string #[inline] -unsafe fn next_code_point(ptr: &mut *const u8) -> u32 { +const unsafe fn next_code_point(ptr: &mut *const u8) -> u32 { // Decode UTF-8 let x = unsafe { **ptr }; *ptr = unsafe { ptr.offset(1) }; @@ -271,7 +271,7 @@ unsafe fn next_code_point(ptr: &mut *const u8) -> u32 { /// /// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string #[inline] -unsafe fn next_code_point_reverse(ptr: &mut *const u8) -> u32 { +const unsafe fn next_code_point_reverse(ptr: &mut *const u8) -> u32 { // Decode UTF-8 *ptr = unsafe { ptr.offset(-1) }; let w = match unsafe { **ptr } { @@ -367,7 +367,7 @@ pub(crate) fn is_loc_word(ch: u32) -> bool { ch == '_' as u32 || is_loc_alnum(ch) } #[inline] -pub(crate) fn is_linebreak(ch: u32) -> bool { +pub(crate) const fn is_linebreak(ch: u32) -> bool { ch == '\n' as u32 } #[inline] @@ -433,7 +433,7 @@ pub(crate) fn is_uni_space(ch: u32) -> bool { ) } #[inline] -pub(crate) fn is_uni_linebreak(ch: u32) -> bool { +pub(crate) const fn is_uni_linebreak(ch: u32) -> bool { matches!( ch, 0x000A | 0x000B | 0x000C | 0x000D | 0x001C | 0x001D | 0x001E | 0x0085 | 0x2028 | 0x2029 From 80fba2f7afe13303d7df1c1c6e428b48b1affc05 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 01:04:07 +0300 Subject: [PATCH 04/16] compiler --- compiler/codegen/src/compile.rs | 4 ++-- compiler/codegen/src/string_parser.rs | 2 +- compiler/codegen/src/symboltable.rs | 6 +++--- compiler/codegen/src/unparse.rs | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/compiler/codegen/src/compile.rs b/compiler/codegen/src/compile.rs index 2bdc5de393d..edbc34c3132 100644 --- a/compiler/codegen/src/compile.rs +++ b/compiler/codegen/src/compile.rs @@ -282,7 +282,7 @@ impl Default for PatternContext { } impl PatternContext { - pub fn new() -> Self { + pub const fn new() -> Self { PatternContext { stores: Vec::new(), allow_irrefutable: false, @@ -4118,7 +4118,7 @@ impl Compiler<'_> { code.current_block = block; } - fn set_source_range(&mut self, range: TextRange) { + const fn set_source_range(&mut self, range: TextRange) { self.current_source_range = range; } diff --git a/compiler/codegen/src/string_parser.rs b/compiler/codegen/src/string_parser.rs index 74f8e300120..ede2f118c37 100644 --- a/compiler/codegen/src/string_parser.rs +++ b/compiler/codegen/src/string_parser.rs @@ -28,7 +28,7 @@ struct StringParser { } impl StringParser { - fn new(source: Box, flags: AnyStringFlags) -> Self { + const fn new(source: Box, flags: AnyStringFlags) -> Self { Self { source, cursor: 0, diff --git a/compiler/codegen/src/symboltable.rs b/compiler/codegen/src/symboltable.rs index 385abfd72f2..dbf39a725c7 100644 --- a/compiler/codegen/src/symboltable.rs +++ b/compiler/codegen/src/symboltable.rs @@ -162,18 +162,18 @@ impl Symbol { } } - pub fn is_global(&self) -> bool { + pub const fn is_global(&self) -> bool { matches!( self.scope, SymbolScope::GlobalExplicit | SymbolScope::GlobalImplicit ) } - pub fn is_local(&self) -> bool { + pub const fn is_local(&self) -> bool { matches!(self.scope, SymbolScope::Local | SymbolScope::Cell) } - pub fn is_bound(&self) -> bool { + pub const fn is_bound(&self) -> bool { self.flags.intersects(SymbolFlags::BOUND) } } diff --git a/compiler/codegen/src/unparse.rs b/compiler/codegen/src/unparse.rs index 1ecf1f9334c..47e883da3af 100644 --- a/compiler/codegen/src/unparse.rs +++ b/compiler/codegen/src/unparse.rs @@ -32,7 +32,7 @@ struct Unparser<'a, 'b, 'c> { source: &'c SourceCode<'c>, } impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { - fn new(f: &'b mut fmt::Formatter<'a>, source: &'c SourceCode<'c>) -> Self { + const fn new(f: &'b mut fmt::Formatter<'a>, source: &'c SourceCode<'c>) -> Self { Unparser { f, source } } @@ -602,7 +602,7 @@ pub struct UnparseExpr<'a> { source: &'a SourceCode<'a>, } -pub fn unparse_expr<'a>(expr: &'a Expr, source: &'a SourceCode<'a>) -> UnparseExpr<'a> { +pub const fn unparse_expr<'a>(expr: &'a Expr, source: &'a SourceCode<'a>) -> UnparseExpr<'a> { UnparseExpr { expr, source } } From 5f790b8a5313843b7839ebd5d514af92daa50a41 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 01:05:19 +0300 Subject: [PATCH 05/16] common --- common/src/cformat.rs | 2 +- common/src/encodings.rs | 2 +- common/src/hash.rs | 4 ++-- common/src/linked_list.rs | 14 +++++++------- common/src/lock/thread_mutex.rs | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/common/src/cformat.rs b/common/src/cformat.rs index 25d9aaca667..9dbc39e742b 100644 --- a/common/src/cformat.rs +++ b/common/src/cformat.rs @@ -136,7 +136,7 @@ bitflags! { impl CConversionFlags { #[inline] - pub fn sign_string(&self) -> &'static str { + pub const fn sign_string(&self) -> &'static str { if self.contains(Self::SIGN_CHAR) { "+" } else if self.contains(Self::BLANK_SIGN) { diff --git a/common/src/encodings.rs b/common/src/encodings.rs index 9e89f9cdec4..6de5e016cb2 100644 --- a/common/src/encodings.rs +++ b/common/src/encodings.rs @@ -137,7 +137,7 @@ struct DecodeError<'a> { /// # Safety /// `v[..valid_up_to]` must be valid utf8 -unsafe fn make_decode_err(v: &[u8], valid_up_to: usize, err_len: Option) -> DecodeError<'_> { +const unsafe fn make_decode_err(v: &[u8], valid_up_to: usize, err_len: Option) -> DecodeError<'_> { let (valid_prefix, rest) = unsafe { v.split_at_unchecked(valid_up_to) }; let valid_prefix = unsafe { core::str::from_utf8_unchecked(valid_prefix) }; DecodeError { diff --git a/common/src/hash.rs b/common/src/hash.rs index a01629efa22..dcf424f7ba9 100644 --- a/common/src/hash.rs +++ b/common/src/hash.rs @@ -164,7 +164,7 @@ pub fn lcg_urandom(mut x: u32, buf: &mut [u8]) { } #[inline] -pub fn hash_object_id_raw(p: usize) -> PyHash { +pub const fn hash_object_id_raw(p: usize) -> PyHash { // TODO: Use commented logic when below issue resolved. // Ref: https://github.com/RustPython/RustPython/pull/3951#issuecomment-1193108966 @@ -175,7 +175,7 @@ pub fn hash_object_id_raw(p: usize) -> PyHash { } #[inline] -pub fn hash_object_id(p: usize) -> PyHash { +pub const fn hash_object_id(p: usize) -> PyHash { fix_sentinel(hash_object_id_raw(p)) } diff --git a/common/src/linked_list.rs b/common/src/linked_list.rs index d3f2ccaff5f..ee905a759f6 100644 --- a/common/src/linked_list.rs +++ b/common/src/linked_list.rs @@ -193,7 +193,7 @@ impl LinkedList { // } /// Returns whether the linked list does not contain any node - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.head.is_none() // if self.head.is_some() { // return false; @@ -284,7 +284,7 @@ pub struct DrainFilter<'a, T: Link, F> { } impl LinkedList { - pub fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F> + pub const fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F> where F: FnMut(&mut T::Target) -> bool, { @@ -323,7 +323,7 @@ where impl Pointers { /// Create a new set of empty pointers - pub fn new() -> Pointers { + pub const fn new() -> Pointers { Pointers { inner: UnsafeCell::new(PointersInner { prev: None, @@ -333,7 +333,7 @@ impl Pointers { } } - fn get_prev(&self) -> Option> { + const fn get_prev(&self) -> Option> { // SAFETY: prev is the first field in PointersInner, which is #[repr(C)]. unsafe { let inner = self.inner.get(); @@ -341,7 +341,7 @@ impl Pointers { ptr::read(prev) } } - fn get_next(&self) -> Option> { + const fn get_next(&self) -> Option> { // SAFETY: next is the second field in PointersInner, which is #[repr(C)]. unsafe { let inner = self.inner.get(); @@ -351,7 +351,7 @@ impl Pointers { } } - fn set_prev(&mut self, value: Option>) { + const fn set_prev(&mut self, value: Option>) { // SAFETY: prev is the first field in PointersInner, which is #[repr(C)]. unsafe { let inner = self.inner.get(); @@ -359,7 +359,7 @@ impl Pointers { ptr::write(prev, value); } } - fn set_next(&mut self, value: Option>) { + const fn set_next(&mut self, value: Option>) { // SAFETY: next is the second field in PointersInner, which is #[repr(C)]. unsafe { let inner = self.inner.get(); diff --git a/common/src/lock/thread_mutex.rs b/common/src/lock/thread_mutex.rs index d730818d8f5..c354e8eed1e 100644 --- a/common/src/lock/thread_mutex.rs +++ b/common/src/lock/thread_mutex.rs @@ -78,7 +78,7 @@ pub struct ThreadMutex { } impl ThreadMutex { - pub fn new(val: T) -> Self { + pub const fn new(val: T) -> Self { ThreadMutex { raw: RawThreadMutex::INIT, data: UnsafeCell::new(val), From 8aef1a3e38fa6bef8de660c206956d53e71cce29 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 01:07:35 +0300 Subject: [PATCH 06/16] stdlib --- stdlib/src/array.rs | 14 +++++++------- stdlib/src/binascii.rs | 4 ++-- stdlib/src/compression.rs | 16 ++++++++-------- stdlib/src/csv.rs | 12 ++++++------ stdlib/src/faulthandler.rs | 4 ++-- stdlib/src/hashlib.rs | 6 +++--- stdlib/src/json/machinery.rs | 2 +- stdlib/src/posixsubprocess.rs | 4 ++-- stdlib/src/pystruct.rs | 2 +- stdlib/src/select.rs | 2 +- stdlib/src/syslog.rs | 4 ++-- stdlib/src/unicodedata.rs | 2 +- 12 files changed, 36 insertions(+), 36 deletions(-) diff --git a/stdlib/src/array.rs b/stdlib/src/array.rs index b306c52185b..ea5270540b2 100644 --- a/stdlib/src/array.rs +++ b/stdlib/src/array.rs @@ -89,26 +89,26 @@ mod array { } } - fn typecode(&self) -> char { + const fn typecode(&self) -> char { match self { $(ArrayContentType::$n(_) => $c,)* } } - fn typecode_str(&self) -> &'static str { + const fn typecode_str(&self) -> &'static str { match self { $(ArrayContentType::$n(_) => $scode,)* } } - fn itemsize_of_typecode(c: char) -> Option { + const fn itemsize_of_typecode(c: char) -> Option { match c { $($c => Some(std::mem::size_of::<$t>()),)* _ => None, } } - fn itemsize(&self) -> usize { + const fn itemsize(&self) -> usize { match self { $(ArrayContentType::$n(_) => std::mem::size_of::<$t>(),)* } @@ -554,11 +554,11 @@ mod array { (f64, f64_try_into_from_object, f64_swap_bytes, PyFloat::from), ); - fn f32_swap_bytes(x: f32) -> f32 { + const fn f32_swap_bytes(x: f32) -> f32 { f32::from_bits(x.to_bits().swap_bytes()) } - fn f64_swap_bytes(x: f64) -> f64 { + const fn f64_swap_bytes(x: f64) -> f64 { f64::from_bits(x.to_bits().swap_bytes()) } @@ -1557,7 +1557,7 @@ mod array { _ => None, } } - fn item_size(self) -> usize { + const fn item_size(self) -> usize { match self { Self::Int8 { .. } => 1, Self::Int16 { .. } | Self::Utf16 { .. } => 2, diff --git a/stdlib/src/binascii.rs b/stdlib/src/binascii.rs index 76fdd7365a4..a2316d3c204 100644 --- a/stdlib/src/binascii.rs +++ b/stdlib/src/binascii.rs @@ -160,7 +160,7 @@ mod decl { }) } - fn unhex_nibble(c: u8) -> Option { + const fn unhex_nibble(c: u8) -> Option { match c { b'0'..=b'9' => Some(c - b'0'), b'a'..=b'f' => Some(c - b'a' + 10), @@ -810,7 +810,7 @@ mod decl { vm: &VirtualMachine, ) -> PyResult> { #[inline] - fn uu_b2a(num: u8, backtick: bool) -> u8 { + const fn uu_b2a(num: u8, backtick: bool) -> u8 { if backtick && num == 0 { 0x60 } else { diff --git a/stdlib/src/compression.rs b/stdlib/src/compression.rs index 3f15088c5dc..9fa7e3e02d1 100644 --- a/stdlib/src/compression.rs +++ b/stdlib/src/compression.rs @@ -66,7 +66,7 @@ impl DecompressFlushKind for () { const SYNC: Self = (); } -pub fn flush_sync(_final_chunk: bool) -> T { +pub const fn flush_sync(_final_chunk: bool) -> T { T::SYNC } @@ -76,13 +76,13 @@ pub struct Chunker<'a> { data2: &'a [u8], } impl<'a> Chunker<'a> { - pub fn new(data: &'a [u8]) -> Self { + pub const fn new(data: &'a [u8]) -> Self { Self { data1: data, data2: &[], } } - pub fn chain(data1: &'a [u8], data2: &'a [u8]) -> Self { + pub const fn chain(data1: &'a [u8], data2: &'a [u8]) -> Self { if data1.is_empty() { Self { data1: data2, @@ -92,10 +92,10 @@ impl<'a> Chunker<'a> { Self { data1, data2 } } } - pub fn len(&self) -> usize { + pub const fn len(&self) -> usize { self.data1.len() + self.data2.len() } - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.data1.is_empty() } pub fn to_vec(&self) -> Vec { @@ -216,7 +216,7 @@ pub struct CompressState { } impl CompressState { - pub fn new(compressor: C) -> Self { + pub const fn new(compressor: C) -> Self { Self { compressor: Some(compressor), } @@ -293,7 +293,7 @@ impl DecompressState { } } - pub fn eof(&self) -> bool { + pub const fn eof(&self) -> bool { self.eof } @@ -301,7 +301,7 @@ impl DecompressState { self.unused_data.clone() } - pub fn needs_input(&self) -> bool { + pub const fn needs_input(&self) -> bool { self.needs_input } diff --git a/stdlib/src/csv.rs b/stdlib/src/csv.rs index 54d956234b1..2f91a45f0c5 100644 --- a/stdlib/src/csv.rs +++ b/stdlib/src/csv.rs @@ -84,11 +84,11 @@ mod _csv { Some(vm.ctx.new_str(format!("{}", self.quotechar? as char))) } #[pygetset] - fn doublequote(&self) -> bool { + const fn doublequote(&self) -> bool { self.doublequote } #[pygetset] - fn skipinitialspace(&self) -> bool { + const fn skipinitialspace(&self) -> bool { self.skipinitialspace } #[pygetset] @@ -108,7 +108,7 @@ mod _csv { Some(vm.ctx.new_str(format!("{}", self.escapechar? as char))) } #[pygetset(name = "strict")] - fn get_strict(&self) -> bool { + const fn get_strict(&self) -> bool { self.strict } } @@ -659,7 +659,7 @@ mod _csv { } impl FormatOptions { - fn update_py_dialect(&self, mut res: PyDialect) -> PyDialect { + const fn update_py_dialect(&self, mut res: PyDialect) -> PyDialect { macro_rules! check_and_fill { ($res:ident, $e:ident) => {{ if let Some(t) = self.$e { @@ -916,7 +916,7 @@ mod _csv { self.state.lock().line_num } #[pygetset] - fn dialect(&self, _vm: &VirtualMachine) -> PyDialect { + const fn dialect(&self, _vm: &VirtualMachine) -> PyDialect { self.dialect } } @@ -1066,7 +1066,7 @@ mod _csv { #[pyclass] impl Writer { #[pygetset(name = "dialect")] - fn get_dialect(&self, _vm: &VirtualMachine) -> PyDialect { + const fn get_dialect(&self, _vm: &VirtualMachine) -> PyDialect { self.dialect } #[pymethod] diff --git a/stdlib/src/faulthandler.rs b/stdlib/src/faulthandler.rs index fcfe423ef53..f358129c873 100644 --- a/stdlib/src/faulthandler.rs +++ b/stdlib/src/faulthandler.rs @@ -39,7 +39,7 @@ mod decl { } #[pyfunction] - fn enable(_args: EnableArgs) { + const fn enable(_args: EnableArgs) { // TODO } @@ -57,7 +57,7 @@ mod decl { } #[pyfunction] - fn register(_args: RegisterArgs) { + const fn register(_args: RegisterArgs) { // TODO } } diff --git a/stdlib/src/hashlib.rs b/stdlib/src/hashlib.rs index 296342f05b5..8e9c260e835 100644 --- a/stdlib/src/hashlib.rs +++ b/stdlib/src/hashlib.rs @@ -190,7 +190,7 @@ pub mod _hashlib { } #[pygetset] - fn digest_size(&self) -> usize { + const fn digest_size(&self) -> usize { 0 } @@ -317,7 +317,7 @@ pub mod _hashlib { b: ArgStrOrBytesLike, vm: &VirtualMachine, ) -> PyResult { - fn is_str(arg: &ArgStrOrBytesLike) -> bool { + const fn is_str(arg: &ArgStrOrBytesLike) -> bool { matches!(arg, ArgStrOrBytesLike::Str(_)) } @@ -381,7 +381,7 @@ pub mod _hashlib { self.inner.update(data); } - fn block_size(&self) -> usize { + const fn block_size(&self) -> usize { self.block_size } diff --git a/stdlib/src/json/machinery.rs b/stdlib/src/json/machinery.rs index d83386232ed..57b8ae441f7 100644 --- a/stdlib/src/json/machinery.rs +++ b/stdlib/src/json/machinery.rs @@ -119,7 +119,7 @@ enum StrOrChar<'a> { Char(CodePoint), } impl StrOrChar<'_> { - fn len(&self) -> usize { + const fn len(&self) -> usize { match self { StrOrChar::Str(s) => s.len(), StrOrChar::Char(c) => c.len_wtf8(), diff --git a/stdlib/src/posixsubprocess.rs b/stdlib/src/posixsubprocess.rs index bcf2e5ddc15..93f1ce40afa 100644 --- a/stdlib/src/posixsubprocess.rs +++ b/stdlib/src/posixsubprocess.rs @@ -116,7 +116,7 @@ struct CharPtrSlice<'a> { } impl CharPtrSlice<'_> { - fn as_ptr(&self) -> *const *const libc::c_char { + const fn as_ptr(&self) -> *const *const libc::c_char { self.slice.as_ptr() } } @@ -174,7 +174,7 @@ enum ExecErrorContext { } impl ExecErrorContext { - fn as_msg(&self) -> &'static str { + const fn as_msg(&self) -> &'static str { match self { ExecErrorContext::NoExec => "noexec", ExecErrorContext::ChDir => "noexec:chdir", diff --git a/stdlib/src/pystruct.rs b/stdlib/src/pystruct.rs index 0fba16794a5..06954bd4a3a 100644 --- a/stdlib/src/pystruct.rs +++ b/stdlib/src/pystruct.rs @@ -315,7 +315,7 @@ pub(crate) mod _struct { // seems weird that this is part of the "public" API, but whatever // TODO: implement a format code->spec cache like CPython does? #[pyfunction] - fn _clearcache() {} + const fn _clearcache() {} #[pyattr(name = "error")] fn error_type(vm: &VirtualMachine) -> PyTypeRef { diff --git a/stdlib/src/select.rs b/stdlib/src/select.rs index f9c86d7a924..29508f30a16 100644 --- a/stdlib/src/select.rs +++ b/stdlib/src/select.rs @@ -24,7 +24,7 @@ mod platform { pub use libc::{FD_ISSET, FD_SET, FD_SETSIZE, FD_ZERO, fd_set, select, timeval}; pub use std::os::unix::io::RawFd; - pub fn check_err(x: i32) -> bool { + pub const fn check_err(x: i32) -> bool { x < 0 } } diff --git a/stdlib/src/syslog.rs b/stdlib/src/syslog.rs index dcdf317b028..e726e67834a 100644 --- a/stdlib/src/syslog.rs +++ b/stdlib/src/syslog.rs @@ -135,13 +135,13 @@ mod syslog { #[inline] #[pyfunction(name = "LOG_MASK")] - fn log_mask(pri: i32) -> i32 { + const fn log_mask(pri: i32) -> i32 { pri << 1 } #[inline] #[pyfunction(name = "LOG_UPTO")] - fn log_upto(pri: i32) -> i32 { + const fn log_upto(pri: i32) -> i32 { (1 << (pri + 1)) - 1 } } diff --git a/stdlib/src/unicodedata.rs b/stdlib/src/unicodedata.rs index 8dbec1ffe8d..4da70f3a3fc 100644 --- a/stdlib/src/unicodedata.rs +++ b/stdlib/src/unicodedata.rs @@ -83,7 +83,7 @@ mod unicodedata { } impl Ucd { - pub fn new(unic_version: UnicodeVersion) -> Self { + pub const fn new(unic_version: UnicodeVersion) -> Self { Self { unic_version } } From 5e086203e23eb17d5269fe2baf3f81057a3845f6 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 01:09:30 +0300 Subject: [PATCH 07/16] vm --- vm/src/stdlib/symtable.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vm/src/stdlib/symtable.rs b/vm/src/stdlib/symtable.rs index 6f6b02c0e08..9178006b360 100644 --- a/vm/src/stdlib/symtable.rs +++ b/vm/src/stdlib/symtable.rs @@ -170,7 +170,7 @@ mod symtable { } #[pymethod] - fn is_global(&self) -> bool { + const fn is_global(&self) -> bool { self.symbol.is_global() || (self.is_top_scope && self.symbol.is_bound()) } @@ -180,7 +180,7 @@ mod symtable { } #[pymethod] - fn is_local(&self) -> bool { + const fn is_local(&self) -> bool { self.symbol.is_local() || (self.is_top_scope && self.symbol.is_bound()) } From 4e91f6a036edefd285a54ffb8caf0d84236b8954 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 01:14:16 +0300 Subject: [PATCH 08/16] cargo fmt --- common/src/encodings.rs | 6 +++++- vm/src/builtins/traceback.rs | 7 ++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/common/src/encodings.rs b/common/src/encodings.rs index 6de5e016cb2..39ca2661262 100644 --- a/common/src/encodings.rs +++ b/common/src/encodings.rs @@ -137,7 +137,11 @@ struct DecodeError<'a> { /// # Safety /// `v[..valid_up_to]` must be valid utf8 -const unsafe fn make_decode_err(v: &[u8], valid_up_to: usize, err_len: Option) -> DecodeError<'_> { +const unsafe fn make_decode_err( + v: &[u8], + valid_up_to: usize, + err_len: Option, +) -> DecodeError<'_> { let (valid_prefix, rest) = unsafe { v.split_at_unchecked(valid_up_to) }; let valid_prefix = unsafe { core::str::from_utf8_unchecked(valid_prefix) }; DecodeError { diff --git a/vm/src/builtins/traceback.rs b/vm/src/builtins/traceback.rs index 91add179175..b170bf9e115 100644 --- a/vm/src/builtins/traceback.rs +++ b/vm/src/builtins/traceback.rs @@ -27,7 +27,12 @@ impl PyPayload for PyTraceback { #[pyclass] impl PyTraceback { - pub const fn new(next: Option>, frame: FrameRef, lasti: u32, lineno: LineNumber) -> Self { + pub const fn new( + next: Option>, + frame: FrameRef, + lasti: u32, + lineno: LineNumber, + ) -> Self { PyTraceback { next: PyMutex::new(next), frame, From 29b26d382d837ff9482a6a3640235a87a2ef35cc Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 12:09:30 +0300 Subject: [PATCH 09/16] vm --- vm/src/buffer.rs | 6 +++--- vm/src/builtins/asyncgenerator.rs | 10 +++++----- vm/src/builtins/builtin_func.rs | 6 +++--- vm/src/builtins/bytearray.rs | 2 +- vm/src/builtins/bytes.rs | 4 ++-- vm/src/builtins/code.rs | 12 ++++++------ vm/src/builtins/complex.rs | 12 ++++++------ vm/src/builtins/coroutine.rs | 6 +++--- vm/src/builtins/dict.rs | 8 ++++---- vm/src/builtins/enumerate.rs | 2 +- vm/src/builtins/float.rs | 2 +- vm/src/builtins/frame.rs | 2 +- vm/src/builtins/function.rs | 4 ++-- vm/src/builtins/iter.rs | 4 ++-- vm/src/builtins/set.rs | 2 +- vm/src/builtins/singletons.rs | 4 ++-- vm/src/builtins/str.rs | 10 +++++----- vm/src/builtins/traceback.rs | 6 +++--- vm/src/builtins/type.rs | 6 +++--- vm/src/builtins/union.rs | 2 +- vm/src/codecs.rs | 2 +- vm/src/function/protocol.rs | 2 +- vm/src/intern.rs | 4 ++-- vm/src/object/core.rs | 12 ++++++------ vm/src/object/ext.rs | 4 ++-- vm/src/protocol/iter.rs | 2 +- vm/src/protocol/sequence.rs | 2 +- vm/src/readline.rs | 2 +- vm/src/sliceable.rs | 4 ++-- vm/src/stdlib/ast.rs | 6 +++--- vm/src/stdlib/collections.rs | 2 +- vm/src/stdlib/imp.rs | 8 ++++---- vm/src/stdlib/io.rs | 18 +++++++++--------- vm/src/stdlib/os.rs | 8 ++++---- vm/src/stdlib/posix.rs | 16 ++++++++-------- vm/src/stdlib/sre.rs | 2 +- vm/src/stdlib/stat.rs | 26 +++++++++++++------------- vm/src/stdlib/symtable.rs | 4 ++-- vm/src/stdlib/sys.rs | 10 +++++----- vm/src/stdlib/typevar.rs | 14 +++++++------- vm/src/stdlib/typing.rs | 2 +- vm/src/types/slot.rs | 10 +++++----- 42 files changed, 135 insertions(+), 135 deletions(-) diff --git a/vm/src/buffer.rs b/vm/src/buffer.rs index eb8732e871a..13cebfc6a28 100644 --- a/vm/src/buffer.rs +++ b/vm/src/buffer.rs @@ -201,7 +201,7 @@ pub(crate) struct FormatCode { } impl FormatCode { - pub fn arg_count(&self) -> usize { + pub const fn arg_count(&self) -> usize { match self.code { FormatType::Pad => 0, FormatType::Str | FormatType::Pascal => 1, @@ -286,7 +286,7 @@ impl FormatCode { } } -fn compensate_alignment(offset: usize, align: usize) -> Option { +const fn compensate_alignment(offset: usize, align: usize) -> Option { if align != 0 && offset != 0 { // a % b == a & (b-1) if b is a power of 2 (align - 1).checked_sub((offset - 1) & (align - 1)) @@ -444,7 +444,7 @@ impl FormatSpec { } #[inline] - pub fn size(&self) -> usize { + pub const fn size(&self) -> usize { self.size } } diff --git a/vm/src/builtins/asyncgenerator.rs b/vm/src/builtins/asyncgenerator.rs index c3c707a69cf..05e8b51514f 100644 --- a/vm/src/builtins/asyncgenerator.rs +++ b/vm/src/builtins/asyncgenerator.rs @@ -29,7 +29,7 @@ impl PyPayload for PyAsyncGen { #[pyclass(with(PyRef, Unconstructible, Representable))] impl PyAsyncGen { - pub fn as_coro(&self) -> &Coro { + pub const fn as_coro(&self) -> &Coro { &self.inner } @@ -76,7 +76,7 @@ impl PyAsyncGen { #[pyclass] impl PyRef { #[pymethod] - fn __aiter__(self, _vm: &VirtualMachine) -> Self { + const fn __aiter__(self, _vm: &VirtualMachine) -> Self { self } @@ -86,7 +86,7 @@ impl PyRef { } #[pymethod] - fn asend(self, value: PyObjectRef, _vm: &VirtualMachine) -> PyAsyncGenASend { + const fn asend(self, value: PyObjectRef, _vm: &VirtualMachine) -> PyAsyncGenASend { PyAsyncGenASend { ag: self, state: AtomicCell::new(AwaitableState::Init), @@ -201,7 +201,7 @@ impl PyPayload for PyAsyncGenASend { #[pyclass(with(IterNext, Iterable))] impl PyAsyncGenASend { #[pymethod(name = "__await__")] - fn r#await(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { + const fn r#await(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { zelf } @@ -295,7 +295,7 @@ impl PyPayload for PyAsyncGenAThrow { #[pyclass(with(IterNext, Iterable))] impl PyAsyncGenAThrow { #[pymethod(name = "__await__")] - fn r#await(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { + const fn r#await(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { zelf } diff --git a/vm/src/builtins/builtin_func.rs b/vm/src/builtins/builtin_func.rs index 43bac5a8846..51729b4ce65 100644 --- a/vm/src/builtins/builtin_func.rs +++ b/vm/src/builtins/builtin_func.rs @@ -36,7 +36,7 @@ impl fmt::Debug for PyNativeFunction { } impl PyNativeFunction { - pub fn with_module(mut self, module: &'static PyStrInterned) -> Self { + pub const fn with_module(mut self, module: &'static PyStrInterned) -> Self { self.module = Some(module); self } @@ -50,7 +50,7 @@ impl PyNativeFunction { } // PyCFunction_GET_SELF - pub fn get_self(&self) -> Option<&PyObjectRef> { + pub const fn get_self(&self) -> Option<&PyObjectRef> { if self.value.flags.contains(PyMethodFlags::STATIC) { return None; } @@ -119,7 +119,7 @@ impl PyNativeFunction { } #[pymethod] - fn __reduce__(&self) -> &'static str { + const fn __reduce__(&self) -> &'static str { // TODO: return (getattr, (self.object, self.name)) if this is a method self.value.name } diff --git a/vm/src/builtins/bytearray.rs b/vm/src/builtins/bytearray.rs index aba1dc2db73..ce48b2bd7cf 100644 --- a/vm/src/builtins/bytearray.rs +++ b/vm/src/builtins/bytearray.rs @@ -77,7 +77,7 @@ impl PyByteArray { PyRef::new_ref(Self::from(data), ctx.types.bytearray_type.to_owned(), None) } - fn from_inner(inner: PyBytesInner) -> Self { + const fn from_inner(inner: PyBytesInner) -> Self { Self { inner: PyRwLock::new(inner), exports: AtomicUsize::new(0), diff --git a/vm/src/builtins/bytes.rs b/vm/src/builtins/bytes.rs index d103e7d4662..22c93ee9298 100644 --- a/vm/src/builtins/bytes.rs +++ b/vm/src/builtins/bytes.rs @@ -149,12 +149,12 @@ impl PyRef { impl PyBytes { #[inline] #[pymethod] - pub fn __len__(&self) -> usize { + pub const fn __len__(&self) -> usize { self.inner.len() } #[inline] - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.inner.is_empty() } diff --git a/vm/src/builtins/code.rs b/vm/src/builtins/code.rs index ada589adc58..0058dbf5556 100644 --- a/vm/src/builtins/code.rs +++ b/vm/src/builtins/code.rs @@ -202,7 +202,7 @@ impl Deref for PyCode { } impl PyCode { - pub fn new(code: CodeObject) -> Self { + pub const fn new(code: CodeObject) -> Self { Self { code } } } @@ -242,17 +242,17 @@ impl PyCode { } #[pygetset] - fn co_posonlyargcount(&self) -> usize { + const fn co_posonlyargcount(&self) -> usize { self.code.posonlyarg_count as usize } #[pygetset] - fn co_argcount(&self) -> usize { + const fn co_argcount(&self) -> usize { self.code.arg_count as usize } #[pygetset] - fn co_stacksize(&self) -> u32 { + const fn co_stacksize(&self) -> u32 { self.code.max_stackdepth } @@ -284,7 +284,7 @@ impl PyCode { } #[pygetset] - fn co_kwonlyargcount(&self) -> usize { + const fn co_kwonlyargcount(&self) -> usize { self.code.kwonlyarg_count as usize } @@ -312,7 +312,7 @@ impl PyCode { } #[pygetset] - fn co_flags(&self) -> u16 { + const fn co_flags(&self) -> u16 { self.code.flags.bits() } diff --git a/vm/src/builtins/complex.rs b/vm/src/builtins/complex.rs index 67e7edebe62..28adb7297b2 100644 --- a/vm/src/builtins/complex.rs +++ b/vm/src/builtins/complex.rs @@ -28,7 +28,7 @@ pub struct PyComplex { } impl PyComplex { - pub fn to_complex64(self) -> Complex64 { + pub const fn to_complex64(self) -> Complex64 { self.value } } @@ -236,7 +236,7 @@ impl PyComplex { PyRef::new_ref(Self::from(value), ctx.types.complex_type.to_owned(), None) } - pub fn to_complex(&self) -> Complex64 { + pub const fn to_complex(&self) -> Complex64 { self.value } } @@ -247,12 +247,12 @@ impl PyComplex { )] impl PyComplex { #[pygetset] - fn real(&self) -> f64 { + const fn real(&self) -> f64 { self.value.re } #[pygetset] - fn imag(&self) -> f64 { + const fn imag(&self) -> f64 { self.value.im } @@ -346,7 +346,7 @@ impl PyComplex { } #[pymethod] - fn __pos__(&self) -> Complex64 { + const fn __pos__(&self) -> Complex64 { self.value } @@ -384,7 +384,7 @@ impl PyComplex { } #[pymethod] - fn __getnewargs__(&self) -> (f64, f64) { + const fn __getnewargs__(&self) -> (f64, f64) { let Complex64 { re, im } = self.value; (re, im) } diff --git a/vm/src/builtins/coroutine.rs b/vm/src/builtins/coroutine.rs index dab6ef87931..e084bf50efc 100644 --- a/vm/src/builtins/coroutine.rs +++ b/vm/src/builtins/coroutine.rs @@ -25,7 +25,7 @@ impl PyPayload for PyCoroutine { #[pyclass(with(Py, Unconstructible, IterNext, Representable))] impl PyCoroutine { - pub fn as_coro(&self) -> &Coro { + pub const fn as_coro(&self) -> &Coro { &self.inner } @@ -46,7 +46,7 @@ impl PyCoroutine { } #[pymethod(name = "__await__")] - fn r#await(zelf: PyRef) -> PyCoroutineWrapper { + const fn r#await(zelf: PyRef) -> PyCoroutineWrapper { PyCoroutineWrapper { coro: zelf } } @@ -69,7 +69,7 @@ impl PyCoroutine { // TODO: coroutine origin tracking: // https://docs.python.org/3/library/sys.html#sys.set_coroutine_origin_tracking_depth #[pygetset] - fn cr_origin(&self, _vm: &VirtualMachine) -> Option<(PyStrRef, usize, PyStrRef)> { + const fn cr_origin(&self, _vm: &VirtualMachine) -> Option<(PyStrRef, usize, PyStrRef)> { None } diff --git a/vm/src/builtins/dict.rs b/vm/src/builtins/dict.rs index d18f7954039..e59aa5bcf74 100644 --- a/vm/src/builtins/dict.rs +++ b/vm/src/builtins/dict.rs @@ -57,7 +57,7 @@ impl PyDict { /// escape hatch to access the underlying data structure directly. prefer adding a method on /// PyDict instead of using this - pub(crate) fn _as_dict_inner(&self) -> &DictContentType { + pub(crate) const fn _as_dict_inner(&self) -> &DictContentType { &self.entries } @@ -376,17 +376,17 @@ impl Py { #[pyclass] impl PyRef { #[pymethod] - fn keys(self) -> PyDictKeys { + const fn keys(self) -> PyDictKeys { PyDictKeys::new(self) } #[pymethod] - fn values(self) -> PyDictValues { + const fn values(self) -> PyDictValues { PyDictValues::new(self) } #[pymethod] - fn items(self) -> PyDictItems { + const fn items(self) -> PyDictItems { PyDictItems::new(self) } diff --git a/vm/src/builtins/enumerate.rs b/vm/src/builtins/enumerate.rs index fd57532da96..64cd4e774e0 100644 --- a/vm/src/builtins/enumerate.rs +++ b/vm/src/builtins/enumerate.rs @@ -101,7 +101,7 @@ impl PyPayload for PyReverseSequenceIterator { #[pyclass(with(IterNext, Iterable))] impl PyReverseSequenceIterator { - pub fn new(obj: PyObjectRef, len: usize) -> Self { + pub const fn new(obj: PyObjectRef, len: usize) -> Self { let position = len.saturating_sub(1); Self { internal: PyMutex::new(PositionIterInternal::new(obj, position)), diff --git a/vm/src/builtins/float.rs b/vm/src/builtins/float.rs index f01eceef0ce..4982615b048 100644 --- a/vm/src/builtins/float.rs +++ b/vm/src/builtins/float.rs @@ -231,7 +231,7 @@ impl PyFloat { } #[pymethod] - fn __abs__(&self) -> f64 { + const fn __abs__(&self) -> f64 { self.value.abs() } diff --git a/vm/src/builtins/frame.rs b/vm/src/builtins/frame.rs index 88337c14946..65ac3e798d7 100644 --- a/vm/src/builtins/frame.rs +++ b/vm/src/builtins/frame.rs @@ -34,7 +34,7 @@ impl Representable for Frame { #[pyclass(with(Unconstructible, Py))] impl Frame { #[pymethod] - fn clear(&self) { + const fn clear(&self) { // TODO } diff --git a/vm/src/builtins/function.rs b/vm/src/builtins/function.rs index ee75f850d01..a29a077e509 100644 --- a/vm/src/builtins/function.rs +++ b/vm/src/builtins/function.rs @@ -722,7 +722,7 @@ impl Constructor for PyBoundMethod { } impl PyBoundMethod { - pub fn new(object: PyObjectRef, function: PyObjectRef) -> Self { + pub const fn new(object: PyObjectRef, function: PyObjectRef) -> Self { Self { object, function } } @@ -846,7 +846,7 @@ impl Constructor for PyCell { #[pyclass(with(Constructor))] impl PyCell { - pub fn new(contents: Option) -> Self { + pub const fn new(contents: Option) -> Self { Self { contents: PyMutex::new(contents), } diff --git a/vm/src/builtins/iter.rs b/vm/src/builtins/iter.rs index 52ee8535493..bea427e6969 100644 --- a/vm/src/builtins/iter.rs +++ b/vm/src/builtins/iter.rs @@ -47,7 +47,7 @@ unsafe impl Traverse for PositionIterInternal { } impl PositionIterInternal { - pub fn new(obj: T, position: usize) -> Self { + pub const fn new(obj: T, position: usize) -> Self { Self { status: IterStatus::Active(obj), position, @@ -256,7 +256,7 @@ impl PyPayload for PyCallableIterator { #[pyclass(with(IterNext, Iterable))] impl PyCallableIterator { - pub fn new(callable: ArgCallable, sentinel: PyObjectRef) -> Self { + pub const fn new(callable: ArgCallable, sentinel: PyObjectRef) -> Self { Self { sentinel, status: PyRwLock::new(IterStatus::Active(callable)), diff --git a/vm/src/builtins/set.rs b/vm/src/builtins/set.rs index 77301bd384f..c4fd116f6a3 100644 --- a/vm/src/builtins/set.rs +++ b/vm/src/builtins/set.rs @@ -441,7 +441,7 @@ impl PySetInner { // This is important because some use cases have many combinations of a // small number of elements with nearby hashes so that many distinct // combinations collapse to only a handful of distinct hash values. - fn _shuffle_bits(h: u64) -> u64 { + const fn _shuffle_bits(h: u64) -> u64 { ((h ^ 89869747) ^ (h.wrapping_shl(16))).wrapping_mul(3644798167) } // Factor in the number of active entries diff --git a/vm/src/builtins/singletons.rs b/vm/src/builtins/singletons.rs index b1b02d3124a..7b674cb35b1 100644 --- a/vm/src/builtins/singletons.rs +++ b/vm/src/builtins/singletons.rs @@ -46,7 +46,7 @@ impl Constructor for PyNone { #[pyclass(with(Constructor, AsNumber, Representable))] impl PyNone { #[pymethod] - fn __bool__(&self) -> bool { + const fn __bool__(&self) -> bool { false } } @@ -98,7 +98,7 @@ impl PyNotImplemented { // in boolean contexts will need to raise a DeprecationWarning in 3.9 // and, eventually, a TypeError. #[pymethod] - fn __bool__(&self) -> bool { + const fn __bool__(&self) -> bool { true } diff --git a/vm/src/builtins/str.rs b/vm/src/builtins/str.rs index a2ea87cd222..f822a124ed9 100644 --- a/vm/src/builtins/str.rs +++ b/vm/src/builtins/str.rs @@ -414,11 +414,11 @@ impl PyStr { } #[inline] - pub fn as_wtf8(&self) -> &Wtf8 { + pub const fn as_wtf8(&self) -> &Wtf8 { self.data.as_wtf8() } - pub fn as_bytes(&self) -> &[u8] { + pub const fn as_bytes(&self) -> &[u8] { self.data.as_wtf8().as_bytes() } @@ -456,7 +456,7 @@ impl PyStr { .unwrap_or_else(|| self.as_wtf8().to_string_lossy()) } - pub fn kind(&self) -> StrKind { + pub const fn kind(&self) -> StrKind { self.data.kind() } @@ -465,7 +465,7 @@ impl PyStr { self.data.as_str_kind() } - pub fn is_utf8(&self) -> bool { + pub const fn is_utf8(&self) -> bool { self.kind().is_utf8() } @@ -601,7 +601,7 @@ impl PyStr { #[pymethod(name = "isascii")] #[inline(always)] - pub fn is_ascii(&self) -> bool { + pub const fn is_ascii(&self) -> bool { matches!(self.kind(), StrKind::Ascii) } diff --git a/vm/src/builtins/traceback.rs b/vm/src/builtins/traceback.rs index 6caa1a1f076..4f6fa512433 100644 --- a/vm/src/builtins/traceback.rs +++ b/vm/src/builtins/traceback.rs @@ -27,7 +27,7 @@ impl PyPayload for PyTraceback { #[pyclass] impl PyTraceback { - pub fn new(next: Option>, frame: FrameRef, lasti: u32, lineno: LineNumber) -> Self { + pub const fn new(next: Option>, frame: FrameRef, lasti: u32, lineno: LineNumber) -> Self { Self { next: PyMutex::new(next), frame, @@ -42,12 +42,12 @@ impl PyTraceback { } #[pygetset] - fn tb_lasti(&self) -> u32 { + const fn tb_lasti(&self) -> u32 { self.lasti } #[pygetset] - fn tb_lineno(&self) -> usize { + const fn tb_lineno(&self) -> usize { self.lineno.get() } diff --git a/vm/src/builtins/type.rs b/vm/src/builtins/type.rs index b18c16a83f4..6a626c5ec73 100644 --- a/vm/src/builtins/type.rs +++ b/vm/src/builtins/type.rs @@ -73,7 +73,7 @@ unsafe impl Sync for PointerSlot {} unsafe impl Send for PointerSlot {} impl PointerSlot { - pub unsafe fn borrow_static(&self) -> &'static T { + pub const unsafe fn borrow_static(&self) -> &'static T { unsafe { self.0.as_ref() } } } @@ -621,12 +621,12 @@ impl PyType { } #[pygetset] - fn __flags__(&self) -> u64 { + const fn __flags__(&self) -> u64 { self.slots.flags.bits() } #[pygetset] - fn __basicsize__(&self) -> usize { + const fn __basicsize__(&self) -> usize { self.slots.basicsize } diff --git a/vm/src/builtins/union.rs b/vm/src/builtins/union.rs index b5a604ec2a8..c7abd634ef5 100644 --- a/vm/src/builtins/union.rs +++ b/vm/src/builtins/union.rs @@ -42,7 +42,7 @@ impl PyUnion { /// Direct access to args field, matching CPython's _Py_union_args #[inline] - pub fn args(&self) -> &PyTupleRef { + pub const fn args(&self) -> &PyTupleRef { &self.args } diff --git a/vm/src/codecs.rs b/vm/src/codecs.rs index 59c5d66fde1..b31222cfee9 100644 --- a/vm/src/codecs.rs +++ b/vm/src/codecs.rs @@ -52,7 +52,7 @@ impl PyCodec { self.0 } #[inline] - pub fn as_tuple(&self) -> &PyTupleRef { + pub const fn as_tuple(&self) -> &PyTupleRef { &self.0 } diff --git a/vm/src/function/protocol.rs b/vm/src/function/protocol.rs index 0601a9f9682..3205f75c27d 100644 --- a/vm/src/function/protocol.rs +++ b/vm/src/function/protocol.rs @@ -130,7 +130,7 @@ pub struct ArgMapping { impl ArgMapping { #[inline] - pub fn with_methods(obj: PyObjectRef, methods: &'static PyMappingMethods) -> Self { + pub const fn with_methods(obj: PyObjectRef, methods: &'static PyMappingMethods) -> Self { Self { obj, methods } } diff --git a/vm/src/intern.rs b/vm/src/intern.rs index 92a02a2648f..8463e3a1c19 100644 --- a/vm/src/intern.rs +++ b/vm/src/intern.rs @@ -118,7 +118,7 @@ impl CachedPyStrRef { /// # Safety /// the given cache must be alive while returned reference is alive #[inline] - unsafe fn as_interned_str(&self) -> &'static PyStrInterned { + const unsafe fn as_interned_str(&self) -> &'static PyStrInterned { unsafe { std::mem::transmute_copy(self) } } @@ -142,7 +142,7 @@ impl PyInterned { } #[inline] - fn as_ptr(&self) -> *const Py { + const fn as_ptr(&self) -> *const Py { self as *const _ as *const _ } diff --git a/vm/src/object/core.rs b/vm/src/object/core.rs index eb3f9dcfcc2..bb057f4906f 100644 --- a/vm/src/object/core.rs +++ b/vm/src/object/core.rs @@ -421,7 +421,7 @@ impl From for InstanceDict { impl InstanceDict { #[inline] - pub fn new(d: PyDictRef) -> Self { + pub const fn new(d: PyDictRef) -> Self { Self { d: PyRwLock::new(d), } @@ -512,7 +512,7 @@ impl ToOwned for PyObject { impl PyObjectRef { #[inline(always)] - pub fn into_raw(self) -> NonNull { + pub const fn into_raw(self) -> NonNull { let ptr = self.ptr; std::mem::forget(self); ptr @@ -524,7 +524,7 @@ impl PyObjectRef { /// dropped more than once due to mishandling the reference count by calling this function /// too many times. #[inline(always)] - pub unsafe fn from_raw(ptr: NonNull) -> Self { + pub const unsafe fn from_raw(ptr: NonNull) -> Self { Self { ptr } } @@ -663,7 +663,7 @@ impl PyObject { /// # Safety /// The actual payload type must be T. #[inline(always)] - pub unsafe fn payload_unchecked(&self) -> &T { + pub const unsafe fn payload_unchecked(&self) -> &T { // we cast to a PyInner first because we don't know T's exact offset because of // varying alignment, but once we get a PyInner the compiler can get it for us let inner = unsafe { &*(&self.0 as *const PyInner as *const PyInner) }; @@ -1019,7 +1019,7 @@ impl Clone for PyRef { impl PyRef { #[inline(always)] - pub(crate) unsafe fn from_raw(raw: *const Py) -> Self { + pub(crate) const unsafe fn from_raw(raw: *const Py) -> Self { Self { ptr: unsafe { NonNull::new_unchecked(raw as *mut _) }, } @@ -1043,7 +1043,7 @@ impl PyRef { } } - pub fn leak(pyref: Self) -> &'static Py { + pub const fn leak(pyref: Self) -> &'static Py { let ptr = pyref.ptr; std::mem::forget(pyref); unsafe { ptr.as_ref() } diff --git a/vm/src/object/ext.rs b/vm/src/object/ext.rs index a635d856c02..2815d2b20e7 100644 --- a/vm/src/object/ext.rs +++ b/vm/src/object/ext.rs @@ -66,7 +66,7 @@ impl PyExact { /// # Safety /// Given reference must be exact type of payload T #[inline(always)] - pub unsafe fn ref_unchecked(r: &Py) -> &Self { + pub const unsafe fn ref_unchecked(r: &Py) -> &Self { unsafe { &*(r as *const _ as *const Self) } } } @@ -141,7 +141,7 @@ pub struct PyRefExact { impl PyRefExact { /// # Safety /// obj must have exact type for the payload - pub unsafe fn new_unchecked(obj: PyRef) -> Self { + pub const unsafe fn new_unchecked(obj: PyRef) -> Self { Self { inner: obj } } diff --git a/vm/src/protocol/iter.rs b/vm/src/protocol/iter.rs index da7ab17382c..18f2b5243e2 100644 --- a/vm/src/protocol/iter.rs +++ b/vm/src/protocol/iter.rs @@ -33,7 +33,7 @@ impl PyIter where O: Borrow, { - pub fn new(obj: O) -> Self { + pub const fn new(obj: O) -> Self { Self(obj) } pub fn next(&self, vm: &VirtualMachine) -> PyResult { diff --git a/vm/src/protocol/sequence.rs b/vm/src/protocol/sequence.rs index 0bfbc0ffc5a..6d9eb56151b 100644 --- a/vm/src/protocol/sequence.rs +++ b/vm/src/protocol/sequence.rs @@ -76,7 +76,7 @@ unsafe impl Traverse for PySequence<'_> { impl<'a> PySequence<'a> { #[inline] - pub fn with_methods(obj: &'a PyObject, methods: &'static PySequenceMethods) -> Self { + pub const fn with_methods(obj: &'a PyObject, methods: &'static PySequenceMethods) -> Self { Self { obj, methods } } diff --git a/vm/src/readline.rs b/vm/src/readline.rs index d37bbb74582..8a90a7ae40e 100644 --- a/vm/src/readline.rs +++ b/vm/src/readline.rs @@ -28,7 +28,7 @@ mod basic_readline { } impl Readline { - pub fn new(helper: H) -> Self { + pub const fn new(helper: H) -> Self { Self { helper } } diff --git a/vm/src/sliceable.rs b/vm/src/sliceable.rs index b394e6f1834..7d175d033e1 100644 --- a/vm/src/sliceable.rs +++ b/vm/src/sliceable.rs @@ -415,7 +415,7 @@ impl SaturatedSliceIter { Self::from_adjust_indices(range, step, len) } - pub fn from_adjust_indices(range: Range, step: isize, len: usize) -> Self { + pub const fn from_adjust_indices(range: Range, step: isize, len: usize) -> Self { let index = if step.is_negative() { range.end as isize - 1 } else { @@ -424,7 +424,7 @@ impl SaturatedSliceIter { Self { index, step, len } } - pub fn positive_order(mut self) -> Self { + pub const fn positive_order(mut self) -> Self { if self.step.is_negative() { self.index += self.step * self.len.saturating_sub(1) as isize; self.step = self.step.saturating_abs() diff --git a/vm/src/stdlib/ast.rs b/vm/src/stdlib/ast.rs index e815bc41596..a65038a7bcb 100644 --- a/vm/src/stdlib/ast.rs +++ b/vm/src/stdlib/ast.rs @@ -103,7 +103,7 @@ impl PySourceLocation { struct Row(OneIndexed); impl Row { - fn get(self) -> usize { + const fn get(self) -> usize { self.0.get() } @@ -117,11 +117,11 @@ impl Row { struct Column(TextSize); impl Column { - fn get(self) -> usize { + const fn get(self) -> usize { self.0.to_usize() } - fn get_one_indexed(self) -> OneIndexed { + const fn get_one_indexed(self) -> OneIndexed { OneIndexed::from_zero_indexed(self.get()) } } diff --git a/vm/src/stdlib/collections.rs b/vm/src/stdlib/collections.rs index ab1fd7d4d0e..6d1cdf1f02d 100644 --- a/vm/src/stdlib/collections.rs +++ b/vm/src/stdlib/collections.rs @@ -273,7 +273,7 @@ mod _collections { } #[pygetset] - fn maxlen(&self) -> Option { + const fn maxlen(&self) -> Option { self.maxlen } diff --git a/vm/src/stdlib/imp.rs b/vm/src/stdlib/imp.rs index 378a1003641..596847776ff 100644 --- a/vm/src/stdlib/imp.rs +++ b/vm/src/stdlib/imp.rs @@ -35,11 +35,11 @@ mod lock { mod lock { use crate::vm::VirtualMachine; #[pyfunction] - pub(super) fn acquire_lock(_vm: &VirtualMachine) {} + pub(super) const fn acquire_lock(_vm: &VirtualMachine) {} #[pyfunction] - pub(super) fn release_lock(_vm: &VirtualMachine) {} + pub(super) const fn release_lock(_vm: &VirtualMachine) {} #[pyfunction] - pub(super) fn lock_held(_vm: &VirtualMachine) -> bool { + pub(super) const fn lock_held(_vm: &VirtualMachine) -> bool { false } } @@ -95,7 +95,7 @@ mod _imp { } #[pyfunction] - fn extension_suffixes() -> PyResult> { + const fn extension_suffixes() -> PyResult> { Ok(Vec::new()) } diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index e6adf07fcd8..dd034924fe5 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -289,7 +289,7 @@ mod _io { Some(b) } - fn tell(&self) -> u64 { + const fn tell(&self) -> u64 { self.cursor.position() } @@ -783,22 +783,22 @@ mod _io { } #[inline] - fn writable(&self) -> bool { + const fn writable(&self) -> bool { self.flags.contains(BufferedFlags::WRITABLE) } #[inline] - fn readable(&self) -> bool { + const fn readable(&self) -> bool { self.flags.contains(BufferedFlags::READABLE) } #[inline] - fn valid_read(&self) -> bool { + const fn valid_read(&self) -> bool { self.readable() && self.read_end != -1 } #[inline] - fn valid_write(&self) -> bool { + const fn valid_write(&self) -> bool { self.writable() && self.write_end != -1 } @@ -820,11 +820,11 @@ mod _io { } } - fn reset_read(&mut self) { + const fn reset_read(&mut self) { self.read_end = -1; } - fn reset_write(&mut self) { + const fn reset_write(&mut self) { self.write_pos = 0; self.write_end = -1; } @@ -2094,7 +2094,7 @@ mod _io { // TODO: implement legit fast-paths for other encodings type EncodeFunc = fn(PyStrRef) -> PendingWrite; - fn textio_encode_utf8(s: PyStrRef) -> PendingWrite { + const fn textio_encode_utf8(s: PyStrRef) -> PendingWrite { PendingWrite::Utf8(s) } @@ -2262,7 +2262,7 @@ mod _io { } } - fn set_num_to_skip(&mut self, num: Utf8size) { + const fn set_num_to_skip(&mut self, num: Utf8size) { self.bytes_to_skip = num.bytes as i32; self.chars_to_skip = num.chars as i32; } diff --git a/vm/src/stdlib/os.rs b/vm/src/stdlib/os.rs index f5863d8969f..19f5e44b34a 100644 --- a/vm/src/stdlib/os.rs +++ b/vm/src/stdlib/os.rs @@ -85,7 +85,7 @@ impl DirFd<1> { } #[inline(always)] - pub(crate) fn fd(&self) -> Fd { + pub(crate) const fn fd(&self) -> Fd { self.0[0] } } @@ -571,7 +571,7 @@ pub(super) mod _os { #[cfg(not(windows))] #[pymethod] - fn is_junction(&self, _vm: &VirtualMachine) -> PyResult { + const fn is_junction(&self, _vm: &VirtualMachine) -> PyResult { Ok(false) } @@ -642,7 +642,7 @@ pub(super) mod _os { } #[pymethod] - fn __enter__(zelf: PyRef) -> PyRef { + const fn __enter__(zelf: PyRef) -> PyRef { zelf } @@ -1495,7 +1495,7 @@ pub(crate) struct SupportFunc { } impl SupportFunc { - pub(crate) fn new( + pub(crate) const fn new( name: &'static str, fd: Option, dir_fd: Option, diff --git a/vm/src/stdlib/posix.rs b/vm/src/stdlib/posix.rs index c58446dc96c..a6453fc032a 100644 --- a/vm/src/stdlib/posix.rs +++ b/vm/src/stdlib/posix.rs @@ -211,7 +211,7 @@ pub mod module { is_executable: bool, } - fn get_permissions(mode: u32) -> Permissions { + const fn get_permissions(mode: u32) -> Permissions { Permissions { is_readable: mode & 4 != 0, is_writable: mode & 2 != 0, @@ -1228,7 +1228,7 @@ pub mod module { } #[pyfunction] - fn sync() { + const fn sync() { #[cfg(not(any(target_os = "redox", target_os = "android")))] unsafe { libc::sync(); @@ -1603,32 +1603,32 @@ pub mod module { } #[pyfunction(name = "WIFSIGNALED")] - fn wifsignaled(status: i32) -> bool { + const fn wifsignaled(status: i32) -> bool { libc::WIFSIGNALED(status) } #[pyfunction(name = "WIFSTOPPED")] - fn wifstopped(status: i32) -> bool { + const fn wifstopped(status: i32) -> bool { libc::WIFSTOPPED(status) } #[pyfunction(name = "WIFEXITED")] - fn wifexited(status: i32) -> bool { + const fn wifexited(status: i32) -> bool { libc::WIFEXITED(status) } #[pyfunction(name = "WTERMSIG")] - fn wtermsig(status: i32) -> i32 { + const fn wtermsig(status: i32) -> i32 { libc::WTERMSIG(status) } #[pyfunction(name = "WSTOPSIG")] - fn wstopsig(status: i32) -> i32 { + const fn wstopsig(status: i32) -> i32 { libc::WSTOPSIG(status) } #[pyfunction(name = "WEXITSTATUS")] - fn wexitstatus(status: i32) -> i32 { + const fn wexitstatus(status: i32) -> i32 { libc::WEXITSTATUS(status) } diff --git a/vm/src/stdlib/sre.rs b/vm/src/stdlib/sre.rs index 2ee3a42573a..33fc977f2c6 100644 --- a/vm/src/stdlib/sre.rs +++ b/vm/src/stdlib/sre.rs @@ -396,7 +396,7 @@ mod _sre { } #[pygetset] - fn flags(&self) -> u16 { + const fn flags(&self) -> u16 { self.flags.bits() } diff --git a/vm/src/stdlib/stat.rs b/vm/src/stdlib/stat.rs index 7cfacf965c5..fdb88b37f08 100644 --- a/vm/src/stdlib/stat.rs +++ b/vm/src/stdlib/stat.rs @@ -246,82 +246,82 @@ mod stat { #[pyfunction] #[allow(non_snake_case)] - fn S_ISDIR(mode: Mode) -> bool { + const fn S_ISDIR(mode: Mode) -> bool { (mode & S_IFMT) == S_IFDIR } #[pyfunction] #[allow(non_snake_case)] - fn S_ISCHR(mode: Mode) -> bool { + const fn S_ISCHR(mode: Mode) -> bool { (mode & S_IFMT) == S_IFCHR } #[pyfunction] #[allow(non_snake_case)] - fn S_ISREG(mode: Mode) -> bool { + const fn S_ISREG(mode: Mode) -> bool { (mode & S_IFMT) == S_IFREG } #[pyfunction] #[allow(non_snake_case)] - fn S_ISBLK(mode: Mode) -> bool { + const fn S_ISBLK(mode: Mode) -> bool { (mode & S_IFMT) == S_IFBLK } #[pyfunction] #[allow(non_snake_case)] - fn S_ISFIFO(mode: Mode) -> bool { + const fn S_ISFIFO(mode: Mode) -> bool { (mode & S_IFMT) == S_IFIFO } #[pyfunction] #[allow(non_snake_case)] - fn S_ISLNK(mode: Mode) -> bool { + const fn S_ISLNK(mode: Mode) -> bool { (mode & S_IFMT) == S_IFLNK } #[pyfunction] #[allow(non_snake_case)] - fn S_ISSOCK(mode: Mode) -> bool { + const fn S_ISSOCK(mode: Mode) -> bool { (mode & S_IFMT) == S_IFSOCK } // TODO: RUSTPYTHON Support Solaris #[pyfunction] #[allow(non_snake_case)] - fn S_ISDOOR(_mode: Mode) -> bool { + const fn S_ISDOOR(_mode: Mode) -> bool { false } // TODO: RUSTPYTHON Support Solaris #[pyfunction] #[allow(non_snake_case)] - fn S_ISPORT(_mode: Mode) -> bool { + const fn S_ISPORT(_mode: Mode) -> bool { false } // TODO: RUSTPYTHON Support BSD #[pyfunction] #[allow(non_snake_case)] - fn S_ISWHT(_mode: Mode) -> bool { + const fn S_ISWHT(_mode: Mode) -> bool { false } #[pyfunction(name = "S_IMODE")] #[allow(non_snake_case)] - fn S_IMODE_method(mode: Mode) -> Mode { + const fn S_IMODE_method(mode: Mode) -> Mode { mode & S_IMODE } #[pyfunction(name = "S_IFMT")] #[allow(non_snake_case)] - fn S_IFMT_method(mode: Mode) -> Mode { + const fn S_IFMT_method(mode: Mode) -> Mode { // 0o170000 is from the S_IFMT definition in CPython include/fileutils.h mode & S_IFMT } #[pyfunction] - fn filetype(mode: Mode) -> char { + const fn filetype(mode: Mode) -> char { if S_ISREG(mode) { '-' } else if S_ISDIR(mode) { diff --git a/vm/src/stdlib/symtable.rs b/vm/src/stdlib/symtable.rs index a848de5dc47..6f6b02c0e08 100644 --- a/vm/src/stdlib/symtable.rs +++ b/vm/src/stdlib/symtable.rs @@ -29,7 +29,7 @@ mod symtable { Ok(py_symbol_table.into_ref(&vm.ctx)) } - fn to_py_symbol_table(symtable: SymbolTable) -> PySymbolTable { + const fn to_py_symbol_table(symtable: SymbolTable) -> PySymbolTable { PySymbolTable { symtable } } @@ -190,7 +190,7 @@ mod symtable { } #[pymethod] - fn is_nested(&self) -> bool { + const fn is_nested(&self) -> bool { // TODO false } diff --git a/vm/src/stdlib/sys.rs b/vm/src/stdlib/sys.rs index a7310fc1028..fbd6f0de8f0 100644 --- a/vm/src/stdlib/sys.rs +++ b/vm/src/stdlib/sys.rs @@ -95,7 +95,7 @@ mod sys { const DLLHANDLE: usize = 0; #[pyattr] - fn default_prefix(_vm: &VirtualMachine) -> &'static str { + const fn default_prefix(_vm: &VirtualMachine) -> &'static str { // TODO: the windows one doesn't really make sense if cfg!(windows) { "C:" } else { "/usr/local" } } @@ -238,7 +238,7 @@ mod sys { } #[pyattr] - fn meta_path(_vm: &VirtualMachine) -> Vec { + const fn meta_path(_vm: &VirtualMachine) -> Vec { Vec::new() } @@ -258,7 +258,7 @@ mod sys { } #[pyattr] - fn path_hooks(_vm: &VirtualMachine) -> Vec { + const fn path_hooks(_vm: &VirtualMachine) -> Vec { Vec::new() } @@ -454,7 +454,7 @@ mod sys { } #[pyfunction] - fn getdefaultencoding() -> &'static str { + const fn getdefaultencoding() -> &'static str { crate::codecs::DEFAULT_ENCODING } @@ -964,7 +964,7 @@ mod sys { #[pyclass(with(PyStructSequence))] impl Flags { - fn from_settings(settings: &Settings) -> Self { + const fn from_settings(settings: &Settings) -> Self { Self { debug: settings.debug, inspect: settings.inspect as u8, diff --git a/vm/src/stdlib/typevar.rs b/vm/src/stdlib/typevar.rs index 5b0158981d1..60d6c5d9c18 100644 --- a/vm/src/stdlib/typevar.rs +++ b/vm/src/stdlib/typevar.rs @@ -124,17 +124,17 @@ impl TypeVar { } #[pygetset] - fn __covariant__(&self) -> bool { + const fn __covariant__(&self) -> bool { self.covariant } #[pygetset] - fn __contravariant__(&self) -> bool { + const fn __contravariant__(&self) -> bool { self.contravariant } #[pygetset] - fn __infer_variance__(&self) -> bool { + const fn __infer_variance__(&self) -> bool { self.infer_variance } @@ -445,17 +445,17 @@ impl ParamSpec { } #[pygetset] - fn __covariant__(&self) -> bool { + const fn __covariant__(&self) -> bool { self.covariant } #[pygetset] - fn __contravariant__(&self) -> bool { + const fn __contravariant__(&self) -> bool { self.contravariant } #[pygetset] - fn __infer_variance__(&self) -> bool { + const fn __infer_variance__(&self) -> bool { self.infer_variance } @@ -627,7 +627,7 @@ impl Representable for ParamSpec { } impl ParamSpec { - pub fn new(name: PyObjectRef) -> Self { + pub const fn new(name: PyObjectRef) -> Self { Self { name, bound: None, diff --git a/vm/src/stdlib/typing.rs b/vm/src/stdlib/typing.rs index ed3b3f0e972..be860fdb0d3 100644 --- a/vm/src/stdlib/typing.rs +++ b/vm/src/stdlib/typing.rs @@ -105,7 +105,7 @@ pub(crate) mod decl { } #[pyclass(flags(BASETYPE))] impl TypeAliasType { - pub fn new(name: PyObjectRef, type_params: PyTupleRef, value: PyObjectRef) -> Self { + pub const fn new(name: PyObjectRef, type_params: PyTupleRef, value: PyObjectRef) -> Self { Self { name, type_params, diff --git a/vm/src/types/slot.rs b/vm/src/types/slot.rs index 7f36a8baf07..704ec3edf0f 100644 --- a/vm/src/types/slot.rs +++ b/vm/src/types/slot.rs @@ -149,12 +149,12 @@ impl PyTypeFlags { } } - pub fn has_feature(self, flag: Self) -> bool { + pub const fn has_feature(self, flag: Self) -> bool { self.contains(flag) } #[cfg(debug_assertions)] - pub fn is_created_with_flags(self) -> bool { + pub const fn is_created_with_flags(self) -> bool { self.contains(Self::_CREATED_WITH_FLAGS) } } @@ -325,7 +325,7 @@ fn iter_wrapper(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { } // PyObject_SelfIter in CPython -fn self_iter(zelf: PyObjectRef, _vm: &VirtualMachine) -> PyResult { +const fn self_iter(zelf: PyObjectRef, _vm: &VirtualMachine) -> PyResult { Ok(zelf) } @@ -1109,7 +1109,7 @@ impl PyComparisonOp { } } - pub fn eval_ord(self, ord: Ordering) -> bool { + pub const fn eval_ord(self, ord: Ordering) -> bool { let bit = match ord { Ordering::Less => Self::Lt, Ordering::Equal => Self::Eq, @@ -1118,7 +1118,7 @@ impl PyComparisonOp { self.0 as u8 & bit.0 as u8 != 0 } - pub fn swapped(self) -> Self { + pub const fn swapped(self) -> Self { match self { Self::Lt => Self::Gt, Self::Le => Self::Ge, From 6cd01bff4b9a9a0f3aaa6fd24c88ba823dafc5b2 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 12:10:19 +0300 Subject: [PATCH 10/16] vm --- vm/src/stdlib/ast.rs | 2 +- vm/src/stdlib/io.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/vm/src/stdlib/ast.rs b/vm/src/stdlib/ast.rs index a65038a7bcb..f6679f18976 100644 --- a/vm/src/stdlib/ast.rs +++ b/vm/src/stdlib/ast.rs @@ -90,7 +90,7 @@ pub struct PySourceLocation { } impl PySourceLocation { - fn to_source_location(&self) -> SourceLocation { + const fn to_source_location(&self) -> SourceLocation { SourceLocation { row: self.row.get_one_indexed(), column: self.column.get_one_indexed(), diff --git a/vm/src/stdlib/io.rs b/vm/src/stdlib/io.rs index dd034924fe5..c546a0c46fe 100644 --- a/vm/src/stdlib/io.rs +++ b/vm/src/stdlib/io.rs @@ -803,7 +803,7 @@ mod _io { } #[inline] - fn raw_offset(&self) -> Offset { + const fn raw_offset(&self) -> Offset { if (self.valid_read() || self.valid_write()) && self.raw_pos >= 0 { self.raw_pos - self.pos } else { @@ -812,7 +812,7 @@ mod _io { } #[inline] - fn readahead(&self) -> Offset { + const fn readahead(&self) -> Offset { if self.valid_read() { self.read_end - self.pos } else { @@ -1278,7 +1278,7 @@ mod _io { } } - fn adjust_position(&mut self, new_pos: Offset) { + const fn adjust_position(&mut self, new_pos: Offset) { self.pos = new_pos; if self.valid_read() && self.read_end < self.pos { self.read_end = self.pos From 6b1deb4f2ae33f27f252195ecbed9c08368c1e4f Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 12:13:56 +0300 Subject: [PATCH 11/16] common --- common/src/cformat.rs | 2 +- common/src/encodings.rs | 2 +- common/src/hash.rs | 4 ++-- common/src/linked_list.rs | 14 +++++++------- common/src/lock/thread_mutex.rs | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/common/src/cformat.rs b/common/src/cformat.rs index 5065bd0a493..b553f0b6b10 100644 --- a/common/src/cformat.rs +++ b/common/src/cformat.rs @@ -136,7 +136,7 @@ bitflags! { impl CConversionFlags { #[inline] - pub fn sign_string(&self) -> &'static str { + pub const fn sign_string(&self) -> &'static str { if self.contains(Self::SIGN_CHAR) { "+" } else if self.contains(Self::BLANK_SIGN) { diff --git a/common/src/encodings.rs b/common/src/encodings.rs index 9e89f9cdec4..6de5e016cb2 100644 --- a/common/src/encodings.rs +++ b/common/src/encodings.rs @@ -137,7 +137,7 @@ struct DecodeError<'a> { /// # Safety /// `v[..valid_up_to]` must be valid utf8 -unsafe fn make_decode_err(v: &[u8], valid_up_to: usize, err_len: Option) -> DecodeError<'_> { +const unsafe fn make_decode_err(v: &[u8], valid_up_to: usize, err_len: Option) -> DecodeError<'_> { let (valid_prefix, rest) = unsafe { v.split_at_unchecked(valid_up_to) }; let valid_prefix = unsafe { core::str::from_utf8_unchecked(valid_prefix) }; DecodeError { diff --git a/common/src/hash.rs b/common/src/hash.rs index a01629efa22..dcf424f7ba9 100644 --- a/common/src/hash.rs +++ b/common/src/hash.rs @@ -164,7 +164,7 @@ pub fn lcg_urandom(mut x: u32, buf: &mut [u8]) { } #[inline] -pub fn hash_object_id_raw(p: usize) -> PyHash { +pub const fn hash_object_id_raw(p: usize) -> PyHash { // TODO: Use commented logic when below issue resolved. // Ref: https://github.com/RustPython/RustPython/pull/3951#issuecomment-1193108966 @@ -175,7 +175,7 @@ pub fn hash_object_id_raw(p: usize) -> PyHash { } #[inline] -pub fn hash_object_id(p: usize) -> PyHash { +pub const fn hash_object_id(p: usize) -> PyHash { fix_sentinel(hash_object_id_raw(p)) } diff --git a/common/src/linked_list.rs b/common/src/linked_list.rs index 29cdcaee9ed..8afc1478e6b 100644 --- a/common/src/linked_list.rs +++ b/common/src/linked_list.rs @@ -193,7 +193,7 @@ impl LinkedList { // } /// Returns whether the linked list does not contain any node - pub fn is_empty(&self) -> bool { + pub const fn is_empty(&self) -> bool { self.head.is_none() // if self.head.is_some() { // return false; @@ -284,7 +284,7 @@ pub struct DrainFilter<'a, T: Link, F> { } impl LinkedList { - pub fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F> + pub const fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F> where F: FnMut(&mut T::Target) -> bool, { @@ -323,7 +323,7 @@ where impl Pointers { /// Create a new set of empty pointers - pub fn new() -> Self { + pub const fn new() -> Self { Self { inner: UnsafeCell::new(PointersInner { prev: None, @@ -333,7 +333,7 @@ impl Pointers { } } - fn get_prev(&self) -> Option> { + const fn get_prev(&self) -> Option> { // SAFETY: prev is the first field in PointersInner, which is #[repr(C)]. unsafe { let inner = self.inner.get(); @@ -341,7 +341,7 @@ impl Pointers { ptr::read(prev) } } - fn get_next(&self) -> Option> { + const fn get_next(&self) -> Option> { // SAFETY: next is the second field in PointersInner, which is #[repr(C)]. unsafe { let inner = self.inner.get(); @@ -351,7 +351,7 @@ impl Pointers { } } - fn set_prev(&mut self, value: Option>) { + const fn set_prev(&mut self, value: Option>) { // SAFETY: prev is the first field in PointersInner, which is #[repr(C)]. unsafe { let inner = self.inner.get(); @@ -359,7 +359,7 @@ impl Pointers { ptr::write(prev, value); } } - fn set_next(&mut self, value: Option>) { + const fn set_next(&mut self, value: Option>) { // SAFETY: next is the second field in PointersInner, which is #[repr(C)]. unsafe { let inner = self.inner.get(); diff --git a/common/src/lock/thread_mutex.rs b/common/src/lock/thread_mutex.rs index 14f4e682664..2949a3c6c14 100644 --- a/common/src/lock/thread_mutex.rs +++ b/common/src/lock/thread_mutex.rs @@ -78,7 +78,7 @@ pub struct ThreadMutex { } impl ThreadMutex { - pub fn new(val: T) -> Self { + pub const fn new(val: T) -> Self { Self { raw: RawThreadMutex::INIT, data: UnsafeCell::new(val), From 8adcaa509fe85f79dcf0f9ce9391c899ff027848 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 12:14:44 +0300 Subject: [PATCH 12/16] compiler --- compiler/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/src/lib.rs b/compiler/src/lib.rs index 9ae5297852a..717593ac4b0 100644 --- a/compiler/src/lib.rs +++ b/compiler/src/lib.rs @@ -62,7 +62,7 @@ impl CompileError { } } - pub fn python_location(&self) -> (usize, usize) { + pub const fn python_location(&self) -> (usize, usize) { match self { Self::Codegen(codegen_error) => { if let Some(location) = &codegen_error.location { From dbf0078c778c53db3333779cc22ae4e7aef6952a Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 12:15:12 +0300 Subject: [PATCH 13/16] compiler codegen --- compiler/codegen/src/compile.rs | 4 ++-- compiler/codegen/src/string_parser.rs | 2 +- compiler/codegen/src/symboltable.rs | 6 +++--- compiler/codegen/src/unparse.rs | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/compiler/codegen/src/compile.rs b/compiler/codegen/src/compile.rs index caca71cef89..bf12e132964 100644 --- a/compiler/codegen/src/compile.rs +++ b/compiler/codegen/src/compile.rs @@ -282,7 +282,7 @@ impl Default for PatternContext { } impl PatternContext { - pub fn new() -> Self { + pub const fn new() -> Self { Self { stores: Vec::new(), allow_irrefutable: false, @@ -4118,7 +4118,7 @@ impl Compiler<'_> { code.current_block = block; } - fn set_source_range(&mut self, range: TextRange) { + const fn set_source_range(&mut self, range: TextRange) { self.current_source_range = range; } diff --git a/compiler/codegen/src/string_parser.rs b/compiler/codegen/src/string_parser.rs index 74f8e300120..ede2f118c37 100644 --- a/compiler/codegen/src/string_parser.rs +++ b/compiler/codegen/src/string_parser.rs @@ -28,7 +28,7 @@ struct StringParser { } impl StringParser { - fn new(source: Box, flags: AnyStringFlags) -> Self { + const fn new(source: Box, flags: AnyStringFlags) -> Self { Self { source, cursor: 0, diff --git a/compiler/codegen/src/symboltable.rs b/compiler/codegen/src/symboltable.rs index c1c75a5d538..2949f39a9f2 100644 --- a/compiler/codegen/src/symboltable.rs +++ b/compiler/codegen/src/symboltable.rs @@ -162,18 +162,18 @@ impl Symbol { } } - pub fn is_global(&self) -> bool { + pub const fn is_global(&self) -> bool { matches!( self.scope, SymbolScope::GlobalExplicit | SymbolScope::GlobalImplicit ) } - pub fn is_local(&self) -> bool { + pub const fn is_local(&self) -> bool { matches!(self.scope, SymbolScope::Local | SymbolScope::Cell) } - pub fn is_bound(&self) -> bool { + pub const fn is_bound(&self) -> bool { self.flags.intersects(SymbolFlags::BOUND) } } diff --git a/compiler/codegen/src/unparse.rs b/compiler/codegen/src/unparse.rs index 1ecf1f9334c..47e883da3af 100644 --- a/compiler/codegen/src/unparse.rs +++ b/compiler/codegen/src/unparse.rs @@ -32,7 +32,7 @@ struct Unparser<'a, 'b, 'c> { source: &'c SourceCode<'c>, } impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { - fn new(f: &'b mut fmt::Formatter<'a>, source: &'c SourceCode<'c>) -> Self { + const fn new(f: &'b mut fmt::Formatter<'a>, source: &'c SourceCode<'c>) -> Self { Unparser { f, source } } @@ -602,7 +602,7 @@ pub struct UnparseExpr<'a> { source: &'a SourceCode<'a>, } -pub fn unparse_expr<'a>(expr: &'a Expr, source: &'a SourceCode<'a>) -> UnparseExpr<'a> { +pub const fn unparse_expr<'a>(expr: &'a Expr, source: &'a SourceCode<'a>) -> UnparseExpr<'a> { UnparseExpr { expr, source } } From 4b125360df9f3ee02c6fdfb51df779cc6797f3c1 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 12:17:03 +0300 Subject: [PATCH 14/16] vm --- vm/src/stdlib/symtable.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vm/src/stdlib/symtable.rs b/vm/src/stdlib/symtable.rs index 6f6b02c0e08..9178006b360 100644 --- a/vm/src/stdlib/symtable.rs +++ b/vm/src/stdlib/symtable.rs @@ -170,7 +170,7 @@ mod symtable { } #[pymethod] - fn is_global(&self) -> bool { + const fn is_global(&self) -> bool { self.symbol.is_global() || (self.is_top_scope && self.symbol.is_bound()) } @@ -180,7 +180,7 @@ mod symtable { } #[pymethod] - fn is_local(&self) -> bool { + const fn is_local(&self) -> bool { self.symbol.is_local() || (self.is_top_scope && self.symbol.is_bound()) } From e55f32b84a0e228239683b85cf2e07405dd86d4b Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 12:19:54 +0300 Subject: [PATCH 15/16] cargo fmt --- common/src/encodings.rs | 6 +++++- vm/src/builtins/traceback.rs | 7 ++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/common/src/encodings.rs b/common/src/encodings.rs index 6de5e016cb2..39ca2661262 100644 --- a/common/src/encodings.rs +++ b/common/src/encodings.rs @@ -137,7 +137,11 @@ struct DecodeError<'a> { /// # Safety /// `v[..valid_up_to]` must be valid utf8 -const unsafe fn make_decode_err(v: &[u8], valid_up_to: usize, err_len: Option) -> DecodeError<'_> { +const unsafe fn make_decode_err( + v: &[u8], + valid_up_to: usize, + err_len: Option, +) -> DecodeError<'_> { let (valid_prefix, rest) = unsafe { v.split_at_unchecked(valid_up_to) }; let valid_prefix = unsafe { core::str::from_utf8_unchecked(valid_prefix) }; DecodeError { diff --git a/vm/src/builtins/traceback.rs b/vm/src/builtins/traceback.rs index 4f6fa512433..33063132c63 100644 --- a/vm/src/builtins/traceback.rs +++ b/vm/src/builtins/traceback.rs @@ -27,7 +27,12 @@ impl PyPayload for PyTraceback { #[pyclass] impl PyTraceback { - pub const fn new(next: Option>, frame: FrameRef, lasti: u32, lineno: LineNumber) -> Self { + pub const fn new( + next: Option>, + frame: FrameRef, + lasti: u32, + lineno: LineNumber, + ) -> Self { Self { next: PyMutex::new(next), frame, From eb3e2b3528c5832ad762182f1f77cf7093359586 Mon Sep 17 00:00:00 2001 From: ShaharNaveh <50263213+ShaharNaveh@users.noreply.github.com> Date: Fri, 4 Jul 2025 12:21:39 +0300 Subject: [PATCH 16/16] remove bad consts --- vm/src/stdlib/posix.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/vm/src/stdlib/posix.rs b/vm/src/stdlib/posix.rs index a6453fc032a..6220a15b8a7 100644 --- a/vm/src/stdlib/posix.rs +++ b/vm/src/stdlib/posix.rs @@ -1228,7 +1228,7 @@ pub mod module { } #[pyfunction] - const fn sync() { + fn sync() { #[cfg(not(any(target_os = "redox", target_os = "android")))] unsafe { libc::sync(); @@ -1603,32 +1603,32 @@ pub mod module { } #[pyfunction(name = "WIFSIGNALED")] - const fn wifsignaled(status: i32) -> bool { + fn wifsignaled(status: i32) -> bool { libc::WIFSIGNALED(status) } #[pyfunction(name = "WIFSTOPPED")] - const fn wifstopped(status: i32) -> bool { + fn wifstopped(status: i32) -> bool { libc::WIFSTOPPED(status) } #[pyfunction(name = "WIFEXITED")] - const fn wifexited(status: i32) -> bool { + fn wifexited(status: i32) -> bool { libc::WIFEXITED(status) } #[pyfunction(name = "WTERMSIG")] - const fn wtermsig(status: i32) -> i32 { + fn wtermsig(status: i32) -> i32 { libc::WTERMSIG(status) } #[pyfunction(name = "WSTOPSIG")] - const fn wstopsig(status: i32) -> i32 { + fn wstopsig(status: i32) -> i32 { libc::WSTOPSIG(status) } #[pyfunction(name = "WEXITSTATUS")] - const fn wexitstatus(status: i32) -> i32 { + fn wexitstatus(status: i32) -> i32 { libc::WEXITSTATUS(status) }