diff --git a/DESIGN.md b/DESIGN.md index a372168..094a557 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -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 @@ -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 @@ -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 diff --git a/README.md b/README.md index e940b43..0d75710 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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| 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 diff --git a/src/dataclass_native/backends/pyo3.py b/src/dataclass_native/backends/pyo3.py index ddbbbc4..e2d6ea9 100644 --- a/src/dataclass_native/backends/pyo3.py +++ b/src/dataclass_native/backends/pyo3.py @@ -228,6 +228,9 @@ def _struct(struct: s.Struct) -> str: " }\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" "}\n" ) diff --git a/src/dataclass_native/rust/src/python.rs b/src/dataclass_native/rust/src/python.rs index 411876a..ec2665d 100644 --- a/src/dataclass_native/rust/src/python.rs +++ b/src/dataclass_native/rust/src/python.rs @@ -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 @@ -24,6 +24,11 @@ pub trait Native: Sized { fn from_native(value: &Bound<'_, PyAny>) -> PyResult; + /// 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> { + 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 { @@ -442,6 +447,13 @@ impl Native for Option { T::from_native(value).map(Some) } } + + fn into_native<'py>(self, py: Python<'py>) -> PyResult> { + 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 @@ -461,6 +473,11 @@ impl Native for Vec { } } + fn into_native<'py>(self, py: Python<'py>) -> PyResult> { + let items = self.into_iter().map(|item| item.into_native(py)).collect::>>()?; + Ok(PyList::new(py, items)?.into_any()) + } + fn is_native(value: &Bound<'_, PyAny>) -> bool { value.is_exact_instance_of::() || value.is_exact_instance_of::() } @@ -565,6 +582,17 @@ impl Native for Arc { } } +/// A frozen struct where it is, which is not copied: as what a function takes of one +impl Native for Held { + fn to_native<'py>(&self, py: Python<'py>) -> PyResult> { + T::wrap(py, self.clone()) + } + + fn from_native(value: &Bound<'_, PyAny>) -> PyResult { + T::unwrap(value) + } +} + impl Native for Mutable { fn to_native<'py>(&self, py: Python<'py>) -> PyResult> { T::wrap(py, self.clone()) @@ -683,3 +711,110 @@ impl Native for MutableArray { 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>(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: Send + Sync + 'static { + fn call(&self, taken: &Bound<'_, PyTuple>) -> PyResult>; +} + +/// What a function gives: a value, or a Result of one +pub trait Returned { + fn returned(self, py: Python<'_>) -> PyResult>; +} + +impl Returned for T { + fn returned(self, py: Python<'_>) -> PyResult> { + Ok(self.into_native(py)?.unbind()) + } +} + +impl Returned for Result { + fn returned(self, py: Python<'_>) -> PyResult> { + 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, Box); + +/// Nothing, which is None +impl Native for () { + fn to_native<'py>(&self, py: Python<'py>) -> PyResult> { + Ok(py.None().into_bound(py)) + } + + fn from_native(value: &Bound<'_, PyAny>) -> PyResult { + 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(taken: &Bound<'_, PyTuple>, index: usize) -> PyResult { + 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 Function<($($name,)*)> for Called + where + Called: Fn($($name),*) -> Given + Send + Sync + 'static, + Given: Returned, + $($name: Native,)* + { + fn call(&self, taken: &Bound<'_, PyTuple>) -> PyResult> { + 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); diff --git a/tests/rust/functions.rs b/tests/rust/functions.rs new file mode 100644 index 0000000..b87d3fa --- /dev/null +++ b/tests/rust/functions.rs @@ -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, 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) -> Party { + Party { name: name.unwrap_or("?".to_string()), ..party } +} + +fn scaled(points: Array, factor: f64) -> Array { + points.as_slice().iter().map(|point| point * factor).collect::>().into() +} + +fn transposed(values: Array) -> Array { + 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 { + 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)?; + 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.amount)?; + function(extension, "halved", halved) +} diff --git a/tests/test_pyo3.py b/tests/test_pyo3.py index 044855b..acfded4 100644 --- a/tests/test_pyo3.py +++ b/tests/test_pyo3.py @@ -27,12 +27,8 @@ "schemas.scalars", "schemas.mutable", ] -# What an extension in Rust is yet to do, so the tests of it are not run: functions and Arrow -TO_COME = [ - "test_runtime.py::test_native_function", - "test_arrow.py::test_bound_objects_are_held_natively", - "test_arrays.py::test_native_function", -] +# What an extension in Rust is yet to do, so the test of it is not run: Arrow +TO_COME = ["test_arrow.py::test_bound_objects_are_held_natively"] _MANIFEST = """\ [package] @@ -56,13 +52,15 @@ #![deny(warnings)] use pyo3::prelude::*; +mod functions; #[allow(dead_code)] mod schemas; mod schemas_native; #[pymodule(name = "_native")] fn init(extension: &Bound<'_, PyModule>) -> PyResult<()> { - schemas_native::register(extension) + schemas_native::register(extension)?; + functions::register(extension) } """ @@ -166,6 +164,7 @@ def built(sources) -> Path: file.parent.mkdir(parents=True, exist_ok=True) file.write_text(source, encoding="utf-8") (crate / "src" / "lib.rs").write_text(_LIBRARY, encoding="utf-8") + shutil.copyfile(TESTS / "rust" / "functions.rs", crate / "src" / "functions.rs") (crate / "build.rs").write_text(_BUILD, encoding="utf-8") (crate / "Cargo.toml").write_text( _MANIFEST.format(runtime=rust_dir().as_posix()), encoding="utf-8" @@ -193,6 +192,9 @@ def built(sources) -> Path: if (path := crate / "target" / "debug" / name).is_file() ) shutil.copyfile(library, root / "schemas" / f"_native{EXTENSION_SUFFIXES[0]}") + # The functions of tests/schemas/functions.py are of schemas._functions, as C++ has them in an extension of their + # own. Those of Rust are in the one which has its classes, so this gives them as that + (root / "schemas" / "_functions.py").write_text("from ._native import *\n") return root @@ -246,3 +248,39 @@ def test_the_extension_holds_them(built): "schemas._native.mutable", "schemas._native.mutable", ] + + +def test_functions(built): + """Of the extension itself, as a project's are: which take a struct where it is, and whose errors are raised""" + script = """ + from dataclass_native import native_function + from schemas.common import Currency, Money + + @native_function("schemas._native") + def total(amounts: tuple[Money, ...], currency: Currency = Currency.USD) -> Money: ... + + @native_function("schemas._native") + def amount(money: Money) -> float: ... + + @native_function("schemas._native") + def halved(whole: int) -> int: ... + + print(total((Money(1.0), Money(2.5), Money(4.0, Currency.EUR))).amount, amount(Money(1.5)), halved(4)) + for wrong in 3, 2**70: + try: + halved(wrong) + 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() + 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: ") diff --git a/tests/test_runtime.py b/tests/test_runtime.py index c64fc2d..6d9599e 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -488,7 +488,7 @@ def test_native_function_rejects(): functions.renamed(FUND) with pytest.raises(TypeError, match="too many positional arguments"): _any(functions.nothing)(1, 2) - # By nanobind + # By the extension with pytest.raises(TypeError, match="incompatible function arguments"): functions.nothing(_any("1")) with pytest.raises(