Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,8 +256,8 @@ 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 functions, nor the
descriptors of fields which C++ has, so a field is read and set by way of Python.
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.

## Python runtime

Expand Down Expand Up @@ -361,6 +361,13 @@ nanobind extension, so that C++ written against the generated structs is called
Running the same tests in `pure` and `strict` modes therefore compares the two implementations.
- Only positional parameters are supported, each annotated, as is what it returns.
- Nothing checks that the C++ function's signature matches the Python one, until a call which nanobind rejects.
- A function of Rust is in the extension which holds the classes, `pkg._native`, as a class of pyo3 is of the
extension it is built in: so that is what its `@native_function` names. `dataclass_native::python::function`
adds it, as nanobind's `def` does one of C++: a plain function of up to 8 arguments, each of which, and what it
gives, is a type which a field may be of, converted as a field is. So a frozen class is taken as its struct,
which is copied, or as a `Shared` or a `Held` of it, which is not, and what is given is not copied. A `Result`
it gives is raised if it is an error: as a `ValueError`, if not an exception of pyo3's. An argument it cannot
take is a `TypeError`, as nanobind's is.

### pydantic dataclasses

Expand Down Expand Up @@ -410,9 +417,9 @@ what an object is made from, before the native class checks it.
5. Rust, for what is written in it to use the classes which Python has: analytics, say. **Done:** structs, enums
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. To come: functions written in Rust,
called as those of C++ are; msgpack, JSON and Arrow in Rust, which Python does until then; the descriptors
of fields which C++ has; and an example built with maturin.
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.
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
Expand Down
22 changes: 20 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,7 @@ fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> {

Built as an extension module (`crate-type = ["cdylib"]`) and placed in the package as `_native`, the classes of
`my_schemas` are then bound to the Rust structs as they would be to those of C++. Rust does not yet serialise
them, which Python does for it, nor have functions called from Python; and an example built with maturin is
to come.
them, which Python does for it, and an example built with maturin is to come.

## Storing Python objects in the structs

Expand Down Expand Up @@ -240,6 +239,25 @@ def rating(trade: Trade) -> int:
it. A struct which C++ returns likewise becomes the object of the return annotation. The body is the function's
Python implementation, which is what runs in `pure` mode. See [examples/functions](examples/functions).

A function of Rust is called likewise. It is added to the extension which holds the classes, `my_schemas._native`,
which is then what its `@native_function` names:

```rust
use dataclass_native::python::{function, Held};

fn rating(trade: &Trade) -> i32 { ... } // Plain Rust, knowing nothing of Python

#[pymodule(name = "_native")]
fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> {
my_schemas_native::register(extension)?;
// A Held is the struct in which the trade's fields are stored, not a copy of it
function(extension, "rating", |trade: Held<Trade>| rating(&trade))
}
```

What it takes and gives are what fields may be of. If it gives a `Result`, Python raises its error: as a
`ValueError`, if it is not an exception of pyo3's.

## Serialising

```python
Expand Down
3 changes: 3 additions & 0 deletions src/dataclass_native/backends/pyo3.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,9 @@ def _struct(struct: s.Struct) -> str:
" }\n\n"
" fn from_native(value: &Bound<'_, PyAny>) -> PyResult<Self> {\n"
f" Ok((*<{plain} as Frozen>::unwrap(value)?).clone())\n"
" }\n\n"
" fn into_native<'py>(self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {\n"
f" <{plain} as Frozen>::wrap(py, Held::new(self))\n"
" }\n"
"}\n"
)
Expand Down
141 changes: 138 additions & 3 deletions src/dataclass_native/rust/src/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ use pyo3::buffer::{Element, PyBuffer};
use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{
PyBool, PyBytes, PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyDict, PyFloat, PyFrozenSet, PyInt,
PyList, PySet, PyString, PyTime, PyTimeAccess, PyTuple, PyTzInfo, PyTzInfoAccess,
PyBool, PyBytes, PyCFunction, PyDate, PyDateAccess, PyDateTime, PyDelta, PyDeltaAccess, PyDict, PyFloat,
PyFrozenSet, PyInt, PyList, PyModule, PySet, PyString, PyTime, PyTimeAccess, PyTuple, PyTzInfo, PyTzInfoAccess,
};
use pyo3::ffi;
use std::any::Any;
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::{c_int, c_void};
use std::ffi::{c_int, c_void, CStr, CString};
use std::sync::Arc;

/// A type which a field may be of: what the extension gives Python of it, and takes from Python for it
Expand All @@ -24,6 +24,11 @@ pub trait Native: Sized {

fn from_native(value: &Bound<'_, PyAny>) -> PyResult<Self>;

/// As to_native, of what is not kept: so not of a copy of it, where that would be of one
fn into_native<'py>(self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
self.to_native(py)
}

/// 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 {
Expand Down Expand Up @@ -442,6 +447,13 @@ impl<T: Native> Native for Option<T> {
T::from_native(value).map(Some)
}
}

fn into_native<'py>(self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
match self {
Some(value) => value.into_native(py),
None => Ok(py.None().into_bound(py)),
}
}
}

/// A list, which Python makes a tuple of: from a list or a tuple
Expand All @@ -461,6 +473,11 @@ impl<T: Native> Native for Vec<T> {
}
}

fn into_native<'py>(self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
let items = self.into_iter().map(|item| item.into_native(py)).collect::<PyResult<Vec<_>>>()?;
Ok(PyList::new(py, items)?.into_any())
}

fn is_native(value: &Bound<'_, PyAny>) -> bool {
value.is_exact_instance_of::<PyList>() || value.is_exact_instance_of::<PyTuple>()
}
Expand Down Expand Up @@ -565,6 +582,17 @@ impl<T: Frozen> Native for Arc<T> {
}
}

/// A frozen struct where it is, which is not copied: as what a function takes of one
impl<T: Frozen> Native for Held<T> {
fn to_native<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
T::wrap(py, self.clone())
}

fn from_native(value: &Bound<'_, PyAny>) -> PyResult<Self> {
T::unwrap(value)
}
}

impl<T: Changing> Native for Mutable<T> {
fn to_native<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
T::wrap(py, self.clone())
Expand Down Expand Up @@ -683,3 +711,110 @@ impl<T: Number, const N: usize> Native for MutableArray<T, N> {
MutableArray::new(numbers, shape).ok_or_else(|| not_a(value, "an array of its shape"))
}
}

/// Adds a function of Rust to an extension module, for the @native_function of its name to call. It takes and
/// gives what fields may be of, each as a field is: so a frozen class as its struct, which is copied, or as a
/// `Shared` or a `Held` of it, which is not. It may give a `Result`, whose error Python raises.
pub fn function<Taken, F: Function<Taken>>(module: &Bound<'_, PyModule>, name: &str, function: F) -> PyResult<()> {
// Kept for as long as the function is, which is as long as the process
let named: &'static CStr = Box::leak(CString::new(name)?.into_boxed_c_str());
let called = move |taken: &Bound<'_, PyTuple>, _: Option<&Bound<'_, PyDict>>| function.call(taken);
module.add(name, PyCFunction::new_closure(module.py(), Some(named), None, called)?)
}

/// A function of Rust which Python may call: one of up to 8 arguments
pub trait Function<Taken>: Send + Sync + 'static {
fn call(&self, taken: &Bound<'_, PyTuple>) -> PyResult<Py<PyAny>>;
}

/// What a function gives: a value, or a Result of one
pub trait Returned {
fn returned(self, py: Python<'_>) -> PyResult<Py<PyAny>>;
}

impl<T: Native> Returned for T {
fn returned(self, py: Python<'_>) -> PyResult<Py<PyAny>> {
Ok(self.into_native(py)?.unbind())
}
}

impl<T: Native, E: Raised> Returned for Result<T, E> {
fn returned(self, py: Python<'_>) -> PyResult<Py<PyAny>> {
self.map_err(Raised::raised)?.returned(py)
}
}

/// The error of a function, as what Python raises: a ValueError of what it says, if it is not one of Python's
pub trait Raised {
fn raised(self) -> PyErr;
}

impl Raised for PyErr {
fn raised(self) -> PyErr {
self
}
}

macro_rules! raised {
($($error:ty),*) => {$(
impl Raised for $error {
fn raised(self) -> PyErr {
PyValueError::new_err(self.to_string())
}
}
)*};
}

raised!(String, &str, Box<dyn std::error::Error>, Box<dyn std::error::Error + Send + Sync>);

/// Nothing, which is None
impl Native for () {
fn to_native<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
Ok(py.None().into_bound(py))
}

fn from_native(value: &Bound<'_, PyAny>) -> PyResult<Self> {
if value.is_none() {
Ok(())
} else {
Err(not_a(value, "None"))
}
}
}

fn incompatible(what: String) -> PyErr {
PyTypeError::new_err(format!("incompatible function arguments: {what}"))
}

fn argument<T: Native>(taken: &Bound<'_, PyTuple>, index: usize) -> PyResult<T> {
T::from_native(&taken.get_item(index)?)
.map_err(|error| incompatible(format!("argument {}: {}", index + 1, error.value(taken.py()))))
}

macro_rules! function {
($count:literal: $($name:ident $index:tt),*) => {
impl<Called, Given, $($name),*> Function<($($name,)*)> for Called
where
Called: Fn($($name),*) -> Given + Send + Sync + 'static,
Given: Returned,
$($name: Native,)*
{
fn call(&self, taken: &Bound<'_, PyTuple>) -> PyResult<Py<PyAny>> {
if taken.len() != $count {
return Err(incompatible(format!("{} given, of {}", taken.len(), $count)));
}
self($(argument::<$name>(taken, $index)?),*).returned(taken.py())
}
}
};
}

function!(0:);
function!(1: A 0);
function!(2: A 0, B 1);
function!(3: A 0, B 1, C 2);
function!(4: A 0, B 1, C 2, D 3);
function!(5: A 0, B 1, C 2, D 3, E 4);
function!(6: A 0, B 1, C 2, D 3, E 4, F 5);
function!(7: A 0, B 1, C 2, D 3, E 4, F 5, G 6);
function!(8: A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7);
50 changes: 50 additions & 0 deletions tests/rust/functions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//! The native functions of tests/schemas/functions.py, written by hand as a project's would be: in the extension
//! which holds its classes, schemas._native
use crate::schemas::common::{Currency, Money, Party};
use dataclass_native::python::{function, Held};
use dataclass_native::{Array, Date, Shared};
use pyo3::prelude::*;

fn total(amounts: Vec<Money>, currency: Currency) -> Money {
let amount = amounts.iter().filter(|money| money.currency == currency).map(|money| money.amount).sum();
Money { amount, currency }
}

fn renamed(party: Party, name: Option<String>) -> Party {
Party { name: name.unwrap_or("?".to_string()), ..party }
}

fn scaled(points: Array<f64>, factor: f64) -> Array<f64> {
points.as_slice().iter().map(|point| point * factor).collect::<Vec<_>>().into()
}

fn transposed(values: Array<f64, 2>) -> Array<f64, 2> {
let [rows, columns] = *values.shape();
let numbers = values.as_slice();
let turned = (0..columns).flat_map(|column| (0..rows).map(move |row| numbers[row * columns + column]));
Array::new(turned.collect(), [columns, rows]).expect("as many numbers as there were")
}

/// Whose error Python raises
fn halved(whole: i64) -> Result<i64, String> {
if whole % 2 == 0 {
Ok(whole / 2)
} else {
Err(format!("{whole} is odd"))
}
}

pub fn register(extension: &Bound<'_, PyModule>) -> PyResult<()> {
function(extension, "implementation", || "native".to_string())?;
function(extension, "total", total)?;
function(extension, "renamed", renamed)?;
function(extension, "same", |party: Shared<Party>| party)?;
function(extension, "later", |day: Date, days: i32| Date(day.0 + days))?;
function(extension, "scaled", scaled)?;
function(extension, "transposed", transposed)?;
function(extension, "nothing", |_: i64| ())?;
function(extension, "unannotated", |value: i64| value)?;
// Which the functions of the schema do not have: a struct where it is, not a copy of it, and an error
function(extension, "amount", |money: Held<Money>| money.amount)?;
function(extension, "halved", halved)
}
Loading
Loading