Skip to main content

rust_anything/
codegen_py.rs

1//! PyO3 bindings and the Python wrapper package for a bridge crate.
2//!
3//! Like the JS side, the binding layer follows `port.rs`: strings, ints, floats, bools and
4//! lists or options of those cross natively; anything structured crosses as JSON text, which
5//! the wrapper package (`python/<lib>/__init__.py`) encodes and decodes with Python markers.
6
7use std::fmt::Write as _;
8
9use crate::bridge::Manifest;
10use crate::codegen::{Modules, PortApi, PortFn, Wire, wire};
11use crate::ts::exports::Param;
12
13/// A Python signature for `#[pyo3(signature = ...)]`: optional parameters default to `None`,
14/// keyword-only ones follow `*`, the rest parameter is `*name`.
15fn signature(f: &PortFn, source: &[Param]) -> String {
16    let mut parts = Vec::new();
17    let mut keyword_only = false;
18    for (name, _) in &f.params {
19        let param = source
20            .iter()
21            .find(|p| crate::bridge::snake_case(&p.name) == *name);
22        if param.is_some_and(|p| p.keyword_only) && !keyword_only {
23            keyword_only = true;
24            parts.push("*".to_string());
25        }
26        let py_name = name.trim_start_matches("r#");
27        match param {
28            Some(p) if p.optional => match p.default.as_deref().and_then(rust_literal) {
29                Some(literal) => parts.push(format!("{py_name}={literal}")),
30                None => parts.push(format!("{py_name}=None")),
31            },
32            _ => parts.push(py_name.to_string()),
33        }
34    }
35    parts.join(", ")
36}
37
38/// A Python literal default as a Rust expression, for `#[pyo3(signature = ...)]`: strings,
39/// numbers and booleans. `None` and other expressions return `None` (the parameter is an
40/// `Option`, and `None` stands for the default).
41pub fn rust_literal(default: &str) -> Option<String> {
42    let d = default.trim();
43    match d {
44        // Python's `True`; Ruby's and Java's `true`.
45        "True" | "true" => return Some("true".into()),
46        "False" | "false" => return Some("false".into()),
47        "None" => return None,
48        _ => {}
49    }
50    let digits = d.replace('_', "");
51    if digits.parse::<i64>().is_ok() {
52        return Some(digits);
53    }
54    if (digits.contains('.') || digits.contains('e')) && digits.parse::<f64>().is_ok() {
55        return Some(if digits.contains('.') {
56            digits
57        } else {
58            format!("{digits}_f64")
59        });
60    }
61    let quote = d.chars().next().filter(|c| *c == '"' || *c == '\'')?;
62    let inner = d.strip_prefix(quote)?.strip_suffix(quote)?;
63    // Plain literals only: escapes and quotes inside would need Python's own parser.
64    if inner.contains('\\') || inner.contains('"') || inner.contains('\'') {
65        return None;
66    }
67    Some(format!("String::from(\"{inner}\")"))
68}
69
70/// Whether a parameter keeps Python's literal default (and is a plain, non-`Option` type).
71pub fn has_literal_default(p: &Param) -> bool {
72    p.optional && p.default.as_deref().and_then(rust_literal).is_some()
73}
74
75fn params_of<'m>(m: &'m Manifest, f: &PortFn, class: Option<&str>) -> &'m [Param] {
76    match class {
77        Some(c) => m
78            .classes
79            .iter()
80            .find(|k| k.name == c)
81            .map(|k| {
82                if f.rust_name == "new" {
83                    k.constructor.as_slice()
84                } else {
85                    k.methods
86                        .iter()
87                        .find(|x| x.name == f.js_name)
88                        .map_or(&[][..], |x| x.params.as_slice())
89                }
90            })
91            .unwrap_or(&[]),
92        None => m
93            .exports
94            .iter()
95            .find(|e| e.name == f.js_name)
96            .map_or(&[][..], |e| e.params.as_slice()),
97    }
98}
99
100/// The inner type of `Option<...>`, if that is what the port declares.
101fn option_inner(ty: &str) -> Option<&str> {
102    ty.strip_prefix("Option<").and_then(|t| t.strip_suffix('>'))
103}
104
105/// Whether the binding for a port parameter is `Option<Bound>`: an optional parameter whose
106/// default is `None` and whose value crosses as a Python object. PyO3 needs `Option<...>` to
107/// accept `None`; a plain `Bound` rejects it and the generated crate does not compile
108/// (`E0308: expected Bound<'_, PyAny>, found Option<_>`).
109fn is_option_bound(ty: &str) -> bool {
110    option_inner(ty).is_some_and(|inner| wire(inner) == Wire::Json)
111}
112
113fn binding_type(ty: &str) -> String {
114    if is_option_bound(ty) {
115        return "Option<Bound<'_, PyAny>>".to_string();
116    }
117    match wire(ty) {
118        // Structured values arrive as Python objects and are converted in Rust: no JSON text.
119        Wire::Json => "Bound<'_, PyAny>".to_string(),
120        _ => ty.to_string(),
121    }
122}
123
124/// Whether `FromPy`/`ToPy` in `pyconv.rs` cover a type: then it converts directly, without
125/// building a `serde_json::Value` first.
126fn direct(ty: &str) -> bool {
127    const KNOWN: &[&str] = &[
128        "Vec",
129        "Option",
130        "HashMap",
131        "std",
132        "collections",
133        "String",
134        "f64",
135        "i64",
136        "bool",
137        "serde_json",
138        "Value",
139        "Num",
140        "crate",
141        "pynum",
142    ];
143    ty.split(|c: char| !(c.is_alphanumeric() || c == '_'))
144        .filter(|w| !w.is_empty())
145        .all(|w| KNOWN.contains(&w))
146}
147
148fn body(f: &PortFn, target: &str, constructor: bool) -> String {
149    let mut body = String::new();
150    for (n, t) in &f.params {
151        if wire(t) == Wire::Json {
152            if is_option_bound(t) {
153                // The binding is `Option<Bound>`: `None` stays `None`, a value converts.
154                if direct(t) {
155                    let _ = writeln!(
156                        body,
157                        "    let {n}: {t} = match &{n} {{\n        None => None,\n        Some(v) => Some(crate::pyconv::FromPy::from_py(v)?),\n    }};"
158                    );
159                } else {
160                    let _ = writeln!(
161                        body,
162                        "    let {n} = match &{n} {{\n        None => None,\n        Some(v) => Some(crate::pyconv::arg(v)?),\n    }};"
163                    );
164                }
165            } else if direct(t) {
166                let _ = writeln!(
167                    body,
168                    "    let {n}: {t} = crate::pyconv::FromPy::from_py(&{n})?;"
169                );
170            } else {
171                let _ = writeln!(body, "    let {n} = crate::pyconv::arg(&{n})?;");
172            }
173        }
174    }
175    let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
176    let call = format!(
177        "{target}({}){}",
178        args.join(", "),
179        if f.fallible { "?" } else { "" }
180    );
181    if !constructor && f.ret.trim() == "()" {
182        let _ = writeln!(body, "    {call};\n    Ok(())");
183        return body;
184    }
185    let _ = writeln!(body, "    let out = {call};");
186    let _ = writeln!(
187        body,
188        "    {}",
189        if !constructor && wire(&f.ret) == Wire::Json && !direct(&f.ret) {
190            "serde_json::to_value(&out).map_err(|e| e.to_string())"
191        } else {
192            "Ok(out)"
193        }
194    );
195    body
196}
197
198/// The `_inner` function's success type: structured results as a `serde_json::Value`.
199fn ret(f: &PortFn) -> String {
200    match wire(&f.ret) {
201        Wire::Json if direct(&f.ret) => f.ret.clone(),
202        Wire::Json => "serde_json::Value".into(),
203        _ => f.ret.clone(),
204    }
205}
206
207/// The `#[pyfunction]`'s success type: structured results as a Python object.
208fn py_ret(f: &PortFn) -> String {
209    match wire(&f.ret) {
210        Wire::Json => "Py<PyAny>".into(),
211        _ => f.ret.clone(),
212    }
213}
214
215/// How the `#[pyfunction]` hands back the `_inner` result.
216fn py_out(f: &PortFn) -> &'static str {
217    match wire(&f.ret) {
218        Wire::Json => ".map_err(error).and_then(|v| crate::pyconv::ToPy::to_py(&v, py))",
219        _ => ".map_err(error)",
220    }
221}
222
223/// A port's `Err("KeyError: missing")` raises that built-in exception type with the message;
224/// without a known type prefix, `ValueError`. Panics become `PanicException`.
225const PY_ERROR: &str = r#"
226fn error(message: String) -> PyErr {
227    use pyo3::exceptions as e;
228    let (kind, text) = message.split_once(": ").unwrap_or(("", message.as_str()));
229    let text = text.to_string();
230    match kind {
231        "TypeError" => e::PyTypeError::new_err(text),
232        "KeyError" => e::PyKeyError::new_err(text),
233        "IndexError" => e::PyIndexError::new_err(text),
234        "OverflowError" => e::PyOverflowError::new_err(text),
235        "ZeroDivisionError" => e::PyZeroDivisionError::new_err(text),
236        "AttributeError" => e::PyAttributeError::new_err(text),
237        "RuntimeError" => e::PyRuntimeError::new_err(text),
238        "NotImplementedError" => e::PyNotImplementedError::new_err(text),
239        "LookupError" => e::PyLookupError::new_err(text),
240        "ArithmeticError" => e::PyArithmeticError::new_err(text),
241        "UnicodeError" => e::PyUnicodeError::new_err(text),
242        "ValueError" => e::PyValueError::new_err(text),
243        _ => e::PyValueError::new_err(message),
244    }
245}
246"#;
247
248pub fn lib_rs(m: &Manifest, api: &PortApi, modules: &Modules) -> String {
249    let mut out = format!(
250        "//! Python bindings for `{}`: generated from the signatures in `port.rs` by rust-anything.\n\
251         //! Regenerate with `rust-anything refresh` after changing them.\n\n\
252         #![allow(clippy::too_many_arguments)]\n\n\
253         use pyo3::prelude::*;\n\n",
254        m.unit
255    );
256    if modules.js {
257        out.push_str("pub mod js;\n");
258    }
259    out.push_str("pub mod port;\n");
260    if api.needs_json() {
261        out.push_str(
262            "pub mod pyconv;\npub mod pynum;\n\n#[allow(unused_imports)]\nuse pynum::Num;\n",
263        );
264    }
265    if modules.utf16 {
266        out.push_str("pub mod utf16;\n");
267    }
268    out.push_str(PY_ERROR);
269    let mut registrations = Vec::new();
270    for f in &api.functions {
271        let params: Vec<String> = f
272            .params
273            .iter()
274            .map(|(n, t)| format!("{n}: {}", binding_type(t)))
275            .collect();
276        let inner = format!("{}_inner", f.rust_name.trim_start_matches("r#"));
277        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
278        let _ = writeln!(
279            out,
280            "\nfn {inner}({}) -> Result<{}, String> {{\n{}}}\n",
281            params.join(", "),
282            ret(f),
283            body(f, &format!("port::{}", f.rust_name), false)
284        );
285        let _ = writeln!(out, "/// `{}`.", f.js_name);
286        let _ = writeln!(out, "#[pyfunction]");
287        let _ = writeln!(
288            out,
289            "#[pyo3(name = \"{}\", signature = ({}))]",
290            f.js_name,
291            signature(f, params_of(m, f, None))
292        );
293        let py_param = if wire(&f.ret) == Wire::Json {
294            "py: Python<'_>, "
295        } else {
296            ""
297        };
298        let _ = writeln!(
299            out,
300            "fn {}({py_param}{}) -> PyResult<{}> {{",
301            f.rust_name,
302            params.join(", "),
303            py_ret(f)
304        );
305        let _ = writeln!(out, "    {inner}({}){}\n}}", args.join(", "), py_out(f));
306        registrations.push(format!(
307            "    m.add_function(wrap_pyfunction!({}, m)?)?;",
308            f.rust_name
309        ));
310    }
311    for c in &api.classes {
312        let (name, js) = (&c.rust_name, &c.js_name);
313        let snake = crate::bridge::snake_case(name);
314        let ctor_params: Vec<String> = c
315            .constructor
316            .params
317            .iter()
318            .map(|(n, t)| format!("{n}: {}", binding_type(t)))
319            .collect();
320        let ctor_args: Vec<&str> = c
321            .constructor
322            .params
323            .iter()
324            .map(|(n, _)| n.as_str())
325            .collect();
326        let _ = writeln!(
327            out,
328            "\nfn {snake}_new_inner({}) -> Result<port::{name}, String> {{\n{}}}",
329            ctor_params.join(", "),
330            body(&c.constructor, &format!("port::{name}::new"), true)
331        );
332        for (method, mutable) in &c.methods {
333            let receiver = if *mutable {
334                format!("inner: &mut port::{name}")
335            } else {
336                format!("inner: &port::{name}")
337            };
338            let params: Vec<String> = std::iter::once(receiver)
339                .chain(
340                    method
341                        .params
342                        .iter()
343                        .map(|(n, t)| format!("{n}: {}", binding_type(t))),
344                )
345                .collect();
346            let _ = writeln!(
347                out,
348                "\nfn {snake}_{}_inner({}) -> Result<{}, String> {{\n{}}}",
349                method.rust_name.trim_start_matches("r#"),
350                params.join(", "),
351                ret(method),
352                body(method, &format!("inner.{}", method.rust_name), false)
353            );
354        }
355        let _ = writeln!(
356            out,
357            "\n/// Class `{js}`.\n#[pyclass(name = \"{js}\")]\npub struct {name} {{\n    inner: port::{name},\n}}\n"
358        );
359        let _ = writeln!(out, "#[pymethods]\nimpl {name} {{");
360        let _ = writeln!(
361            out,
362            "    #[new]\n    #[pyo3(signature = ({}))]\n    fn new({}) -> PyResult<Self> {{\n        \
363             {snake}_new_inner({}).map(|inner| Self {{ inner }}).map_err(error)\n    }}",
364            signature(&c.constructor, params_of(m, &c.constructor, Some(js))),
365            ctor_params.join(", "),
366            ctor_args.join(", ")
367        );
368        for (method, mutable) in &c.methods {
369            let receiver = if *mutable { "&mut self" } else { "&self" };
370            let params: Vec<String> = method
371                .params
372                .iter()
373                .map(|(n, t)| format!("{n}: {}", binding_type(t)))
374                .collect();
375            let sig = std::iter::once(receiver.to_string())
376                .chain(params)
377                .collect::<Vec<_>>()
378                .join(", ");
379            let borrow = if *mutable {
380                "&mut self.inner"
381            } else {
382                "&self.inner"
383            };
384            let args = std::iter::once(borrow)
385                .chain(method.params.iter().map(|(n, _)| n.as_str()))
386                .collect::<Vec<_>>();
387            let sig = if wire(&method.ret) == Wire::Json {
388                sig.replacen("self", "self, py: Python<'_>", 1)
389            } else {
390                sig
391            };
392            let _ = writeln!(
393                out,
394                "\n    #[pyo3(name = \"{}\", signature = ({}))]\n    fn {}({sig}) -> PyResult<{}> {{\n        \
395                 {snake}_{}_inner({}){}\n    }}",
396                method.js_name,
397                signature(method, params_of(m, method, Some(js))),
398                method.rust_name,
399                py_ret(method),
400                method.rust_name.trim_start_matches("r#"),
401                args.join(", "),
402                py_out(method)
403            );
404        }
405        out.push_str("}\n");
406        registrations.push(format!("    m.add_class::<{name}>()?;"));
407    }
408    if !m.batches.is_empty() {
409        match crate::codegen_batch::py_rs(m, api) {
410            Ok((code, classes)) => {
411                out.push_str(&code);
412                for c in classes {
413                    registrations.push(format!("    m.add_class::<{c}>()?;"));
414                }
415            }
416            Err(e) => {
417                let _ = writeln!(out, "\ncompile_error!({e:?});");
418            }
419        }
420    }
421    let _ = writeln!(
422        out,
423        "\n#[pymodule]\n#[pyo3(name = \"_native\")]\nfn native_module(m: &Bound<'_, PyModule>) -> PyResult<()> {{\n{}\n    Ok(())\n}}",
424        registrations.join("\n")
425    );
426    out
427}
428
429/// The wrapper package: imports `_native`, converting structured values.
430pub fn package_init(m: &Manifest, api: &PortApi) -> String {
431    // Structured values are converted in Rust (`pyconv.rs`): every export is the native one.
432    let structured = |_: &PortFn| -> (Vec<String>, bool) { (Vec::new(), false) };
433    let mut out = format!(
434        "\"\"\"Rust port of `{}`, generated by rust-anything. Import this package where the code\n\
435         imported the original module.\"\"\"\n\nfrom . import _native\n{CODEC_PY}\n",
436        m.unit
437    );
438    let mut names = Vec::new();
439    for f in &api.functions {
440        let (json_params, json_ret) = structured(f);
441        let positions: Vec<String> = f
442            .params
443            .iter()
444            .enumerate()
445            .filter(|(_, (_, t))| wire(t) == Wire::Json)
446            .map(|(i, _)| i.to_string())
447            .collect();
448        if json_params.is_empty() && !json_ret {
449            let _ = writeln!(out, "{} = _native.{}", f.js_name, f.js_name);
450        } else {
451            let _ = writeln!(
452                out,
453                "{name} = _wrap(_native.{name}, ({positions}), ({names_list}), {json_ret})",
454                name = f.js_name,
455                positions = positions
456                    .iter()
457                    .map(|p| format!("{p},"))
458                    .collect::<String>(),
459                names_list = json_params
460                    .iter()
461                    .map(|n| format!("'{n}',"))
462                    .collect::<String>(),
463                json_ret = if json_ret { "True" } else { "False" }
464            );
465        }
466        names.push(f.js_name.clone());
467    }
468    for c in &api.classes {
469        let needs = std::iter::once(&c.constructor)
470            .chain(c.methods.iter().map(|(x, _)| x))
471            .any(|f| {
472                let (p, r) = structured(f);
473                !p.is_empty() || r
474            });
475        if !needs {
476            let _ = writeln!(out, "{} = _native.{}", c.js_name, c.js_name);
477        } else {
478            let methods: String = c
479                .methods
480                .iter()
481                .map(|(method, _)| {
482                    let (params, json_ret) = structured(method);
483                    let positions: String = method
484                        .params
485                        .iter()
486                        .enumerate()
487                        .filter(|(_, (_, t))| wire(t) == Wire::Json)
488                        .map(|(i, _)| format!("{i},"))
489                        .collect();
490                    format!(
491                        "    {name} = _method('{name}', ({positions}), ({params}), {ret})\n",
492                        name = method.js_name,
493                        params = params.iter().map(|n| format!("'{n}',")).collect::<String>(),
494                        ret = if json_ret { "True" } else { "False" }
495                    )
496                })
497                .collect();
498            let (ctor_params, _) = structured(&c.constructor);
499            let ctor_positions: String = c
500                .constructor
501                .params
502                .iter()
503                .enumerate()
504                .filter(|(_, (_, t))| wire(t) == Wire::Json)
505                .map(|(i, _)| format!("{i},"))
506                .collect();
507            let _ = writeln!(
508                out,
509                "\nclass {js}:\n    def __init__(self, *args, **kwargs):\n        \
510                 args, kwargs = _encode_args(args, kwargs, ({ctor_positions}), ({}))\n        \
511                 self._inner = _native.{js}(*args, **kwargs)\n{methods}",
512                ctor_params
513                    .iter()
514                    .map(|n| format!("'{n}',"))
515                    .collect::<String>(),
516                js = c.js_name
517            );
518        }
519        names.push(c.js_name.clone());
520    }
521    for b in &m.batches {
522        let class = format!("{}Batch", crate::codegen_batch::pascal(&b.function));
523        let _ = writeln!(out, "{class} = _native.{class}");
524        names.push(class);
525    }
526    let _ = writeln!(
527        out,
528        "\n__all__ = [{}]",
529        names
530            .iter()
531            .map(|n| format!("'{n}'"))
532            .collect::<Vec<_>>()
533            .join(", ")
534    );
535    out
536}
537
538const CODEC_PY: &str = r#"
539import json as _json
540import math as _math
541
542# Structured values cross as JSON text. JSON has no NaN, tuples, sets, bytes, big ints or
543# non-string keys: those travel as markers (see `js.rs`) and come back as Python values.
544_BIG = 2 ** 53
545
546
547def _enc(v):
548    if v is None or isinstance(v, (bool, str)):
549        return v
550    if isinstance(v, int):
551        return v if -_BIG <= v <= _BIG else {"$int": str(v)}
552    if isinstance(v, float):
553        if _math.isnan(v):
554            return {"$num": "NaN"}
555        if _math.isinf(v):
556            return {"$num": "Infinity" if v > 0 else "-Infinity"}
557        if v == 0 and _math.copysign(1, v) < 0:
558            return {"$num": "-0"}
559        return v
560    if isinstance(v, list):
561        return [_enc(x) for x in v]
562    if isinstance(v, tuple):
563        return {"$tuple": [_enc(x) for x in v]}
564    if isinstance(v, (set, frozenset)):
565        return {"$set": sorted((_enc(x) for x in v), key=_json.dumps)}
566    if isinstance(v, (bytes, bytearray)):
567        return {"$bytes": list(v)}
568    if isinstance(v, dict):
569        if all(isinstance(k, str) for k in v):
570            return {k: _enc(x) for k, x in v.items()}
571        return {"$dict": [[_enc(k), _enc(x)] for k, x in v.items()]}
572    return {"$repr": repr(v)}
573
574
575def _dec(v):
576    if isinstance(v, list):
577        return [_dec(x) for x in v]
578    if not isinstance(v, dict):
579        return v
580    if len(v) == 1:
581        (key, inner), = v.items()
582        if key == "$undefined":
583            return None
584        if key == "$num":
585            return {"NaN": _math.nan, "Infinity": _math.inf, "-Infinity": -_math.inf, "-0": -0.0}[inner]
586        if key == "$int":
587            return int(inner)
588        if key == "$tuple":
589            return tuple(_dec(x) for x in inner)
590        if key == "$set":
591            return {_dec(x) for x in inner}
592        if key == "$bytes":
593            return bytes(inner)
594        if key == "$dict":
595            return {_dec(k): _dec(x) for k, x in inner}
596    return {k: _dec(x) for k, x in v.items()}
597
598
599def _encode_args(args, kwargs, positions, names):
600    args = tuple(_json.dumps(_enc(a)) if i in positions else a for i, a in enumerate(args))
601    kwargs = {k: (_json.dumps(_enc(a)) if k in names else a) for k, a in kwargs.items()}
602    return args, kwargs
603
604
605def _wrap(fn, positions, names, json_result):
606    def call(*args, **kwargs):
607        args, kwargs = _encode_args(args, kwargs, positions, names)
608        out = fn(*args, **kwargs)
609        return _dec(_json.loads(out)) if json_result else out
610    call.__name__ = fn.__name__
611    call.__doc__ = fn.__doc__
612    return call
613
614
615def _method(name, positions, names, json_result):
616    def call(self, *args, **kwargs):
617        args, kwargs = _encode_args(args, kwargs, positions, names)
618        out = getattr(self._inner, name)(*args, **kwargs)
619        return _dec(_json.loads(out)) if json_result else out
620    call.__name__ = name
621    return call
622"#;
623
624/// `src/pyconv.rs`: Python objects to `serde_json::Value` and back, in Rust, without JSON text.
625/// Values the JSON model lacks use the same markers as recorded cases: `$tuple`, `$set`,
626/// `$bytes`, `$int` (beyond i64), `$dict` (non-string keys), `$num` (NaN, infinities, -0).
627pub const PYCONV_RS: &str = r#"//! Python objects to `serde_json::Value` and back, in Rust. Generated by rust-anything.
628
629#![forbid(unsafe_code)]
630
631use pyo3::prelude::*;
632use pyo3::types::{PyBool, PyBytes, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PySet, PyString, PyTuple};
633use serde_json::{Map, Value, json};
634
635fn type_error(obj: &Bound<'_, PyAny>) -> String {
636    let name = obj.get_type().name().map(|n| n.to_string()).unwrap_or_default();
637    format!("TypeError: unsupported argument type {name}")
638}
639
640fn float(x: f64) -> Value {
641    if x.is_nan() {
642        json!({"$num": "NaN"})
643    } else if x.is_infinite() {
644        json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
645    } else if x == 0.0 && x.is_sign_negative() {
646        json!({"$num": "-0"})
647    } else {
648        json!(x)
649    }
650}
651
652fn items(obj: &Bound<'_, PyAny>) -> Result<Vec<Value>, String> {
653    let mut out = Vec::new();
654    for item in obj.try_iter().map_err(|e| e.to_string())? {
655        out.push(from_py(&item.map_err(|e| e.to_string())?)?);
656    }
657    Ok(out)
658}
659
660/// A Python object as a JSON value.
661pub fn from_py(obj: &Bound<'_, PyAny>) -> Result<Value, String> {
662    if obj.is_none() {
663        return Ok(Value::Null);
664    }
665    if obj.is_instance_of::<PyBool>() {
666        return Ok(Value::Bool(obj.extract::<bool>().map_err(|e| e.to_string())?));
667    }
668    if obj.is_instance_of::<PyInt>() {
669        return Ok(match obj.extract::<i64>() {
670            Ok(i) => json!(i),
671            Err(_) => json!({"$int": obj.str().map_err(|e| e.to_string())?.to_string()}),
672        });
673    }
674    if obj.is_instance_of::<PyFloat>() {
675        return Ok(float(obj.extract::<f64>().map_err(|e| e.to_string())?));
676    }
677    if obj.is_instance_of::<PyString>() {
678        return Ok(Value::String(obj.extract::<String>().map_err(|e| e.to_string())?));
679    }
680    if obj.is_instance_of::<PyList>() {
681        return Ok(Value::Array(items(obj)?));
682    }
683    if obj.is_instance_of::<PyTuple>() {
684        return Ok(json!({"$tuple": items(obj)?}));
685    }
686    if obj.is_instance_of::<PyDict>() {
687        let dict = obj.cast::<PyDict>().map_err(|e| e.to_string())?;
688        let mut map = Map::new();
689        let mut pairs = Vec::new();
690        let mut string_keys = true;
691        for (k, v) in dict.iter() {
692            let value = from_py(&v)?;
693            if let Ok(key) = k.extract::<String>() {
694                map.insert(key.clone(), value.clone());
695                pairs.push(json!([key, value]));
696            } else {
697                string_keys = false;
698                pairs.push(json!([from_py(&k)?, value]));
699            }
700        }
701        return Ok(if string_keys { Value::Object(map) } else { json!({"$dict": pairs}) });
702    }
703    if obj.is_instance_of::<PySet>() || obj.is_instance_of::<PyFrozenSet>() {
704        return Ok(json!({"$set": items(obj)?}));
705    }
706    if obj.is_instance_of::<PyBytes>() {
707        return Ok(json!({"$bytes": obj.extract::<Vec<u8>>().map_err(|e| e.to_string())?}));
708    }
709    Err(type_error(obj))
710}
711
712/// A structured argument, converted to the port's parameter type.
713pub fn arg<T: serde::de::DeserializeOwned>(obj: &Bound<'_, PyAny>) -> Result<T, String> {
714    serde_json::from_value(from_py(obj)?).map_err(|e| format!("TypeError: {e}"))
715}
716
717/// A Python argument as a Rust value, without going through JSON.
718pub trait FromPy: Sized {
719    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String>;
720}
721
722/// A Rust result as a Python object, without going through JSON.
723pub trait ToPy {
724    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>>;
725}
726
727macro_rules! extract {
728    ($($t:ty),*) => {$(
729        impl FromPy for $t {
730            fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
731                obj.extract::<$t>().map_err(|_| type_error(obj))
732            }
733        }
734        impl ToPy for $t {
735            fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
736                Ok(self.clone().into_pyobject(py)?.to_owned().into_any().unbind())
737            }
738        }
739    )*};
740}
741extract!(i64, bool, String);
742
743impl FromPy for f64 {
744    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
745        if obj.is_instance_of::<PyFloat>() || obj.is_instance_of::<PyInt>() {
746            obj.extract::<f64>().map_err(|_| type_error(obj))
747        } else {
748            Err(type_error(obj))
749        }
750    }
751}
752
753impl ToPy for f64 {
754    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
755        Ok(PyFloat::new(py, *self).into_any().unbind())
756    }
757}
758
759impl FromPy for crate::pynum::Num {
760    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
761        use crate::pynum::Num;
762        if obj.is_instance_of::<PyFloat>() {
763            return obj.extract::<f64>().map(Num::Float).map_err(|_| type_error(obj));
764        }
765        if obj.is_instance_of::<PyInt>() {
766            return obj
767                .extract::<i64>()
768                .map(Num::Int)
769                .map_err(|_| "OverflowError: int too large for the port".to_string());
770        }
771        Err(type_error(obj))
772    }
773}
774
775impl ToPy for crate::pynum::Num {
776    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
777        match *self {
778            crate::pynum::Num::Int(i) => i.to_py(py),
779            crate::pynum::Num::Float(x) => x.to_py(py),
780        }
781    }
782}
783
784impl FromPy for Value {
785    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
786        from_py(obj)
787    }
788}
789
790impl ToPy for Value {
791    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
792        to_py(py, self)
793    }
794}
795
796impl<T: FromPy> FromPy for Option<T> {
797    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
798        if obj.is_none() { Ok(None) } else { T::from_py(obj).map(Some) }
799    }
800}
801
802impl<T: ToPy> ToPy for Option<T> {
803    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
804        match self {
805            Some(v) => v.to_py(py),
806            None => Ok(py.None()),
807        }
808    }
809}
810
811impl<T: FromPy> FromPy for Vec<T> {
812    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
813        if !obj.is_instance_of::<PyList>() && !obj.is_instance_of::<PyTuple>() {
814            return Err(type_error(obj));
815        }
816        let mut out = Vec::new();
817        for item in obj.try_iter().map_err(|e| e.to_string())? {
818            out.push(T::from_py(&item.map_err(|e| e.to_string())?)?);
819        }
820        Ok(out)
821    }
822}
823
824impl<T: ToPy> ToPy for Vec<T> {
825    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
826        let items: PyResult<Vec<Py<PyAny>>> = self.iter().map(|x| x.to_py(py)).collect();
827        Ok(PyList::new(py, items?)?.into_any().unbind())
828    }
829}
830
831impl<T: FromPy> FromPy for std::collections::HashMap<String, T> {
832    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
833        let dict = obj.cast::<PyDict>().map_err(|_| type_error(obj))?;
834        let mut out = Self::new();
835        for (k, v) in dict.iter() {
836            out.insert(k.extract::<String>().map_err(|_| type_error(&k))?, T::from_py(&v)?);
837        }
838        Ok(out)
839    }
840}
841
842impl<T: ToPy> ToPy for std::collections::HashMap<String, T> {
843    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
844        let dict = PyDict::new(py);
845        for (k, v) in self {
846            dict.set_item(k, v.to_py(py)?)?;
847        }
848        Ok(dict.into_any().unbind())
849    }
850}
851
852macro_rules! tuples {
853    ($(($($t:ident $i:tt),+)),*) => {$(
854        impl<$($t: FromPy),+> FromPy for ($($t,)+) {
855            fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
856                let t = obj.cast::<PyTuple>().map_err(|_| type_error(obj))?;
857                Ok(($($t::from_py(&t.get_item($i).map_err(|e| e.to_string())?)?,)+))
858            }
859        }
860        impl<$($t: ToPy),+> ToPy for ($($t,)+) {
861            fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
862                Ok(PyTuple::new(py, [$(self.$i.to_py(py)?),+])?.into_any().unbind())
863            }
864        }
865    )*};
866}
867tuples!((A 0, B 1), (A 0, B 1, C 2), (A 0, B 1, C 2, D 3));
868
869/// A JSON value as a Python object; markers become the Python types they stand for.
870pub fn to_py(py: Python<'_>, v: &Value) -> PyResult<Py<PyAny>> {
871    let list = |items: &[Value]| -> PyResult<Vec<Py<PyAny>>> { items.iter().map(|x| to_py(py, x)).collect() };
872    Ok(match v {
873        Value::Null => py.None(),
874        Value::Bool(b) => PyBool::new(py, *b).to_owned().into_any().unbind(),
875        Value::Number(n) => match n.as_i64() {
876            Some(i) if !n.is_f64() => i.into_pyobject(py)?.into_any().unbind(),
877            _ => match n.as_u64() {
878                Some(u) if !n.is_f64() => u.into_pyobject(py)?.into_any().unbind(),
879                _ => PyFloat::new(py, n.as_f64().unwrap_or(f64::NAN)).into_any().unbind(),
880            },
881        },
882        Value::String(s) => PyString::new(py, s).into_any().unbind(),
883        Value::Array(items) => PyList::new(py, list(items)?)?.into_any().unbind(),
884        Value::Object(o) if o.len() == 1 => {
885            let (key, inner) = o.iter().next().expect("one entry");
886            let items = || inner.as_array().map(Vec::as_slice).unwrap_or_default();
887            match key.as_str() {
888                "$tuple" => PyTuple::new(py, list(items())?)?.into_any().unbind(),
889                "$set" => PySet::new(py, list(items())?)?.into_any().unbind(),
890                "$bytes" => {
891                    let bytes: Vec<u8> = items().iter().filter_map(|b| b.as_u64()).map(|b| b as u8).collect();
892                    PyBytes::new(py, &bytes).into_any().unbind()
893                }
894                "$int" => py
895                    .import("builtins")?
896                    .getattr("int")?
897                    .call1((inner.as_str().unwrap_or("0"),))?
898                    .unbind(),
899                "$float" => PyFloat::new(py, inner.as_str().and_then(|s| s.parse().ok()).unwrap_or(f64::NAN)).into_any().unbind(),
900                "$num" => PyFloat::new(
901                    py,
902                    match inner.as_str() {
903                        Some("Infinity") => f64::INFINITY,
904                        Some("-Infinity") => f64::NEG_INFINITY,
905                        Some("-0") => -0.0,
906                        _ => f64::NAN,
907                    },
908                )
909                .into_any()
910                .unbind(),
911                "$dict" => {
912                    let dict = PyDict::new(py);
913                    for pair in items() {
914                        if let Some([k, v]) = pair.as_array().map(Vec::as_slice) {
915                            dict.set_item(to_py(py, k)?, to_py(py, v)?)?;
916                        }
917                    }
918                    dict.into_any().unbind()
919                }
920                _ => {
921                    let dict = PyDict::new(py);
922                    dict.set_item(key, to_py(py, inner)?)?;
923                    dict.into_any().unbind()
924                }
925            }
926        }
927        Value::Object(o) => {
928            let dict = PyDict::new(py);
929            for (k, x) in o {
930                dict.set_item(k, to_py(py, x)?)?;
931            }
932            dict.into_any().unbind()
933        }
934    })
935}
936"#;
937
938/// `src/pynum.rs`: Python's int-or-float, for ports of code that takes either.
939pub const PYNUM_RS: &str = r#"//! Python numbers: an int stays an int through `+`, `-`, `*`, `//` and `%`; `/` gives a float.
940//! Generated by rust-anything. Ints beyond i64 become floats (Python would keep a big int).
941
942#![forbid(unsafe_code)]
943
944use std::cmp::Ordering;
945use std::ops::{Add, Mul, Neg, Sub};
946
947#[derive(Clone, Copy, Debug)]
948pub enum Num {
949    Int(i64),
950    Float(f64),
951}
952
953impl Num {
954    pub fn f(self) -> f64 {
955        match self {
956            Self::Int(i) => i as f64,
957            Self::Float(x) => x,
958        }
959    }
960
961    fn op(self, o: Self, int: fn(i64, i64) -> Option<i64>, float: fn(f64, f64) -> f64) -> Self {
962        match (self, o) {
963            (Self::Int(a), Self::Int(b)) => int(a, b).map_or_else(|| Self::Float(float(a as f64, b as f64)), Self::Int),
964            (a, b) => Self::Float(float(a.f(), b.f())),
965        }
966    }
967
968    /// `/`: always a float; `ZeroDivisionError` for zero.
969    pub fn true_div(self, o: Self) -> Result<Self, String> {
970        match (self, o) {
971            (_, o) if o.f() == 0.0 => Err(match (self, o) {
972                (Self::Int(_), Self::Int(_)) => "ZeroDivisionError: division by zero".into(),
973                _ => "ZeroDivisionError: float division by zero".into(),
974            }),
975            (a, b) => Ok(Self::Float(a.f() / b.f())),
976        }
977    }
978
979    /// `%`: the result takes the divisor's sign.
980    pub fn modulo(self, o: Self) -> Result<Self, String> {
981        match (self, o) {
982            (Self::Int(_), Self::Int(0)) => Err("ZeroDivisionError: integer modulo by zero".into()),
983            (Self::Int(a), Self::Int(b)) => {
984                let r = a.wrapping_rem(b);
985                Ok(Self::Int(if r != 0 && (r < 0) != (b < 0) { r + b } else { r }))
986            }
987            (a, b) => {
988                let (x, y) = (a.f(), b.f());
989                if y == 0.0 {
990                    return Err("ZeroDivisionError: float modulo".into());
991                }
992                let m = x % y;
993                Ok(Self::Float(if m != 0.0 {
994                    if (y < 0.0) != (m < 0.0) { m + y } else { m }
995                } else {
996                    0.0_f64.copysign(y)
997                }))
998            }
999        }
1000    }
1001
1002    /// Python's `max(a, b, ...)`: the first value no later value is greater than.
1003    pub fn max(values: &[Self]) -> Self {
1004        values[1..].iter().fold(values[0], |m, &x| if x > m { x } else { m })
1005    }
1006
1007    /// Python's `min(a, b, ...)`.
1008    pub fn min(values: &[Self]) -> Self {
1009        values[1..].iter().fold(values[0], |m, &x| if x < m { x } else { m })
1010    }
1011}
1012
1013impl From<f64> for Num {
1014    fn from(x: f64) -> Self {
1015        Self::Float(x)
1016    }
1017}
1018
1019impl From<i64> for Num {
1020    fn from(i: i64) -> Self {
1021        Self::Int(i)
1022    }
1023}
1024
1025impl Add for Num {
1026    type Output = Self;
1027    fn add(self, o: Self) -> Self {
1028        self.op(o, i64::checked_add, |a, b| a + b)
1029    }
1030}
1031
1032impl Sub for Num {
1033    type Output = Self;
1034    fn sub(self, o: Self) -> Self {
1035        self.op(o, i64::checked_sub, |a, b| a - b)
1036    }
1037}
1038
1039impl Mul for Num {
1040    type Output = Self;
1041    fn mul(self, o: Self) -> Self {
1042        self.op(o, i64::checked_mul, |a, b| a * b)
1043    }
1044}
1045
1046impl Neg for Num {
1047    type Output = Self;
1048    fn neg(self) -> Self {
1049        match self {
1050            Self::Int(i) => i.checked_neg().map_or(Self::Float(-(i as f64)), Self::Int),
1051            Self::Float(x) => Self::Float(-x),
1052        }
1053    }
1054}
1055
1056impl PartialEq for Num {
1057    fn eq(&self, o: &Self) -> bool {
1058        match (*self, *o) {
1059            (Self::Int(a), Self::Int(b)) => a == b,
1060            (a, b) => a.f() == b.f(),
1061        }
1062    }
1063}
1064
1065impl PartialOrd for Num {
1066    fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
1067        match (*self, *o) {
1068            (Self::Int(a), Self::Int(b)) => a.partial_cmp(&b),
1069            (a, b) => a.f().partial_cmp(&b.f()),
1070        }
1071    }
1072}
1073"#;
1074
1075#[cfg(test)]
1076mod tests {
1077    use super::*;
1078    use crate::bridge::{Kind, Manifest};
1079    use crate::codegen::{Modules, PortApi, PortFn};
1080    use crate::lang::Lang;
1081    use crate::ts::exports::{ExportedFn, Param};
1082
1083    #[test]
1084    fn converts_python_literals() {
1085        assert_eq!(rust_literal("'-'").as_deref(), Some("String::from(\"-\")"));
1086        assert_eq!(rust_literal("8").as_deref(), Some("8"));
1087        assert_eq!(rust_literal("1_000").as_deref(), Some("1000"));
1088        assert_eq!(rust_literal("0.5").as_deref(), Some("0.5"));
1089        assert_eq!(rust_literal("True").as_deref(), Some("true"));
1090        assert_eq!(rust_literal("None"), None);
1091        assert_eq!(rust_literal("[]"), None);
1092        assert_eq!(rust_literal("'a\\nb'"), None);
1093    }
1094
1095    #[test]
1096    fn optional_object_params_bind_as_option_bound() {
1097        // `thresholds=None` must bind as `Option<Bound>` so PyO3 accepts `None`;
1098        // required structured parameters stay a plain `Bound`, native options are untouched.
1099        assert_eq!(
1100            binding_type("Option<serde_json::Value>").as_str(),
1101            "Option<Bound<'_, PyAny>>"
1102        );
1103        assert_eq!(
1104            binding_type("serde_json::Value").as_str(),
1105            "Bound<'_, PyAny>"
1106        );
1107        assert_eq!(binding_type("Option<i64>").as_str(), "Option<i64>");
1108        assert_eq!(binding_type("String").as_str(), "String");
1109    }
1110
1111    fn verdict_port() -> PortFn {
1112        PortFn {
1113            js_name: "verdict".into(),
1114            rust_name: "verdict".into(),
1115            params: vec![
1116                ("readings".into(), "serde_json::Value".into()),
1117                ("thresholds".into(), "Option<serde_json::Value>".into()),
1118            ],
1119            ret: "serde_json::Value".into(),
1120            fallible: true,
1121            is_async: false,
1122        }
1123    }
1124
1125    fn verdict_manifest() -> Manifest {
1126        let param = |name: &str, ts_type: &str, optional: bool, default: Option<&str>| Param {
1127            name: name.into(),
1128            ts_type: ts_type.into(),
1129            optional,
1130            default: default.map(str::to_string),
1131            ..Default::default()
1132        };
1133        Manifest {
1134            schema: "1".into(),
1135            root: std::path::PathBuf::from("/tmp"),
1136            root_written: None,
1137            unit: "hpdet/".into(),
1138            language: Lang::Python,
1139            kind: Kind::Pyo3,
1140            crate_name: "hpdet-rs".into(),
1141            exports: vec![ExportedFn {
1142                name: "verdict".into(),
1143                file: "hpdet/verdict.py".into(),
1144                line: 1,
1145                params: vec![
1146                    param("readings", "Record<string, number>", false, None),
1147                    param("thresholds", "Thresholds | undefined", true, Some("None")),
1148                ],
1149                returns: "Record<string, number>".into(),
1150                ..Default::default()
1151            }],
1152            classes: Vec::new(),
1153            js_only: Vec::new(),
1154            batches: Vec::new(),
1155            allocator: Default::default(),
1156            float_tolerance: None,
1157        }
1158    }
1159
1160    #[test]
1161    fn optional_object_wrapper_accepts_none() {
1162        let api = PortApi {
1163            functions: vec![verdict_port()],
1164            ..Default::default()
1165        };
1166        let modules = Modules {
1167            utf16: false,
1168            js: false,
1169        };
1170        let lib = lib_rs(&verdict_manifest(), &api, &modules);
1171        assert!(
1172            lib.contains("#![allow(clippy::too_many_arguments)]"),
1173            "{lib}"
1174        );
1175        // The signature still defaults to `None`, and the Rust parameter takes `Option`.
1176        assert!(
1177            lib.contains("#[pyo3(name = \"verdict\", signature = (readings, thresholds=None))]"),
1178            "{lib}"
1179        );
1180        assert!(
1181            lib.contains(
1182                "fn verdict_inner(readings: Bound<'_, PyAny>, \
1183                 thresholds: Option<Bound<'_, PyAny>>)"
1184            ),
1185            "{lib}"
1186        );
1187        // `None` converts to `None`; a value converts through the port's type.
1188        assert!(lib.contains("match &thresholds"), "{lib}");
1189        assert!(lib.contains("None => None,"), "{lib}");
1190    }
1191}