Visitar URL original
Implement tp_repr and tp_str · Issue #4653 · RustPython/RustPython · GitHub
The Wayback Machine - https://web.archive.org/web/20230326202929/https://github.com/RustPython/RustPython/issues/4653
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement tp_repr and tp_str #4653

Open
youknowone opened this issue Mar 7, 2023 · 1 comment
Open

Implement tp_repr and tp_str #4653

youknowone opened this issue Mar 7, 2023 · 1 comment
Assignees
Labels
A-vm Area: virtual machine C-enhancement New feature or request

Comments

@youknowone
Copy link
Member

youknowone commented Mar 7, 2023 •

part of #3244

The slot field to start:

In Python side, str(1) hits this line :

input.str(vm)?

input.str(vm) in the line is calling rust side rust side PyObjectRef::str which is:

// Container of the virtual machine state:
pub fn str(&self, vm: &VirtualMachine) -> PyResult<PyStrRef> {
let obj = match self.to_owned().downcast_exact::<PyStr>(vm) {
Ok(s) => return Ok(s.into_pyref()),
Err(obj) => obj,
};
// TODO: replace to obj.class().slots.str
let str_method = match vm.get_special_method(obj, identifier!(vm, __str__))? {
Ok(str_method) => str_method,
Err(obj) => return obj.repr(vm),
};
let s = str_method.invoke((), vm)?;
s.downcast::<PyStr>().map_err(|obj| {
vm.new_type_error(format!(
"__str__ returned non-string (type {})",
obj.class().name()
))
})
}

And object.__str__, which every other object's __str__ inherits as default is:

#[pymethod(magic)]
fn str(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyStrRef> {
// FIXME: try tp_repr first and fallback to object.__repr__
zelf.repr(vm)
}

Once this is done, a wrapper need to be added to update_slot! to connect python side defined magic methods to rust type slots.

pub(crate) fn update_slot<const ADD: bool>(&self, name: &'static PyStrInterned, ctx: &Context) {

Once those are finished, we can actually replace the implementation of other types' __str__ to this new implementation
We typically did it using trait.
One of the good example is Hashable:

#[pyclass]
pub trait Hashable: PyPayload {
#[inline]
#[pyslot]
fn slot_hash(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyHash> {
if let Some(zelf) = zelf.downcast_ref() {
Self::hash(zelf, vm)
} else {
Err(vm.new_type_error("unexpected payload for __hash__".to_owned()))
}
}
#[inline]
#[pymethod]
fn __hash__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyHash> {
Self::slot_hash(&zelf, vm)
}
fn hash(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyHash>;
}

And the adaption is looking like this:

impl Hashable for PyComplex {
#[inline]
fn hash(zelf: &crate::Py<Self>, _vm: &VirtualMachine) -> PyResult<hash::PyHash> {
let value = zelf.value;
let re_hash =
hash::hash_float(value.re).unwrap_or_else(|| hash::hash_object_id(zelf.get_id()));
let im_hash =
hash::hash_float(value.im).unwrap_or_else(|| hash::hash_object_id(zelf.get_id()));
let Wrapping(ret) = Wrapping(re_hash) + Wrapping(im_hash) * Wrapping(hash::IMAG);
Ok(hash::fix_sentinel(ret))
}
}

@youknowone youknowone changed the title Implementing tp_repr and tp_str Implement tp_repr and tp_str Mar 7, 2023
@haxelion
Copy link
Contributor

haxelion commented Mar 7, 2023

@youknowone Please assign me 🙂

@youknowone youknowone added C-enhancement New feature or request A-vm Area: virtual machine labels Mar 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-vm Area: virtual machine C-enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants