Skip to content

Commit 23cfdff

Browse files
haxelionyouknowone
authored andcommitted
Implemented repr slot
1 parent 21615cb commit 23cfdff

37 files changed

+806
-510
lines changed

vm/src/builtins/asyncgenerator.rs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
use super::{PyCode, PyGenericAlias, PyStrRef, PyType, PyTypeRef};
1+
use super::{PyCode, PyGenericAlias, PyStr, PyStrRef, PyType, PyTypeRef};
22
use crate::{
33
builtins::PyBaseExceptionRef,
44
class::PyClassImpl,
55
coroutine::Coro,
66
frame::FrameRef,
77
function::OptionalArg,
88
protocol::PyIterReturn,
9-
types::{Constructor, IterNext, IterNextIterable, Unconstructible},
9+
types::{Constructor, IterNext, IterNextIterable, Representable, Unconstructible},
1010
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
1111
};
1212

@@ -26,7 +26,7 @@ impl PyPayload for PyAsyncGen {
2626
}
2727
}
2828

29-
#[pyclass(with(Constructor))]
29+
#[pyclass(with(Constructor, Representable))]
3030
impl PyAsyncGen {
3131
pub fn as_coro(&self) -> &Coro {
3232
&self.inner
@@ -49,11 +49,6 @@ impl PyAsyncGen {
4949
self.inner.set_name(name)
5050
}
5151

52-
#[pymethod(magic)]
53-
fn repr(zelf: PyRef<Self>, vm: &VirtualMachine) -> String {
54-
zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm)
55-
}
56-
5752
#[pymethod(magic)]
5853
fn aiter(zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyRef<Self> {
5954
zelf
@@ -129,6 +124,14 @@ impl PyAsyncGen {
129124
PyGenericAlias::new(cls, args, vm)
130125
}
131126
}
127+
128+
impl Representable for PyAsyncGen {
129+
#[inline]
130+
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
131+
Ok(PyStr::from(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm)).into_ref(vm))
132+
}
133+
}
134+
132135
impl Unconstructible for PyAsyncGen {}
133136

134137
#[pyclass(module = false, name = "async_generator_wrapped_value")]

vm/src/builtins/bool.rs

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::{
55
function::OptionalArg,
66
identifier,
77
protocol::PyNumberMethods,
8-
types::{AsNumber, Constructor},
8+
types::{AsNumber, Constructor, Representable},
99
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromBorrowedObject,
1010
VirtualMachine,
1111
};
@@ -107,18 +107,8 @@ impl Constructor for PyBool {
107107
}
108108
}
109109

110-
#[pyclass(with(Constructor, AsNumber))]
110+
#[pyclass(with(Constructor, AsNumber, Representable))]
111111
impl PyBool {
112-
#[pymethod(magic)]
113-
fn repr(zelf: bool, vm: &VirtualMachine) -> PyStrRef {
114-
if zelf {
115-
vm.ctx.names.True
116-
} else {
117-
vm.ctx.names.False
118-
}
119-
.to_owned()
120-
}
121-
122112
#[pymethod(magic)]
123113
fn format(obj: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
124114
if format_spec.is_empty() {
@@ -189,6 +179,31 @@ impl AsNumber for PyBool {
189179
}
190180
}
191181

182+
impl Representable for PyBool {
183+
#[inline]
184+
fn slot_repr(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> {
185+
if get_value(zelf) {
186+
Ok(vm.ctx.names.True.to_owned())
187+
} else {
188+
Ok(vm.ctx.names.False.to_owned())
189+
}
190+
}
191+
192+
#[inline]
193+
fn __repr__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
194+
Self::slot_repr(&zelf, vm)
195+
}
196+
197+
#[inline]
198+
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
199+
if get_value(zelf.as_object()) {
200+
Ok(vm.ctx.names.True.to_owned())
201+
} else {
202+
Ok(vm.ctx.names.False.to_owned())
203+
}
204+
}
205+
}
206+
192207
pub(crate) fn init(context: &Context) {
193208
PyBool::extend_class(context, context.types.bool_type);
194209
}

vm/src/builtins/builtin_func.rs

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use crate::{
33
builtins::PyBoundMethod,
44
class::PyClassImpl,
55
function::{FuncArgs, IntoPyNativeFunc, PyNativeFunc},
6-
types::{Callable, Constructor, GetDescriptor, Unconstructible},
6+
types::{Callable, Constructor, GetDescriptor, Representable, Unconstructible},
77
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
88
};
99
use std::fmt;
@@ -145,10 +145,6 @@ impl PyBuiltinFunction {
145145
fn reduce_ex(&self, _ver: PyObjectRef) -> PyStrRef {
146146
self.name()
147147
}
148-
#[pymethod(magic)]
149-
fn repr(&self) -> String {
150-
format!("<built-in function {}>", self.value.name)
151-
}
152148
#[pygetset(magic)]
153149
fn text_signature(&self) -> Option<String> {
154150
self.value.doc.as_ref().and_then(|doc| {
@@ -157,6 +153,14 @@ impl PyBuiltinFunction {
157153
})
158154
}
159155
}
156+
157+
impl Representable for PyBuiltinFunction {
158+
#[inline]
159+
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
160+
Ok(PyStr::from(format!("<built-in function {}>", zelf.value.name)).into_ref(vm))
161+
}
162+
}
163+
160164
impl Unconstructible for PyBuiltinFunction {}
161165

162166
// `PyBuiltinMethod` is similar to both `PyMethodDescrObject` in
@@ -225,7 +229,10 @@ impl PyBuiltinMethod {
225229
}
226230
}
227231

