Name generated signature parameters the way CPython names them (#8725)

* Leave Rust-only name decoration out of a generated signature

A leading underscore marks an argument Rust sees as unused and `r#`
escapes a Rust keyword. Neither describes the parameter a Python caller
passes, and `r#` is not valid Python, so `inspect.signature()` rejects
any signature carrying one.

Reporting the bare name fixes _sre.template, select.epoll.__exit__ and
bytearray.__reduce_ex__ without touching them, and lets a method name a
parameter after a Rust keyword.

A parameter CPython itself names with a leading underscore, such as
compile's `_feature_version`, reaches Python through a FromArgs field,
which this never sees.

Assisted-by: Claude Code:claude-opus-5

* Name builtin type parameters the way CPython names them

A generated __text_signature__ reports the Rust parameter name, so a
name chosen for Rust reaches anyone reading help() or inspect. Rename
the ones CPython describes differently: list.pop's `i` becomes `index`,
list.count's `needle` becomes `value`, __format__'s `spec` becomes
`format_spec`, bytes.strip's `chars` becomes `bytes`, and
object.__reduce_ex__'s `proto` becomes `protocol`.

Left alone are the parameters CPython reports as `object` or `unused`.
Those are synthesised from the METH_* flags rather than named: CPython
reports slice.indices as ($self, object, /) while its own docstring
calls the argument len.

Assisted-by: Claude Code:claude-opus-5

* Name os parameters the way CPython names them

os.read's `n` becomes `length`, os.lseek's `how` becomes `whence`,
os.kill's `sig` becomes `signal`, os.stat's `file` becomes `path`, and
os.putenv's `key` becomes `name`, among others.

os.chmod is left alone. It reports (path, dir_fd, mode, follow_symlinks)
while the call binds mode second and takes follow_symlinks by keyword, so
the order and the kind are wrong rather than the names, which a rename
cannot fix.

os.fstatvfs is left alone too: it shares one Rust function with statvfs,
which CPython names `path`, so the two aliases cannot report different
names.

Assisted-by: Claude Code:claude-opus-5

* Name sys parameters the way CPython names them

sys.excepthook's (exc_type, exc_val, exc_tb) become (exctype, value,
traceback), sys._getframe's `offset` becomes `depth`, sys.intern's `s`
becomes `string`, and sys.settrace's `tracefunc` becomes `function`.

sys._clear_type_descriptors takes the name CPython gives it, which
Rust spells r#type.

Assisted-by: Claude Code:claude-opus-5

* Name vm stdlib parameters the way CPython names them

deque.rotate's `mid` becomes `n`, deque.extend's `iter` becomes
`iterable`, _sre.ascii_tolower's `ch` becomes `character`,
_operator.neg's `pos` becomes `a`, signal.alarm's `time` becomes
`seconds`, and codecs.register_error's `name` becomes `errors`.

gc.collect and charmap_build keep theirs. Their argument is a FromArgs
struct or a PosArgs bundle, so the reported name is the binding rather
than a parameter, and renaming the binding would only disguise that.

Assisted-by: Claude Code:claude-opus-5

* Name stdlib crate parameters the way CPython names them

unicodedata.category's `character` becomes `chr`, math.isqrt's `x`
becomes `n`, cmath.polar's `x` becomes `z`, struct.calcsize's `fmt`
becomes `format`, binascii.crc32's `init` becomes `crc`, zlib.adler32's
`begin_state` becomes `value`, and array.append's `x` becomes `v`.

array.fromunicode's parameter is `ustr`, which cspell has to be told
about.

array.__deepcopy__ keeps `_memo`, which the generator now reports as
`memo`; CPython calls it `unused`, a name synthesised from METH_O rather
than chosen.

Assisted-by: Claude Code:claude-opus-5

* Name BaseExceptionGroup.split's parameter the way CPython names it

CPython calls the argument of split and subgroup `matcher_value`.

Assisted-by: Claude Code:claude-opus-5

* Strip a generated parameter name with unraw and one prefix check

syn already removes r# through IdentExt::unraw, the way from_args.rs
does for a field name. The empty-name guard never ran: a bare `_` is
Pat::Wild, which func_sig has already refused.

Assisted-by: Claude Code:claude-fable-5-1

* Take object and unused from CPython's Clinic signatures

CPython also falls back to these names for METH_O, but list.append and
insert, set.add, discard and remove, _weakref.getweakrefcount and
getweakrefs, sys.displayhook and getrefcount, and array.__deepcopy__
get them from an Argument Clinic signature. The earlier commit that
kept array.__deepcopy__'s `_memo` was wrong to call `unused`
synthesised.

test_pydoc's set.add summary-line tests now pass.

Assisted-by: Claude Code:claude-opus-5
This commit is contained in:
Hanjeong Lee authored and GitHub committed 2026-09-17 20:10:16 +09:00
1 parent 3191ecaf38
commit df653cea69
33 files changed
+333 -325

No files matched your search

+1
View File
@@ -119,6 +119,7 @@
"TESTFN", "TESTFN",
"TZPATH", "TZPATH",
"unraisable", "unraisable",
"ustr",
"wasi", "wasi",
"weaked", "weaked",
// unix // unix
-2
View File
@@ -1604,12 +1604,10 @@ class TestDescriptions(unittest.TestCase):
self.assertEqual(self._get_summary_line(''.lower), self.assertEqual(self._get_summary_line(''.lower),
"lower() method of builtins.str instance") "lower() method of builtins.str instance")
@unittest.expectedFailure # TODO: RUSTPYTHON
def test_unbound_builtin_method_o(self): def test_unbound_builtin_method_o(self):
self.assertEqual(self._get_summary_line(set.add), self.assertEqual(self._get_summary_line(set.add),
"add(self, object, /) unbound builtins.set method") "add(self, object, /) unbound builtins.set method")
@unittest.expectedFailure # TODO: RUSTPYTHON
def test_bound_builtin_method_o(self): def test_bound_builtin_method_o(self):
self.assertEqual(self._get_summary_line(set().add), self.assertEqual(self._get_summary_line(set().add),
"add(object, /) method of builtins.set instance") "add(object, /) method of builtins.set instance")
+5 -3
View File
@@ -2,7 +2,7 @@ use itertools::Itertools;
use proc_macro2::{Span, TokenStream}; use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, quote}; use quote::{ToTokens, quote};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use syn::{Attribute, FnArg, Ident, Result, Signature, UseTree, spanned::Spanned}; use syn::{Attribute, FnArg, Ident, Result, Signature, UseTree, ext::IdentExt, spanned::Spanned};
use syn_ext::{ use syn_ext::{
ext::{AttributeExt as SynAttributeExt, *}, ext::{AttributeExt as SynAttributeExt, *},
types::*, types::*,
@@ -868,11 +868,13 @@ fn func_sig(sig: &Signature, mut implicit_self: Option<&str>) -> Option<String>
let syn::Pat::Ident(pat) = arg.pat.as_ref() else { let syn::Pat::Ident(pat) = arg.pat.as_ref() else {
return None; return None;
}; };
let ident = pat.ident.to_string(); let ident = pat.ident.unraw().to_string();
if ident == "vm" { if ident == "vm" {
unreachable!("type &VirtualMachine(`{ty}`) must be filtered already"); unreachable!("type &VirtualMachine(`{ty}`) must be filtered already");
} }
params.push(ident); // A leading `_` only marks the argument unused in Rust. A parameter whose
// Python name really starts with `_` has to be a FromArgs field instead.
params.push(ident.strip_prefix('_').unwrap_or(&ident).to_owned());
} }
Some(params.join(", ")) Some(params.join(", "))
} }
+22 -22
View File
@@ -798,8 +798,8 @@ pub mod array {
} }
#[pymethod] #[pymethod]
fn append(zelf: &Py<Self>, x: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn append(zelf: &Py<Self>, v: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
zelf.try_resizable(vm)?.push(x, vm) zelf.try_resizable(vm)?.push(v, vm)
} }
#[pymethod] #[pymethod]
@@ -814,24 +814,24 @@ pub mod array {
} }
#[pymethod] #[pymethod]
fn count(&self, x: PyObjectRef, vm: &VirtualMachine) -> usize { fn count(&self, v: PyObjectRef, vm: &VirtualMachine) -> usize {
self.read().count(x, vm) self.read().count(v, vm)
} }
#[pymethod] #[pymethod]
fn remove(zelf: &Py<Self>, x: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn remove(zelf: &Py<Self>, v: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
zelf.try_resizable(vm)?.remove(x, vm) zelf.try_resizable(vm)?.remove(v, vm)
} }
#[pymethod] #[pymethod]
fn extend(zelf: &Py<Self>, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn extend(zelf: &Py<Self>, bb: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let mut w = zelf.try_resizable(vm)?; let mut w = zelf.try_resizable(vm)?;
if zelf.is(&obj) { if zelf.is(&bb) {
w.imul(2, vm) w.imul(2, vm)
} else if let Some(array) = obj.downcast_ref::<Self>() { } else if let Some(array) = bb.downcast_ref::<Self>() {
w.iadd(&array.read(), vm) w.iadd(&array.read(), vm)
} else { } else {
let iter = ArgIterable::try_from_object(vm, obj)?; let iter = ArgIterable::try_from_object(vm, bb)?;
// zelf.extend_from_iterable(iter, vm) // zelf.extend_from_iterable(iter, vm)
for obj in iter.iter(vm)? { for obj in iter.iter(vm)? {
w.push(obj?, vm)?; w.push(obj?, vm)?;
@@ -883,11 +883,11 @@ pub mod array {
} }
#[pymethod] #[pymethod]
fn fromunicode(zelf: &Py<Self>, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn fromunicode(zelf: &Py<Self>, ustr: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let wtf8: &Wtf8 = obj.try_to_value(vm).map_err(|_| { let wtf8: &Wtf8 = ustr.try_to_value(vm).map_err(|_| {
vm.new_type_error(format!( vm.new_type_error(format!(
"fromunicode() argument must be str, not {}", "fromunicode() argument must be str, not {}",
obj.class().name() ustr.class().name()
)) ))
})?; })?;
if !matches!(zelf.read().typecode(), 'u' | 'w') { if !matches!(zelf.read().typecode(), 'u' | 'w') {
@@ -924,15 +924,15 @@ pub mod array {
} }
#[pymethod] #[pymethod]
fn frombytes(&self, b: ArgBytesLike, vm: &VirtualMachine) -> PyResult<()> { fn frombytes(&self, buffer: ArgBytesLike, vm: &VirtualMachine) -> PyResult<()> {
// The source is read as bytes, so items of any other width would // The source is read as bytes, so items of any other width would
// be reinterpreted rather than appended. // be reinterpreted rather than appended.
if b.itemsize() != 1 { if buffer.itemsize() != 1 {
return Err(vm.new_type_error("a bytes-like object is required")); return Err(vm.new_type_error("a bytes-like object is required"));
} }
let b = b.borrow_buf(); let buffer = buffer.borrow_buf();
let itemsize = self.read().itemsize(); let itemsize = self.read().itemsize();
self._from_bytes(&b, itemsize, vm) self._from_bytes(&buffer, itemsize, vm)
} }
#[pymethod] #[pymethod]
@@ -977,9 +977,9 @@ pub mod array {
} }
#[pymethod] #[pymethod]
fn insert(zelf: &Py<Self>, i: isize, x: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn insert(zelf: &Py<Self>, i: isize, v: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let mut w = zelf.try_resizable(vm)?; let mut w = zelf.try_resizable(vm)?;
w.insert(i, x, vm) w.insert(i, v, vm)
} }
#[pymethod] #[pymethod]
@@ -1049,7 +1049,7 @@ pub mod array {
} }
#[pymethod] #[pymethod]
fn __deepcopy__(&self, _memo: PyObjectRef) -> Self { fn __deepcopy__(&self, _unused: PyObjectRef) -> Self {
self.__copy__() self.__copy__()
} }
@@ -1198,10 +1198,10 @@ pub mod array {
#[pymethod] #[pymethod]
fn __reduce_ex__( fn __reduce_ex__(
zelf: &Py<Self>, zelf: &Py<Self>,
proto: usize, value: usize,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<(PyObjectRef, PyTupleRef, Option<PyDictRef>)> { ) -> PyResult<(PyObjectRef, PyTupleRef, Option<PyDictRef>)> {
if proto < 3 { if value < 3 {
return Self::__reduce__(zelf, vm); return Self::__reduce__(zelf, vm);
} }
let array = zelf.read(); let array = zelf.read();
+10 -9
View File
@@ -56,20 +56,21 @@ mod decl {
#[pyfunction(name = "a2b_hex")] #[pyfunction(name = "a2b_hex")]
#[pyfunction] #[pyfunction]
fn unhexlify(data: ArgAsciiBuffer, vm: &VirtualMachine) -> PyResult<Vec<u8>> { fn unhexlify(hexstr: ArgAsciiBuffer, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
data.with_ref(binascii::unhexlify) hexstr
.with_ref(binascii::unhexlify)
.map_err(|e| new_binascii_error(e, vm)) .map_err(|e| new_binascii_error(e, vm))
} }
#[pyfunction] #[pyfunction]
pub(crate) fn crc32(data: ArgBytesLike, init: OptionalArg<PyIntRef>) -> u32 { pub(crate) fn crc32(data: ArgBytesLike, crc: OptionalArg<PyIntRef>) -> u32 {
let init = init.map_or(0, |i| i.as_u32_mask()); let crc = crc.map_or(0, |i| i.as_u32_mask());
data.with_ref(|bytes| binascii::crc32(bytes, init)) data.with_ref(|bytes| binascii::crc32(bytes, crc))
} }
#[pyfunction] #[pyfunction]
pub(crate) fn crc_hqx(data: ArgBytesLike, init: PyIntRef) -> u32 { pub(crate) fn crc_hqx(data: ArgBytesLike, crc: PyIntRef) -> u32 {
data.with_ref(|bytes| binascii::crc_hqx(bytes, init.as_u32_mask())) data.with_ref(|bytes| binascii::crc_hqx(bytes, crc.as_u32_mask()))
} }
#[derive(FromArgs)] #[derive(FromArgs)]
@@ -136,8 +137,8 @@ mod decl {
} }
#[pyfunction] #[pyfunction]
fn a2b_uu(s: ArgAsciiBuffer, vm: &VirtualMachine) -> PyResult<Vec<u8>> { fn a2b_uu(data: ArgAsciiBuffer, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
s.with_ref(binascii::a2b_uu) data.with_ref(binascii::a2b_uu)
.map_err(|e| new_binascii_error(e, vm)) .map_err(|e| new_binascii_error(e, vm))
} }
+2 -2
View File
@@ -32,8 +32,8 @@ mod cmath {
} }
#[pyfunction] #[pyfunction]
fn polar(x: ArgIntoComplex, vm: &VirtualMachine) -> PyResult<(f64, f64)> { fn polar(z: ArgIntoComplex, vm: &VirtualMachine) -> PyResult<(f64, f64)> {
pymath::cmath::polar(x.into_complex()).map_err(|err| pymath_exception(err, vm)) pymath::cmath::polar(z.into_complex()).map_err(|err| pymath_exception(err, vm))
} }
#[pyfunction] #[pyfunction]
+5 -5
View File
@@ -762,8 +762,8 @@ mod math {
// Integer functions: // Integer functions:
#[pyfunction] #[pyfunction]
fn isqrt(x: ArgIndex, vm: &VirtualMachine) -> PyResult<BigInt> { fn isqrt(n: ArgIndex, vm: &VirtualMachine) -> PyResult<BigInt> {
let value = x.into_int_ref(); let value = n.into_int_ref();
pymath::math::integer::isqrt(value.as_bigint()) pymath::math::integer::isqrt(value.as_bigint())
.map_err(|_| vm.new_value_error("isqrt() argument must be nonnegative")) .map_err(|_| vm.new_value_error("isqrt() argument must be nonnegative"))
} }
@@ -791,12 +791,12 @@ mod math {
} }
#[pyfunction] #[pyfunction]
fn factorial(x: PyIntRef, vm: &VirtualMachine) -> PyResult<BigInt> { fn factorial(n: PyIntRef, vm: &VirtualMachine) -> PyResult<BigInt> {
// Check for negative before overflow - negative values are always invalid // Check for negative before overflow - negative values are always invalid
if x.as_bigint().is_negative() { if n.as_bigint().is_negative() {
return Err(vm.new_value_error("factorial() not defined for negative values")); return Err(vm.new_value_error("factorial() not defined for negative values"));
} }
let n: i64 = x.try_to_primitive(vm).map_err(|_| { let n: i64 = n.try_to_primitive(vm).map_err(|_| {
vm.new_overflow_error("factorial() argument should not exceed 9223372036854775807") vm.new_overflow_error("factorial() argument should not exceed 9223372036854775807")
})?; })?;
pymath::math::integer::factorial(n) pymath::math::integer::factorial(n)
+8 -8
View File
@@ -144,11 +144,11 @@ pub(crate) mod _struct {
#[pyfunction] #[pyfunction]
fn unpack( fn unpack(
fmt: IntoStructFormatBytes, format: IntoStructFormatBytes,
buffer: ArgBytesLike, buffer: ArgBytesLike,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<PyTupleRef> { ) -> PyResult<PyTupleRef> {
let format_spec = fmt.format_spec(vm)?; let format_spec = format.format_spec(vm)?;
buffer.with_ref(|buf| format_spec.unpack(buf, vm)) buffer.with_ref(|buf| format_spec.unpack(buf, vm))
} }
@@ -239,17 +239,17 @@ pub(crate) mod _struct {
#[pyfunction] #[pyfunction]
fn iter_unpack( fn iter_unpack(
fmt: IntoStructFormatBytes, format: IntoStructFormatBytes,
buffer: ArgBytesLike, buffer: ArgBytesLike,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<UnpackIterator> { ) -> PyResult<UnpackIterator> {
let format_spec = fmt.format_spec(vm)?; let format_spec = format.format_spec(vm)?;
UnpackIterator::with_buffer(vm, format_spec, buffer) UnpackIterator::with_buffer(vm, format_spec, buffer)
} }
#[pyfunction] #[pyfunction]
fn calcsize(fmt: IntoStructFormatBytes, vm: &VirtualMachine) -> PyResult<usize> { fn calcsize(format: IntoStructFormatBytes, vm: &VirtualMachine) -> PyResult<usize> {
Ok(fmt.format_spec(vm)?.size) Ok(format.format_spec(vm)?.size)
} }
/// What a `Struct` is once a format has been read into it. Held apart /// What a `Struct` is once a format has been read into it. Held apart
@@ -342,9 +342,9 @@ pub(crate) mod _struct {
} }
#[pymethod] #[pymethod]
fn unpack(&self, data: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyTupleRef> { fn unpack(&self, buffer: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
let inner = self.ready(vm)?; let inner = self.ready(vm)?;
data.with_ref(|buf| inner.spec.unpack(buf, vm)) buffer.with_ref(|buf| inner.spec.unpack(buf, vm))
} }
#[pymethod] #[pymethod]
+20 -31
View File
@@ -93,9 +93,8 @@ mod unicodedata {
#[pyclass(flags(DISALLOW_INSTANTIATION))] #[pyclass(flags(DISALLOW_INSTANTIATION))]
impl Ucd { impl Ucd {
#[pymethod] #[pymethod]
fn category(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> { fn category(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> {
self.extract_char(character, vm) self.extract_char(chr, vm).map(|c| self.inner.category(c))
.map(|c| self.inner.category(c))
} }
#[pymethod] #[pymethod]
@@ -118,11 +117,11 @@ mod unicodedata {
#[pymethod] #[pymethod]
fn name( fn name(
&self, &self,
character: PyStrRef, chr: PyStrRef,
default: OptionalArg<PyObjectRef>, default: OptionalArg<PyObjectRef>,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult { ) -> PyResult {
if let Some(name) = self.extract_char(character, vm)?.to_char().and_then(|ch| { if let Some(name) = self.extract_char(chr, vm)?.to_char().and_then(|ch| {
self.inner self.inner
.membership(ch) .membership(ch)
.then(|| unicode_core::character_name(ch)) .then(|| unicode_core::character_name(ch))
@@ -134,22 +133,14 @@ mod unicodedata {
} }
#[pymethod] #[pymethod]
fn bidirectional( fn bidirectional(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> {
&self, self.extract_char(chr, vm)
character: PyStrRef,
vm: &VirtualMachine,
) -> PyResult<&'static str> {
self.extract_char(character, vm)
.map(|c| self.inner.bidirectional(c)) .map(|c| self.inner.bidirectional(c))
} }
#[pymethod] #[pymethod]
fn east_asian_width( fn east_asian_width(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> {
&self, self.extract_char(chr, vm)
character: PyStrRef,
vm: &VirtualMachine,
) -> PyResult<&'static str> {
self.extract_char(character, vm)
.map(|c| self.inner.east_asian_width(c)) .map(|c| self.inner.east_asian_width(c))
} }
@@ -164,31 +155,29 @@ mod unicodedata {
} }
#[pymethod] #[pymethod]
fn mirrored(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<i32> { fn mirrored(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<i32> {
self.extract_char(character, vm) self.extract_char(chr, vm).map(|c| self.inner.mirrored(c))
.map(|c| self.inner.mirrored(c))
} }
#[pymethod] #[pymethod]
fn combining(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<u8> { fn combining(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<u8> {
self.extract_char(character, vm) self.extract_char(chr, vm).map(|c| self.inner.combining(c))
.map(|c| self.inner.combining(c))
} }
#[pymethod] #[pymethod]
fn decomposition(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<String> { fn decomposition(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
self.extract_char(character, vm) self.extract_char(chr, vm)
.map(|c| self.inner.decomposition(c)) .map(|c| self.inner.decomposition(c))
} }
#[pymethod] #[pymethod]
fn digit( fn digit(
&self, &self,
character: PyStrRef, chr: PyStrRef,
default: OptionalArg<PyObjectRef>, default: OptionalArg<PyObjectRef>,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<Option<PyObjectRef>> { ) -> PyResult<Option<PyObjectRef>> {
let ch = self.extract_char(character, vm)?; let ch = self.extract_char(chr, vm)?;
self.inner self.inner
.digit(ch) .digit(ch)
.map(|value| vm.ctx.new_int(value).into()) .map(|value| vm.ctx.new_int(value).into())
@@ -200,11 +189,11 @@ mod unicodedata {
#[pymethod] #[pymethod]
fn decimal( fn decimal(
&self, &self,
character: PyStrRef, chr: PyStrRef,
default: OptionalArg<PyObjectRef>, default: OptionalArg<PyObjectRef>,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<Option<PyObjectRef>> { ) -> PyResult<Option<PyObjectRef>> {
let ch = self.extract_char(character, vm)?; let ch = self.extract_char(chr, vm)?;
self.inner self.inner
.decimal(ch) .decimal(ch)
.map(|value| vm.ctx.new_int(value).into()) .map(|value| vm.ctx.new_int(value).into())
@@ -216,11 +205,11 @@ mod unicodedata {
#[pymethod] #[pymethod]
fn numeric( fn numeric(
&self, &self,
character: PyStrRef, chr: PyStrRef,
default: OptionalArg<PyObjectRef>, default: OptionalArg<PyObjectRef>,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<Option<PyObjectRef>> { ) -> PyResult<Option<PyObjectRef>> {
let ch = self.extract_char(character, vm)?; let ch = self.extract_char(chr, vm)?;
self.inner self.inner
.numeric(ch) .numeric(ch)
.map(|value| vm.ctx.new_float(value).into()) .map(|value| vm.ctx.new_float(value).into())
+5 -5
View File
@@ -50,18 +50,18 @@ mod zlib {
} }
#[pyfunction] #[pyfunction]
fn adler32(data: ArgBytesLike, begin_state: OptionalArg<PyIntRef>) -> u32 { fn adler32(data: ArgBytesLike, value: OptionalArg<PyIntRef>) -> u32 {
data.with_ref(|data| { data.with_ref(|data| {
let begin_state = begin_state.map_or(1, |i| i.as_u32_mask()); let value = value.map_or(1, |i| i.as_u32_mask());
let mut hasher = Adler32::from_value(begin_state); let mut hasher = Adler32::from_value(value);
hasher.update_buffer(data); hasher.update_buffer(data);
hasher.hash() hasher.hash()
}) })
} }
#[pyfunction] #[pyfunction]
fn crc32(data: ArgBytesLike, begin_state: OptionalArg<PyIntRef>) -> u32 { fn crc32(data: ArgBytesLike, value: OptionalArg<PyIntRef>) -> u32 {
crate::binascii::crc32(data, begin_state) crate::binascii::crc32(data, value)
} }
#[derive(FromArgs)] #[derive(FromArgs)]
+6 -2
View File
@@ -106,9 +106,13 @@ impl Constructor for PyBool {
#[pyclass(with(Constructor, AsNumber, Representable), flags(_MATCH_SELF))] #[pyclass(with(Constructor, AsNumber, Representable), flags(_MATCH_SELF))]
impl PyBool { impl PyBool {
#[pymethod] #[pymethod]
fn __format__(zelf: PyObjectRef, spec: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<String> { fn __format__(
zelf: PyObjectRef,
format_spec: PyUtf8StrRef,
vm: &VirtualMachine,
) -> PyResult<String> {
let new_bool = zelf.try_to_bool(vm)?; let new_bool = zelf.try_to_bool(vm)?;
FormatSpec::parse(spec.as_str()) FormatSpec::parse(format_spec.as_str())
.and_then(|format_spec| format_spec.format_bool(new_bool)) .and_then(|format_spec| format_spec.format_bool(new_bool))
.map_err(|err| err.into_pyexception(vm)) .map_err(|err| err.into_pyexception(vm))
} }
+21 -21
View File
@@ -353,11 +353,11 @@ impl PyByteArray {
} }
#[pymethod] #[pymethod]
fn join(&self, iter: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> { fn join(&self, iterable_of_bytes: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
// Driving the iterable runs Python, which can reach this bytearray, // Driving the iterable runs Python, which can reach this bytearray,
// so the separator is taken by value rather than left borrowed. // so the separator is taken by value rather than left borrowed.
let separator = self.inner().clone(); let separator = self.inner().clone();
Ok(separator.join(iter, vm)?.into()) Ok(separator.join(iterable_of_bytes, vm)?.into())
} }
#[pymethod] #[pymethod]
@@ -428,8 +428,8 @@ impl PyByteArray {
} }
#[pymethod] #[pymethod]
fn strip(&self, chars: OptionalOption<PyBytesInner>) -> Self { fn strip(&self, bytes: OptionalOption<PyBytesInner>) -> Self {
self.inner().strip(chars).into() self.inner().strip(bytes).into()
} }
#[pymethod] #[pymethod]
@@ -588,8 +588,8 @@ impl Py<PyByteArray> {
} }
#[pymethod] #[pymethod]
fn insert(&self, index: isize, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn insert(&self, index: isize, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let value = value_from_object(vm, &object)?; let value = value_from_object(vm, &item)?;
let elements = &mut self.try_resizable(vm)?.elements; let elements = &mut self.try_resizable(vm)?.elements;
let index = elements.saturate_index(index); let index = elements.saturate_index(index);
elements.insert(index, value); elements.insert(index, value);
@@ -597,39 +597,39 @@ impl Py<PyByteArray> {
} }
#[pymethod] #[pymethod]
fn append(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn append(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let value = value_from_object(vm, &object)?; let value = value_from_object(vm, &item)?;
self.try_resizable(vm)?.elements.push(value); self.try_resizable(vm)?.elements.push(value);
Ok(()) Ok(())
} }
#[pymethod] #[pymethod]
fn remove(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn remove(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let value = value_from_object(vm, &object)?; let byte = value_from_object(vm, &value)?;
let elements = &mut self.try_resizable(vm)?.elements; let elements = &mut self.try_resizable(vm)?.elements;
let index = elements let index = elements
.find_byte(value) .find_byte(byte)
.ok_or_else(|| vm.new_value_error("value not found in bytearray"))?; .ok_or_else(|| vm.new_value_error("value not found in bytearray"))?;
elements.remove(index); elements.remove(index);
Ok(()) Ok(())
} }
#[pymethod] #[pymethod]
fn extend(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn extend(&self, iterable_of_ints: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if self.is(&object) { if self.is(&iterable_of_ints) {
return PyByteArray::irepeat(self, 2, vm); return PyByteArray::irepeat(self, 2, vm);
} }
// bytearray_setslice keeps the export alive across the resize, so a value // bytearray_setslice keeps the export alive across the resize, so a value
// looking at this bytearray is what stops it from growing. // looking at this bytearray is what stops it from growing.
let buffer = object let buffer = iterable_of_ints
.check_buffer() .check_buffer()
.then(|| { .then(|| {
PyBuffer::from_object(vm, &object, BufferFlags::SIMPLE).map_err(|_| { PyBuffer::from_object(vm, &iterable_of_ints, BufferFlags::SIMPLE).map_err(|_| {
// What an exporter refuses to hand out leaves the value simply // What an exporter refuses to hand out leaves the value simply
// not usable here, whatever the exporter's own complaint was. // not usable here, whatever the exporter's own complaint was.
vm.new_type_error(format!( vm.new_type_error(format!(
"can't set bytearray slice from {}", "can't set bytearray slice from {}",
object.class().name() iterable_of_ints.class().name()
)) ))
}) })
}) })
@@ -641,7 +641,7 @@ impl Py<PyByteArray> {
vm.new_buffer_error("non-contiguous buffer is not a bytes-like object") vm.new_buffer_error("non-contiguous buffer is not a bytes-like object")
})? })?
.to_vec(), .to_vec(),
None => bytearray_extend_from_object(vm, &object)?, None => bytearray_extend_from_object(vm, &iterable_of_ints)?,
}; };
self.try_resizable(vm)?.elements.extend(items); self.try_resizable(vm)?.elements.extend(items);
Ok(()) Ok(())
@@ -676,9 +676,9 @@ impl Py<PyByteArray> {
#[pyclass] #[pyclass]
impl PyRef<PyByteArray> { impl PyRef<PyByteArray> {
#[pymethod] #[pymethod]
fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self { fn lstrip(self, bytes: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
let inner = self.inner(); let inner = self.inner();
let stripped = inner.lstrip(chars); let stripped = inner.lstrip(bytes);
let elements = &inner.elements; let elements = &inner.elements;
if stripped == elements { if stripped == elements {
drop(inner); drop(inner);
@@ -689,9 +689,9 @@ impl PyRef<PyByteArray> {
} }
#[pymethod] #[pymethod]
fn rstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self { fn rstrip(self, bytes: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
let inner = self.inner(); let inner = self.inner();
let stripped = inner.rstrip(chars); let stripped = inner.rstrip(bytes);
let elements = &inner.elements; let elements = &inner.elements;
if stripped == elements { if stripped == elements {
drop(inner); drop(inner);
+8 -8
View File
@@ -356,8 +356,8 @@ impl PyBytes {
} }
#[pymethod] #[pymethod]
fn join(&self, iter: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> { fn join(&self, iterable_of_bytes: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
Ok(self.inner.join(iter, vm)?.into()) Ok(self.inner.join(iterable_of_bytes, vm)?.into())
} }
#[pymethod] #[pymethod]
@@ -426,8 +426,8 @@ impl PyBytes {
} }
#[pymethod] #[pymethod]
fn strip(&self, chars: OptionalOption<PyBytesInner>) -> Self { fn strip(&self, bytes: OptionalOption<PyBytesInner>) -> Self {
self.inner.strip(chars).into() self.inner.strip(bytes).into()
} }
#[pymethod] #[pymethod]
@@ -582,8 +582,8 @@ impl PyRef<PyBytes> {
} }
#[pymethod] #[pymethod]
fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self { fn lstrip(self, bytes: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
let stripped = self.inner.lstrip(chars); let stripped = self.inner.lstrip(bytes);
if stripped == self.as_bytes() { if stripped == self.as_bytes() {
self self
} else { } else {
@@ -592,8 +592,8 @@ impl PyRef<PyBytes> {
} }
#[pymethod] #[pymethod]
fn rstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self { fn rstrip(self, bytes: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
let stripped = self.inner.rstrip(chars); let stripped = self.inner.rstrip(bytes);
if stripped == self.as_bytes() { if stripped == self.as_bytes() {
self self
} else { } else {
+7 -3
View File
@@ -563,13 +563,17 @@ impl PyComplex {
} }
#[pymethod] #[pymethod]
fn __format__(zelf: &Py<Self>, spec: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<Wtf8Buf> { fn __format__(
zelf: &Py<Self>,
format_spec: PyUtf8StrRef,
vm: &VirtualMachine,
) -> PyResult<Wtf8Buf> {
// Empty format spec: equivalent to str(self) // Empty format spec: equivalent to str(self)
if spec.is_empty() { if format_spec.is_empty() {
return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned()); return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned());
} }
let format_spec = let format_spec =
FormatSpec::parse(spec.as_str()).map_err(|err| err.into_pyexception(vm))?; FormatSpec::parse(format_spec.as_str()).map_err(|err| err.into_pyexception(vm))?;
let result = if format_spec.has_locale_format() { let result = if format_spec.has_locale_format() {
let locale = crate::format::get_locale_info(); let locale = crate::format::get_locale_info();
format_spec.format_complex_locale(&zelf.value, &locale) format_spec.format_complex_locale(&zelf.value, &locale)
+7 -3
View File
@@ -245,13 +245,17 @@ pub fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult<f64>
)] )]
impl PyFloat { impl PyFloat {
#[pymethod] #[pymethod]
fn __format__(zelf: &Py<Self>, spec: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<Wtf8Buf> { fn __format__(
zelf: &Py<Self>,
format_spec: PyUtf8StrRef,
vm: &VirtualMachine,
) -> PyResult<Wtf8Buf> {
// Empty format spec: equivalent to str(self) // Empty format spec: equivalent to str(self)
if spec.is_empty() { if format_spec.is_empty() {
return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned()); return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned());
} }
let format_spec = let format_spec =
FormatSpec::parse(spec.as_str()).map_err(|err| err.into_pyexception(vm))?; FormatSpec::parse(format_spec.as_str()).map_err(|err| err.into_pyexception(vm))?;
let result = if format_spec.has_locale_format() { let result = if format_spec.has_locale_format() {
let locale = crate::format::get_locale_info(); let locale = crate::format::get_locale_info();
format_spec.format_float_locale(zelf.value, &locale) format_spec.format_float_locale(zelf.value, &locale)
+7 -3
View File
@@ -524,13 +524,17 @@ impl PyInt {
} }
#[pymethod] #[pymethod]
fn __format__(zelf: &Py<Self>, spec: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<Wtf8Buf> { fn __format__(
zelf: &Py<Self>,
format_spec: PyUtf8StrRef,
vm: &VirtualMachine,
) -> PyResult<Wtf8Buf> {
// Empty format spec on a subclass: equivalent to str(self) // Empty format spec on a subclass: equivalent to str(self)
if spec.is_empty() && !zelf.class().is(vm.ctx.types.int_type) { if format_spec.is_empty() && !zelf.class().is(vm.ctx.types.int_type) {
return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned()); return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned());
} }
let format_spec = let format_spec =
FormatSpec::parse(spec.as_str()).map_err(|err| err.into_pyexception(vm))?; FormatSpec::parse(format_spec.as_str()).map_err(|err| err.into_pyexception(vm))?;
if format_spec.is_decimal_int_format() { if format_spec.is_decimal_int_format() {
check_int_to_str_digits(&zelf.value, vm)?; check_int_to_str_digits(&zelf.value, vm)?;
} }
+19 -18
View File
@@ -182,26 +182,27 @@ pub type PyListRef = PyRef<PyList>;
)] )]
impl PyList { impl PyList {
#[pymethod] #[pymethod]
pub(crate) fn append(&self, x: PyObjectRef) { pub(crate) fn append(&self, object: PyObjectRef) {
self.borrow_vec_mut().push(x); self.borrow_vec_mut().push(object);
} }
#[pymethod] #[pymethod]
pub(crate) fn extend(&self, x: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { pub(crate) fn extend(&self, iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
// What is already here decides whether the iterable's length hint is // What is already here decides whether the iterable's length hint is
// believable, so it goes along with the request for the elements. It is // believable, so it goes along with the request for the elements. It is
// counted where `list_extend()` reads `Py_SIZE(self)`, after the // counted where `list_extend()` reads `Py_SIZE(self)`, after the
// iterable has answered, because answering runs code that can change it. // iterable has answered, because answering runs code that can change it.
let mut new_elements = vm.extract_elements_sized(&x, &|| self.borrow_vec().len(), Ok)?; let mut new_elements =
vm.extract_elements_sized(&iterable, &|| self.borrow_vec().len(), Ok)?;
self.borrow_vec_mut().append(&mut new_elements); self.borrow_vec_mut().append(&mut new_elements);
Ok(()) Ok(())
} }
#[pymethod] #[pymethod]
pub(crate) fn insert(&self, position: isize, element: PyObjectRef) { pub(crate) fn insert(&self, index: isize, object: PyObjectRef) {
let mut elements = self.borrow_vec_mut(); let mut elements = self.borrow_vec_mut();
let position = elements.saturate_index(position); let index = elements.saturate_index(index);
elements.insert(position, element); elements.insert(index, object);
} }
fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult<PyRef<Self>> { fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
@@ -331,8 +332,8 @@ impl PyList {
} }
#[pymethod] #[pymethod]
fn count(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> { fn count(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
self.mut_count(vm, &needle) self.mut_count(vm, &value)
} }
pub(crate) fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> { pub(crate) fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
@@ -356,24 +357,24 @@ impl PyList {
} }
#[pymethod] #[pymethod]
fn pop(&self, i: OptionalArg<isize>, vm: &VirtualMachine) -> PyResult { fn pop(&self, index: OptionalArg<isize>, vm: &VirtualMachine) -> PyResult {
let mut i = i.into_option().unwrap_or(-1); let mut index = index.into_option().unwrap_or(-1);
let mut elements = self.borrow_vec_mut(); let mut elements = self.borrow_vec_mut();
if i < 0 { if index < 0 {
i += elements.len() as isize; index += elements.len() as isize;
} }
if elements.is_empty() { if elements.is_empty() {
Err(vm.new_index_error("pop from empty list")) Err(vm.new_index_error("pop from empty list"))
} else if i < 0 || i as usize >= elements.len() { } else if index < 0 || index as usize >= elements.len() {
Err(vm.new_index_error("pop index out of range")) Err(vm.new_index_error("pop index out of range"))
} else { } else {
Ok(elements.remove(i as usize)) Ok(elements.remove(index as usize))
} }
} }
#[pymethod] #[pymethod]
fn remove(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn remove(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let index = self.mut_index(vm, &needle)?; let index = self.mut_index(vm, &value)?;
if let Some(index) = index.into() { if let Some(index) = index.into() {
// defer delete out of borrow // defer delete out of borrow
@@ -384,7 +385,7 @@ impl PyList {
drop(removed); drop(removed);
Ok(()) Ok(())
} else { } else {
Err(vm.new_value_error(format!("'{}' is not in list", needle.str(vm)?))) Err(vm.new_value_error(format!("'{}' is not in list", value.str(vm)?)))
} }
} }
+2 -2
View File
@@ -473,7 +473,7 @@ impl PyBaseObject {
} }
#[pymethod] #[pymethod]
fn __reduce_ex__(zelf: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult { fn __reduce_ex__(zelf: PyObjectRef, protocol: usize, vm: &VirtualMachine) -> PyResult {
let __reduce__ = identifier!(vm, __reduce__); let __reduce__ = identifier!(vm, __reduce__);
if let Some(reduce) = vm.get_attribute_opt(zelf.clone(), __reduce__)? { if let Some(reduce) = vm.get_attribute_opt(zelf.clone(), __reduce__)? {
let object_reduce = vm.ctx.types.object_type.get_attr(__reduce__).unwrap(); let object_reduce = vm.ctx.types.object_type.get_attr(__reduce__).unwrap();
@@ -483,7 +483,7 @@ impl PyBaseObject {
return reduce.call((), vm); return reduce.call((), vm);
} }
} }
common_reduce(zelf, proto, vm) common_reduce(zelf, protocol, vm)
} }
#[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")]
+6 -6
View File
@@ -776,18 +776,18 @@ impl PySet {
} }
#[pymethod] #[pymethod]
pub fn add(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { pub fn add(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.inner.add(item, vm) self.inner.add(object, vm)
} }
#[pymethod] #[pymethod]
fn remove(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn remove(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.inner.remove(item, vm) self.inner.remove(object, vm)
} }
#[pymethod] #[pymethod]
pub fn discard(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { pub fn discard(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.inner.discard(&item, vm).map(|_| ()) self.inner.discard(&object, vm).map(|_| ())
} }
#[pymethod] #[pymethod]
+5 -5
View File
@@ -1004,9 +1004,9 @@ impl PyStr {
} }
#[pymethod] #[pymethod]
fn removeprefix(&self, pref: PyStrRef) -> Wtf8Buf { fn removeprefix(&self, prefix: PyStrRef) -> Wtf8Buf {
self.as_wtf8() self.as_wtf8()
.py_removeprefix(pref.as_wtf8(), pref.byte_len(), |s, p| s.starts_with(p)) .py_removeprefix(prefix.as_wtf8(), prefix.byte_len(), |s, p| s.starts_with(p))
.to_owned() .to_owned()
} }
@@ -1058,10 +1058,10 @@ impl PyStr {
#[pymethod] #[pymethod]
fn __format__( fn __format__(
zelf: PyRef<Self>, zelf: PyRef<Self>,
spec: PyUtf8StrRef, format_spec: PyUtf8StrRef,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> { ) -> PyResult<PyRef<Self>> {
if spec.is_empty() { if format_spec.is_empty() {
return if zelf.class().is(vm.ctx.types.str_type) { return if zelf.class().is(vm.ctx.types.str_type) {
Ok(zelf) Ok(zelf)
} else { } else {
@@ -1069,7 +1069,7 @@ impl PyStr {
}; };
} }
let zelf = zelf.try_into_utf8(vm)?; let zelf = zelf.try_into_utf8(vm)?;
let s = FormatSpec::parse(spec.as_str()) let s = FormatSpec::parse(format_spec.as_str())
.and_then(|format_spec| { .and_then(|format_spec| {
format_spec.format_string(&CharLenStr(zelf.as_str(), zelf.char_len())) format_spec.format_string(&CharLenStr(zelf.as_str(), zelf.char_len()))
}) })
+2 -2
View File
@@ -435,10 +435,10 @@ impl PyTuple {
} }
#[pymethod] #[pymethod]
fn count(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> { fn count(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
let mut count: usize = 0; let mut count: usize = 0;
for element in self { for element in self {
if vm.identical_or_equal(element, &needle)? { if vm.identical_or_equal(element, &value)? {
count += 1; count += 1;
} }
} }
+2 -2
View File
@@ -2919,9 +2919,9 @@ impl Py<PyType> {
} }
#[pymethod] #[pymethod]
fn __instancecheck__(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> { fn __instancecheck__(&self, instance: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
// Use real_is_instance to avoid infinite recursion // Use real_is_instance to avoid infinite recursion
obj.real_is_instance(self.as_object(), vm) instance.real_is_instance(self.as_object(), vm)
} }
#[pymethod] #[pymethod]
+6 -6
View File
@@ -79,10 +79,10 @@ pub(super) mod types {
#[pymethod] #[pymethod]
fn subgroup( fn subgroup(
zelf: PyRef<PyBaseException>, zelf: PyRef<PyBaseException>,
condition: PyObjectRef, matcher_value: PyObjectRef,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult { ) -> PyResult {
let matcher = get_condition_matcher(&condition, vm)?; let matcher = get_condition_matcher(&matcher_value, vm)?;
// If self matches the condition entirely, return self // If self matches the condition entirely, return self
let zelf_obj: PyObjectRef = zelf.clone().into(); let zelf_obj: PyObjectRef = zelf.clone().into();
@@ -101,7 +101,7 @@ pub(super) mod types {
// unless this guard is here. // unless this guard is here.
let subgroup_result = vm let subgroup_result = vm
.with_recursion("in exception group subgroup", || { .with_recursion("in exception group subgroup", || {
vm.call_method(&exc, "subgroup", (condition.clone(),)) vm.call_method(&exc, "subgroup", (matcher_value.clone(),))
})?; })?;
if !vm.is_none(&subgroup_result) { if !vm.is_none(&subgroup_result) {
matching.push(subgroup_result.clone()); matching.push(subgroup_result.clone());
@@ -131,10 +131,10 @@ pub(super) mod types {
#[pymethod] #[pymethod]
fn split( fn split(
zelf: PyRef<PyBaseException>, zelf: PyRef<PyBaseException>,
condition: PyObjectRef, matcher_value: PyObjectRef,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<PyTupleRef> { ) -> PyResult<PyTupleRef> {
let matcher = get_condition_matcher(&condition, vm)?; let matcher = get_condition_matcher(&matcher_value, vm)?;
// If self matches the condition entirely // If self matches the condition entirely
let zelf_obj: PyObjectRef = zelf.clone().into(); let zelf_obj: PyObjectRef = zelf.clone().into();
@@ -151,7 +151,7 @@ pub(super) mod types {
// Same as in subgroup: nothing else bounds this recursion // Same as in subgroup: nothing else bounds this recursion
// against the native stack. // against the native stack.
let result = vm.with_recursion("in exception group split", || { let result = vm.with_recursion("in exception group split", || {
vm.call_method(&exc, "split", (condition.clone(),)) vm.call_method(&exc, "split", (matcher_value.clone(),))
})?; })?;
let result_tuple: PyTupleRef = result.try_into_value(vm)?; let result_tuple: PyTupleRef = result.try_into_value(vm)?;
let match_part = result_tuple let match_part = result_tuple
+2 -2
View File
@@ -94,7 +94,7 @@ mod _codecs {
#[pyfunction] #[pyfunction]
fn register_error( fn register_error(
name: PyUtf8StrRef, errors: PyUtf8StrRef,
handler: PyObjectRef, handler: PyObjectRef,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<()> { ) -> PyResult<()> {
@@ -103,7 +103,7 @@ mod _codecs {
} }
vm.state vm.state
.codec_registry .codec_registry
.register_error(name.as_str().to_owned(), handler); .register_error(errors.as_str().to_owned(), handler);
Ok(()) Ok(())
} }
+24 -24
View File
@@ -97,10 +97,10 @@ mod _collections {
)] )]
impl PyDeque { impl PyDeque {
#[pymethod] #[pymethod]
fn append(&self, obj: PyObjectRef) { fn append(&self, item: PyObjectRef) {
self.state.fetch_add(1); self.state.fetch_add(1);
let mut deque = self.borrow_deque_mut(); let mut deque = self.borrow_deque_mut();
deque.push_back(obj); deque.push_back(item);
// Trim after pushing, so that a `maxlen` of zero drops what just // Trim after pushing, so that a `maxlen` of zero drops what just
// arrived instead of popping from an empty deque and keeping it. // arrived instead of popping from an empty deque and keeping it.
if self.is_over_maxlen(&deque) { if self.is_over_maxlen(&deque) {
@@ -109,10 +109,10 @@ mod _collections {
} }
#[pymethod] #[pymethod]
fn appendleft(&self, obj: PyObjectRef) { fn appendleft(&self, item: PyObjectRef) {
self.state.fetch_add(1); self.state.fetch_add(1);
let mut deque = self.borrow_deque_mut(); let mut deque = self.borrow_deque_mut();
deque.push_front(obj); deque.push_front(item);
if self.is_over_maxlen(&deque) { if self.is_over_maxlen(&deque) {
deque.pop_back(); deque.pop_back();
} }
@@ -136,9 +136,9 @@ mod _collections {
} }
#[pymethod] #[pymethod]
fn count(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> { fn count(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
let start_state = self.state.load(); let start_state = self.state.load();
let count = self.mut_count(vm, &obj)?; let count = self.mut_count(vm, &value)?;
if start_state != self.state.load() { if start_state != self.state.load() {
return Err(vm.new_runtime_error("deque mutated during iteration")); return Err(vm.new_runtime_error("deque mutated during iteration"));
@@ -147,8 +147,8 @@ mod _collections {
} }
#[pymethod] #[pymethod]
fn extend(&self, iter: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn extend(&self, iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self._extend(&iter, vm) self._extend(&iterable, vm)
} }
fn _extend(&self, iter: &PyObject, vm: &VirtualMachine) -> PyResult<()> { fn _extend(&self, iter: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
@@ -170,9 +170,9 @@ mod _collections {
} }
#[pymethod] #[pymethod]
fn extendleft(&self, iter: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn extendleft(&self, iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let max_len = self.maxlen; let max_len = self.maxlen;
let mut elements: Vec<PyObjectRef> = iter.try_to_value(vm)?; let mut elements: Vec<PyObjectRef> = iterable.try_to_value(vm)?;
elements.reverse(); elements.reverse();
if let Some(max_len) = max_len { if let Some(max_len) = max_len {
@@ -217,7 +217,7 @@ mod _collections {
} }
#[pymethod] #[pymethod]
fn insert(&self, idx: i32, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn insert(&self, index: i32, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
self.state.fetch_add(1); self.state.fetch_add(1);
let mut deque = self.borrow_deque_mut(); let mut deque = self.borrow_deque_mut();
@@ -225,19 +225,19 @@ mod _collections {
return Err(vm.new_index_error("deque already at its maximum size")); return Err(vm.new_index_error("deque already at its maximum size"));
} }
let idx = if idx < 0 { let index = if index < 0 {
if -idx as usize > deque.len() { if -index as usize > deque.len() {
0 0
} else { } else {
deque.len() - ((-idx) as usize) deque.len() - ((-index) as usize)
} }
} else if idx as usize > deque.len() { } else if index as usize > deque.len() {
deque.len() deque.len()
} else { } else {
idx as usize index as usize
}; };
deque.insert(idx, obj); deque.insert(index, value);
Ok(()) Ok(())
} }
@@ -259,9 +259,9 @@ mod _collections {
} }
#[pymethod] #[pymethod]
fn remove(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { fn remove(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let start_state = self.state.load(); let start_state = self.state.load();
let index = self.mut_index(vm, &obj)?; let index = self.mut_index(vm, &value)?;
if start_state != self.state.load() { if start_state != self.state.load() {
Err(vm.new_index_error("deque mutated during remove().")) Err(vm.new_index_error("deque mutated during remove()."))
@@ -290,15 +290,15 @@ mod _collections {
} }
#[pymethod] #[pymethod]
fn rotate(&self, mid: OptionalArg<isize>) { fn rotate(&self, n: OptionalArg<isize>) {
self.state.fetch_add(1); self.state.fetch_add(1);
let mut deque = self.borrow_deque_mut(); let mut deque = self.borrow_deque_mut();
if !deque.is_empty() { if !deque.is_empty() {
let mid = mid.unwrap_or(1) % deque.len() as isize; let n = n.unwrap_or(1) % deque.len() as isize;
if mid.is_negative() { if n.is_negative() {
deque.rotate_left(-mid as usize); deque.rotate_left(-n as usize);
} else { } else {
deque.rotate_right(mid as usize); deque.rotate_right(n as usize);
} }
} }
} }
+6 -6
View File
@@ -92,8 +92,8 @@ mod _operator {
} }
#[pyfunction] #[pyfunction]
fn invert(pos: PyObjectRef, vm: &VirtualMachine) -> PyResult { fn invert(a: PyObjectRef, vm: &VirtualMachine) -> PyResult {
vm._invert(&pos) vm._invert(&a)
} }
#[pyfunction] #[pyfunction]
@@ -117,8 +117,8 @@ mod _operator {
} }
#[pyfunction] #[pyfunction]
fn neg(pos: PyObjectRef, vm: &VirtualMachine) -> PyResult { fn neg(a: PyObjectRef, vm: &VirtualMachine) -> PyResult {
vm._neg(&pos) vm._neg(&a)
} }
#[pyfunction] #[pyfunction]
@@ -127,8 +127,8 @@ mod _operator {
} }
#[pyfunction] #[pyfunction]
fn pos(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { fn pos(a: PyObjectRef, vm: &VirtualMachine) -> PyResult {
vm._pos(&obj) vm._pos(&a)
} }
#[pyfunction] #[pyfunction]
+6 -6
View File
@@ -266,8 +266,8 @@ pub(crate) mod _signal {
#[cfg(unix)] #[cfg(unix)]
#[pyfunction] #[pyfunction]
fn alarm(time: u32) -> u32 { fn alarm(seconds: u32) -> u32 {
rustpython_host_env::signal::alarm(time) rustpython_host_env::signal::alarm(seconds)
} }
#[cfg(unix)] #[cfg(unix)]
@@ -307,8 +307,8 @@ pub(crate) mod _signal {
#[pyfunction] #[pyfunction]
fn default_int_handler( fn default_int_handler(
_signum: PyObjectRef, _signalnum: PyObjectRef,
_arg: PyObjectRef, _frame: PyObjectRef,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult { ) -> PyResult {
Err(vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.to_owned())) Err(vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.to_owned()))
@@ -394,8 +394,8 @@ pub(crate) mod _signal {
#[cfg(all(unix, not(target_os = "redox")))] #[cfg(all(unix, not(target_os = "redox")))]
#[pyfunction(name = "siginterrupt")] #[pyfunction(name = "siginterrupt")]
fn py_siginterrupt(signum: SignalNum, flag: i32, vm: &VirtualMachine) -> PyResult<()> { fn py_siginterrupt(signalnum: SignalNum, flag: i32, vm: &VirtualMachine) -> PyResult<()> {
host_signal::siginterrupt(signum.into(), flag).map_err(|_| vm.new_last_errno_error()) host_signal::siginterrupt(signalnum.into(), flag).map_err(|_| vm.new_last_errno_error())
} }
#[cfg(any(unix, windows))] #[cfg(any(unix, windows))]
+9 -8
View File
@@ -35,23 +35,24 @@ mod _sre {
} }
#[pyfunction] #[pyfunction]
fn ascii_iscased(ch: i32) -> bool { fn ascii_iscased(character: i32) -> bool {
(b'a' as i32..=b'z' as i32).contains(&ch) || (b'A' as i32..=b'Z' as i32).contains(&ch) (b'a' as i32..=b'z' as i32).contains(&character)
|| (b'A' as i32..=b'Z' as i32).contains(&character)
} }
#[pyfunction] #[pyfunction]
fn unicode_iscased(ch: i32) -> bool { fn unicode_iscased(character: i32) -> bool {
char::from_u32(ch as u32).is_some_and(rustpython_unicode::case::is_cased) char::from_u32(character as u32).is_some_and(rustpython_unicode::case::is_cased)
} }
#[pyfunction] #[pyfunction]
fn ascii_tolower(ch: i32) -> i32 { fn ascii_tolower(character: i32) -> i32 {
lower_ascii(ch as u32) as i32 lower_ascii(character as u32) as i32
} }
#[pyfunction] #[pyfunction]
fn unicode_tolower(ch: i32) -> i32 { fn unicode_tolower(character: i32) -> i32 {
lower_unicode(ch as u32) as i32 lower_unicode(character as u32) as i32
} }
trait SreStr: StrDrive { trait SreStr: StrDrive {
+7 -10
View File
@@ -39,23 +39,20 @@ mod _weakref {
} }
#[pyfunction] #[pyfunction]
fn getweakrefcount(obj: PyObjectRef) -> usize { fn getweakrefcount(object: PyObjectRef) -> usize {
obj.weak_count().unwrap_or(0) object.weak_count().unwrap_or(0)
} }
#[pyfunction] #[pyfunction]
fn getweakrefs(obj: PyObjectRef) -> Vec<PyObjectRef> { fn getweakrefs(object: PyObjectRef) -> Vec<PyObjectRef> {
obj.get_weak_references() object
.get_weak_references()
.map_or_else(Vec::new, |v| v.into_iter().map(Into::into).collect()) .map_or_else(Vec::new, |v| v.into_iter().map(Into::into).collect())
} }
#[pyfunction] #[pyfunction]
fn _remove_dead_weakref( fn _remove_dead_weakref(dct: PyDictRef, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
dict: PyDictRef, dct._as_dict_inner()
key: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
dict._as_dict_inner()
.delete_if(vm, &*key, |wr| { .delete_if(vm, &*key, |wr| {
let wr = wr let wr = wr
.downcast_ref::<PyWeak>() .downcast_ref::<PyWeak>()
+2 -2
View File
@@ -49,11 +49,11 @@ mod decl {
#[pyclassmethod] #[pyclassmethod]
fn from_iterable( fn from_iterable(
cls: PyTypeRef, cls: PyTypeRef,
source: PyObjectRef, iterable: PyObjectRef,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<PyRef<Self>> { ) -> PyResult<PyRef<Self>> {
Self { Self {
source: PyRwLock::new(Some(source.get_iter(vm)?)), source: PyRwLock::new(Some(iterable.get_iter(vm)?)),
active: PyRwLock::new(None), active: PyRwLock::new(None),
} }
.into_ref_with_type(vm, cls) .into_ref_with_type(vm, cls)
+41 -41
View File
@@ -270,8 +270,8 @@ pub(super) mod _os {
const ST_NOSUID: libc::c_ulong = libc::ST_NOSUID; const ST_NOSUID: libc::c_ulong = libc::ST_NOSUID;
#[pyfunction] #[pyfunction]
fn close(fileno: crt_fd::Owned) -> io::Result<()> { fn close(fd: crt_fd::Owned) -> io::Result<()> {
crt_fd::close(fileno) crt_fd::close(fd)
} }
#[pyfunction] #[pyfunction]
@@ -341,8 +341,8 @@ pub(super) mod _os {
} }
#[pyfunction] #[pyfunction]
fn read(fd: crt_fd::Borrowed<'_>, n: usize, vm: &VirtualMachine) -> PyResult<PyBytesRef> { fn read(fd: crt_fd::Borrowed<'_>, length: usize, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
let mut buffer = vm.new_zeroed_bytes(n)?; let mut buffer = vm.new_zeroed_bytes(length)?;
loop { loop {
match vm.allow_threads(|| crt_fd::read(fd, &mut buffer)) { match vm.allow_threads(|| crt_fd::read(fd, &mut buffer)) {
Ok(n) => { Ok(n) => {
@@ -555,20 +555,20 @@ pub(super) mod _os {
#[cfg(windows)] #[cfg(windows)]
#[pyfunction] #[pyfunction]
fn putenv(key: PyStrRef, value: PyStrRef, vm: &VirtualMachine) -> PyResult<()> { fn putenv(name: PyStrRef, value: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
let key_str = key.expect_str(); let name_str = name.expect_str();
let value_str = value.expect_str(); let value_str = value.expect_str();
// Search from index 1 because on Windows starting '=' is allowed for // Search from index 1 because on Windows starting '=' is allowed for
// defining hidden environment variables. // defining hidden environment variables.
if key_str.is_empty() if name_str.is_empty()
|| key_str.get(1..).is_some_and(|s| s.contains('=')) || name_str.get(1..).is_some_and(|s| s.contains('='))
|| key.contains_nuls() || name.contains_nuls()
|| value.contains_nuls() || value.contains_nuls()
{ {
cold_path(); cold_path();
return Err(vm.new_value_error("illegal environment variable name")); return Err(vm.new_value_error("illegal environment variable name"));
} }
let env_str = format!("{key_str}={value_str}"); let env_str = format!("{name_str}={value_str}");
// env_str is guaranteed nul-free by the checks above. // env_str is guaranteed nul-free by the checks above.
let wide = widestring::WideCString::from_str(&env_str) let wide = widestring::WideCString::from_str(&env_str)
.expect("env_str validated to contain no NUL"); .expect("env_str validated to contain no NUL");
@@ -581,42 +581,42 @@ pub(super) mod _os {
#[cfg(not(windows))] #[cfg(not(windows))]
#[pyfunction] #[pyfunction]
fn putenv( fn putenv(
key: crate::function::Either<PyStrRef, PyBytesRef>, name: crate::function::Either<PyStrRef, PyBytesRef>,
value: crate::function::Either<PyStrRef, PyBytesRef>, value: crate::function::Either<PyStrRef, PyBytesRef>,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<()> { ) -> PyResult<()> {
let (Some(key), Some(value)) = ( let (Some(name), Some(value)) = (
env_bytes_as_bytes_checked(&key), env_bytes_as_bytes_checked(&name),
env_bytes_as_bytes_checked(&value), env_bytes_as_bytes_checked(&value),
) else { ) else {
cold_path(); cold_path();
return Err(exceptions::nul_byte_error(vm)); return Err(exceptions::nul_byte_error(vm));
}; };
if key.is_empty() || key.contains(&b'=') { if name.is_empty() || name.contains(&b'=') {
return Err(vm.new_value_error("illegal environment variable name")); return Err(vm.new_value_error("illegal environment variable name"));
} }
let key = super::bytes_as_os_str(key, vm)?; let name = super::bytes_as_os_str(name, vm)?;
let value = super::bytes_as_os_str(value, vm)?; let value = super::bytes_as_os_str(value, vm)?;
// SAFETY: requirements forwarded from the caller // SAFETY: requirements forwarded from the caller
unsafe { crate::host_env::os::set_var(key, value) }; unsafe { crate::host_env::os::set_var(name, value) };
Ok(()) Ok(())
} }
#[cfg(windows)] #[cfg(windows)]
#[pyfunction] #[pyfunction]
fn unsetenv(key: PyStrRef, vm: &VirtualMachine) -> PyResult<()> { fn unsetenv(name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
let key_str = key.expect_str(); let name_str = name.expect_str();
// Search from index 1 because on Windows starting '=' is allowed for // Search from index 1 because on Windows starting '=' is allowed for
// defining hidden environment variables. // defining hidden environment variables.
if key_str.is_empty() if name_str.is_empty()
|| key_str.get(1..).is_some_and(|s| s.contains('=')) || name_str.get(1..).is_some_and(|s| s.contains('='))
|| key.contains_nuls() || name.contains_nuls()
{ {
cold_path(); cold_path();
return Err(vm.new_value_error("illegal environment variable name")); return Err(vm.new_value_error("illegal environment variable name"));
} }
// "key=" to unset (empty value removes the variable) // "name=" to unset (empty value removes the variable)
let env_str = format!("{key_str}="); let env_str = format!("{name_str}=");
// env_str is guaranteed nul-free by the checks above. // env_str is guaranteed nul-free by the checks above.
let wide = widestring::WideCString::from_str(&env_str) let wide = widestring::WideCString::from_str(&env_str)
.expect("env_str validated to contain no NUL"); .expect("env_str validated to contain no NUL");
@@ -629,27 +629,27 @@ pub(super) mod _os {
#[cfg(not(windows))] #[cfg(not(windows))]
#[pyfunction] #[pyfunction]
fn unsetenv( fn unsetenv(
key: crate::function::Either<PyStrRef, PyBytesRef>, name: crate::function::Either<PyStrRef, PyBytesRef>,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<()> { ) -> PyResult<()> {
let Some(key) = env_bytes_as_bytes_checked(&key) else { let Some(name) = env_bytes_as_bytes_checked(&name) else {
cold_path(); cold_path();
return Err(exceptions::nul_byte_error(vm)); return Err(exceptions::nul_byte_error(vm));
}; };
if key.is_empty() || key.contains(&b'=') { if name.is_empty() || name.contains(&b'=') {
let x = vm.new_errno_error( let x = vm.new_errno_error(
22, 22,
format!( format!(
"Invalid argument: {}", "Invalid argument: {}",
core::str::from_utf8(key).unwrap_or("<bytes encoding failure>") core::str::from_utf8(name).unwrap_or("<bytes encoding failure>")
), ),
); );
return Err(x.upcast()); return Err(x.upcast());
} }
let key = super::bytes_as_os_str(key, vm)?; let name = super::bytes_as_os_str(name, vm)?;
// SAFETY: requirements forwarded from the caller // SAFETY: requirements forwarded from the caller
unsafe { crate::host_env::os::remove_var(key) }; unsafe { crate::host_env::os::remove_var(name) };
Ok(()) Ok(())
} }
@@ -1416,27 +1416,27 @@ pub(super) mod _os {
#[pyfunction] #[pyfunction]
#[pyfunction(name = "fstat")] #[pyfunction(name = "fstat")]
fn stat( fn stat(
file: OsPathOrFd<'_>, path: OsPathOrFd<'_>,
dir_fd: DirFd<'_, { STAT_DIR_FD as usize }>, dir_fd: DirFd<'_, { STAT_DIR_FD as usize }>,
follow_symlinks: FollowSymlinks, follow_symlinks: FollowSymlinks,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult { ) -> PyResult {
if matches!(file, OsPathOrFd::Fd(_)) && !follow_symlinks.0 { if matches!(path, OsPathOrFd::Fd(_)) && !follow_symlinks.0 {
return Err(vm.new_value_error("stat: cannot use fd and follow_symlinks together")); return Err(vm.new_value_error("stat: cannot use fd and follow_symlinks together"));
} }
let stat = stat_inner(file.clone(), dir_fd, follow_symlinks) let stat = stat_inner(path.clone(), dir_fd, follow_symlinks)
.map_err(|err| OSErrorBuilder::with_filename(&err, file, vm))? .map_err(|err| OSErrorBuilder::with_filename(&err, path, vm))?
.ok_or_else(|| crate::exceptions::nul_char_error(vm))?; .ok_or_else(|| crate::exceptions::nul_char_error(vm))?;
Ok(StatResultData::from_stat(&stat, vm).to_pyobject(vm)) Ok(StatResultData::from_stat(&stat, vm).to_pyobject(vm))
} }
#[pyfunction] #[pyfunction]
fn lstat( fn lstat(
file: OsPath, path: OsPath,
dir_fd: DirFd<'_, { STAT_DIR_FD as usize }>, dir_fd: DirFd<'_, { STAT_DIR_FD as usize }>,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult { ) -> PyResult {
stat(file.into(), dir_fd, FollowSymlinks(false), vm) stat(path.into(), dir_fd, FollowSymlinks(false), vm)
} }
fn curdir_inner(vm: &VirtualMachine) -> PyResult<PathBuf> { fn curdir_inner(vm: &VirtualMachine) -> PyResult<PathBuf> {
@@ -1561,8 +1561,8 @@ pub(super) mod _os {
} }
#[pyfunction] #[pyfunction]
fn _exit(code: i32) { fn _exit(status: i32) {
crate::host_env::os::exit(code) crate::host_env::os::exit(status)
} }
#[pyfunction] #[pyfunction]
@@ -1587,10 +1587,10 @@ pub(super) mod _os {
pub(crate) fn lseek( pub(crate) fn lseek(
fd: crt_fd::Borrowed<'_>, fd: crt_fd::Borrowed<'_>,
position: crt_fd::Offset, position: crt_fd::Offset,
how: i32, whence: i32,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<crt_fd::Offset> { ) -> PyResult<crt_fd::Offset> {
crate::host_env::os::seek_fd(fd, position, how).map_err(|e| e.into_pyexception(vm)) crate::host_env::os::seek_fd(fd, position, whence).map_err(|e| e.into_pyexception(vm))
} }
#[derive(FromArgs)] #[derive(FromArgs)]
@@ -1902,8 +1902,8 @@ pub(super) mod _os {
} }
#[pyfunction] #[pyfunction]
fn strerror(e: i32) -> String { fn strerror(code: i32) -> String {
crate::host_env::time::strerror(e) crate::host_env::time::strerror(code)
} }
#[pyfunction] #[pyfunction]
+18 -13
View File
@@ -1197,8 +1197,8 @@ pub mod module {
} }
#[pyfunction] #[pyfunction]
fn setpgid(pid: u32, pgid: u32, vm: &VirtualMachine) -> PyResult<()> { fn setpgid(pid: u32, pgrp: u32, vm: &VirtualMachine) -> PyResult<()> {
rustpython_host_env::posix::setpgid(pid, pgid).map_err(|err| err.into_pyexception(vm)) rustpython_host_env::posix::setpgid(pid, pgrp).map_err(|err| err.into_pyexception(vm))
} }
#[pyfunction] #[pyfunction]
@@ -1391,19 +1391,19 @@ pub mod module {
// cfg from nix // cfg from nix
#[cfg(any(target_os = "freebsd", target_os = "linux", target_os = "openbsd"))] #[cfg(any(target_os = "freebsd", target_os = "linux", target_os = "openbsd"))]
#[pyfunction] #[pyfunction]
fn initgroups(user_name: PyUtf8StrRef, gid: RawGid, vm: &VirtualMachine) -> PyResult<()> { fn initgroups(username: PyUtf8StrRef, gid: RawGid, vm: &VirtualMachine) -> PyResult<()> {
let user = user_name.to_cstring(vm)?; let user = username.to_cstring(vm)?;
rustpython_host_env::posix::initgroups(&user, gid.0).map_err(|err| err.into_pyexception(vm)) rustpython_host_env::posix::initgroups(&user, gid.0).map_err(|err| err.into_pyexception(vm))
} }
// cfg from nix // cfg from nix
#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox")))] #[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox")))]
#[pyfunction] #[pyfunction]
fn setgroups(group_ids: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn setgroups(groups: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
group_ids groups
.try_sequence(vm) .try_sequence(vm)
.map_err(|_| vm.new_type_error("setgroups argument must be a sequence"))?; .map_err(|_| vm.new_type_error("setgroups argument must be a sequence"))?;
let gids = vm.extract_elements_with(&group_ids, |gid| { let gids = vm.extract_elements_with(&groups, |gid| {
RawGid::try_from_object(vm, gid).map(|gid| gid.0) RawGid::try_from_object(vm, gid).map(|gid| gid.0)
})?; })?;
rustpython_host_env::posix::setgroups_raw(&gids).map_err(|err| err.into_pyexception(vm)) rustpython_host_env::posix::setgroups_raw(&gids).map_err(|err| err.into_pyexception(vm))
@@ -1746,11 +1746,15 @@ pub mod module {
} }
#[pyfunction] #[pyfunction]
fn waitpid(pid: libc::pid_t, opt: i32, vm: &VirtualMachine) -> PyResult<(libc::pid_t, i32)> { fn waitpid(
pid: libc::pid_t,
options: i32,
vm: &VirtualMachine,
) -> PyResult<(libc::pid_t, i32)> {
let mut status = 0; let mut status = 0;
loop { loop {
let res = let res =
vm.allow_threads(|| rustpython_host_env::posix::waitpid(pid, &mut status, opt)); vm.allow_threads(|| rustpython_host_env::posix::waitpid(pid, &mut status, options));
match res { match res {
Err(err) if err.raw_os_error() == Some(libc::EINTR) => { Err(err) if err.raw_os_error() == Some(libc::EINTR) => {
vm.check_signals()?; vm.check_signals()?;
@@ -1768,13 +1772,14 @@ pub mod module {
} }
#[pyfunction] #[pyfunction]
fn kill(pid: i32, sig: isize, vm: &VirtualMachine) -> PyResult<()> { fn kill(pid: i32, signal: isize, vm: &VirtualMachine) -> PyResult<()> {
rustpython_host_env::posix::kill(pid, sig as i32).map_err(|err| err.into_pyexception(vm)) rustpython_host_env::posix::kill(pid, signal as i32).map_err(|err| err.into_pyexception(vm))
} }
#[pyfunction] #[pyfunction]
fn killpg(pgid: i32, sig: isize, vm: &VirtualMachine) -> PyResult<()> { fn killpg(pgid: i32, signal: isize, vm: &VirtualMachine) -> PyResult<()> {
rustpython_host_env::posix::killpg(pgid, sig as i32).map_err(|err| err.into_pyexception(vm)) rustpython_host_env::posix::killpg(pgid, signal as i32)
.map_err(|err| err.into_pyexception(vm))
} }
#[pyfunction] #[pyfunction]
+42 -45
View File
@@ -770,8 +770,8 @@ pub mod sys {
} }
#[pyfunction] #[pyfunction]
fn exit(code: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult { fn exit(status: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult {
let status = code.unwrap_or_none(vm); let status = status.unwrap_or_none(vm);
let args = if let Some(status_tuple) = status.downcast_ref::<PyTuple>() { let args = if let Some(status_tuple) = status.downcast_ref::<PyTuple>() {
status_tuple.as_slice().to_vec() status_tuple.as_slice().to_vec()
} else { } else {
@@ -795,32 +795,32 @@ pub mod sys {
#[pyfunction(name = "__displayhook__")] #[pyfunction(name = "__displayhook__")]
#[pyfunction] #[pyfunction]
fn displayhook(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { fn displayhook(object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
// Save non-None values as "_" // Save non-None values as "_"
if vm.is_none(&obj) { if vm.is_none(&object) {
return Ok(()); return Ok(());
} }
// set to none to avoid recursion while printing // set to none to avoid recursion while printing
vm.builtins.set_attr("_", vm.ctx.none(), vm)?; vm.builtins.set_attr("_", vm.ctx.none(), vm)?;
// TODO: catch encoding errors // TODO: catch encoding errors
let repr = obj.repr(vm)?.into(); let repr = object.repr(vm)?.into();
builtins::print(PosArgs::new(vec![repr]), Default::default(), vm)?; builtins::print(PosArgs::new(vec![repr]), Default::default(), vm)?;
vm.builtins.set_attr("_", obj, vm)?; vm.builtins.set_attr("_", object, vm)?;
Ok(()) Ok(())
} }
#[pyfunction(name = "__excepthook__")] #[pyfunction(name = "__excepthook__")]
#[pyfunction] #[pyfunction]
fn excepthook( fn excepthook(
exc_type: PyObjectRef, exctype: PyObjectRef,
exc_val: PyObjectRef, value: PyObjectRef,
exc_tb: PyObjectRef, traceback: PyObjectRef,
vm: &VirtualMachine, vm: &VirtualMachine,
) -> PyResult<()> { ) -> PyResult<()> {
let stderr = super::get_stderr(vm)?; let stderr = super::get_stderr(vm)?;
// Keep runtime SyntaxErrors on the normal traceback path. // Keep runtime SyntaxErrors on the normal traceback path.
let has_traceback = !vm.is_none(&exc_tb); let has_traceback = !vm.is_none(&traceback);
match vm.normalize_exception(exc_type, exc_val.clone(), exc_tb) { match vm.normalize_exception(exctype, value.clone(), traceback) {
Ok(exc) => { Ok(exc) => {
let native_syntax_error_display = !has_traceback let native_syntax_error_display = !has_traceback
&& exc.fast_isinstance(vm.ctx.exceptions.syntax_error) && exc.fast_isinstance(vm.ctx.exceptions.syntax_error)
@@ -852,7 +852,7 @@ pub mod sys {
vm.write_exception(&mut crate::py_io::PyWriter(stderr, vm), &exc) vm.write_exception(&mut crate::py_io::PyWriter(stderr, vm), &exc)
} }
Err(_) => { Err(_) => {
let type_name = exc_val.class().name(); let type_name = value.class().name();
let msg = format!( let msg = format!(
"TypeError: print_exception(): Exception expected for value, {type_name} found\n" "TypeError: print_exception(): Exception expected for value, {type_name} found\n"
); );
@@ -942,8 +942,8 @@ pub mod sys {
} }
#[pyfunction] #[pyfunction]
fn getrefcount(obj: PyObjectRef) -> usize { fn getrefcount(object: PyObjectRef) -> usize {
obj.strong_count() object.strong_count()
} }
#[pyfunction] #[pyfunction]
@@ -986,9 +986,9 @@ pub mod sys {
} }
#[pyfunction] #[pyfunction]
fn _getframe(offset: OptionalArg<usize>, vm: &VirtualMachine) -> PyResult<FrameObjectRef> { fn _getframe(depth: OptionalArg<usize>, vm: &VirtualMachine) -> PyResult<FrameObjectRef> {
let offset = offset.into_option().unwrap_or(0); let depth = depth.into_option().unwrap_or(0);
let frame_ref = crate::frame::frame_at_offset(offset, vm) let frame_ref = crate::frame::frame_at_offset(depth, vm)
.ok_or_else(|| vm.new_value_error("call stack is not deep enough"))?; .ok_or_else(|| vm.new_value_error("call stack is not deep enough"))?;
if let Ok(audit) = vm.sys_module.get_attr("audit", vm) { if let Ok(audit) = vm.sys_module.get_attr("audit", vm) {
audit.call((vm.ctx.new_str("sys._getframe"), frame_ref.to_owned()), vm)?; audit.call((vm.ctx.new_str("sys._getframe"), frame_ref.to_owned()), vm)?;
@@ -1211,8 +1211,8 @@ pub mod sys {
} }
#[pyfunction] #[pyfunction]
fn intern(s: PyRefExact<PyStr>, vm: &VirtualMachine) -> PyRef<PyStr> { fn intern(string: PyRefExact<PyStr>, vm: &VirtualMachine) -> PyRef<PyStr> {
vm.ctx.intern_str(s).to_owned() vm.ctx.intern_str(string).to_owned()
} }
#[pyattr] #[pyattr]
@@ -1249,50 +1249,47 @@ pub mod sys {
} }
#[pyfunction] #[pyfunction]
fn setprofile(profilefunc: PyObjectRef, vm: &VirtualMachine) { fn setprofile(function: PyObjectRef, vm: &VirtualMachine) {
vm.profile_func.replace(profilefunc); vm.profile_func.replace(function);
update_use_tracing(vm); update_use_tracing(vm);
} }
#[pyfunction] #[pyfunction]
fn setrecursionlimit(recursion_limit: i32, vm: &VirtualMachine) -> PyResult<()> { fn setrecursionlimit(limit: i32, vm: &VirtualMachine) -> PyResult<()> {
let recursion_limit = recursion_limit let limit = limit.to_usize().filter(|&u| u >= 1).ok_or_else(|| {
.to_usize() vm.new_value_error("recursion limit must be greater than or equal to one")
.filter(|&u| u >= 1) })?;
.ok_or_else(|| {
vm.new_value_error("recursion limit must be greater than or equal to one")
})?;
let recursion_depth = vm.current_recursion_depth(); let recursion_depth = vm.current_recursion_depth();
if recursion_limit > recursion_depth { if limit > recursion_depth {
vm.recursion_limit.set(recursion_limit); vm.recursion_limit.set(limit);
Ok(()) Ok(())
} else { } else {
Err(vm.new_recursion_error(format!( Err(vm.new_recursion_error(format!(
"cannot set the recursion limit to {recursion_limit} at the recursion depth {recursion_depth}: the limit is too low" "cannot set the recursion limit to {limit} at the recursion depth {recursion_depth}: the limit is too low"
))) )))
} }
} }
#[pyfunction] #[pyfunction]
fn settrace(tracefunc: PyObjectRef, vm: &VirtualMachine) { fn settrace(function: PyObjectRef, vm: &VirtualMachine) {
vm.trace_func.replace(tracefunc); vm.trace_func.replace(function);
update_use_tracing(vm); update_use_tracing(vm);
} }
#[pyfunction] #[pyfunction]
fn _settraceallthreads(tracefunc: PyObjectRef, vm: &VirtualMachine) { fn _settraceallthreads(function: PyObjectRef, vm: &VirtualMachine) {
let func = (!vm.is_none(&tracefunc)).then(|| tracefunc.clone()); let func = (!vm.is_none(&function)).then(|| function.clone());
*vm.state.global_trace_func.lock() = func; *vm.state.global_trace_func.lock() = func;
vm.trace_func.replace(tracefunc); vm.trace_func.replace(function);
update_use_tracing(vm); update_use_tracing(vm);
} }
#[pyfunction] #[pyfunction]
fn _setprofileallthreads(profilefunc: PyObjectRef, vm: &VirtualMachine) { fn _setprofileallthreads(function: PyObjectRef, vm: &VirtualMachine) {
let func = (!vm.is_none(&profilefunc)).then(|| profilefunc.clone()); let func = (!vm.is_none(&function)).then(|| function.clone());
*vm.state.global_profile_func.lock() = func; *vm.state.global_profile_func.lock() = func;
vm.profile_func.replace(profilefunc); vm.profile_func.replace(function);
update_use_tracing(vm); update_use_tracing(vm);
} }
@@ -1329,23 +1326,23 @@ pub mod sys {
} }
#[pyfunction] #[pyfunction]
fn _clear_type_descriptors(type_obj: PyTypeRef, vm: &VirtualMachine) -> PyResult<()> { fn _clear_type_descriptors(r#type: PyTypeRef, vm: &VirtualMachine) -> PyResult<()> {
use crate::types::PyTypeFlags; use crate::types::PyTypeFlags;
// Check if type is immutable // Check if type is immutable
if type_obj.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) { if r#type.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) {
return Err(vm.new_type_error("argument is immutable")); return Err(vm.new_type_error("argument is immutable"));
} }
// Remove __dict__ descriptor if present // Remove __dict__ descriptor if present
type_obj.attributes.remove(identifier!(vm, __dict__)); r#type.attributes.remove(identifier!(vm, __dict__));
// Remove __weakref__ descriptor if present // Remove __weakref__ descriptor if present
type_obj.attributes.remove(identifier!(vm, __weakref__)); r#type.attributes.remove(identifier!(vm, __weakref__));
// Update slots to notify subclasses and recalculate cached values // Update slots to notify subclasses and recalculate cached values
type_obj.update_slot::<true>(identifier!(vm, __dict__), &vm.ctx); r#type.update_slot::<true>(identifier!(vm, __dict__), &vm.ctx);
type_obj.update_slot::<true>(identifier!(vm, __weakref__), &vm.ctx); r#type.update_slot::<true>(identifier!(vm, __weakref__), &vm.ctx);
Ok(()) Ok(())
} }