Simplify Representable impls

This commit is contained in:
Jeong YunWon
2023-03-18 20:14:58 +09:00
parent 23cfdfffba
commit 8851a246de
47 changed files with 289 additions and 261 deletions

View File

@@ -1,4 +1,4 @@
use super::{PyCode, PyGenericAlias, PyStr, PyStrRef, PyType, PyTypeRef};
use super::{PyCode, PyGenericAlias, PyStrRef, PyType, PyTypeRef};
use crate::{
builtins::PyBaseExceptionRef,
class::PyClassImpl,
@@ -127,8 +127,8 @@ impl PyAsyncGen {
impl Representable for PyAsyncGen {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm)).into_ref(vm))
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
Ok(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm))
}
}
@@ -267,7 +267,7 @@ impl PyAsyncGenASend {
impl IterNextIterable for PyAsyncGenASend {}
impl IterNext for PyAsyncGenASend {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
PyIterReturn::from_pyresult(zelf.send(vm.ctx.none(), vm), vm)
}
}
@@ -413,7 +413,7 @@ impl PyAsyncGenAThrow {
impl IterNextIterable for PyAsyncGenAThrow {}
impl IterNext for PyAsyncGenAThrow {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
PyIterReturn::from_pyresult(zelf.send(vm.ctx.none(), vm), vm)
}
}

View File