228-
#[pyclass(with(GetDescriptor, Callable, Constructor), flags(METHOD_DESCR))]
232+
#[pyclass(
233+
with(GetDescriptor, Callable, Constructor, Representable),
234+
flags(METHOD_DESCR)
235+
)]
229236
impl PyBuiltinMethod {
230237
#[pygetset(magic)]
231238
fn name(&self) -> PyStrRef {
@@ -247,14 +254,6 @@ impl PyBuiltinMethod {
247254
})
248255
}
249256
#[pymethod(magic)]
250-
fn repr(&self) -> String {
251-
format!(
252-
"<method '{}' of '{}' objects>",
253-
&self.value.name,
254-
self.class.name()
255-
)
256-
}
257-
#[pymethod(magic)]
258257
fn reduce(
259258
&self,
260259
vm: &VirtualMachine,
@@ -264,6 +263,19 @@ impl PyBuiltinMethod {
264263
(builtins_getattr, (classname, self.value.name.clone()))
265264
}
266265
}
266+
267+
impl Representable for PyBuiltinMethod {
268+
#[inline]
269+
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
270+
Ok(PyStr::from(format!(
271+
"<method '{}' of '{}' objects>",
272+
&zelf.value.name,
273+
zelf.class.name()
274+
))
275+
.into_ref(vm))
276+
}
277+
}
278+
267279
impl Unconstructible for PyBuiltinMethod {}
268280

269281
pub fn init(context: &Context) {

vm/src/builtins/bytearray.rs

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Implementation of the python bytearray object.
22
use super::{
3-
PositionIterInternal, PyBytes, PyBytesRef, PyDictRef, PyIntRef, PyStrRef, PyTuple, PyTupleRef,
4-
PyType, PyTypeRef,
3+
PositionIterInternal, PyBytes, PyBytesRef, PyDictRef, PyIntRef, PyStr, PyStrRef, PyTuple,
4+
PyTupleRef, PyType, PyTypeRef,
55
};
66
use crate::{
77
anystr::{self, AnyStr},
@@ -31,7 +31,7 @@ use crate::{
3131
sliceable::{SequenceIndex, SliceableSequenceMutOp, SliceableSequenceOp},
3232
types::{
3333
AsBuffer, AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, Initializer,
34-
IterNext, IterNextIterable, Iterable, PyComparisonOp, Unconstructible,
34+
IterNext, IterNextIterable, Iterable, PyComparisonOp, Representable, Unconstructible,
3535
},
3636
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
3737
VirtualMachine,
@@ -107,7 +107,8 @@ pub(crate) fn init(context: &Context) {
107107
AsMapping,
108108
AsSequence,
109109
AsNumber,
110-
Iterable
110+
Iterable,
111+
Representable
111112
)
112113
)]
113114
impl PyByteArray {
@@ -126,13 +127,6 @@ impl PyByteArray {
126127
self.inner.write()
127128
}
128129

129-
#[pymethod(magic)]
130-
fn repr(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<String> {
131-
let class = zelf.class();
132-
let class_name = class.name();
133-
zelf.inner().repr(Some(&class_name), vm)
134-
}
135-
136130
#[pymethod(magic)]
137131
fn alloc(&self) -> usize {
138132
self.inner().capacity()
@@ -886,6 +880,17 @@ impl Iterable for PyByteArray {
886880
}
887881
}
888882

883+
impl Representable for PyByteArray {
884+
#[inline]
885+
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
886+
let class = zelf.class();
887+
let class_name = class.name();
888+
zelf.inner()
889+
.repr(Some(&class_name), vm)
890+
.map(|s| PyStr::from(s).into_ref(vm))
891+
}
892+
}
893+
889894
// fn set_value(obj: &PyObject, value: Vec<u8>) {
890895
// obj.borrow_mut().kind = PyObjectPayload::Bytes { value };
891896
// }
@@ -922,6 +927,7 @@ impl PyByteArrayIterator {
922927
.set_state(state, |obj, pos| pos.min(obj.len()), vm)
923928
}
924929
}
930+
925931
impl Unconstructible for PyByteArrayIterator {}
926932

927933
impl IterNextIterable for PyByteArrayIterator {}

vm/src/builtins/bytes.rs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
use super::{
2-
PositionIterInternal, PyDictRef, PyIntRef, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef,
2+
PositionIterInternal, PyDictRef, PyIntRef, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType,
3+
PyTypeRef,
34
};
45
use crate::{
56
anystr::{self, AnyStr},
@@ -21,7 +22,7 @@ use crate::{
2122
sliceable::{SequenceIndex, SliceableSequenceOp},
2223
types::{
2324
AsBuffer, AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, Hashable,
24-
IterNext, IterNextIterable, Iterable, PyComparisonOp, Unconstructible,
25+
IterNext, IterNextIterable, Iterable, PyComparisonOp, Representable, Unconstructible,
2526
},
2627
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult,
2728
TryFromBorrowedObject, TryFromObject, VirtualMachine,
@@ -125,15 +126,11 @@ impl PyBytes {
125126
AsBuffer,
126127
Iterable,
127128
Constructor,
128-
AsNumber
129+
AsNumber,
130+
Representable,
129131
)
130132
)]
131133
impl PyBytes {
132-
#[pymethod(magic)]
133-
pub(crate) fn repr(&self, vm: &VirtualMachine) -> PyResult<String> {
134-
self.inner.repr(None, vm)
135-
}
136-
137134
#[pymethod(magic)]
138135
#[inline]
139136
pub fn len(&self) -> usize {
@@ -689,6 +686,15 @@ impl Iterable for PyBytes {
689686
}
690687
}
691688

689+
impl Representable for PyBytes {
690+
#[inline]
691+
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
692+
zelf.inner
693+
.repr(None, vm)
694+
.map(|s| PyStr::from(s).into_ref(vm))
695+
}
696+
}
697+
692698
#[pyclass(module = false, name = "bytes_iterator")]
693699
#[derive(Debug)]
694700
pub struct PyBytesIterator {

vm/src/builtins/classmethod.rs

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
use super::{PyBoundMethod, PyStr, PyType, PyTypeRef};
1+
use super::{PyBoundMethod, PyStr, PyStrRef, PyType, PyTypeRef};
22
use crate::{
33
class::PyClassImpl,
44
common::lock::PyMutex,
5-
types::{Constructor, GetDescriptor, Initializer},
5+
types::{Constructor, GetDescriptor, Initializer, Representable},
66
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
77
};
88

@@ -104,7 +104,10 @@ impl PyClassMethod {
104104
}
105105
}
106106

107-
#[pyclass(with(GetDescriptor, Constructor), flags(BASETYPE, HAS_DICT))]
107+
#[pyclass(
108+
with(GetDescriptor, Constructor, Representable),
109+
flags(BASETYPE, HAS_DICT)
110+
)]
108111
impl PyClassMethod {
109112
#[pygetset(magic)]
110113
fn func(&self) -> PyObjectRef {
@@ -136,26 +139,6 @@ impl PyClassMethod {
136139
self.callable.lock().get_attr("__annotations__", vm)
137140
}
138141

139-
#[pymethod(magic)]
140-
fn repr(&self, vm: &VirtualMachine) -> Option<String> {
141-
let callable = self.callable.lock().repr(vm).unwrap();
142-
let class = Self::class(vm);
143-
144-
match (
145-
class
146-
.qualname(vm)
147-
.downcast_ref::<PyStr>()
148-
.map(|n| n.as_str()),
149-
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
150-
) {
151-
(None, _) => None,
152-
(Some(qualname), Some(module)) if module != "builtins" => {
153-
Some(format!("<{module}.{qualname}({callable})>"))
154-
}
155-
_ => Some(format!("<{}({})>", class.slot_name(), callable)),
156-
}
157-
}
158-
159142
#[pygetset(magic)]
160143
fn isabstractmethod(&self, vm: &VirtualMachine) -> PyObjectRef {
161144
match vm.get_attribute_opt(self.callable.lock().clone(), "__isabstractmethod__") {
@@ -173,6 +156,28 @@ impl PyClassMethod {
173156
}
174157
}
175158

159+
impl Representable for PyClassMethod {
160+
#[inline]
161+
fn repr(zelf: &crate::Py<Self>, vm: &VirtualMachine) -> PyResult<PyStrRef> {
162+
let callable = zelf.callable.lock().repr(vm).unwrap();
163+
let class = Self::class(vm);
164+
165+
match (
166+
class
167+
.qualname(vm)
168+
.downcast_ref::<PyStr>()
169+
.map(|n| n.as_str()),
170+
class.module(vm).downcast_ref::<PyStr>().map(|m| m.as_str()),
171+
) {
172+
(None, _) => Err(vm.new_type_error("Unknown qualified name".into())),
173+
(Some(qualname), Some(module)) if module != "builtins" => {
174+
Ok(PyStr::from(format!("<{module}.{qualname}({callable})>")).into_ref(vm))
175+
}
176+
_ => Ok(PyStr::from(format!("<{}({})>", class.slot_name(), callable)).into_ref(vm)),
177+
}
178+
}
179+
}
180+
176181
pub(crate) fn init(context: &Context) {
177182
PyClassMethod::extend_class(context, context.types.classmethod_type);
178183
}

0 commit comments

Comments
 (0)