diff --git a/DESIGN.md b/DESIGN.md index 094a557..73faaa3 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -256,8 +256,13 @@ the structs, by [pyo3](https://pyo3.rs), as nanobind does in those of C++. - pyo3 says an int which is too great for its field is an `OverflowError`: the runtime makes of it the `TypeError` which any value a field cannot be is. -Not yet in Rust, so done by Python for what is held in it: msgpack, JSON and Arrow. Nor are the descriptors of -fields which C++ has, so a field is read and set by way of Python. +- The extension has the `__fields__` and `__maker__` which one of C++ has, in each of its modules, so a field + is read and set, and an object made, without Python: by the crate's `Field`, which the generated code gives + what reads and writes the field of a struct. A type says how it is made as Python itself is to have it, and + taken from that, with what the field is told: an enum by its members, a frozen struct by its class, and a + tuple or a frozenset of what is as Python has it. The rest, Python's converters do, as for C++. + +Not yet in Rust, so done by Python for what is held in it: msgpack, JSON and Arrow. ## Python runtime @@ -418,8 +423,9 @@ what an object is made from, before the native class checks it. and their defaults, generated as modules which cargo compiles, with a crate of the types they use which depends on nothing; and Python's objects stored in the structs, as they are in those of C++, by an extension generated for pyo3, with arrays which share their numbers with numpy; and functions written in Rust, - called as those of C++ are. To come: msgpack, JSON and Arrow in Rust, which Python does until then; the - descriptors of fields which C++ has; and an example built with maturin. + called as those of C++ are, and fields read and set by descriptors of the extension's own, as those of + C++ are. To come: msgpack, JSON and Arrow in Rust, which Python does until then; and an example built + with maturin. 6. **Done:** classes which are not frozen, whose fields may be set, held by reference, and whose arrays may be written to. To come: lists. 7. JSON. The aim is that pydantic's `TypeAdapter` reads what this writes, and this reads what it writes: not that diff --git a/README.md b/README.md index 0d75710..5d09b53 100644 --- a/README.md +++ b/README.md @@ -351,41 +351,42 @@ Apple M1 with Python 3.14, of extensions built for release: `uv run python tests tables, of the classes of [tests/schemas](tests/schemas). - `pure`: plain dataclasses, as Python has them. -- C++: bound to the C++ structs, whose extension reads and sets fields itself, as of 1.1.0. -- C++, Python's descriptors: the same, read and set by way of Python, as an extension built by 1.0.0 is. -- Rust: bound to the Rust structs. Its extension does not yet read and set fields itself, so Python does. - -| Nanoseconds to | `pure` | C++ | C++, Python's descriptors | Rust | -|---|---:|---:|---:|---:| -| Make `Money(1.5, Currency.EUR)` | 156 | 293 | 840 | 891 | -| Make a `Trade`, of 19 fields | 1,113 | 3,537 | 6,129 | 6,771 | -| Make a `Customer`, which is not frozen | 103 | 339 | 1,436 | 1,542 | -| Read a float | 9 | 29 | 113 | 111 | -| Read an enum | 17 | 25 | 176 | 186 | -| Read a str | 9 | 37 | 121 | 120 | -| Read a nested object | 17 | 147 | 295 | 320 | -| Read a `Shared` object | 9 | 139 | 215 | 258 | -| Read a tuple of 3 strs | 9 | 104 | 210 | 247 | -| Read an array of 1,000 floats | 9 | 301 | 394 | 723 | -| Set an int | 17 | 24 | 139 | 134 | -| Set a str | 9 | 30 | 147 | 150 | -| Set a nested object | 9 | 58 | 195 | 233 | +- C++ and Rust: bound to the structs of each, whose extension reads and sets fields itself. C++'s does as of + 1.1.0. +- Python's descriptors: the same, read and set by way of Python, as an extension built before it did so is. + +| Nanoseconds to | `pure` | C++ | Rust | C++, Python's descriptors | Rust, Python's descriptors | +|---|---:|---:|---:|---:|---:| +| Make `Money(1.5, Currency.EUR)` | 159 | 300 | 431 | 838 | 904 | +| Make a `Trade`, of 19 fields | 1,126 | 3,568 | 4,006 | 6,293 | 6,705 | +| Make a `Customer`, which is not frozen | 104 | 338 | 563 | 1,447 | 1,566 | +| Read a float | 9 | 29 | 46 | 113 | 112 | +| Read an enum | 18 | 25 | 40 | 174 | 187 | +| Read a str | 9 | 39 | 56 | 121 | 119 | +| Read a nested object | 18 | 153 | 169 | 298 | 312 | +| Read a `Shared` object | 9 | 149 | 203 | 217 | 262 | +| Read a tuple of 3 strs | 9 | 104 | 154 | 210 | 262 | +| Read an array of 1,000 floats | 9 | 299 | 418 | 400 | 485 | +| Set an int | 17 | 24 | 41 | 132 | 134 | +| Set a str | 9 | 30 | 60 | 139 | 152 | +| Set a nested object | 9 | 58 | 107 | 190 | 235 | A bound object is slower to make and to read than a plain dataclass, as each field is converted to and from what -the struct holds, where Python only keeps a reference: by some three times for a number, and more for what -Python must make an object of each time it is read. An array is not copied, whatever its size. +the struct holds, where Python only keeps a reference: by some three times for a number in C++, and five in +Rust, and more for what Python must make an object of each time it is read. An array is not copied, whatever +its size. What is gained is in what native code then does with the structs, without Python: as in serialising. An `Order` here is of two customers, each with two addresses: 15 values, in 7 objects. Arrow is of 10,000 of them. | Microseconds, for each `Order`, to | `pure` | C++ | Rust | |---|---:|---:|---:| -| Write msgpack | 8.8 | 1.9 | 18.1 | -| Read msgpack | 24.3 | 2.6 | 36.5 | -| Write JSON | 10.7 | 2.3 | 20.1 | -| Read JSON | 13.5 | 3.1 | 25.8 | -| Write Arrow | 11.2 | 0.4 | 19.0 | -| Read Arrow | 9.3 | 0.7 | 19.6 | +| Write msgpack | 8.9 | 2.0 | 15.0 | +| Read msgpack | 24.5 | 2.7 | 31.1 | +| Write JSON | 10.8 | 2.4 | 17.0 | +| Read JSON | 13.6 | 3.2 | 20.5 | +| Write Arrow | 11.3 | 0.4 | 16.1 | +| Read Arrow | 9.4 | 0.8 | 14.2 | C++ writes and reads the structs itself. Rust does not yet, so Python does, reading each field from the struct: which is slower than `pure`, until Rust has its own. diff --git a/src/dataclass_native/backends/pyo3.py b/src/dataclass_native/backends/pyo3.py index e2d6ea9..21552ce 100644 --- a/src/dataclass_native/backends/pyo3.py +++ b/src/dataclass_native/backends/pyo3.py @@ -63,8 +63,8 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str: f"// Generated by dataclass-native from {package}: do not edit\n" f"//! The classes which hold Python's objects of {package} in the structs generated for it. `register` adds\n" f"//! them to an extension module, which is to be {package}._native\n" - "#![allow(non_camel_case_types, non_snake_case, clippy::all)]\n\n" - f"use {RUNTIME}::python::{{member, Changing, Frozen, Held, Native}};\n" + "#![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, clippy::all)]\n\n" + f"use {RUNTIME}::python::{{maker, member, Changing, Fields, Frozen, Held, Native, Told}};\n" f"use {RUNTIME}::Mutable;\n" "use pyo3::exceptions::PyTypeError;\n" "use pyo3::prelude::*;\n" @@ -75,7 +75,7 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str: for module in modules: generator = _ModuleGenerator(schema, module) generator.generate() - added, hashes = [], [] + added, hashes, structs = [], [], [] for enum in module.enums: parts.append(_enum(enum)) added.append(_class(enum.module, enum.name)) @@ -86,7 +86,8 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str: parts.append(_struct(struct)) added.append(_class(struct.module, struct.name)) hashes.append((struct.name, s.schema_hash(struct))) - registered.append(_registered(package, module.name, added, hashes)) + structs.append((struct.name, added[-1])) + registered.append(_registered(module.name, added, hashes, structs)) parts.append( f"/// Adds a module for each schema module of {package} to an extension module, which is to be\n" @@ -98,7 +99,10 @@ def _package(schema: s.Schema, package: str, modules: list[s.Module]) -> str: def _registered( - package: str, module: str, classes: list[str], hashes: list[tuple[str, str]] + module: str, + classes: list[str], + hashes: list[tuple[str, str]], + structs: list[tuple[str, str]], ) -> str: within = module.split(".")[1:] lines = [ @@ -123,7 +127,18 @@ def _registered( lines += [ f' schema.set_item("{name}", "{digest}")?;\n' for name, digest in hashes ] - lines += [' module.add("__schema__", schema)?;\n', " }\n"] + lines.append(' module.add("__schema__", schema)?;\n') + # What reads, sets and makes the objects of its classes without Python + lines.append(" let fields = PyDict::new(py);\n") + lines += [ + f' fields.set_item("{name}", {cls}::fields(py)?)?;\n' + for name, cls in structs + ] + lines += [ + ' module.add("__fields__", fields)?;\n', + ' module.add("__maker__", maker(py)?)?;\n', + " }\n", + ] return "".join(lines) @@ -149,8 +164,18 @@ def _enum(enum: s.Enum) -> str: f" let held = value.cast_exact::<{name}>()\n" f' .map_err(|_| PyTypeError::new_err("not a {enum.name}"))?;\n' f" Ok(match held.get() {{\n{back} }})\n" + " }\n\n" + " fn to_python<'py>(&self, _py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> {\n" + f" told.member({name}__MEMBERS.iter().position(|member| member == self))\n" + " }\n\n" + " fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> {\n" + f" Ok(told.place(value).and_then(|at| {name}__MEMBERS.get(at).copied()))\n" " }\n" - "}\n" + "}\n\n" + "/// In the order of Python's\n" + f"const {name}__MEMBERS: [{plain}; {len(members)}] = [\n" + + "".join(f" {plain}::{m},\n" for m in members) + + "];\n" ) @@ -217,22 +242,28 @@ def _struct(struct: s.Struct) -> str: " }\n" ) - by_value = ( + # What reads and sets each field without Python + registered = [] + for f in struct.fields: + match f.type: + case s.StructRef(mutable=False) if not struct.mutable: + kind = "within" + case _: + kind = "changing" if struct.mutable else "frozen" + field = identifier(f.name) + registered.append( + f' fields.{kind}::<{plain}, _>("{f.name}", |held| &held.{field}, |held| &mut held.{field})?;\n' + ) + write = ( "" if struct.mutable else ( - "\n/// Held by value: so a copy of it\n" - f"impl Native for {plain} {{\n" - " fn to_native<'py>(&self, py: Python<'py>) -> PyResult> {\n" - f" <{plain} as Frozen>::wrap(py, Held::new(self.clone()))\n" - " }\n\n" - " fn from_native(value: &Bound<'_, PyAny>) -> PyResult {\n" - f" Ok((*<{plain} as Frozen>::unwrap(value)?).clone())\n" - " }\n\n" - " fn into_native<'py>(self, py: Python<'py>) -> PyResult> {\n" - f" <{plain} as Frozen>::wrap(py, Held::new(self))\n" + "\n fn write(value: &Bound<'_, PyAny>, write: impl FnOnce(&mut Self) -> R) -> PyResult {\n" + f" let held = value.cast_exact::<{name}>()\n" + f' .map_err(|_| PyTypeError::new_err("not a {struct.name}"))?;\n' + " let mut held = held.try_borrow_mut()?;\n" + " Ok(write(held.0.make_mut()))\n" " }\n" - "}\n" ) ) return ( @@ -247,8 +278,16 @@ def _struct(struct: s.Struct) -> str: f' .map_err(|_| PyTypeError::new_err("not a {struct.name}"))?;\n' " Ok(held.borrow().0.clone())\n" " }\n" - "}\n" - f"{by_value}\n" + f"{write}" + "}\n\n" + f"impl {name} {{\n" + " fn fields(py: Python<'_>) -> PyResult> {\n" + " let fields = Fields::new(py.get_type::());\n" + + "".join(registered) + + "" + " Ok(fields.into_dict())\n" + " }\n" + "}\n\n" "#[pymethods]\n" f"impl {name} {{\n" " #[new]\n" diff --git a/src/dataclass_native/rust/src/fields.rs b/src/dataclass_native/rust/src/fields.rs new file mode 100644 index 0000000..c164ec7 --- /dev/null +++ b/src/dataclass_native/rust/src/fields.rs @@ -0,0 +1,423 @@ +//! What reads, sets and makes Python's objects of the bound classes without Python: the descriptor of each field, +//! which an extension gives as its `__fields__`, and what makes an object, its `__maker__`. As those of C++ are, +//! by dataclass_native/python.hpp: dataclass_native._runtime binds either alike. + +use crate::python::{Changing, Frozen, Native}; +use pyo3::exceptions::{PyAttributeError, PyOverflowError, PyTypeError, PyValueError}; +use pyo3::prelude::*; +use pyo3::types::{PyCFunction, PyDict, PyString, PyTuple, PyType}; +use pyo3::{ffi, intern, PyTraverseError, PyVisit}; +use std::sync::Arc; + +/// What a field is told by dataclass_native._runtime, of what it could not know: with which a value is made as +/// Python is to have it, not as Python would convert it +pub struct Told<'a, 'py> { + /// The members of the enum the field is of, in their order + pub members: Option<&'a Bound<'py, PyTuple>>, + /// The class of the struct which the field is by value, or is a tuple of + pub wraps: Option<&'a Bound<'py, PyType>>, + /// Whether what a container holds is as Python has it + pub direct: bool, +} + +impl<'py> Told<'_, 'py> { + /// The member of the enum which is at a place among them + pub fn member(&self, at: Option) -> PyResult>> { + match (self.members, at) { + (Some(members), Some(at)) => members.get_item(at).map(Some), + _ => Ok(None), + } + } + + /// The place of a member of the enum: not of its value, which Python is left to find the member of + pub fn place(&self, value: &Bound<'py, PyAny>) -> Option { + self.members?.iter().position(|member| member.is(value)) + } + + /// An object of the class which the field is of, holding a native object + pub fn wrapped(&self, handle: Bound<'py, PyAny>) -> PyResult>> { + self.wraps.map(|class| instance(class, &handle)).transpose() + } + + /// The native object of an object of exactly the class which the field is of, if it has one + pub fn unwrapped(&self, value: &Bound<'py, PyAny>) -> Option> { + self.wraps.filter(|class| value.get_type().is(*class)).and_then(|_| handle_of(value)) + } +} + +/// The native object of a Python one, if it has one +fn handle_of<'py>(obj: &Bound<'py, PyAny>) -> Option> { + let py = obj.py(); + let attributes = unsafe { + let attributes = ffi::PyObject_GenericGetDict(obj.as_ptr(), std::ptr::null_mut()); + if attributes.is_null() { + ffi::PyErr_Clear(); + return None; + } + Bound::from_owned_ptr(py, attributes).cast_into_unchecked::() + }; + attributes.get_item(intern!(py, "__native__")).ok().flatten() +} + +/// An object of a bound class, which holds a native object: as dataclass_native._runtime.wrap makes +fn instance<'py>(class: &Bound<'py, PyType>, handle: &Bound<'py, PyAny>) -> PyResult> { + let py = class.py(); + let (obj, attributes) = unsafe { + let obj = Bound::from_owned_ptr_or_err(py, ffi::PyType_GenericAlloc(class.as_type_ptr(), 0))?; + let attributes = ffi::PyObject_GenericGetDict(obj.as_ptr(), std::ptr::null_mut()); + (obj, Bound::from_owned_ptr_or_err(py, attributes)?.cast_into_unchecked::()) + }; + attributes.set_item(intern!(py, "__native__"), handle)?; + Ok(obj) +} + +/// What reads and sets a field of a native object, of the class it is of +trait Member: Send + Sync { + /// As the extension gives it + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult>; + + /// As Python is to have it, if that can be made with what was told + fn give<'py>(&self, handle: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult>>; + + /// From what the extension is given + fn set(&self, handle: &Bound<'_, PyAny>, value: &Bound<'_, PyAny>) -> PyResult<()>; + + /// From what Python has, if it can be taken with what was told: giving whether it was + fn take<'py>(&self, handle: &Bound<'py, PyAny>, value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) + -> PyResult; +} + +/// A field of a frozen struct +struct OfFrozen { + read: fn(&T) -> &M, + written: fn(&mut T) -> &mut M, +} + +impl Member for OfFrozen { + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult> { + (self.read)(&*T::unwrap(handle)?).to_native(handle.py()) + } + + fn give<'py>(&self, handle: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult>> { + (self.read)(&*T::unwrap(handle)?).to_python(handle.py(), told) + } + + fn set(&self, handle: &Bound<'_, PyAny>, value: &Bound<'_, PyAny>) -> PyResult<()> { + // Read before the struct is written to, as it may be of the struct itself + let value = M::from_native(value)?; + T::write(handle, |held| *(self.written)(held) = value) + } + + fn take<'py>( + &self, + handle: &Bound<'py, PyAny>, + value: &Bound<'py, PyAny>, + told: &Told<'_, 'py>, + ) -> PyResult { + let Some(value) = M::from_python(value, told)? else { return Ok(false) }; + T::write(handle, |held| *(self.written)(held) = value)?; + Ok(true) + } +} + +/// A field of a frozen struct which is itself one: read where it is, not copied +struct Within(OfFrozen); + +impl Member for Within { + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult> { + M::wrap(handle.py(), T::unwrap(handle)?.member(self.0.read)) + } + + fn give<'py>(&self, handle: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult>> { + if told.wraps.is_none() { + return Ok(None); + } + told.wrapped(self.get(handle)?) + } + + fn set(&self, handle: &Bound<'_, PyAny>, value: &Bound<'_, PyAny>) -> PyResult<()> { + self.0.set(handle, value) + } + + fn take<'py>( + &self, + handle: &Bound<'py, PyAny>, + value: &Bound<'py, PyAny>, + told: &Told<'_, 'py>, + ) -> PyResult { + self.0.take(handle, value, told) + } +} + +/// A field of a struct which is not frozen +struct OfChanging { + read: fn(&T) -> &M, + written: fn(&mut T) -> &mut M, +} + +impl Member for OfChanging { + fn get<'py>(&self, handle: &Bound<'py, PyAny>) -> PyResult> { + (self.read)(&T::unwrap(handle)?.read()).to_native(handle.py()) + } + + fn give<'py>(&self, handle: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult>> { + (self.read)(&T::unwrap(handle)?.read()).to_python(handle.py(), told) + } + + fn set(&self, handle: &Bound<'_, PyAny>, value: &Bound<'_, PyAny>) -> PyResult<()> { + let value = M::from_native(value)?; + *(self.written)(&mut T::unwrap(handle)?.write()) = value; + Ok(()) + } + + fn take<'py>( + &self, + handle: &Bound<'py, PyAny>, + value: &Bound<'py, PyAny>, + told: &Told<'_, 'py>, + ) -> PyResult { + let Some(value) = M::from_python(value, told)? else { return Ok(false) }; + *(self.written)(&mut T::unwrap(handle)?.write()) = value; + Ok(true) + } +} + +/// The descriptors of a native class's fields, by name: what an extension's `__fields__` has for it +pub struct Fields<'py> { + native: Bound<'py, PyType>, + fields: Bound<'py, PyDict>, +} + +impl<'py> Fields<'py> { + pub fn new(native: Bound<'py, PyType>) -> Self { + let fields = PyDict::new(native.py()); + Self { native, fields } + } + + pub fn into_dict(self) -> Bound<'py, PyDict> { + self.fields + } + + fn add(&self, name: &str, member: impl Member + 'static) -> PyResult<()> { + let py = self.native.py(); + let field = Field { + name: PyString::intern(py, name).unbind(), + native: self.native.clone().unbind(), + member: Arc::new(member), + bound: None, + }; + self.fields.set_item(name, Bound::new(py, field)?) + } + + /// A field of a frozen struct, by what gives it of one + pub fn frozen( + &self, + name: &str, + read: fn(&T) -> &M, + written: fn(&mut T) -> &mut M, + ) -> PyResult<()> { + self.add(name, OfFrozen { read, written }) + } + + /// A field of a frozen struct which is itself a frozen struct + pub fn within( + &self, + name: &str, + read: fn(&T) -> &M, + written: fn(&mut T) -> &mut M, + ) -> PyResult<()> { + self.add(name, Within(OfFrozen { read, written })) + } + + /// A field of a struct which is not frozen + pub fn changing( + &self, + name: &str, + read: fn(&T) -> &M, + written: fn(&mut T) -> &mut M, + ) -> PyResult<()> { + self.add(name, OfChanging { read, written }) + } +} + +/// What bound() gave a field: the Python descriptor it is in place of, with what that has, and what it was told +struct Bound_ { + fallback: Py, + default: Option>, + to_native: Option>, + from_native: Option>, + members: Option>, + wraps: Option>, + direct: bool, +} + +/// The descriptor of a field of a bound class: reads and sets the member of the native object of an instance +#[pyclass(frozen, module = "dataclass_native", name = "Field")] +pub struct Field { + name: Py, + native: Py, + member: Arc, + bound: Option, +} + +/// An attribute, or None if it is +fn held(from: &Bound<'_, PyAny>, name: &str) -> PyResult>> { + let value = from.getattr(name)?; + Ok((!value.is_none()).then(|| value.unbind())) +} + +#[pymethods] +impl Field { + /// A descriptor as this, in place of the Python one of the field: which it is as, for what has no native + /// object. The rest is what it is told, by which it need not call Python's converters + fn bound<'py>( + &self, + py: Python<'py>, + fallback: Bound<'py, PyAny>, + missing: Bound<'py, PyAny>, + members: Option>, + wraps: Option>, + direct: bool, + ) -> PyResult { + let default = fallback.getattr("default")?; + Ok(Field { + name: self.name.clone_ref(py), + native: self.native.clone_ref(py), + member: Arc::clone(&self.member), + bound: Some(Bound_ { + // A default which is None is one: only what is missing is not + default: (!default.is(&missing)).then(|| default.unbind()), + to_native: held(&fallback, "to_native")?, + from_native: held(&fallback, "from_native")?, + fallback: fallback.unbind(), + members: members.map(Bound::unbind), + wraps: wraps.map(Bound::unbind), + direct, + }), + }) + } + + fn __get__<'py>( + &self, + py: Python<'py>, + obj: Option<&Bound<'py, PyAny>>, + owner: Option<&Bound<'py, PyAny>>, + ) -> PyResult> { + let bound = self.bound.as_ref(); + let Some(obj) = obj else { + // As the dataclass's own attribute: its default, if any + return match bound.and_then(|bound| bound.default.as_ref()) { + Some(default) => Ok(default.bind(py).clone()), + None => Err(PyAttributeError::new_err(self.name.clone_ref(py))), + }; + }; + let Some(bound) = bound else { return Err(PyAttributeError::new_err(self.name.clone_ref(py))) }; + let Some(handle) = handle_of(obj) else { + // Made by pydantic, or of a subclass which is not bound: as the Python has it + return bound.fallback.bind(py).call_method1(intern!(py, "__get__"), (obj, owner)); + }; + + let from_native = bound.from_native.as_ref().map(|convert| convert.bind(py)); + let value = if !handle.get_type().is(&self.native) { + handle.getattr(&self.name)? + } else if from_native.is_none() { + return self.member.get(&handle); + } else { + match self.member.give(&handle, &bound.told(py))? { + Some(given) => return Ok(given), + None => self.member.get(&handle)?, + } + }; + match from_native { + Some(convert) => convert.call1((value,)), + None => Ok(value), + } + } + + fn __set__<'py>(&self, py: Python<'py>, obj: &Bound<'py, PyAny>, value: &Bound<'py, PyAny>) -> PyResult<()> { + let Some(bound) = self.bound.as_ref() else { return Err(PyAttributeError::new_err(self.name.clone_ref(py))) }; + let Some(handle) = handle_of(obj) else { + return bound.fallback.bind(py).call_method1(intern!(py, "__set__"), (obj, value)).map(drop); + }; + + let of_native = handle.get_type().is(&self.native); + let set = || -> PyResult<()> { + let Some(to_native) = bound.to_native.as_ref() else { + return if of_native { self.member.set(&handle, value) } else { handle.setattr(&self.name, value) }; + }; + // What it does not itself take, Python converts: and says why it cannot be, if it cannot + if of_native && self.member.take(&handle, value, &bound.told(py)).unwrap_or(false) { + return Ok(()); + } + let converted = to_native.bind(py).call1((value,))?; + if of_native { + self.member.set(&handle, &converted) + } else { + handle.setattr(&self.name, converted) + } + }; + set().map_err(|error| { + // A ValueError from bytes(), of ints which are not bytes: and an OverflowError of an int + let rejected = error.is_instance_of::(py) + || error.is_instance_of::(py) + || error.is_instance_of::(py); + match (rejected, obj.get_type().qualname(), value.repr()) { + (true, Ok(class), Ok(value)) => { + PyTypeError::new_err(format!("{class}.{} cannot be {value}", self.name.bind(py))) + } + _ => error, + } + }) + } + + fn __delete__(&self, _obj: &Bound<'_, PyAny>) -> PyResult<()> { + Err(PyAttributeError::new_err("__delete__")) + } + + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + visit.call(&self.native)?; + if let Some(bound) = &self.bound { + visit.call(&bound.fallback)?; + for held in [&bound.default, &bound.to_native, &bound.from_native].into_iter().flatten() { + visit.call(held)?; + } + if let Some(members) = &bound.members { + visit.call(members)?; + } + if let Some(wraps) = &bound.wraps { + visit.call(wraps)?; + } + } + Ok(()) + } +} + +impl Bound_ { + fn told<'a, 'py>(&'a self, py: Python<'py>) -> Told<'a, 'py> { + Told { + members: self.members.as_ref().map(|members| members.bind(py)), + wraps: self.wraps.as_ref().map(|wraps| wraps.bind(py)), + direct: self.direct, + } + } +} + +/// What an extension's `__maker__` is: maker(cls, native, new) gives the `__new__` of a bound class, which makes an +/// object with its native object. As the Python `__new__` which it is in place of, and which it calls for a +/// subclass: which is not of its native class +pub fn maker(py: Python<'_>) -> PyResult> { + PyCFunction::new_closure(py, Some(c"maker"), None, |given: &Bound<'_, PyTuple>, _: Option<&Bound<'_, PyDict>>| { + let (class, native, new): (Bound<'_, PyType>, Bound<'_, PyAny>, Bound<'_, PyAny>) = given.extract()?; + let (class, native, new) = (class.unbind(), native.unbind(), new.unbind()); + let made = move |taken: &Bound<'_, PyTuple>, named: Option<&Bound<'_, PyDict>>| -> PyResult> { + let py = taken.py(); + let class = class.bind(py); + let is_abstract = unsafe { ffi::PyType_GetFlags(class.as_type_ptr()) } & ffi::Py_TPFLAGS_IS_ABSTRACT != 0; + if is_abstract || !taken.get_item(0).is_ok_and(|first| first.is(class)) { + return Ok(new.bind(py).call(taken, named)?.unbind()); + } + Ok(instance(class, &native.bind(py).call0()?)?.unbind()) + }; + PyCFunction::new_closure(given.py(), Some(c"__new__"), None, made).map(Bound::unbind) + }) +} diff --git a/src/dataclass_native/rust/src/lib.rs b/src/dataclass_native/rust/src/lib.rs index a6558ef..63f72e8 100644 --- a/src/dataclass_native/rust/src/lib.rs +++ b/src/dataclass_native/rust/src/lib.rs @@ -5,6 +5,8 @@ use std::cmp::Ordering; use std::fmt; use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; +#[cfg(feature = "python")] +mod fields; #[cfg(feature = "python")] pub mod python; diff --git a/src/dataclass_native/rust/src/python.rs b/src/dataclass_native/rust/src/python.rs index ec2665d..8f8c4fd 100644 --- a/src/dataclass_native/rust/src/python.rs +++ b/src/dataclass_native/rust/src/python.rs @@ -5,9 +5,11 @@ use crate::{ Array, Bytes, Date, DateTime, Decimal, Indirect, Mutable, MutableArray, NaiveDateTime, Ordered, TimeDelta, TimeOfDay, Uuid, }; +pub use crate::fields::{maker, Field, Fields, Told}; use pyo3::buffer::{Element, PyBuffer}; use pyo3::exceptions::{PyTypeError, PyValueError}; use pyo3::prelude::*; +use pyo3::sync::PyOnceLock; use pyo3::types::{ PyBool, PyBytes, PyCFunction, PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PyModule, PySet, PyString, PyTime, PyTimeAccess, PyTuple, PyTzInfo, PyTzInfoAccess, @@ -29,6 +31,17 @@ pub trait Native: Sized { self.to_native(py) } + /// As Python itself is to have it, not as to_native gives it for Python to convert: where it differs, and + /// can be made with what a field is told. Else None, and Python converts + fn to_python<'py>(&self, _py: Python<'py>, _told: &Told<'_, 'py>) -> PyResult>> { + Ok(None) + } + + /// From what Python itself has, likewise: or None, of what Python is to convert, or to say is wrong + fn from_python<'py>(_value: &Bound<'py, PyAny>, _told: &Told<'_, 'py>) -> PyResult> { + Ok(None) + } + /// Whether a value is of its kind, where that is quicker to tell than to read it: by which a union tells which /// of its members not to try fn is_native(_value: &Bound<'_, PyAny>) -> bool { @@ -41,6 +54,36 @@ pub trait Frozen: Clone + Send + Sync + 'static { fn wrap(py: Python<'_>, held: Held) -> PyResult>; fn unwrap(value: &Bound<'_, PyAny>) -> PyResult>; + + /// Writes to the struct which an object of the class holds: its own, which is first copied if it is held + /// elsewhere + fn write(value: &Bound<'_, PyAny>, write: impl FnOnce(&mut Self) -> R) -> PyResult; +} + +/// Held by value: so a copy of it +impl Native for T { + fn to_native<'py>(&self, py: Python<'py>) -> PyResult> { + T::wrap(py, Held::new(self.clone())) + } + + fn from_native(value: &Bound<'_, PyAny>) -> PyResult { + Ok((*T::unwrap(value)?).clone()) + } + + fn into_native<'py>(self, py: Python<'py>) -> PyResult> { + T::wrap(py, Held::new(self)) + } + + fn to_python<'py>(&self, py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> { + if told.wraps.is_none() { + return Ok(None); + } + told.wrapped(self.to_native(py)?) + } + + fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + told.unwrapped(value).map(|handle| Self::from_native(&handle)).transpose() + } } /// What the class of a frozen struct holds: a struct of its own, shared so that nothing is copied to share it, or @@ -454,6 +497,21 @@ impl Native for Option { None => Ok(py.None().into_bound(py)), } } + + fn to_python<'py>(&self, py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> { + match self { + Some(value) => value.to_python(py, told), + None => Ok(Some(py.None().into_bound(py))), + } + } + + fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + if value.is_none() { + Ok(Some(None)) + } else { + Ok(T::from_python(value, told)?.map(Some)) + } + } } /// A list, which Python makes a tuple of: from a list or a tuple @@ -478,11 +536,38 @@ impl Native for Vec { Ok(PyList::new(py, items)?.into_any()) } + /// A tuple, of what each is: if that is as to_native gives it, or can be made with what was told + fn to_python<'py>(&self, py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> { + let items = self.iter().map(|item| each_to(item, py, told)).collect::>>>()?; + items.map(|items| Ok(PyTuple::new(py, items)?.into_any())).transpose() + } + + /// From a tuple alone + fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + let Ok(tuple) = value.cast_exact::() else { return Ok(None) }; + tuple.iter().map(|item| each_from(&item, told)).collect() + } + fn is_native(value: &Bound<'_, PyAny>) -> bool { value.is_exact_instance_of::() || value.is_exact_instance_of::() } } +/// What a container holds, as Python is to have it +fn each_to<'py, T: Native>(item: &T, py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> { + match item.to_python(py, told)? { + None if told.direct => item.to_native(py).map(Some), + made => Ok(made), + } +} + +fn each_from<'py, T: Native>(item: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + match T::from_python(item, told)? { + None if told.direct => T::from_native(item).map(Some), + taken => Ok(taken), + } +} + /// A set, which Python makes a frozenset of: from either impl Native for BTreeSet { fn to_native<'py>(&self, py: Python<'py>) -> PyResult> { @@ -503,6 +588,19 @@ impl Native for BTreeSet { fn is_native(value: &Bound<'_, PyAny>) -> bool { value.is_exact_instance_of::() || value.is_exact_instance_of::() } + + fn to_python<'py>(&self, py: Python<'py>, told: &Told<'_, 'py>) -> PyResult>> { + let items = self.iter().map(|item| each_to(item, py, told)).collect::>>>()?; + items.map(|items| Ok(PyFrozenSet::new(py, items)?.into_any())).transpose() + } + + /// From a frozenset alone + fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + if !value.is_exact_instance_of::() { + return Ok(None); + } + value.try_iter()?.map(|item| each_from(&item?, told)).collect() + } } impl Native for BTreeMap { @@ -522,6 +620,15 @@ impl Native for BTreeMap { fn is_native(value: &Bound<'_, PyAny>) -> bool { value.is_exact_instance_of::() } + + /// From a dict alone, of what is as Python has it: read, it is as to_native gives it + fn from_python<'py>(value: &Bound<'py, PyAny>, told: &Told<'_, 'py>) -> PyResult> { + if told.direct && value.is_exact_instance_of::() { + Self::from_native(value).map(Some) + } else { + Ok(None) + } + } } macro_rules! ordered { @@ -668,7 +775,10 @@ fn shared<'py, T: Number, const N: usize>( ) -> PyResult> { let bytes = count * std::mem::size_of::(); let numbers = Bound::new(py, Numbers { _held: Box::new(held), at: at as usize, bytes, readonly })?; - let flat = py.import("numpy")?.call_method1("frombuffer", (numbers, T::DTYPE))?; + // Found once, as it is called for each array which is read + static FROM: PyOnceLock> = PyOnceLock::new(); + let from = FROM.get_or_try_init(py, || py.import("numpy")?.getattr("frombuffer").map(Bound::unbind))?; + let flat = from.bind(py).call1((numbers, T::DTYPE))?; if N == 1 { return Ok(flat); } diff --git a/tests/performance.py b/tests/performance.py index 8041e82..1f07908 100644 --- a/tests/performance.py +++ b/tests/performance.py @@ -75,7 +75,11 @@ def _measure(root: str, python_descriptors: bool) -> dict[str, float]: if python_descriptors: # As an extension built before it had its own: so before any class is bound to it for module in ("common", "trades", "mutable", "arrays"): - extension = import_module(f"schemas._{module}_native") + try: + extension = import_module(f"schemas._{module}_native") + except ImportError: + # Of Rust, which has one extension for them all + extension = getattr(import_module("schemas._native"), module) delattr(extension, "__fields__") delattr(extension, "__maker__") names: dict = {"ORDERS": ORDERS} @@ -124,11 +128,13 @@ def main(): from dataclass_native import ENV_VAR, Mode # Each in a process of its own, as a process has one mode + rust = _rust() configurations = { "`pure`": (Mode.PURE, TESTS, ""), "C++": (Mode.STRICT, BUILD / "src", ""), + "Rust": (Mode.STRICT, rust, ""), "C++, Python's descriptors": (Mode.STRICT, BUILD / "src", "python"), - "Rust": (Mode.STRICT, _rust(), ""), + "Rust, Python's descriptors": (Mode.STRICT, rust, "python"), } times = {} for name, (mode, root, descriptors) in configurations.items(): diff --git a/tests/test_pyo3.py b/tests/test_pyo3.py index acfded4..28b456e 100644 --- a/tests/test_pyo3.py +++ b/tests/test_pyo3.py @@ -9,6 +9,7 @@ from pathlib import Path import pytest +from test_bindings import _AS_DESCRIBED, _DESCRIPTORS, _run from dataclass_native import ENV_VAR, Mode, rust_dir from dataclass_native.backends import pyo3 @@ -122,6 +123,19 @@ def test_classes(sources): """\ module.add_class::()?; """, + # What reads and sets each field without Python: where it is, if it is a struct which is not set + """\ + fields.frozen::("amount", |held| &held.amount, |held| &mut held.amount)?; + """, + """\ + fields.within::("money", |held| &held.money, |held| &mut held.money)?; + """, + """\ + fields.changing::("name", |held| &held.name, |held| &mut held.name)?; + """, + """\ + module.add("__maker__", maker(py)?)?; + """, # A struct which is a field is read where it is, if neither may be set """\ fn get_money<'py>(&self, py: Python<'py>) -> PyResult> { @@ -234,15 +248,7 @@ def test_the_extension_holds_them(built): for cls in Money, Order, Customer, Path: print(type(vars(cls.__new__(cls)).get("__native__")).__module__) """ - result = subprocess.run( - [sys.executable, "-c", textwrap.dedent(script)], - env=os.environ | {ENV_VAR: Mode.MIXED, "PYTHONPATH": str(built)}, - capture_output=True, - text=True, - check=False, - ) - assert result.returncode == 0, result.stderr - assert result.stdout.split() == [ + assert _run(built, Mode.MIXED, script).split() == [ "schemas._native.common", "schemas._native.sub.inner", "schemas._native.mutable", @@ -272,15 +278,25 @@ def halved(whole: int) -> int: ... except (ValueError, TypeError) as e: print(type(e).__name__, e) """ - result = subprocess.run( - [sys.executable, "-c", textwrap.dedent(script)], - env=os.environ | {ENV_VAR: Mode.STRICT, "PYTHONPATH": str(built)}, - capture_output=True, - text=True, - check=False, - ) - assert result.returncode == 0, result.stderr - done, odd, great = result.stdout.splitlines() + done, odd, great = _run(built, Mode.STRICT, script).splitlines() assert (done, odd) == ("3.5 1.5 2", "ValueError 3 is odd") # Then what Python says of it, which is not the same everywhere assert great.startswith("TypeError incompatible function arguments: argument 1: ") + + +@pytest.mark.parametrize( + ("before", "types"), + [ + ("", "Field builtin_function_or_method"), + # As one built before it had them, which is used as it was + ("del extension.__fields__, extension.__maker__", "_Field function"), + ], +) +def test_fields(built, before, types): + """Each field of a bound class is a descriptor of the extension, and its objects are made by it: as of C++""" + script = _DESCRIPTORS.replace( + "import schemas._common_native as extension", + "from schemas._native import common as extension", + ) + lines = _run(built, Mode.STRICT, script.format(before=before)).splitlines() + assert lines == [types, *_AS_DESCRIBED]