@@ -182,25 +182,17 @@ impl AsNumber for PyBool {
impl Representable for PyBool {
#[inline]
fn slot_repr(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> {
if get_value(zelf) {
Ok(vm.ctx.names.True.to_owned())
let name = if get_value(zelf.as_object()) {
vm.ctx.names.True
} else {
Ok(vm.ctx.names.False.to_owned())
}
vm.ctx.names.False
};
Ok(name.to_owned())
}
#[inline]
fn __repr__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Self::slot_repr(&zelf, vm)
}
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
if get_value(zelf.as_object()) {
Ok(vm.ctx.names.True.to_owned())
} else {
Ok(vm.ctx.names.False.to_owned())
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use slot_repr instead")
}
}

View File

@@ -109,7 +109,7 @@ impl PyBuiltinFunction {
impl Callable for PyBuiltinFunction {
type Args = FuncArgs;
#[inline]
fn call(zelf: &crate::Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
(zelf.value.func)(vm, args)
}
}
@@ -156,8 +156,8 @@ impl PyBuiltinFunction {
impl Representable for PyBuiltinFunction {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from(format!("<built-in function {}>", zelf.value.name)).into_ref(vm))
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(format!("<built-in function {}>", zelf.value.name))
}
}
@@ -210,7 +210,7 @@ impl GetDescriptor for PyBuiltinMethod {
impl Callable for PyBuiltinMethod {
type Args = FuncArgs;
#[inline]
fn call(zelf: &crate::Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
(zelf.value.func)(vm, args)
}
}
@@ -266,13 +266,12 @@ impl PyBuiltinMethod {
impl Representable for PyBuiltinMethod {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from(format!(
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(format!(
"<method '{}' of '{}' objects>",
&zelf.value.name,
zelf.class.name()
))
.into_ref(vm))
}
}

View File

@@ -1,7 +1,7 @@
//! Implementation of the python bytearray object.
use super::{
PositionIterInternal, PyBytes, PyBytesRef, PyDictRef, PyIntRef, PyStr, PyStrRef, PyTuple,
PyTupleRef, PyType, PyTypeRef,
PositionIterInternal, PyBytes, PyBytesRef, PyDictRef, PyIntRef, PyStrRef, PyTuple, PyTupleRef,
PyType, PyTypeRef,
};
use crate::{
anystr::{self, AnyStr},
@@ -294,7 +294,7 @@ impl PyByteArray {
}
}
fn irepeat(zelf: &crate::Py<Self>, n: isize, vm: &VirtualMachine) -> PyResult<()> {
fn irepeat(zelf: &Py<Self>, n: isize, vm: &VirtualMachine) -> PyResult<()> {
if n == 1 {
return Ok(());
}
@@ -733,7 +733,7 @@ impl Initializer for PyByteArray {
impl Comparable for PyByteArray {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -882,12 +882,10 @@ impl Iterable for PyByteArray {
impl Representable for PyByteArray {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let class = zelf.class();
let class_name = class.name();
zelf.inner()
.repr(Some(&class_name), vm)
.map(|s| PyStr::from(s).into_ref(vm))
zelf.inner().repr(Some(&class_name), vm)
}
}
@@ -932,7 +930,7 @@ impl Unconstructible for PyByteArrayIterator {}
impl IterNextIterable for PyByteArrayIterator {}
impl IterNext for PyByteArrayIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().next(|bytearray, pos| {
let buf = bytearray.borrow_buf();
Ok(PyIterReturn::from_result(

View File

@@ -1,6 +1,5 @@
use super::{
PositionIterInternal, PyDictRef, PyIntRef, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType,
PyTypeRef,
PositionIterInternal, PyDictRef, PyIntRef, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef,
};
use crate::{
anystr::{self, AnyStr},
@@ -647,14 +646,14 @@ impl AsNumber for PyBytes {
impl Hashable for PyBytes {
#[inline]
fn hash(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
Ok(zelf.inner.hash(vm))
}
}
impl Comparable for PyBytes {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -688,10 +687,8 @@ impl Iterable for PyBytes {
impl Representable for PyBytes {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
zelf.inner
.repr(None, vm)
.map(|s| PyStr::from(s).into_ref(vm))
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
zelf.inner.repr(None, vm)
}
}
@@ -732,7 +729,7 @@ impl Unconstructible for PyBytesIterator {}
impl IterNextIterable for PyBytesIterator {}
impl IterNext for PyBytesIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().next(|bytes, pos| {
Ok(PyIterReturn::from_result(
bytes

View File

@@ -1,4 +1,4 @@
use super::{PyBoundMethod, PyStr, PyStrRef, PyType, PyTypeRef};
use super::{PyBoundMethod, PyStr, PyType, PyTypeRef};
use crate::{
class::PyClassImpl,
common::lock::PyMutex,
@@ -158,23 +158,24 @@ impl PyClassMethod {
impl Representable for PyClassMethod {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let callable = zelf.callable.lock().repr(vm).unwrap();
let class = Self::class(vm);
match (
let repr = match (
class
.qualname(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str()),
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
) {
(None, _) => Err(vm.new_type_error("Unknown qualified name".into())),
(None, _) => return Err(vm.new_type_error("Unknown qualified name".into())),
(Some(qualname), Some(module)) if module != "builtins" => {
Ok(PyStr::from(format!("<{module}.{qualname}({callable})>")).into_ref(vm))
format!("<{module}.{qualname}({callable})>")
}
_ => Ok(PyStr::from(format!("<{}({})>", class.slot_name(), callable)).into_ref(vm)),
}
_ => format!("<{}({})>", class.slot_name(), callable),
};
Ok(repr)
}
}

View File

@@ -2,7 +2,7 @@
*/
use super::{PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef};
use super::{PyStrRef, PyTupleRef, PyType, PyTypeRef};
use crate::{
builtins::PyStrInterned,
bytecode::{self, AsBag, BorrowedConstant, CodeFlags, Constant, ConstantBag},
@@ -221,16 +221,15 @@ impl PyCode {}
impl Representable for PyCode {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
let code = &zelf.code;
Ok(PyStr::from(format!(
Ok(format!(
"<code object {} at {:#x} file {:?}, line {}>",
code.obj_name,
zelf.get_id(),
code.source_path.as_str(),
code.first_line_number
))
.into_ref(vm))
}
}

View File

@@ -1,4 +1,4 @@
use super::{float, PyStr, PyStrRef, PyType, PyTypeRef};
use super::{float, PyStr, PyType, PyTypeRef};
use crate::{
class::PyClassImpl,
convert::{ToPyObject, ToPyResult},
@@ -371,7 +371,7 @@ impl PyComplex {
impl Comparable for PyComplex {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -401,7 +401,7 @@ impl Comparable for PyComplex {
impl Hashable for PyComplex {
#[inline]
fn hash(zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> {
fn hash(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> {
let value = zelf.value;
let re_hash =
@@ -455,7 +455,7 @@ impl AsNumber for PyComplex {
impl Representable for PyComplex {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
// TODO: when you fix this, move it to rustpython_common::complex::repr and update
// ast/src/unparse.rs + impl Display for Constant in ast/src/constant.rs
let Complex64 { re, im } = zelf.value;
@@ -470,7 +470,7 @@ impl Representable for PyComplex {
// positive empty => return im_part, integer => drop ., fractional => float_ops
let re_part = if re == 0.0 {
if re.is_sign_positive() {
return Ok(PyStr::from(im_part).into_ref(vm));
return Ok(im_part);
} else {
re.to_string()
}
@@ -489,7 +489,7 @@ impl Representable for PyComplex {
}
result.push_str(&im_part);
result.push(')');
Ok(PyStr::from(result).into_ref(vm))
Ok(result)
}
}

View File

@@ -1,4 +1,4 @@
use super::{PyCode, PyStr, PyStrRef, PyType};
use super::{PyCode, PyStrRef, PyType};
use crate::{
class::PyClassImpl,
coroutine::Coro,
@@ -103,14 +103,14 @@ impl Unconstructible for PyCoroutine {}
impl Representable for PyCoroutine {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm)).into_ref(vm))
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
Ok(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm))
}
}
impl IterNextIterable for PyCoroutine {}
impl IterNext for PyCoroutine {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
Self::send(zelf.to_owned(), vm.ctx.none(), vm)
}
}
@@ -149,7 +149,7 @@ impl PyCoroutineWrapper {
impl IterNextIterable for PyCoroutineWrapper {}
impl IterNext for PyCoroutineWrapper {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
Self::send(zelf.to_owned(), vm.ctx.none(), vm)
}
}

View File

@@ -1,4 +1,4 @@
use super::{PyStr, PyStrRef, PyType, PyTypeRef};
use super::{PyStr, PyType, PyTypeRef};
use crate::{
class::PyClassImpl,
function::PySetterValue,
@@ -190,13 +190,12 @@ impl Unconstructible for MemberDescrObject {}
impl Representable for MemberDescrObject {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from(format!(
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(format!(
"<member '{}' of '{}' objects>",
zelf.common.name,
zelf.common.typ.name(),
))
.into_ref(vm))
}
}

View File

@@ -506,7 +506,7 @@ impl Iterable for PyDict {
impl Representable for PyDict {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let s = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
let mut str_parts = Vec::with_capacity(zelf.len());
for (key, value) in zelf {
@@ -515,11 +515,16 @@ impl Representable for PyDict {
str_parts.push(format!("{key_repr}: {value_repr}"));
}
format!("{{{}}}", str_parts.join(", "))
vm.ctx.new_str(format!("{{{}}}", str_parts.join(", ")))
} else {
"{...}".to_owned()
vm.ctx.intern_str("{...}").to_owned()
};
Ok(PyStr::from(s).into_ref(vm))
Ok(s)
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use repr instead")
}
}
@@ -792,18 +797,24 @@ macro_rules! dict_view {
impl Representable for $name {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let s = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
let mut str_parts = Vec::with_capacity(zelf.len());
for (key, value) in zelf.dict().clone() {
let s = &Self::item(vm, key, value).repr(vm)?;
str_parts.push(s.as_str().to_owned());
}
format!("{}([{}])", Self::NAME, str_parts.join(", "))
vm.ctx
.new_str(format!("{}([{}])", Self::NAME, str_parts.join(", ")))
} else {
"{...}".to_owned()
vm.ctx.intern_str("{...}").to_owned()
};
Ok(PyStr::from(s).into_ref(vm))
Ok(s)
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use repr instead")
}
}

View File

@@ -68,7 +68,7 @@ impl PyEnumerate {
impl IterNextIterable for PyEnumerate {}
impl IterNext for PyEnumerate {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
let next_obj = match zelf.iterator.next(vm)? {
PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)),
PyIterReturn::Return(obj) => obj,
@@ -127,7 +127,7 @@ impl PyReverseSequenceIterator {
impl IterNextIterable for PyReverseSequenceIterator {}
impl IterNext for PyReverseSequenceIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal
.lock()
.rev_next(|obj, pos| PyIterReturn::from_getitem_result(obj.get_item(&pos, vm), vm))

View File

@@ -45,7 +45,7 @@ impl PyFilter {
impl IterNextIterable for PyFilter {}
impl IterNext for PyFilter {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
let predicate = &zelf.predicate;
loop {
let next_obj = match zelf.iterator.next(vm)? {

View File

@@ -495,7 +495,7 @@ impl PyFloat {
impl Comparable for PyFloat {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -536,7 +536,7 @@ impl Comparable for PyFloat {
impl Hashable for PyFloat {
#[inline]
fn hash(zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> {
fn hash(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> {
Ok(hash::hash_float(zelf.to_f64()).unwrap_or_else(|| hash::hash_object_id(zelf.get_id())))
}
}
@@ -580,8 +580,8 @@ impl AsNumber for PyFloat {
impl Representable for PyFloat {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from(float_ops::to_string(zelf.value)).into_ref(vm))
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(float_ops::to_string(zelf.value))
}
}

View File

@@ -2,14 +2,13 @@
*/
use super::{PyCode, PyDictRef, PyIntRef, PyStr, PyStrRef};
use super::{PyCode, PyDictRef, PyIntRef, PyStrRef};
use crate::{
class::PyClassImpl,
frame::{Frame, FrameRef},
function::PySetterValue,
object::PyPayload,
types::{Constructor, Representable, Unconstructible},
AsObject, Context, PyObjectRef, PyRef, PyResult, VirtualMachine,
AsObject, Context, Py, PyObjectRef, PyRef, PyResult, VirtualMachine,
};
use num_traits::Zero;
@@ -24,8 +23,14 @@ impl Unconstructible for Frame {}
impl Representable for Frame {
#[inline]
fn repr(_zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from("<frame object at .. >").into_ref(vm))
fn repr(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
const REPR: &str = "<frame object at .. >";
Ok(vm.ctx.intern_str(REPR).to_owned())
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use repr instead")
}
}

View File

@@ -452,20 +452,19 @@ impl GetDescriptor for PyFunction {
impl Callable for PyFunction {
type Args = FuncArgs;
#[inline]
fn call(zelf: &crate::Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
zelf.invoke(args, vm)
}
}
impl Representable for PyFunction {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from(format!(
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(format!(
"<function {} at {:#x}>",
zelf.qualname(),
zelf.get_id()
))
.into_ref(vm))
}
}
@@ -479,7 +478,7 @@ pub struct PyBoundMethod {
impl Callable for PyBoundMethod {
type Args = FuncArgs;
#[inline]
fn call(zelf: &crate::Py<Self>, mut args: FuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &Py<Self>, mut args: FuncArgs, vm: &VirtualMachine) -> PyResult {
args.prepend_arg(zelf.object.clone());
zelf.function.call(args, vm)
}
@@ -487,7 +486,7 @@ impl Callable for PyBoundMethod {
impl Comparable for PyBoundMethod {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
_vm: &VirtualMachine,

View File

@@ -3,7 +3,7 @@ use crate::{
bytecode::CodeFlags,
convert::ToPyObject,
function::FuncArgs,
AsObject, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine,
AsObject, Py, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine,
};
use num_traits::ToPrimitive;
use rustpython_jit::{AbiValue, Args, CompiledCode, JitArgumentError, JitType};
@@ -64,10 +64,7 @@ fn get_jit_arg_type(dict: &PyDictRef, name: &str, vm: &VirtualMachine) -> PyResu
}
}
pub fn get_jit_arg_types(
func: &crate::Py<PyFunction>,
vm: &VirtualMachine,
) -> PyResult<Vec<JitType>> {
pub fn get_jit_arg_types(func: &Py<PyFunction>, vm: &VirtualMachine) -> PyResult<Vec<JitType>> {
let arg_names = func.code.arg_names();
if func

View File

@@ -2,7 +2,7 @@
* The mythical generator.
*/
use super::{PyCode, PyStr, PyStrRef, PyType};
use super::{PyCode, PyStrRef, PyType};
use crate::{
class::PyClassImpl,
coroutine::Coro,
@@ -96,14 +96,14 @@ impl Unconstructible for PyGenerator {}
impl Representable for PyGenerator {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm)).into_ref(vm))
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
Ok(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm))
}
}
impl IterNextIterable for PyGenerator {}
impl IterNext for PyGenerator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
Self::send(zelf.to_owned(), vm.ctx.none(), vm)
}
}

View File

@@ -344,7 +344,7 @@ impl AsMapping for PyGenericAlias {
impl Callable for PyGenericAlias {
type Args = FuncArgs;
fn call(zelf: &crate::Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
PyType::call(&zelf.origin, args, vm).map(|obj| {
if let Err(exc) = obj.set_attr(identifier!(vm, __orig_class__), zelf.to_owned(), vm) {
if !exc.fast_isinstance(vm.ctx.exceptions.attribute_error)
@@ -360,7 +360,7 @@ impl Callable for PyGenericAlias {
impl Comparable for PyGenericAlias {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -384,7 +384,7 @@ impl Comparable for PyGenericAlias {
impl Hashable for PyGenericAlias {
#[inline]
fn hash(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<hash::PyHash> {
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<hash::PyHash> {
Ok(zelf.origin.as_object().hash(vm)? ^ zelf.args.as_object().hash(vm)?)
}
}
@@ -402,8 +402,8 @@ impl GetAttr for PyGenericAlias {
impl Representable for PyGenericAlias {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
zelf.repr(vm).map(|s| PyStr::from(s).into_ref(vm))
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
zelf.repr(vm)
}
}

View File

@@ -700,7 +700,7 @@ impl PyInt {
impl Comparable for PyInt {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -714,14 +714,14 @@ impl Comparable for PyInt {
impl Representable for PyInt {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from(zelf.value.to_string()).into_ref(vm))
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
Ok(zelf.value.to_string())
}
}
impl Hashable for PyInt {
#[inline]
fn hash(zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> {
fn hash(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> {
Ok(hash::hash_bigint(zelf.as_bigint()))
}
}

View File

@@ -211,7 +211,7 @@ impl PySequenceIterator {
impl IterNextIterable for PySequenceIterator {}
impl IterNext for PySequenceIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().next(|obj, pos| {
let seq = PySequence {
obj,
@@ -247,7 +247,7 @@ impl PyCallableIterator {
impl IterNextIterable for PyCallableIterator {}
impl IterNext for PyCallableIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
let status = zelf.status.upgradable_read();
let next = if let IterStatus::Active(callable) = &*status {
let ret = callable.invoke((), vm)?;

View File

@@ -1,4 +1,4 @@
use super::{PositionIterInternal, PyGenericAlias, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef};
use super::{PositionIterInternal, PyGenericAlias, PyTupleRef, PyType, PyTypeRef};
use crate::atomic_func;
use crate::common::lock::{
PyMappedRwLockReadGuard, PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard,
@@ -472,7 +472,7 @@ impl Iterable for PyList {
impl Comparable for PyList {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -491,7 +491,7 @@ impl Comparable for PyList {
impl Representable for PyList {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let s = if zelf.len() == 0 {
"[]".to_owned()
} else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
@@ -499,7 +499,7 @@ impl Representable for PyList {
} else {
"[...]".to_owned()
};
Ok(PyStr::from(s).into_ref(vm))
Ok(s)
}
}
@@ -567,7 +567,7 @@ impl Unconstructible for PyListIterator {}
impl IterNextIterable for PyListIterator {}
impl IterNext for PyListIterator {
fn next(zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().next(|list, pos| {
let vec = list.borrow_vec();
Ok(PyIterReturn::from_result(vec.get(pos).cloned().ok_or(None)))
@@ -612,7 +612,7 @@ impl Unconstructible for PyListReverseIterator {}
impl IterNextIterable for PyListReverseIterator {}
impl IterNext for PyListReverseIterator {
fn next(zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().rev_next(|list, pos| {
let vec = list.borrow_vec();
Ok(PyIterReturn::from_result(vec.get(pos).cloned().ok_or(None)))

View File

@@ -53,7 +53,7 @@ impl PyMap {
impl IterNextIterable for PyMap {}
impl IterNext for PyMap {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
let mut next_objs = Vec::new();
for iterator in &zelf.iterators {
let item = match iterator.next(vm)? {

View File

@@ -1,6 +1,4 @@
use super::{
PyDict, PyDictRef, PyGenericAlias, PyList, PyStr, PyStrRef, PyTuple, PyType, PyTypeRef,
};
use super::{PyDict, PyDictRef, PyGenericAlias, PyList, PyTuple, PyType, PyTypeRef};
use crate::{
atomic_func,
class::PyClassImpl,
@@ -200,7 +198,7 @@ impl PyMappingProxy {
impl Comparable for PyMappingProxy {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -270,9 +268,9 @@ impl Iterable for PyMappingProxy {
impl Representable for PyMappingProxy {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let obj = zelf.to_object(vm)?;
Ok(PyStr::from(format!("mappingproxy({})", obj.repr(vm)?)).into_ref(vm))
Ok(format!("mappingproxy({})", obj.repr(vm)?))
}
}

View File

@@ -715,7 +715,7 @@ impl PyMemoryView {
}
}
fn eq(zelf: &crate::Py<Self>, other: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
fn eq(zelf: &Py<Self>, other: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
if zelf.is(other) {
return Ok(true);
}
@@ -1008,7 +1008,7 @@ impl AsSequence for PyMemoryView {
impl Comparable for PyMemoryView {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -1029,7 +1029,7 @@ impl Comparable for PyMemoryView {
}
impl Hashable for PyMemoryView {
fn hash(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
zelf.hash
.get_or_try_init(|| {
zelf.try_not_released(vm)?;
@@ -1052,12 +1052,13 @@ impl PyPayload for PyMemoryView {
impl Representable for PyMemoryView {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
if zelf.released.load() {
Ok(PyStr::from(format!("<released memory at {:#x}>", zelf.get_id())).into_ref(vm))
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
let repr = if zelf.released.load() {
format!("<released memory at {:#x}>", zelf.get_id())
} else {
Ok(PyStr::from(format!("<memory at {:#x}>", zelf.get_id())).into_ref(vm))
}
format!("<memory at {:#x}>", zelf.get_id())
};
Ok(repr)
}
}
@@ -1142,7 +1143,7 @@ impl Unconstructible for PyMemoryViewIterator {}
impl IterNextIterable for PyMemoryViewIterator {}
impl IterNext for PyMemoryViewIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().next(|mv, pos| {
let len = mv.len(vm)?;
Ok(if pos >= len {

View File

@@ -142,7 +142,7 @@ impl GetAttr for PyModule {
impl Representable for PyModule {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let importlib = vm.import("_frozen_importlib", None, 0)?;
let module_repr = importlib.get_attr("_module_repr", vm)?;
module_repr.call((zelf.to_owned(),), vm).and_then(|obj| {
@@ -150,6 +150,11 @@ impl Representable for PyModule {
.map_err(|_| vm.new_type_error("_module_repr did not return a string".into()))
})
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use repr instead")
}
}
pub(crate) fn init(context: &Context) {

View File

@@ -1,4 +1,4 @@
use super::{PyStr, PyStrRef, PyType, PyTypeRef};
use super::{PyType, PyTypeRef};
use crate::{
builtins::PyDict,
class::PyClassImpl,
@@ -61,7 +61,7 @@ impl Initializer for PyNamespace {
impl Comparable for PyNamespace {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -77,7 +77,7 @@ impl Comparable for PyNamespace {
impl Representable for PyNamespace {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let o = zelf.as_object();
let name = if o.class().is(vm.ctx.types.namespace_type) {
"namespace".to_owned()
@@ -98,7 +98,7 @@ impl Representable for PyNamespace {
} else {
format!("{name}(...)")
};
Ok(PyStr::from(repr).into_ref(vm))
Ok(repr)
}
}

View File

@@ -1,6 +1,5 @@
use super::{
builtins_iter, tuple::tuple_hash, PyInt, PyIntRef, PySlice, PyStr, PyStrRef, PyTupleRef,
PyType, PyTypeRef,
builtins_iter, tuple::tuple_hash, PyInt, PyIntRef, PySlice, PyTupleRef, PyType, PyTypeRef,
};
use crate::{
atomic_func,
@@ -418,7 +417,7 @@ impl AsSequence for PyRange {
}
impl Hashable for PyRange {
fn hash(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
let length = zelf.compute_length();
let elements = if length.is_zero() {
[vm.ctx.new_int(length).into(), vm.ctx.none(), vm.ctx.none()]
@@ -505,16 +504,13 @@ impl Iterable for PyRange {
impl Representable for PyRange {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
if zelf.step.as_bigint().is_one() {
Ok(PyStr::from(format!("range({}, {})", zelf.start, zelf.stop)).into_ref(vm))
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
let repr = if zelf.step.as_bigint().is_one() {
format!("range({}, {})", zelf.start, zelf.stop)
} else {
Ok(PyStr::from(format!(
"range({}, {}, {})",
zelf.start, zelf.stop, zelf.step
))
.into_ref(vm))
}
format!("range({}, {}, {})", zelf.start, zelf.stop, zelf.step)
};
Ok(repr)
}
}
@@ -574,7 +570,7 @@ impl Unconstructible for PyLongRangeIterator {}
impl IterNextIterable for PyLongRangeIterator {}
impl IterNext for PyLongRangeIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
// TODO: In pathological case (index == usize::MAX) this can wrap around
// (since fetch_add wraps). This would result in the iterator spinning again
// from the beginning.
@@ -640,7 +636,7 @@ impl Unconstructible for PyRangeIterator {}
impl IterNextIterable for PyRangeIterator {}
impl IterNext for PyRangeIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
// TODO: In pathological case (index == usize::MAX) this can wrap around
// (since fetch_add wraps). This would result in the iterator spinning again
// from the beginning.

View File

@@ -2,8 +2,8 @@
* Builtin set type with a sequence of unique items.
*/
use super::{
builtins_iter, IterStatus, PositionIterInternal, PyDict, PyDictRef, PyGenericAlias, PyStr,
PyStrRef, PyTupleRef, PyType, PyTypeRef,
builtins_iter, IterStatus, PositionIterInternal, PyDict, PyDictRef, PyGenericAlias, PyTupleRef,
PyType, PyTypeRef,
};
use crate::{
atomic_func,
@@ -878,7 +878,7 @@ impl AsNumber for PySet {
impl Representable for PySet {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let class = zelf.class();
let borrowed_name = class.name();
let class_name = borrowed_name.deref();
@@ -894,7 +894,7 @@ impl Representable for PySet {
} else {
format!("{class_name}(...)")
};
Ok(PyStr::from(s).into_ref(vm))
Ok(s)
}
}
@@ -1169,7 +1169,7 @@ impl AsNumber for PyFrozenSet {
impl Representable for PyFrozenSet {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let inner = &zelf.inner;
let class = zelf.class();
let class_name = class.name();
@@ -1180,7 +1180,7 @@ impl Representable for PyFrozenSet {
} else {
format!("{class_name}(...)")
};
Ok(PyStr::from(s).into_ref(vm))
Ok(s)
}
}

View File

@@ -1,4 +1,4 @@
use super::{PyStr, PyStrRef, PyType, PyTypeRef};
use super::{PyStrRef, PyType, PyTypeRef};
use crate::{
class::PyClassImpl,
convert::ToPyObject,
@@ -52,8 +52,13 @@ impl PyNone {
impl Representable for PyNone {
#[inline]
fn repr(_zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from("None").into_ref(vm))
fn repr(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(vm.ctx.names.None.to_owned())
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use repr instead")
}
}
@@ -96,15 +101,20 @@ impl PyNotImplemented {
}
#[pymethod(magic)]
fn reduce(&self) -> String {
"NotImplemented".to_owned()
fn reduce(&self, vm: &VirtualMachine) -> PyStrRef {
vm.ctx.names.NotImplemented.to_owned()
}
}
impl Representable for PyNotImplemented {
#[inline]
fn repr(_zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from("NotImplemented").into_ref(vm))
fn repr(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(vm.ctx.names.NotImplemented.to_owned())
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use repr instead")
}
}

View File

@@ -1,6 +1,6 @@
// sliceobject.{h,c} in CPython
// spell-checker:ignore sliceobject
use super::{PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef};
use super::{PyStrRef, PyTupleRef, PyType, PyTypeRef};
use crate::{
class::PyClassImpl,
convert::ToPyObject,
@@ -199,7 +199,7 @@ impl PySlice {
impl Comparable for PySlice {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -246,18 +246,17 @@ impl Comparable for PySlice {
}
impl Representable for PySlice {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let start_repr = zelf.start_ref(vm).repr(vm)?;
let stop_repr = &zelf.stop.repr(vm)?;
let step_repr = zelf.step_ref(vm).repr(vm)?;
Ok(PyStr::from(format!(
Ok(format!(
"slice({}, {}, {})",
start_repr.as_str(),
stop_repr.as_str(),
step_repr.as_str()
))
.into_ref(vm))
}
}
@@ -282,15 +281,20 @@ impl Constructor for PyEllipsis {
#[pyclass(with(Constructor, Representable))]
impl PyEllipsis {
#[pymethod(magic)]
fn reduce(&self) -> String {
"Ellipsis".to_owned()
fn reduce(&self, vm: &VirtualMachine) -> PyStrRef {
vm.ctx.names.Ellipsis.to_owned()
}
}
impl Representable for PyEllipsis {
#[inline]
fn repr(_zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(PyStr::from("Ellipsis").into_ref(vm))
fn repr(_zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
Ok(vm.ctx.names.Ellipsis.to_owned())
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use repr instead")
}
}

View File

@@ -1,4 +1,4 @@
use super::{PyStr, PyStrRef, PyType, PyTypeRef};
use super::{PyStr, PyType, PyTypeRef};
use crate::{
builtins::builtin_func::PyBuiltinMethod,
class::PyClassImpl,
@@ -158,15 +158,14 @@ impl PyStaticMethod {
impl Callable for PyStaticMethod {
type Args = FuncArgs;
#[inline]
fn call(zelf: &crate::Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
let callable = zelf.callable.lock().clone();
callable.call(args, vm)
}
}
impl Representable for PyStaticMethod {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let callable = zelf.callable.lock().repr(vm).unwrap();
let class = Self::class(vm);
@@ -179,9 +178,9 @@ impl Representable for PyStaticMethod {
) {
(None, _) => Err(vm.new_type_error("Unknown qualified name".into())),
(Some(qualname), Some(module)) if module != "builtins" => {
Ok(PyStr::from(format!("<{module}.{qualname}({callable})>")).into_ref(vm))
Ok(format!("<{module}.{qualname}({callable})>"))
}
_ => Ok(PyStr::from(format!("<{}({})>", class.slot_name(), callable)).into_ref(vm)),
_ => Ok(format!("<{}({})>", class.slot_name(), callable)),
}
}
}

View File

@@ -229,7 +229,7 @@ impl Unconstructible for PyStrIterator {}
impl IterNextIterable for PyStrIterator {}
impl IterNext for PyStrIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
let mut internal = zelf.internal.lock();
if let IterStatus::Active(s) = &internal.0.status {
@@ -497,11 +497,10 @@ impl PyStr {
}
#[inline]
pub(crate) fn repr(&self, vm: &VirtualMachine) -> PyResult<PyStrRef> {
pub(crate) fn repr(&self, vm: &VirtualMachine) -> PyResult<String> {
rustpython_common::str::repr(self.as_str())
.to_string_checked()
.map_err(|err| vm.new_overflow_error(err.to_string()))
.map(|s| PyStr::from(s).into_ref(vm))
}
#[pymethod]
@@ -1263,21 +1262,21 @@ impl PyStrRef {
impl Representable for PyStr {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
zelf.repr(vm)
}
}
impl Hashable for PyStr {
#[inline]
fn hash(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<hash::PyHash> {
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<hash::PyHash> {
Ok(zelf.hash(vm))
}
}
impl Comparable for PyStr {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
_vm: &VirtualMachine,

View File

@@ -3,7 +3,7 @@
See also [CPython source code.](https://github.com/python/cpython/blob/50b48572d9a90c5bb36e2bef6179548ea927a35a/Objects/typeobject.c#L7663)
*/
use super::{PyStr, PyStrRef, PyType, PyTypeRef};
use super::{PyStrRef, PyType, PyTypeRef};
use crate::{
class::PyClassImpl,
function::{IntoFuncArgs, OptionalArg},
@@ -186,17 +186,15 @@ impl GetDescriptor for PySuper {
impl Representable for PySuper {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let typname = &zelf.typ.name();
match zelf.obj {
Some((_, ref ty)) => Ok(PyStr::from(format!(
"<super: <class '{}'>, <{} object>>",
typname,
ty.name()
))
.into_ref(vm)),
None => Ok(PyStr::from(format!("<super: <class '{typname}'>, NULL>")).into_ref(vm)),
}
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
let type_name = &zelf.typ.name();
let repr = match zelf.obj {
Some((_, ref ty)) => {
format!("<super: <class '{}'>, <{} object>>", type_name, ty.name())
}
None => format!("<super: <class '{type_name}'>, NULL>"),
};
Ok(repr)
}
}

View File

@@ -1,6 +1,4 @@
use once_cell::sync::Lazy;
use super::{PositionIterInternal, PyGenericAlias, PyStr, PyStrRef, PyType, PyTypeRef};
use super::{PositionIterInternal, PyGenericAlias, PyStrRef, PyType, PyTypeRef};
use crate::common::{hash::PyHash, lock::PyMutex};
use crate::{
atomic_func,
@@ -20,6 +18,7 @@ use crate::{
vm::VirtualMachine,
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
};
use once_cell::sync::Lazy;
use std::{fmt, marker::PhantomData};
#[pyclass(module = false, name = "tuple")]
@@ -367,14 +366,14 @@ impl AsSequence for PyTuple {
impl Hashable for PyTuple {
#[inline]
fn hash(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
tuple_hash(zelf.as_slice(), vm)
}
}
impl Comparable for PyTuple {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -400,19 +399,25 @@ impl Iterable for PyTuple {
impl Representable for PyTuple {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let s = if zelf.len() == 0 {
"()".to_owned()
vm.ctx.intern_str("()").to_owned()
} else if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
if zelf.len() == 1 {
let s = if zelf.len() == 1 {
format!("({},)", zelf.elements[0].repr(vm)?)
} else {
collection_repr(None, "(", ")", zelf.elements.iter(), vm)?
}
};
vm.ctx.new_str(s)
} else {
"(...)".to_owned()
vm.ctx.intern_str("(...)").to_owned()
};
Ok(PyStr::from(s).into_ref(vm))
Ok(s)
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use repr instead")
}
}
@@ -453,7 +458,7 @@ impl Unconstructible for PyTupleIterator {}
impl IterNextIterable for PyTupleIterator {}
impl IterNext for PyTupleIterator {
fn next(zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().next(|tuple, pos| {
Ok(PyIterReturn::from_result(
tuple.get(pos).cloned().ok_or(None),

View File

@@ -985,7 +985,7 @@ impl GetAttr for PyType {
impl SetAttr for PyType {
fn setattro(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
attr_name: PyStrRef,
value: PySetterValue,
vm: &VirtualMachine,
@@ -1024,7 +1024,7 @@ impl SetAttr for PyType {
impl Callable for PyType {
type Args = FuncArgs;
fn call(zelf: &crate::Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &Py<Self>, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
vm_trace!("type_call: {:?}", zelf);
let obj = call_slot_new(zelf.to_owned(), zelf.to_owned(), args.clone(), vm)?;
@@ -1055,25 +1055,25 @@ impl AsNumber for PyType {
impl Representable for PyType {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let module = zelf.module(vm);
let module = module.downcast_ref::<PyStr>().map(|m| m.as_str());
match module {
let repr = match module {
Some(module) if module != "builtins" => {
let name = zelf.name();
Ok(PyStr::from(format!(
format!(
"<class '{}.{}'>",
module,
zelf.qualname(vm)
.downcast_ref::<PyStr>()
.map(|n| n.as_str())
.unwrap_or_else(|| &name)
))
.into_ref(vm))
)
}
_ => Ok(PyStr::from(format!("<class '{}'>", zelf.slot_name())).into_ref(vm)),
}
_ => format!("<class '{}'>", zelf.slot_name()),
};
Ok(repr)
}
}

View File

@@ -34,10 +34,6 @@ impl PyPayload for PyUnion {
}
}
#[pyclass(
flags(BASETYPE),
with(Hashable, Comparable, AsMapping, AsNumber, Representable)
)]
impl PyUnion {
pub fn new(args: PyTupleRef, vm: &VirtualMachine) -> Self {
let parameters = make_parameters(&args, vm);
@@ -82,7 +78,13 @@ impl PyUnion {
.collect::<PyResult<Vec<_>>>()?
.join(" | "))
}
}
#[pyclass(
flags(BASETYPE),
with(Hashable, Comparable, AsMapping, AsNumber, Representable)
)]
impl PyUnion {
#[pygetset(magic)]
fn parameters(&self) -> PyObjectRef {
self.parameters.clone().into()
@@ -270,7 +272,7 @@ impl AsNumber for PyUnion {
impl Comparable for PyUnion {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -292,7 +294,7 @@ impl Comparable for PyUnion {
impl Hashable for PyUnion {
#[inline]
fn hash(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<hash::PyHash> {
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<hash::PyHash> {
let set = PyFrozenSet::from_iter(vm, zelf.args.into_iter().cloned())?;
PyFrozenSet::hash(&set.into_ref(vm), vm)
}
@@ -311,8 +313,8 @@ impl GetAttr for PyUnion {
impl Representable for PyUnion {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
zelf.repr(vm).map(|s| PyStr::from(s).into_ref(vm))
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
zelf.repr(vm)
}
}

View File

@@ -140,7 +140,7 @@ impl GetAttr for PyWeakProxy {
impl SetAttr for PyWeakProxy {
fn setattro(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
attr_name: PyStrRef,
value: PySetterValue,
vm: &VirtualMachine,
@@ -152,7 +152,7 @@ impl SetAttr for PyWeakProxy {
impl Comparable for PyWeakProxy {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -199,9 +199,14 @@ impl AsMapping for PyWeakProxy {
impl Representable for PyWeakProxy {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
zelf.try_upgrade(vm)?.repr(vm)
}
#[cold]
fn repr_str(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
unreachable!("use repr instead")
}
}
pub fn init(context: &Context) {

View File

@@ -1,4 +1,4 @@
use super::{PyGenericAlias, PyStr, PyStrRef, PyType, PyTypeRef};
use super::{PyGenericAlias, PyType, PyTypeRef};
use crate::common::{
atomic::{Ordering, Radium},
hash::{self, PyHash},
@@ -29,7 +29,7 @@ impl PyPayload for PyWeak {
impl Callable for PyWeak {
type Args = ();
#[inline]
fn call(zelf: &crate::Py<Self>, _: Self::Args, vm: &VirtualMachine) -> PyResult {
fn call(zelf: &Py<Self>, _: Self::Args, vm: &VirtualMachine) -> PyResult {
Ok(vm.unwrap_or_none(zelf.upgrade()))
}
}
@@ -59,7 +59,7 @@ impl PyWeak {
}
impl Hashable for PyWeak {
fn hash(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash> {
let hash = match zelf.hash.load(Ordering::Relaxed) {
hash::SENTINEL => {
let obj = zelf
@@ -85,7 +85,7 @@ impl Hashable for PyWeak {
impl Comparable for PyWeak {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -104,19 +104,19 @@ impl Comparable for PyWeak {
impl Representable for PyWeak {
#[inline]
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
fn repr_str(zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<String> {
let id = zelf.get_id();
if let Some(o) = zelf.upgrade() {
Ok(PyStr::from(format!(
let repr = if let Some(o) = zelf.upgrade() {
format!(
"<weakref at {:#x}; to '{}' at {:#x}>",
id,
o.class().name(),
o.get_id(),
))
.into_ref(vm))
)
} else {
Ok(PyStr::from(format!("<weakref at {id:#x}; dead>")).into_ref(vm))
}
format!("<weakref at {id:#x}; dead>")
};
Ok(repr)
}
}

View File

@@ -69,7 +69,7 @@ impl PyZip {
impl IterNextIterable for PyZip {}
impl IterNext for PyZip {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
if zelf.iterators.is_empty() {
return Ok(PyIterReturn::StopIteration(None));
}

View File

@@ -549,7 +549,7 @@ impl PyObjectRef {
/// # Safety
/// T must be the exact payload type
#[inline(always)]
pub unsafe fn downcast_unchecked_ref<T: PyObjectPayload>(&self) -> &crate::Py<T> {
pub unsafe fn downcast_unchecked_ref<T: PyObjectPayload>(&self) -> &Py<T> {
debug_assert!(self.payload_is::<T>());
&*(self as *const PyObjectRef as *const PyRef<T>)
}

View File

@@ -321,7 +321,7 @@ impl PyObject {
Some(slot) => slot(self, vm),
None => vm
.call_special_method(self.to_owned(), identifier!(vm, __repr__), ())?
.try_into_value(vm),
.try_into_value(vm), // TODO: remove magic method call once __repr__ is fully ported to slot
}
})
}

View File

@@ -20,7 +20,7 @@ mod _collections {
PyComparisonOp,
},
utils::collection_repr,
AsObject, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
};
use crossbeam_utils::atomic::AtomicCell;
use std::cmp::max;
@@ -557,7 +557,7 @@ mod _collections {
impl Comparable for PyDeque {
fn cmp(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
@@ -647,7 +647,7 @@ mod _collections {
impl IterNextIterable for PyDequeIterator {}
impl IterNext for PyDequeIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().next(|deque, pos| {
if zelf.state != deque.state.load() {
return Err(vm.new_runtime_error("Deque mutated during iteration".to_owned()));
@@ -713,7 +713,7 @@ mod _collections {
impl IterNextIterable for PyReverseDequeIterator {}
impl IterNext for PyReverseDequeIterator {
fn next(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.internal.lock().next(|deque, pos| {
if deque.state.load() != zelf.state {
return Err(vm.new_runtime_error("Deque mutated during iteration".to_owned()));

View File

@@ -545,7 +545,7 @@ mod _io {
}
#[cold]
fn del(_zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyResult<()> {
fn del(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_del is implemented")
}
}
@@ -571,7 +571,7 @@ mod _io {
})
}
fn next(_zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> {
fn next(_zelf: &Py<Self>, _vm: &VirtualMachine) -> PyResult<PyIterReturn> {
unreachable!("slot_iternext is implemented")
}
}

View File

@@ -380,7 +380,7 @@ pub(crate) mod _thread {
impl SetAttr for Local {
fn setattro(
zelf: &crate::Py<Self>,
zelf: &Py<Self>,
attr: PyStrRef,
value: PySetterValue,
vm: &VirtualMachine,

View File

@@ -45,7 +45,8 @@ pub struct PyTypeSlots {
// More standard operations (here for binary compatibility)
pub hash: AtomicCell<Option<HashFunc>>,
pub call: AtomicCell<Option<GenericMethod>>,
pub repr: AtomicCell<Option<ReprFunc>>,
// tp_str
pub repr: AtomicCell<Option<StringifyFunc>>,
pub getattro: AtomicCell<Option<GetattroFunc>>,
pub setattro: AtomicCell<Option<SetattroFunc>>,
@@ -275,7 +276,7 @@ impl Default for PyTypeFlags {
pub(crate) type GenericMethod = fn(&PyObject, FuncArgs, &VirtualMachine) -> PyResult;
pub(crate) type HashFunc = fn(&PyObject, &VirtualMachine) -> PyResult<PyHash>;
// CallFunc = GenericMethod
pub(crate) type ReprFunc = fn(&PyObject, &VirtualMachine) -> PyResult<PyStrRef>;
pub(crate) type StringifyFunc = fn(&PyObject, &VirtualMachine) -> PyResult<PyStrRef>;
pub(crate) type GetattroFunc = fn(&PyObject, PyStrRef, &VirtualMachine) -> PyResult;
pub(crate) type SetattroFunc =
fn(&PyObject, PyStrRef, PySetterValue, &VirtualMachine) -> PyResult<()>;
@@ -1027,7 +1028,12 @@ pub trait Representable: PyPayload {
Self::slot_repr(&zelf, vm)
}
fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef>;
fn repr(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let repr = Self::repr_str(zelf, vm)?;
Ok(vm.ctx.new_str(repr))
}
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String>;
}
#[pyclass]

View File

@@ -70,6 +70,9 @@ macro_rules! declare_const_name {
declare_const_name! {
True,
False,
None,
NotImplemented,
Ellipsis,
// magic methods
__abs__,