Repository navigation
Generate __str__ and __repr__ slots with #[pymethod] #6485
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
Open
youknowone
wants to merge
5
commits into
RustPython:main
Choose a base branch
from
youknowone:__str__
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
c5eed1f
auto-generate slot_str
youknowone 6cfc6fa
Complete native __str__ slot generation
youknowdot ba8bcf5
Use current VM helper in str slot regression
youknowdot 282aafe
Exercise native str slots through Python snippets
youknowdot 577dcb1
Generate repr slots from methods and remove Representable
youknowdot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1216,8 +1216,6 @@ where | |
| // Constructor/Initializer traits | ||
| ("__new__", "Constructor"), | ||
| ("__init__", "Initializer"), | ||
| // Representable trait | ||
| ("__repr__", "Representable"), | ||
| // ("__str__", "???"), // allow __str__ | ||
| // Hashable trait | ||
| ("__hash__", "Hashable"), | ||
|
|
@@ -1342,6 +1340,52 @@ where | |
| args.attrs.push(allow_attr); | ||
| } | ||
|
|
||
| // __str__ and __repr__ are single-method protocols: register its implementation as a | ||
| // slot and let add_operators expose the usual wrapper_descriptor. Other | ||
| // protocols still use their traits. Reuse native argument and result | ||
| // conversion so this keeps the same Rust signatures as a normal method. | ||
| if matches!(py_name.as_str(), "__str__" | "__repr__") | ||
| && self.inner.attr_name == AttrName::Method | ||
| && !coexist | ||
| { | ||
| let slot_name = py_name.trim_matches('_'); | ||
| let slot_ident = Ident::new(slot_name, ident.span()); | ||
| let return_error = format!("{py_name} returned non-string (type {{}})"); | ||
| if raw { | ||
| return Err(syn::Error::new_spanned( | ||
| item_attr, | ||
| format!( | ||
| "#[pymethod(raw)] cannot define '{py_name}'; use #[pyslot({slot_name})] instead" | ||
| ), | ||
| )); | ||
| } | ||
| let slot_tokens = quote_spanned! { ident.span() => | ||
| slots.#slot_ident.store(Some(|zelf, vm| { | ||
| use ::rustpython_vm::{AsObject as _, function::IntoPyNativeFn}; | ||
| let result = IntoPyNativeFn::call( | ||
| &Self::#ident, | ||
| vm, | ||
| vec![zelf.to_owned()].into(), | ||
| ::rustpython_vm::function::Callee::named(#py_name).with_instance_arg(true), | ||
| )?; | ||
| result.downcast::<::rustpython_vm::builtins::PyStr>().map_err(|obj| { | ||
| vm.new_type_error(format!( | ||
| #return_error, | ||
| obj.class().slot_name() | ||
| )) | ||
| }) | ||
| })); | ||
| }; | ||
| args.context.extend_slots_items.add_item( | ||
| ident.clone(), | ||
| vec![format!("(slot {slot_name})")], | ||
| args.cfgs.to_vec(), | ||
| slot_tokens, | ||
| 2, | ||
| ); | ||
| return Ok(()); | ||
| } | ||
|
|
||
| let rust_doc = args.attrs.doc(); | ||
| let doc = internal_doc_tokens( | ||
| func.sig(), | ||
|
|
@@ -1367,6 +1411,7 @@ where | |
| coexist, | ||
| attr_name: self.inner.attr_name, | ||
| }); | ||
|
|
||
| Ok(()) | ||
| } | ||
| } | ||
|
|
@@ -2842,3 +2887,164 @@ fn parse_vec_ident( | |
| })? | ||
| .to_string()) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod string_slot_tests { | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. do we need this? isn't python test cover it? |
||
| use super::*; | ||
|
|
||
| fn expand(item: Item) -> String { | ||
| impl_pyclass_impl(parse_quote!(), item) | ||
| .expect("class expansion should succeed") | ||
| .to_string() | ||
| } | ||
|
|
||
| fn protocols() -> [(Ident, &'static str); 2] { | ||
| [("__str__", "str"), ("__repr__", "repr")] | ||
| .map(|(method, slot)| (Ident::new(method, Span::call_site()), slot)) | ||
| } | ||
|
|
||
| #[test] | ||
| fn alias_uses_native_conversion_without_method_entry() { | ||
| for (method, slot) in protocols() { | ||
| let method = method.to_string(); | ||
| let tokens = expand(parse_quote! { | ||
| impl Py<Example> { | ||
| #[pymethod(name = #method)] | ||
| fn display(&self) -> String { String::new() } | ||
| } | ||
| }); | ||
| assert!(tokens.contains(&format!("slots . {slot} . store"))); | ||
| assert!(tokens.contains("& Self :: display")); | ||
| assert!(tokens.contains("IntoPyNativeFn")); | ||
| assert!(!tokens.contains("PyMethodDef :: new_const")); | ||
| assert!(!tokens.contains(&format!("fn slot_{slot}"))); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn slot_preserves_cfg_on_assignment() { | ||
| for (method, slot) in protocols() { | ||
| let tokens = expand(parse_quote! { | ||
| impl Py<Example> { | ||
| #[cfg(feature = "example")] | ||
| #[pymethod] | ||
| fn #method(&self) -> String { String::new() } | ||
| } | ||
| }); | ||
| assert!(tokens.contains(&format!( | ||
| "# [cfg (feature = \"example\")] {{ slots . {slot} . store" | ||
| ))); | ||
| assert_eq!(tokens.matches("cfg (feature = \"example\")").count(), 2); | ||
| assert!(!tokens.contains(&format!("fn slot_{slot}"))); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn trait_method_is_registered_inside_extend_slots() { | ||
| for (method, slot) in protocols() { | ||
| let tokens = expand(parse_quote! { | ||
| trait Display: PyPayload { | ||
| #[pymethod] | ||
| fn #method(zelf: &Py<Self>) -> String { String::new() } | ||
| } | ||
| }); | ||
| assert!(tokens.contains("fn __extend_slots")); | ||
| assert!(tokens.contains(&format!("slots . {slot} . store"))); | ||
| assert!(tokens.contains(&format!("& Self :: {method}"))); | ||
| assert!(!tokens.contains(&format!("fn slot_{slot}"))); | ||
| assert!(!tokens.contains("PyMethodDef :: new_const")); | ||
| } | ||
|
|
||
| let consumer = impl_pyclass_impl( | ||
| parse_quote!(with(Display)), | ||
| parse_quote!(impl Py<Example> {}), | ||
| ) | ||
| .unwrap() | ||
| .to_string(); | ||
| assert!(consumer.contains("< Self as Display > :: __extend_slots (slots)")); | ||
| } | ||
|
|
||
| #[test] | ||
| fn method_is_registered_as_slot() { | ||
| for (method, slot) in protocols() { | ||
| let tokens = expand(parse_quote! { | ||
| impl Py<Example> { | ||
| #[pymethod] | ||
| fn #method(&self) -> String { String::new() } | ||
| } | ||
| }); | ||
| assert!(!tokens.contains("compile_error")); | ||
| assert!(tokens.contains(&format!("slots . {slot} . store"))); | ||
| assert!(tokens.contains(&format!("{method} returned non-string (type {{}})"))); | ||
| assert!(!tokens.contains("PyMethodDef :: new_const")); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn class_and_static_methods_remain_methods() { | ||
| for (method, slot) in protocols() { | ||
| for attribute in [quote!(pyclassmethod), quote!(pystaticmethod)] { | ||
| let tokens = expand(parse_quote! { | ||
| impl Py<Example> { | ||
| #[#attribute] | ||
| fn #method() -> String { String::new() } | ||
| } | ||
| }); | ||
| assert!(tokens.contains("PyMethodDef :: new_const")); | ||
| assert!(!tokens.contains(&format!("slots . {slot} . store"))); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn coexist_remains_an_ordinary_method() { | ||
| for (method, slot) in protocols() { | ||
| let tokens = expand(parse_quote! { | ||
| impl Py<Example> { | ||
| #[pymethod(coexist)] | ||
| fn #method(&self) -> String { String::new() } | ||
| } | ||
| }); | ||
| assert!(tokens.contains("PyMethodDef :: new_const")); | ||
| assert!(tokens.contains("COEXIST")); | ||
| assert!(!tokens.contains(&format!("slots . {slot} . store"))); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn explicit_and_method_slots_conflict() { | ||
| for (method, slot) in protocols() { | ||
| let slot_ident = Ident::new(slot, Span::call_site()); | ||
| let error = impl_pyclass_impl( | ||
| parse_quote!(), | ||
| parse_quote! { | ||
| impl Py<Example> { | ||
| #[pymethod] | ||
| fn #method(&self) -> String { String::new() } | ||
| #[pyslot(#slot_ident)] | ||
| fn stringify(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyStrRef> { | ||
| todo!() | ||
| } | ||
| } | ||
| }, | ||
| ) | ||
| .expect_err("two implementations of the same slot must be rejected"); | ||
| assert!(error.to_string().contains(&format!("(slot {slot})"))); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn raw_method_reports_an_explicit_error() { | ||
| for (method, slot) in protocols() { | ||
| let tokens = expand(parse_quote! { | ||
| impl Py<Example> { | ||
| #[pymethod(raw)] | ||
| fn #method(vm: &VirtualMachine, args: FuncArgs) -> PyResult { todo!() } | ||
| } | ||
| }); | ||
| assert!(tokens.contains("compile_error")); | ||
| assert!(tokens.contains(&format!("#[pymethod(raw)] cannot define '{method}'"))); | ||
| assert!(!tokens.contains(&format!("slots . {slot} . store"))); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
rg -n 'SLOT_DEFS|__str__|plain_off|doc_body_pending' crates/vm/src/types/slot.rs crates/vm/src/builtins/descriptor.rs crates/vm/src/class.rsRepository: RustPython/RustPython
Length of output: 2438
Script executed:
Repository: RustPython/RustPython
Length of output: 42054
Script executed:
Repository: RustPython/RustPython
Length of output: 13790
Script executed:
Repository: RustPython/RustPython
Length of output: 27533
Script executed:
Repository: RustPython/RustPython
Length of output: 15580
Preserve explicit
__str__docstrings on slot wrappers.When a non-coexisting
#[pymethod]defines__str__, the early return discards its Rust docstring. Introspection can expose generic or stored documentation instead. Pass the explicit docstring to the wrapper and give it precedence.As per coding guidelines, “A
///doc comment on a Python-exposed item … is that item's docstring and overrides the stored docs.”Source: Coding guidelines