mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-28 10:44:36 +08:00
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:
1 parent
3191ecaf38
commit
df653cea69
33 files changed
+331
-323
No files matched your search
@@ -119,6 +119,7 @@
|
||||
"TESTFN",
|
||||
"TZPATH",
|
||||
"unraisable",
|
||||
"ustr",
|
||||
"wasi",
|
||||
"weaked",
|
||||
// unix
|
||||
|
||||
Vendored
-2
@@ -1604,12 +1604,10 @@ class TestDescriptions(unittest.TestCase):
|
||||
self.assertEqual(self._get_summary_line(''.lower),
|
||||
"lower() method of builtins.str instance")
|
||||
|
||||
@unittest.expectedFailure # TODO: RUSTPYTHON
|
||||
def test_unbound_builtin_method_o(self):
|
||||
self.assertEqual(self._get_summary_line(set.add),
|
||||
"add(self, object, /) unbound builtins.set method")
|
||||
|
||||
@unittest.expectedFailure # TODO: RUSTPYTHON
|
||||
def test_bound_builtin_method_o(self):
|
||||
self.assertEqual(self._get_summary_line(set().add),
|
||||
"add(object, /) method of builtins.set instance")
|
||||
|
||||
@@ -2,7 +2,7 @@ use itertools::Itertools;
|
||||
use proc_macro2::{Span, TokenStream};
|
||||
use quote::{ToTokens, quote};
|
||||
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::{
|
||||
ext::{AttributeExt as SynAttributeExt, *},
|
||||
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 {
|
||||
return None;
|
||||
};
|
||||
let ident = pat.ident.to_string();
|
||||
let ident = pat.ident.unraw().to_string();
|
||||
if ident == "vm" {
|
||||
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(", "))
|
||||
}
|
||||
|
||||
+22
-22
@@ -798,8 +798,8 @@ pub mod array {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn append(zelf: &Py<Self>, x: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
zelf.try_resizable(vm)?.push(x, vm)
|
||||
fn append(zelf: &Py<Self>, v: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
zelf.try_resizable(vm)?.push(v, vm)
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -814,24 +814,24 @@ pub mod array {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn count(&self, x: PyObjectRef, vm: &VirtualMachine) -> usize {
|
||||
self.read().count(x, vm)
|
||||
fn count(&self, v: PyObjectRef, vm: &VirtualMachine) -> usize {
|
||||
self.read().count(v, vm)
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn remove(zelf: &Py<Self>, x: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
zelf.try_resizable(vm)?.remove(x, vm)
|
||||
fn remove(zelf: &Py<Self>, v: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
zelf.try_resizable(vm)?.remove(v, vm)
|
||||
}
|
||||
|
||||
#[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)?;
|
||||
if zelf.is(&obj) {
|
||||
if zelf.is(&bb) {
|
||||
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)
|
||||
} else {
|
||||
let iter = ArgIterable::try_from_object(vm, obj)?;
|
||||
let iter = ArgIterable::try_from_object(vm, bb)?;
|
||||
// zelf.extend_from_iterable(iter, vm)
|
||||
for obj in iter.iter(vm)? {
|
||||
w.push(obj?, vm)?;
|
||||
@@ -883,11 +883,11 @@ pub mod array {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn fromunicode(zelf: &Py<Self>, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let wtf8: &Wtf8 = obj.try_to_value(vm).map_err(|_| {
|
||||
fn fromunicode(zelf: &Py<Self>, ustr: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let wtf8: &Wtf8 = ustr.try_to_value(vm).map_err(|_| {
|
||||
vm.new_type_error(format!(
|
||||
"fromunicode() argument must be str, not {}",
|
||||
obj.class().name()
|
||||
ustr.class().name()
|
||||
))
|
||||
})?;
|
||||
if !matches!(zelf.read().typecode(), 'u' | 'w') {
|
||||
@@ -924,15 +924,15 @@ pub mod array {
|
||||
}
|
||||
|
||||
#[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
|
||||
// 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"));
|
||||
}
|
||||
let b = b.borrow_buf();
|
||||
let buffer = buffer.borrow_buf();
|
||||
let itemsize = self.read().itemsize();
|
||||
self._from_bytes(&b, itemsize, vm)
|
||||
self._from_bytes(&buffer, itemsize, vm)
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -977,9 +977,9 @@ pub mod array {
|
||||
}
|
||||
|
||||
#[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)?;
|
||||
w.insert(i, x, vm)
|
||||
w.insert(i, v, vm)
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -1049,7 +1049,7 @@ pub mod array {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn __deepcopy__(&self, _memo: PyObjectRef) -> Self {
|
||||
fn __deepcopy__(&self, _unused: PyObjectRef) -> Self {
|
||||
self.__copy__()
|
||||
}
|
||||
|
||||
@@ -1198,10 +1198,10 @@ pub mod array {
|
||||
#[pymethod]
|
||||
fn __reduce_ex__(
|
||||
zelf: &Py<Self>,
|
||||
proto: usize,
|
||||
value: usize,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<(PyObjectRef, PyTupleRef, Option<PyDictRef>)> {
|
||||
if proto < 3 {
|
||||
if value < 3 {
|
||||
return Self::__reduce__(zelf, vm);
|
||||
}
|
||||
let array = zelf.read();
|
||||
|
||||
@@ -56,20 +56,21 @@ mod decl {
|
||||
|
||||
#[pyfunction(name = "a2b_hex")]
|
||||
#[pyfunction]
|
||||
fn unhexlify(data: ArgAsciiBuffer, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
data.with_ref(binascii::unhexlify)
|
||||
fn unhexlify(hexstr: ArgAsciiBuffer, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
hexstr
|
||||
.with_ref(binascii::unhexlify)
|
||||
.map_err(|e| new_binascii_error(e, vm))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
pub(crate) fn crc32(data: ArgBytesLike, init: OptionalArg<PyIntRef>) -> u32 {
|
||||
let init = init.map_or(0, |i| i.as_u32_mask());
|
||||
data.with_ref(|bytes| binascii::crc32(bytes, init))
|
||||
pub(crate) fn crc32(data: ArgBytesLike, crc: OptionalArg<PyIntRef>) -> u32 {
|
||||
let crc = crc.map_or(0, |i| i.as_u32_mask());
|
||||
data.with_ref(|bytes| binascii::crc32(bytes, crc))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
pub(crate) fn crc_hqx(data: ArgBytesLike, init: PyIntRef) -> u32 {
|
||||
data.with_ref(|bytes| binascii::crc_hqx(bytes, init.as_u32_mask()))
|
||||
pub(crate) fn crc_hqx(data: ArgBytesLike, crc: PyIntRef) -> u32 {
|
||||
data.with_ref(|bytes| binascii::crc_hqx(bytes, crc.as_u32_mask()))
|
||||
}
|
||||
|
||||
#[derive(FromArgs)]
|
||||
@@ -136,8 +137,8 @@ mod decl {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn a2b_uu(s: ArgAsciiBuffer, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
s.with_ref(binascii::a2b_uu)
|
||||
fn a2b_uu(data: ArgAsciiBuffer, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
|
||||
data.with_ref(binascii::a2b_uu)
|
||||
.map_err(|e| new_binascii_error(e, vm))
|
||||
}
|
||||
|
||||
|
||||
@@ -32,8 +32,8 @@ mod cmath {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn polar(x: ArgIntoComplex, vm: &VirtualMachine) -> PyResult<(f64, f64)> {
|
||||
pymath::cmath::polar(x.into_complex()).map_err(|err| pymath_exception(err, vm))
|
||||
fn polar(z: ArgIntoComplex, vm: &VirtualMachine) -> PyResult<(f64, f64)> {
|
||||
pymath::cmath::polar(z.into_complex()).map_err(|err| pymath_exception(err, vm))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
|
||||
@@ -762,8 +762,8 @@ mod math {
|
||||
// Integer functions:
|
||||
|
||||
#[pyfunction]
|
||||
fn isqrt(x: ArgIndex, vm: &VirtualMachine) -> PyResult<BigInt> {
|
||||
let value = x.into_int_ref();
|
||||
fn isqrt(n: ArgIndex, vm: &VirtualMachine) -> PyResult<BigInt> {
|
||||
let value = n.into_int_ref();
|
||||
pymath::math::integer::isqrt(value.as_bigint())
|
||||
.map_err(|_| vm.new_value_error("isqrt() argument must be nonnegative"))
|
||||
}
|
||||
@@ -791,12 +791,12 @@ mod math {
|
||||
}
|
||||
|
||||
#[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
|
||||
if x.as_bigint().is_negative() {
|
||||
if n.as_bigint().is_negative() {
|
||||
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")
|
||||
})?;
|
||||
pymath::math::integer::factorial(n)
|
||||
|
||||
@@ -144,11 +144,11 @@ pub(crate) mod _struct {
|
||||
|
||||
#[pyfunction]
|
||||
fn unpack(
|
||||
fmt: IntoStructFormatBytes,
|
||||
format: IntoStructFormatBytes,
|
||||
buffer: ArgBytesLike,
|
||||
vm: &VirtualMachine,
|
||||
) -> 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))
|
||||
}
|
||||
|
||||
@@ -239,17 +239,17 @@ pub(crate) mod _struct {
|
||||
|
||||
#[pyfunction]
|
||||
fn iter_unpack(
|
||||
fmt: IntoStructFormatBytes,
|
||||
format: IntoStructFormatBytes,
|
||||
buffer: ArgBytesLike,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<UnpackIterator> {
|
||||
let format_spec = fmt.format_spec(vm)?;
|
||||
let format_spec = format.format_spec(vm)?;
|
||||
UnpackIterator::with_buffer(vm, format_spec, buffer)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn calcsize(fmt: IntoStructFormatBytes, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
Ok(fmt.format_spec(vm)?.size)
|
||||
fn calcsize(format: IntoStructFormatBytes, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
Ok(format.format_spec(vm)?.size)
|
||||
}
|
||||
|
||||
/// What a `Struct` is once a format has been read into it. Held apart
|
||||
@@ -342,9 +342,9 @@ pub(crate) mod _struct {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn unpack(&self, data: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
|
||||
fn unpack(&self, buffer: ArgBytesLike, vm: &VirtualMachine) -> PyResult<PyTupleRef> {
|
||||
let inner = self.ready(vm)?;
|
||||
data.with_ref(|buf| inner.spec.unpack(buf, vm))
|
||||
buffer.with_ref(|buf| inner.spec.unpack(buf, vm))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
|
||||
@@ -93,9 +93,8 @@ mod unicodedata {
|
||||
#[pyclass(flags(DISALLOW_INSTANTIATION))]
|
||||
impl Ucd {
|
||||
#[pymethod]
|
||||
fn category(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> {
|
||||
self.extract_char(character, vm)
|
||||
.map(|c| self.inner.category(c))
|
||||
fn category(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> {
|
||||
self.extract_char(chr, vm).map(|c| self.inner.category(c))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -118,11 +117,11 @@ mod unicodedata {
|
||||
#[pymethod]
|
||||
fn name(
|
||||
&self,
|
||||
character: PyStrRef,
|
||||
chr: PyStrRef,
|
||||
default: OptionalArg<PyObjectRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> 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
|
||||
.membership(ch)
|
||||
.then(|| unicode_core::character_name(ch))
|
||||
@@ -134,22 +133,14 @@ mod unicodedata {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn bidirectional(
|
||||
&self,
|
||||
character: PyStrRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<&'static str> {
|
||||
self.extract_char(character, vm)
|
||||
fn bidirectional(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> {
|
||||
self.extract_char(chr, vm)
|
||||
.map(|c| self.inner.bidirectional(c))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn east_asian_width(
|
||||
&self,
|
||||
character: PyStrRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<&'static str> {
|
||||
self.extract_char(character, vm)
|
||||
fn east_asian_width(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> {
|
||||
self.extract_char(chr, vm)
|
||||
.map(|c| self.inner.east_asian_width(c))
|
||||
}
|
||||
|
||||
@@ -164,31 +155,29 @@ mod unicodedata {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn mirrored(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<i32> {
|
||||
self.extract_char(character, vm)
|
||||
.map(|c| self.inner.mirrored(c))
|
||||
fn mirrored(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<i32> {
|
||||
self.extract_char(chr, vm).map(|c| self.inner.mirrored(c))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn combining(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<u8> {
|
||||
self.extract_char(character, vm)
|
||||
.map(|c| self.inner.combining(c))
|
||||
fn combining(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<u8> {
|
||||
self.extract_char(chr, vm).map(|c| self.inner.combining(c))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn decomposition(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
|
||||
self.extract_char(character, vm)
|
||||
fn decomposition(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<String> {
|
||||
self.extract_char(chr, vm)
|
||||
.map(|c| self.inner.decomposition(c))
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn digit(
|
||||
&self,
|
||||
character: PyStrRef,
|
||||
chr: PyStrRef,
|
||||
default: OptionalArg<PyObjectRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Option<PyObjectRef>> {
|
||||
let ch = self.extract_char(character, vm)?;
|
||||
let ch = self.extract_char(chr, vm)?;
|
||||
self.inner
|
||||
.digit(ch)
|
||||
.map(|value| vm.ctx.new_int(value).into())
|
||||
@@ -200,11 +189,11 @@ mod unicodedata {
|
||||
#[pymethod]
|
||||
fn decimal(
|
||||
&self,
|
||||
character: PyStrRef,
|
||||
chr: PyStrRef,
|
||||
default: OptionalArg<PyObjectRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Option<PyObjectRef>> {
|
||||
let ch = self.extract_char(character, vm)?;
|
||||
let ch = self.extract_char(chr, vm)?;
|
||||
self.inner
|
||||
.decimal(ch)
|
||||
.map(|value| vm.ctx.new_int(value).into())
|
||||
@@ -216,11 +205,11 @@ mod unicodedata {
|
||||
#[pymethod]
|
||||
fn numeric(
|
||||
&self,
|
||||
character: PyStrRef,
|
||||
chr: PyStrRef,
|
||||
default: OptionalArg<PyObjectRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<Option<PyObjectRef>> {
|
||||
let ch = self.extract_char(character, vm)?;
|
||||
let ch = self.extract_char(chr, vm)?;
|
||||
self.inner
|
||||
.numeric(ch)
|
||||
.map(|value| vm.ctx.new_float(value).into())
|
||||
|
||||
@@ -50,18 +50,18 @@ mod zlib {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn adler32(data: ArgBytesLike, begin_state: OptionalArg<PyIntRef>) -> u32 {
|
||||
fn adler32(data: ArgBytesLike, value: OptionalArg<PyIntRef>) -> u32 {
|
||||
data.with_ref(|data| {
|
||||
let begin_state = begin_state.map_or(1, |i| i.as_u32_mask());
|
||||
let mut hasher = Adler32::from_value(begin_state);
|
||||
let value = value.map_or(1, |i| i.as_u32_mask());
|
||||
let mut hasher = Adler32::from_value(value);
|
||||
hasher.update_buffer(data);
|
||||
hasher.hash()
|
||||
})
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn crc32(data: ArgBytesLike, begin_state: OptionalArg<PyIntRef>) -> u32 {
|
||||
crate::binascii::crc32(data, begin_state)
|
||||
fn crc32(data: ArgBytesLike, value: OptionalArg<PyIntRef>) -> u32 {
|
||||
crate::binascii::crc32(data, value)
|
||||
}
|
||||
|
||||
#[derive(FromArgs)]
|
||||
|
||||
@@ -106,9 +106,13 @@ impl Constructor for PyBool {
|
||||
#[pyclass(with(Constructor, AsNumber, Representable), flags(_MATCH_SELF))]
|
||||
impl PyBool {
|
||||
#[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)?;
|
||||
FormatSpec::parse(spec.as_str())
|
||||
FormatSpec::parse(format_spec.as_str())
|
||||
.and_then(|format_spec| format_spec.format_bool(new_bool))
|
||||
.map_err(|err| err.into_pyexception(vm))
|
||||
}
|
||||
|
||||
@@ -353,11 +353,11 @@ impl PyByteArray {
|
||||
}
|
||||
|
||||
#[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,
|
||||
// so the separator is taken by value rather than left borrowed.
|
||||
let separator = self.inner().clone();
|
||||
Ok(separator.join(iter, vm)?.into())
|
||||
Ok(separator.join(iterable_of_bytes, vm)?.into())
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -428,8 +428,8 @@ impl PyByteArray {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn strip(&self, chars: OptionalOption<PyBytesInner>) -> Self {
|
||||
self.inner().strip(chars).into()
|
||||
fn strip(&self, bytes: OptionalOption<PyBytesInner>) -> Self {
|
||||
self.inner().strip(bytes).into()
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -588,8 +588,8 @@ impl Py<PyByteArray> {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn insert(&self, index: isize, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let value = value_from_object(vm, &object)?;
|
||||
fn insert(&self, index: isize, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let value = value_from_object(vm, &item)?;
|
||||
let elements = &mut self.try_resizable(vm)?.elements;
|
||||
let index = elements.saturate_index(index);
|
||||
elements.insert(index, value);
|
||||
@@ -597,39 +597,39 @@ impl Py<PyByteArray> {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn append(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let value = value_from_object(vm, &object)?;
|
||||
fn append(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let value = value_from_object(vm, &item)?;
|
||||
self.try_resizable(vm)?.elements.push(value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn remove(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let value = value_from_object(vm, &object)?;
|
||||
fn remove(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let byte = value_from_object(vm, &value)?;
|
||||
let elements = &mut self.try_resizable(vm)?.elements;
|
||||
let index = elements
|
||||
.find_byte(value)
|
||||
.find_byte(byte)
|
||||
.ok_or_else(|| vm.new_value_error("value not found in bytearray"))?;
|
||||
elements.remove(index);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn extend(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if self.is(&object) {
|
||||
fn extend(&self, iterable_of_ints: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
if self.is(&iterable_of_ints) {
|
||||
return PyByteArray::irepeat(self, 2, vm);
|
||||
}
|
||||
// bytearray_setslice keeps the export alive across the resize, so a value
|
||||
// looking at this bytearray is what stops it from growing.
|
||||
let buffer = object
|
||||
let buffer = iterable_of_ints
|
||||
.check_buffer()
|
||||
.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
|
||||
// not usable here, whatever the exporter's own complaint was.
|
||||
vm.new_type_error(format!(
|
||||
"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")
|
||||
})?
|
||||
.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);
|
||||
Ok(())
|
||||
@@ -676,9 +676,9 @@ impl Py<PyByteArray> {
|
||||
#[pyclass]
|
||||
impl PyRef<PyByteArray> {
|
||||
#[pymethod]
|
||||
fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
fn lstrip(self, bytes: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
let inner = self.inner();
|
||||
let stripped = inner.lstrip(chars);
|
||||
let stripped = inner.lstrip(bytes);
|
||||
let elements = &inner.elements;
|
||||
if stripped == elements {
|
||||
drop(inner);
|
||||
@@ -689,9 +689,9 @@ impl PyRef<PyByteArray> {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn rstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
fn rstrip(self, bytes: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
let inner = self.inner();
|
||||
let stripped = inner.rstrip(chars);
|
||||
let stripped = inner.rstrip(bytes);
|
||||
let elements = &inner.elements;
|
||||
if stripped == elements {
|
||||
drop(inner);
|
||||
|
||||
@@ -356,8 +356,8 @@ impl PyBytes {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn join(&self, iter: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner.join(iter, vm)?.into())
|
||||
fn join(&self, iterable_of_bytes: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
|
||||
Ok(self.inner.join(iterable_of_bytes, vm)?.into())
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -426,8 +426,8 @@ impl PyBytes {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn strip(&self, chars: OptionalOption<PyBytesInner>) -> Self {
|
||||
self.inner.strip(chars).into()
|
||||
fn strip(&self, bytes: OptionalOption<PyBytesInner>) -> Self {
|
||||
self.inner.strip(bytes).into()
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
@@ -582,8 +582,8 @@ impl PyRef<PyBytes> {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn lstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
let stripped = self.inner.lstrip(chars);
|
||||
fn lstrip(self, bytes: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
let stripped = self.inner.lstrip(bytes);
|
||||
if stripped == self.as_bytes() {
|
||||
self
|
||||
} else {
|
||||
@@ -592,8 +592,8 @@ impl PyRef<PyBytes> {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn rstrip(self, chars: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
let stripped = self.inner.rstrip(chars);
|
||||
fn rstrip(self, bytes: OptionalOption<PyBytesInner>, vm: &VirtualMachine) -> Self {
|
||||
let stripped = self.inner.rstrip(bytes);
|
||||
if stripped == self.as_bytes() {
|
||||
self
|
||||
} else {
|
||||
|
||||
@@ -563,13 +563,17 @@ impl PyComplex {
|
||||
}
|
||||
|
||||
#[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)
|
||||
if spec.is_empty() {
|
||||
if format_spec.is_empty() {
|
||||
return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned());
|
||||
}
|
||||
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 locale = crate::format::get_locale_info();
|
||||
format_spec.format_complex_locale(&zelf.value, &locale)
|
||||
|
||||
@@ -245,13 +245,17 @@ pub fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult<f64>
|
||||
)]
|
||||
impl PyFloat {
|
||||
#[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)
|
||||
if spec.is_empty() {
|
||||
if format_spec.is_empty() {
|
||||
return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned());
|
||||
}
|
||||
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 locale = crate::format::get_locale_info();
|
||||
format_spec.format_float_locale(zelf.value, &locale)
|
||||
|
||||
@@ -524,13 +524,17 @@ impl PyInt {
|
||||
}
|
||||
|
||||
#[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)
|
||||
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());
|
||||
}
|
||||
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() {
|
||||
check_int_to_str_digits(&zelf.value, vm)?;
|
||||
}
|
||||
|
||||
@@ -182,26 +182,27 @@ pub type PyListRef = PyRef<PyList>;
|
||||
)]
|
||||
impl PyList {
|
||||
#[pymethod]
|
||||
pub(crate) fn append(&self, x: PyObjectRef) {
|
||||
self.borrow_vec_mut().push(x);
|
||||
pub(crate) fn append(&self, object: PyObjectRef) {
|
||||
self.borrow_vec_mut().push(object);
|
||||
}
|
||||
|
||||
#[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
|
||||
// believable, so it goes along with the request for the elements. It is
|
||||
// counted where `list_extend()` reads `Py_SIZE(self)`, after the
|
||||
// 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);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[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 position = elements.saturate_index(position);
|
||||
elements.insert(position, element);
|
||||
let index = elements.saturate_index(index);
|
||||
elements.insert(index, object);
|
||||
}
|
||||
|
||||
fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
|
||||
@@ -331,8 +332,8 @@ impl PyList {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn count(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
self.mut_count(vm, &needle)
|
||||
fn count(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
self.mut_count(vm, &value)
|
||||
}
|
||||
|
||||
pub(crate) fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
|
||||
@@ -356,24 +357,24 @@ impl PyList {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn pop(&self, i: OptionalArg<isize>, vm: &VirtualMachine) -> PyResult {
|
||||
let mut i = i.into_option().unwrap_or(-1);
|
||||
fn pop(&self, index: OptionalArg<isize>, vm: &VirtualMachine) -> PyResult {
|
||||
let mut index = index.into_option().unwrap_or(-1);
|
||||
let mut elements = self.borrow_vec_mut();
|
||||
if i < 0 {
|
||||
i += elements.len() as isize;
|
||||
if index < 0 {
|
||||
index += elements.len() as isize;
|
||||
}
|
||||
if elements.is_empty() {
|
||||
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"))
|
||||
} else {
|
||||
Ok(elements.remove(i as usize))
|
||||
Ok(elements.remove(index as usize))
|
||||
}
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn remove(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let index = self.mut_index(vm, &needle)?;
|
||||
fn remove(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let index = self.mut_index(vm, &value)?;
|
||||
|
||||
if let Some(index) = index.into() {
|
||||
// defer delete out of borrow
|
||||
@@ -384,7 +385,7 @@ impl PyList {
|
||||
drop(removed);
|
||||
Ok(())
|
||||
} 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)?)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -473,7 +473,7 @@ impl PyBaseObject {
|
||||
}
|
||||
|
||||
#[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__);
|
||||
if let Some(reduce) = vm.get_attribute_opt(zelf.clone(), __reduce__)? {
|
||||
let object_reduce = vm.ctx.types.object_type.get_attr(__reduce__).unwrap();
|
||||
@@ -483,7 +483,7 @@ impl PyBaseObject {
|
||||
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")]
|
||||
|
||||
@@ -776,18 +776,18 @@ impl PySet {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
pub fn add(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
self.inner.add(item, vm)
|
||||
pub fn add(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
self.inner.add(object, vm)
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn remove(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
self.inner.remove(item, vm)
|
||||
fn remove(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
self.inner.remove(object, vm)
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
pub fn discard(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
self.inner.discard(&item, vm).map(|_| ())
|
||||
pub fn discard(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
self.inner.discard(&object, vm).map(|_| ())
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
|
||||
@@ -1004,9 +1004,9 @@ impl PyStr {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn removeprefix(&self, pref: PyStrRef) -> Wtf8Buf {
|
||||
fn removeprefix(&self, prefix: PyStrRef) -> Wtf8Buf {
|
||||
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()
|
||||
}
|
||||
|
||||
@@ -1058,10 +1058,10 @@ impl PyStr {
|
||||
#[pymethod]
|
||||
fn __format__(
|
||||
zelf: PyRef<Self>,
|
||||
spec: PyUtf8StrRef,
|
||||
format_spec: PyUtf8StrRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyRef<Self>> {
|
||||
if spec.is_empty() {
|
||||
if format_spec.is_empty() {
|
||||
return if zelf.class().is(vm.ctx.types.str_type) {
|
||||
Ok(zelf)
|
||||
} else {
|
||||
@@ -1069,7 +1069,7 @@ impl PyStr {
|
||||
};
|
||||
}
|
||||
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| {
|
||||
format_spec.format_string(&CharLenStr(zelf.as_str(), zelf.char_len()))
|
||||
})
|
||||
|
||||
@@ -435,10 +435,10 @@ impl PyTuple {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn count(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
fn count(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
|
||||
let mut count: usize = 0;
|
||||
for element in self {
|
||||
if vm.identical_or_equal(element, &needle)? {
|
||||
if vm.identical_or_equal(element, &value)? {
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2919,9 +2919,9 @@ impl Py<PyType> {
|
||||
}
|
||||
|
||||
#[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
|
||||
obj.real_is_instance(self.as_object(), vm)
|
||||
instance.real_is_instance(self.as_object(), vm)
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
|
||||
@@ -79,10 +79,10 @@ pub(super) mod types {
|
||||
#[pymethod]
|
||||
fn subgroup(
|
||||
zelf: PyRef<PyBaseException>,
|
||||
condition: PyObjectRef,
|
||||
matcher_value: PyObjectRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
let matcher = get_condition_matcher(&condition, vm)?;
|
||||
let matcher = get_condition_matcher(&matcher_value, vm)?;
|
||||
|
||||
// If self matches the condition entirely, return self
|
||||
let zelf_obj: PyObjectRef = zelf.clone().into();
|
||||
@@ -101,7 +101,7 @@ pub(super) mod types {
|
||||
// unless this guard is here.
|
||||
let subgroup_result = vm
|
||||
.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) {
|
||||
matching.push(subgroup_result.clone());
|
||||
@@ -131,10 +131,10 @@ pub(super) mod types {
|
||||
#[pymethod]
|
||||
fn split(
|
||||
zelf: PyRef<PyBaseException>,
|
||||
condition: PyObjectRef,
|
||||
matcher_value: PyObjectRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyTupleRef> {
|
||||
let matcher = get_condition_matcher(&condition, vm)?;
|
||||
let matcher = get_condition_matcher(&matcher_value, vm)?;
|
||||
|
||||
// If self matches the condition entirely
|
||||
let zelf_obj: PyObjectRef = zelf.clone().into();
|
||||
@@ -151,7 +151,7 @@ pub(super) mod types {
|
||||
// Same as in subgroup: nothing else bounds this recursion
|
||||
// against the native stack.
|
||||
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 match_part = result_tuple
|
||||
|
||||
@@ -94,7 +94,7 @@ mod _codecs {
|
||||
|
||||
#[pyfunction]
|
||||
fn register_error(
|
||||
name: PyUtf8StrRef,
|
||||
errors: PyUtf8StrRef,
|
||||
handler: PyObjectRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
@@ -103,7 +103,7 @@ mod _codecs {
|
||||
}
|
||||
vm.state
|
||||
.codec_registry
|
||||
.register_error(name.as_str().to_owned(), handler);
|
||||
.register_error(errors.as_str().to_owned(), handler);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -97,10 +97,10 @@ mod _collections {
|
||||
)]
|
||||
impl PyDeque {
|
||||
#[pymethod]
|
||||
fn append(&self, obj: PyObjectRef) {
|
||||
fn append(&self, item: PyObjectRef) {
|
||||
self.state.fetch_add(1);
|
||||
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
|
||||
// arrived instead of popping from an empty deque and keeping it.
|
||||
if self.is_over_maxlen(&deque) {
|
||||
@@ -109,10 +109,10 @@ mod _collections {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn appendleft(&self, obj: PyObjectRef) {
|
||||
fn appendleft(&self, item: PyObjectRef) {
|
||||
self.state.fetch_add(1);
|
||||
let mut deque = self.borrow_deque_mut();
|
||||
deque.push_front(obj);
|
||||
deque.push_front(item);
|
||||
if self.is_over_maxlen(&deque) {
|
||||
deque.pop_back();
|
||||
}
|
||||
@@ -136,9 +136,9 @@ mod _collections {
|
||||
}
|
||||
|
||||
#[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 count = self.mut_count(vm, &obj)?;
|
||||
let count = self.mut_count(vm, &value)?;
|
||||
|
||||
if start_state != self.state.load() {
|
||||
return Err(vm.new_runtime_error("deque mutated during iteration"));
|
||||
@@ -147,8 +147,8 @@ mod _collections {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn extend(&self, iter: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
self._extend(&iter, vm)
|
||||
fn extend(&self, iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
self._extend(&iterable, vm)
|
||||
}
|
||||
|
||||
fn _extend(&self, iter: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
|
||||
@@ -170,9 +170,9 @@ mod _collections {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn extendleft(&self, iter: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
fn extendleft(&self, iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
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();
|
||||
|
||||
if let Some(max_len) = max_len {
|
||||
@@ -217,7 +217,7 @@ mod _collections {
|
||||
}
|
||||
|
||||
#[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);
|
||||
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"));
|
||||
}
|
||||
|
||||
let idx = if idx < 0 {
|
||||
if -idx as usize > deque.len() {
|
||||
let index = if index < 0 {
|
||||
if -index as usize > deque.len() {
|
||||
0
|
||||
} 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()
|
||||
} else {
|
||||
idx as usize
|
||||
index as usize
|
||||
};
|
||||
|
||||
deque.insert(idx, obj);
|
||||
deque.insert(index, value);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -259,9 +259,9 @@ mod _collections {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn remove(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
fn remove(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
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() {
|
||||
Err(vm.new_index_error("deque mutated during remove()."))
|
||||
@@ -290,15 +290,15 @@ mod _collections {
|
||||
}
|
||||
|
||||
#[pymethod]
|
||||
fn rotate(&self, mid: OptionalArg<isize>) {
|
||||
fn rotate(&self, n: OptionalArg<isize>) {
|
||||
self.state.fetch_add(1);
|
||||
let mut deque = self.borrow_deque_mut();
|
||||
if !deque.is_empty() {
|
||||
let mid = mid.unwrap_or(1) % deque.len() as isize;
|
||||
if mid.is_negative() {
|
||||
deque.rotate_left(-mid as usize);
|
||||
let n = n.unwrap_or(1) % deque.len() as isize;
|
||||
if n.is_negative() {
|
||||
deque.rotate_left(-n as usize);
|
||||
} else {
|
||||
deque.rotate_right(mid as usize);
|
||||
deque.rotate_right(n as usize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,8 +92,8 @@ mod _operator {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn invert(pos: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
vm._invert(&pos)
|
||||
fn invert(a: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
vm._invert(&a)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -117,8 +117,8 @@ mod _operator {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn neg(pos: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
vm._neg(&pos)
|
||||
fn neg(a: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
vm._neg(&a)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -127,8 +127,8 @@ mod _operator {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn pos(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
vm._pos(&obj)
|
||||
fn pos(a: PyObjectRef, vm: &VirtualMachine) -> PyResult {
|
||||
vm._pos(&a)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
|
||||
@@ -266,8 +266,8 @@ pub(crate) mod _signal {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[pyfunction]
|
||||
fn alarm(time: u32) -> u32 {
|
||||
rustpython_host_env::signal::alarm(time)
|
||||
fn alarm(seconds: u32) -> u32 {
|
||||
rustpython_host_env::signal::alarm(seconds)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -307,8 +307,8 @@ pub(crate) mod _signal {
|
||||
|
||||
#[pyfunction]
|
||||
fn default_int_handler(
|
||||
_signum: PyObjectRef,
|
||||
_arg: PyObjectRef,
|
||||
_signalnum: PyObjectRef,
|
||||
_frame: PyObjectRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
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")))]
|
||||
#[pyfunction(name = "siginterrupt")]
|
||||
fn py_siginterrupt(signum: SignalNum, flag: i32, vm: &VirtualMachine) -> PyResult<()> {
|
||||
host_signal::siginterrupt(signum.into(), flag).map_err(|_| vm.new_last_errno_error())
|
||||
fn py_siginterrupt(signalnum: SignalNum, flag: i32, vm: &VirtualMachine) -> PyResult<()> {
|
||||
host_signal::siginterrupt(signalnum.into(), flag).map_err(|_| vm.new_last_errno_error())
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
|
||||
@@ -35,23 +35,24 @@ mod _sre {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn ascii_iscased(ch: i32) -> bool {
|
||||
(b'a' as i32..=b'z' as i32).contains(&ch) || (b'A' as i32..=b'Z' as i32).contains(&ch)
|
||||
fn ascii_iscased(character: i32) -> bool {
|
||||
(b'a' as i32..=b'z' as i32).contains(&character)
|
||||
|| (b'A' as i32..=b'Z' as i32).contains(&character)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn unicode_iscased(ch: i32) -> bool {
|
||||
char::from_u32(ch as u32).is_some_and(rustpython_unicode::case::is_cased)
|
||||
fn unicode_iscased(character: i32) -> bool {
|
||||
char::from_u32(character as u32).is_some_and(rustpython_unicode::case::is_cased)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn ascii_tolower(ch: i32) -> i32 {
|
||||
lower_ascii(ch as u32) as i32
|
||||
fn ascii_tolower(character: i32) -> i32 {
|
||||
lower_ascii(character as u32) as i32
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn unicode_tolower(ch: i32) -> i32 {
|
||||
lower_unicode(ch as u32) as i32
|
||||
fn unicode_tolower(character: i32) -> i32 {
|
||||
lower_unicode(character as u32) as i32
|
||||
}
|
||||
|
||||
trait SreStr: StrDrive {
|
||||
|
||||
@@ -39,23 +39,20 @@ mod _weakref {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn getweakrefcount(obj: PyObjectRef) -> usize {
|
||||
obj.weak_count().unwrap_or(0)
|
||||
fn getweakrefcount(object: PyObjectRef) -> usize {
|
||||
object.weak_count().unwrap_or(0)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn getweakrefs(obj: PyObjectRef) -> Vec<PyObjectRef> {
|
||||
obj.get_weak_references()
|
||||
fn getweakrefs(object: PyObjectRef) -> Vec<PyObjectRef> {
|
||||
object
|
||||
.get_weak_references()
|
||||
.map_or_else(Vec::new, |v| v.into_iter().map(Into::into).collect())
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn _remove_dead_weakref(
|
||||
dict: PyDictRef,
|
||||
key: PyObjectRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
dict._as_dict_inner()
|
||||
fn _remove_dead_weakref(dct: PyDictRef, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
dct._as_dict_inner()
|
||||
.delete_if(vm, &*key, |wr| {
|
||||
let wr = wr
|
||||
.downcast_ref::<PyWeak>()
|
||||
|
||||
@@ -49,11 +49,11 @@ mod decl {
|
||||
#[pyclassmethod]
|
||||
fn from_iterable(
|
||||
cls: PyTypeRef,
|
||||
source: PyObjectRef,
|
||||
iterable: PyObjectRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<PyRef<Self>> {
|
||||
Self {
|
||||
source: PyRwLock::new(Some(source.get_iter(vm)?)),
|
||||
source: PyRwLock::new(Some(iterable.get_iter(vm)?)),
|
||||
active: PyRwLock::new(None),
|
||||
}
|
||||
.into_ref_with_type(vm, cls)
|
||||
|
||||
+41
-41
@@ -270,8 +270,8 @@ pub(super) mod _os {
|
||||
const ST_NOSUID: libc::c_ulong = libc::ST_NOSUID;
|
||||
|
||||
#[pyfunction]
|
||||
fn close(fileno: crt_fd::Owned) -> io::Result<()> {
|
||||
crt_fd::close(fileno)
|
||||
fn close(fd: crt_fd::Owned) -> io::Result<()> {
|
||||
crt_fd::close(fd)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -341,8 +341,8 @@ pub(super) mod _os {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn read(fd: crt_fd::Borrowed<'_>, n: usize, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
|
||||
let mut buffer = vm.new_zeroed_bytes(n)?;
|
||||
fn read(fd: crt_fd::Borrowed<'_>, length: usize, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
|
||||
let mut buffer = vm.new_zeroed_bytes(length)?;
|
||||
loop {
|
||||
match vm.allow_threads(|| crt_fd::read(fd, &mut buffer)) {
|
||||
Ok(n) => {
|
||||
@@ -555,20 +555,20 @@ pub(super) mod _os {
|
||||
|
||||
#[cfg(windows)]
|
||||
#[pyfunction]
|
||||
fn putenv(key: PyStrRef, value: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let key_str = key.expect_str();
|
||||
fn putenv(name: PyStrRef, value: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let name_str = name.expect_str();
|
||||
let value_str = value.expect_str();
|
||||
// Search from index 1 because on Windows starting '=' is allowed for
|
||||
// defining hidden environment variables.
|
||||
if key_str.is_empty()
|
||||
|| key_str.get(1..).is_some_and(|s| s.contains('='))
|
||||
|| key.contains_nuls()
|
||||
if name_str.is_empty()
|
||||
|| name_str.get(1..).is_some_and(|s| s.contains('='))
|
||||
|| name.contains_nuls()
|
||||
|| value.contains_nuls()
|
||||
{
|
||||
cold_path();
|
||||
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.
|
||||
let wide = widestring::WideCString::from_str(&env_str)
|
||||
.expect("env_str validated to contain no NUL");
|
||||
@@ -581,42 +581,42 @@ pub(super) mod _os {
|
||||
#[cfg(not(windows))]
|
||||
#[pyfunction]
|
||||
fn putenv(
|
||||
key: crate::function::Either<PyStrRef, PyBytesRef>,
|
||||
name: crate::function::Either<PyStrRef, PyBytesRef>,
|
||||
value: crate::function::Either<PyStrRef, PyBytesRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
let (Some(key), Some(value)) = (
|
||||
env_bytes_as_bytes_checked(&key),
|
||||
let (Some(name), Some(value)) = (
|
||||
env_bytes_as_bytes_checked(&name),
|
||||
env_bytes_as_bytes_checked(&value),
|
||||
) else {
|
||||
cold_path();
|
||||
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"));
|
||||
}
|
||||
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)?;
|
||||
// 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(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[pyfunction]
|
||||
fn unsetenv(key: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let key_str = key.expect_str();
|
||||
fn unsetenv(name: PyStrRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let name_str = name.expect_str();
|
||||
// Search from index 1 because on Windows starting '=' is allowed for
|
||||
// defining hidden environment variables.
|
||||
if key_str.is_empty()
|
||||
|| key_str.get(1..).is_some_and(|s| s.contains('='))
|
||||
|| key.contains_nuls()
|
||||
if name_str.is_empty()
|
||||
|| name_str.get(1..).is_some_and(|s| s.contains('='))
|
||||
|| name.contains_nuls()
|
||||
{
|
||||
cold_path();
|
||||
return Err(vm.new_value_error("illegal environment variable name"));
|
||||
}
|
||||
// "key=" to unset (empty value removes the variable)
|
||||
let env_str = format!("{key_str}=");
|
||||
// "name=" to unset (empty value removes the variable)
|
||||
let env_str = format!("{name_str}=");
|
||||
// env_str is guaranteed nul-free by the checks above.
|
||||
let wide = widestring::WideCString::from_str(&env_str)
|
||||
.expect("env_str validated to contain no NUL");
|
||||
@@ -629,27 +629,27 @@ pub(super) mod _os {
|
||||
#[cfg(not(windows))]
|
||||
#[pyfunction]
|
||||
fn unsetenv(
|
||||
key: crate::function::Either<PyStrRef, PyBytesRef>,
|
||||
name: crate::function::Either<PyStrRef, PyBytesRef>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
let Some(key) = env_bytes_as_bytes_checked(&key) else {
|
||||
let Some(name) = env_bytes_as_bytes_checked(&name) else {
|
||||
cold_path();
|
||||
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(
|
||||
22,
|
||||
format!(
|
||||
"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());
|
||||
}
|
||||
let key = super::bytes_as_os_str(key, vm)?;
|
||||
let name = super::bytes_as_os_str(name, vm)?;
|
||||
// SAFETY: requirements forwarded from the caller
|
||||
unsafe { crate::host_env::os::remove_var(key) };
|
||||
unsafe { crate::host_env::os::remove_var(name) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1416,27 +1416,27 @@ pub(super) mod _os {
|
||||
#[pyfunction]
|
||||
#[pyfunction(name = "fstat")]
|
||||
fn stat(
|
||||
file: OsPathOrFd<'_>,
|
||||
path: OsPathOrFd<'_>,
|
||||
dir_fd: DirFd<'_, { STAT_DIR_FD as usize }>,
|
||||
follow_symlinks: FollowSymlinks,
|
||||
vm: &VirtualMachine,
|
||||
) -> 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"));
|
||||
}
|
||||
let stat = stat_inner(file.clone(), dir_fd, follow_symlinks)
|
||||
.map_err(|err| OSErrorBuilder::with_filename(&err, file, vm))?
|
||||
let stat = stat_inner(path.clone(), dir_fd, follow_symlinks)
|
||||
.map_err(|err| OSErrorBuilder::with_filename(&err, path, vm))?
|
||||
.ok_or_else(|| crate::exceptions::nul_char_error(vm))?;
|
||||
Ok(StatResultData::from_stat(&stat, vm).to_pyobject(vm))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn lstat(
|
||||
file: OsPath,
|
||||
path: OsPath,
|
||||
dir_fd: DirFd<'_, { STAT_DIR_FD as usize }>,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult {
|
||||
stat(file.into(), dir_fd, FollowSymlinks(false), vm)
|
||||
stat(path.into(), dir_fd, FollowSymlinks(false), vm)
|
||||
}
|
||||
|
||||
fn curdir_inner(vm: &VirtualMachine) -> PyResult<PathBuf> {
|
||||
@@ -1561,8 +1561,8 @@ pub(super) mod _os {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn _exit(code: i32) {
|
||||
crate::host_env::os::exit(code)
|
||||
fn _exit(status: i32) {
|
||||
crate::host_env::os::exit(status)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -1587,10 +1587,10 @@ pub(super) mod _os {
|
||||
pub(crate) fn lseek(
|
||||
fd: crt_fd::Borrowed<'_>,
|
||||
position: crt_fd::Offset,
|
||||
how: i32,
|
||||
whence: i32,
|
||||
vm: &VirtualMachine,
|
||||
) -> 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)]
|
||||
@@ -1902,8 +1902,8 @@ pub(super) mod _os {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn strerror(e: i32) -> String {
|
||||
crate::host_env::time::strerror(e)
|
||||
fn strerror(code: i32) -> String {
|
||||
crate::host_env::time::strerror(code)
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
|
||||
@@ -1197,8 +1197,8 @@ pub mod module {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn setpgid(pid: u32, pgid: u32, vm: &VirtualMachine) -> PyResult<()> {
|
||||
rustpython_host_env::posix::setpgid(pid, pgid).map_err(|err| err.into_pyexception(vm))
|
||||
fn setpgid(pid: u32, pgrp: u32, vm: &VirtualMachine) -> PyResult<()> {
|
||||
rustpython_host_env::posix::setpgid(pid, pgrp).map_err(|err| err.into_pyexception(vm))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -1391,19 +1391,19 @@ pub mod module {
|
||||
// cfg from nix
|
||||
#[cfg(any(target_os = "freebsd", target_os = "linux", target_os = "openbsd"))]
|
||||
#[pyfunction]
|
||||
fn initgroups(user_name: PyUtf8StrRef, gid: RawGid, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let user = user_name.to_cstring(vm)?;
|
||||
fn initgroups(username: PyUtf8StrRef, gid: RawGid, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let user = username.to_cstring(vm)?;
|
||||
rustpython_host_env::posix::initgroups(&user, gid.0).map_err(|err| err.into_pyexception(vm))
|
||||
}
|
||||
|
||||
// cfg from nix
|
||||
#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox")))]
|
||||
#[pyfunction]
|
||||
fn setgroups(group_ids: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
group_ids
|
||||
fn setgroups(groups: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
groups
|
||||
.try_sequence(vm)
|
||||
.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)
|
||||
})?;
|
||||
rustpython_host_env::posix::setgroups_raw(&gids).map_err(|err| err.into_pyexception(vm))
|
||||
@@ -1746,11 +1746,15 @@ pub mod module {
|
||||
}
|
||||
|
||||
#[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;
|
||||
loop {
|
||||
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 {
|
||||
Err(err) if err.raw_os_error() == Some(libc::EINTR) => {
|
||||
vm.check_signals()?;
|
||||
@@ -1768,13 +1772,14 @@ pub mod module {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn kill(pid: i32, sig: isize, vm: &VirtualMachine) -> PyResult<()> {
|
||||
rustpython_host_env::posix::kill(pid, sig as i32).map_err(|err| err.into_pyexception(vm))
|
||||
fn kill(pid: i32, signal: isize, vm: &VirtualMachine) -> PyResult<()> {
|
||||
rustpython_host_env::posix::kill(pid, signal as i32).map_err(|err| err.into_pyexception(vm))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn killpg(pgid: i32, sig: isize, vm: &VirtualMachine) -> PyResult<()> {
|
||||
rustpython_host_env::posix::killpg(pgid, sig as i32).map_err(|err| err.into_pyexception(vm))
|
||||
fn killpg(pgid: i32, signal: isize, vm: &VirtualMachine) -> PyResult<()> {
|
||||
rustpython_host_env::posix::killpg(pgid, signal as i32)
|
||||
.map_err(|err| err.into_pyexception(vm))
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
|
||||
+40
-43
@@ -770,8 +770,8 @@ pub mod sys {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn exit(code: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult {
|
||||
let status = code.unwrap_or_none(vm);
|
||||
fn exit(status: OptionalArg<PyObjectRef>, vm: &VirtualMachine) -> PyResult {
|
||||
let status = status.unwrap_or_none(vm);
|
||||
let args = if let Some(status_tuple) = status.downcast_ref::<PyTuple>() {
|
||||
status_tuple.as_slice().to_vec()
|
||||
} else {
|
||||
@@ -795,32 +795,32 @@ pub mod sys {
|
||||
|
||||
#[pyfunction(name = "__displayhook__")]
|
||||
#[pyfunction]
|
||||
fn displayhook(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
fn displayhook(object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
|
||||
// Save non-None values as "_"
|
||||
if vm.is_none(&obj) {
|
||||
if vm.is_none(&object) {
|
||||
return Ok(());
|
||||
}
|
||||
// set to none to avoid recursion while printing
|
||||
vm.builtins.set_attr("_", vm.ctx.none(), vm)?;
|
||||
// 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)?;
|
||||
vm.builtins.set_attr("_", obj, vm)?;
|
||||
vm.builtins.set_attr("_", object, vm)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[pyfunction(name = "__excepthook__")]
|
||||
#[pyfunction]
|
||||
fn excepthook(
|
||||
exc_type: PyObjectRef,
|
||||
exc_val: PyObjectRef,
|
||||
exc_tb: PyObjectRef,
|
||||
exctype: PyObjectRef,
|
||||
value: PyObjectRef,
|
||||
traceback: PyObjectRef,
|
||||
vm: &VirtualMachine,
|
||||
) -> PyResult<()> {
|
||||
let stderr = super::get_stderr(vm)?;
|
||||
// Keep runtime SyntaxErrors on the normal traceback path.
|
||||
let has_traceback = !vm.is_none(&exc_tb);
|
||||
match vm.normalize_exception(exc_type, exc_val.clone(), exc_tb) {
|
||||
let has_traceback = !vm.is_none(&traceback);
|
||||
match vm.normalize_exception(exctype, value.clone(), traceback) {
|
||||
Ok(exc) => {
|
||||
let native_syntax_error_display = !has_traceback
|
||||
&& 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)
|
||||
}
|
||||
Err(_) => {
|
||||
let type_name = exc_val.class().name();
|
||||
let type_name = value.class().name();
|
||||
let msg = format!(
|
||||
"TypeError: print_exception(): Exception expected for value, {type_name} found\n"
|
||||
);
|
||||
@@ -942,8 +942,8 @@ pub mod sys {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn getrefcount(obj: PyObjectRef) -> usize {
|
||||
obj.strong_count()
|
||||
fn getrefcount(object: PyObjectRef) -> usize {
|
||||
object.strong_count()
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
@@ -986,9 +986,9 @@ pub mod sys {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn _getframe(offset: OptionalArg<usize>, vm: &VirtualMachine) -> PyResult<FrameObjectRef> {
|
||||
let offset = offset.into_option().unwrap_or(0);
|
||||
let frame_ref = crate::frame::frame_at_offset(offset, vm)
|
||||
fn _getframe(depth: OptionalArg<usize>, vm: &VirtualMachine) -> PyResult<FrameObjectRef> {
|
||||
let depth = depth.into_option().unwrap_or(0);
|
||||
let frame_ref = crate::frame::frame_at_offset(depth, vm)
|
||||
.ok_or_else(|| vm.new_value_error("call stack is not deep enough"))?;
|
||||
if let Ok(audit) = vm.sys_module.get_attr("audit", vm) {
|
||||
audit.call((vm.ctx.new_str("sys._getframe"), frame_ref.to_owned()), vm)?;
|
||||
@@ -1211,8 +1211,8 @@ pub mod sys {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn intern(s: PyRefExact<PyStr>, vm: &VirtualMachine) -> PyRef<PyStr> {
|
||||
vm.ctx.intern_str(s).to_owned()
|
||||
fn intern(string: PyRefExact<PyStr>, vm: &VirtualMachine) -> PyRef<PyStr> {
|
||||
vm.ctx.intern_str(string).to_owned()
|
||||
}
|
||||
|
||||
#[pyattr]
|
||||
@@ -1249,50 +1249,47 @@ pub mod sys {
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn setprofile(profilefunc: PyObjectRef, vm: &VirtualMachine) {
|
||||
vm.profile_func.replace(profilefunc);
|
||||
fn setprofile(function: PyObjectRef, vm: &VirtualMachine) {
|
||||
vm.profile_func.replace(function);
|
||||
update_use_tracing(vm);
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn setrecursionlimit(recursion_limit: i32, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let recursion_limit = recursion_limit
|
||||
.to_usize()
|
||||
.filter(|&u| u >= 1)
|
||||
.ok_or_else(|| {
|
||||
fn setrecursionlimit(limit: i32, vm: &VirtualMachine) -> PyResult<()> {
|
||||
let limit = limit.to_usize().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();
|
||||
|
||||
if recursion_limit > recursion_depth {
|
||||
vm.recursion_limit.set(recursion_limit);
|
||||
if limit > recursion_depth {
|
||||
vm.recursion_limit.set(limit);
|
||||
Ok(())
|
||||
} else {
|
||||
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]
|
||||
fn settrace(tracefunc: PyObjectRef, vm: &VirtualMachine) {
|
||||
vm.trace_func.replace(tracefunc);
|
||||
fn settrace(function: PyObjectRef, vm: &VirtualMachine) {
|
||||
vm.trace_func.replace(function);
|
||||
update_use_tracing(vm);
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn _settraceallthreads(tracefunc: PyObjectRef, vm: &VirtualMachine) {
|
||||
let func = (!vm.is_none(&tracefunc)).then(|| tracefunc.clone());
|
||||
fn _settraceallthreads(function: PyObjectRef, vm: &VirtualMachine) {
|
||||
let func = (!vm.is_none(&function)).then(|| function.clone());
|
||||
*vm.state.global_trace_func.lock() = func;
|
||||
vm.trace_func.replace(tracefunc);
|
||||
vm.trace_func.replace(function);
|
||||
update_use_tracing(vm);
|
||||
}
|
||||
|
||||
#[pyfunction]
|
||||
fn _setprofileallthreads(profilefunc: PyObjectRef, vm: &VirtualMachine) {
|
||||
let func = (!vm.is_none(&profilefunc)).then(|| profilefunc.clone());
|
||||
fn _setprofileallthreads(function: PyObjectRef, vm: &VirtualMachine) {
|
||||
let func = (!vm.is_none(&function)).then(|| function.clone());
|
||||
*vm.state.global_profile_func.lock() = func;
|
||||
vm.profile_func.replace(profilefunc);
|
||||
vm.profile_func.replace(function);
|
||||
update_use_tracing(vm);
|
||||
}
|
||||
|
||||
@@ -1329,23 +1326,23 @@ pub mod sys {
|
||||
}
|
||||
|
||||
#[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;
|
||||
|
||||
// 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"));
|
||||
}
|
||||
|
||||
// Remove __dict__ descriptor if present
|
||||
type_obj.attributes.remove(identifier!(vm, __dict__));
|
||||
r#type.attributes.remove(identifier!(vm, __dict__));
|
||||
|
||||
// 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
|
||||
type_obj.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, __dict__), &vm.ctx);
|
||||
r#type.update_slot::<true>(identifier!(vm, __weakref__), &vm.ctx);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user