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         use pyo3::prelude::*;\n\n",
253        m.unit
254    );
255    if modules.js {
256        out.push_str("pub mod js;\n");
257    }
258    out.push_str("pub mod port;\n");
259    if api.needs_json() {
260        out.push_str(
261            "pub mod pyconv;\npub mod pynum;\n\n#[allow(unused_imports)]\nuse pynum::Num;\n",
262        );
263    }
264    if modules.utf16 {
265        out.push_str("pub mod utf16;\n");
266    }
267    out.push_str(PY_ERROR);
268    let mut registrations = Vec::new();
269    for f in &api.functions {
270        let params: Vec<String> = f
271            .params
272            .iter()
273            .map(|(n, t)| format!("{n}: {}", binding_type(t)))
274            .collect();
275        let inner = format!("{}_inner", f.rust_name.trim_start_matches("r#"));
276        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
277        let _ = writeln!(
278            out,
279            "\nfn {inner}({}) -> Result<{}, String> {{\n{}}}\n",
280            params.join(", "),
281            ret(f),
282            body(f, &format!("port::{}", f.rust_name), false)
283        );
284        let _ = writeln!(out, "/// `{}`.", f.js_name);
285        let _ = writeln!(out, "#[pyfunction]");
286        let _ = writeln!(
287            out,
288            "#[pyo3(name = \"{}\", signature = ({}))]",
289            f.js_name,
290            signature(f, params_of(m, f, None))
291        );
292        let py_param = if wire(&f.ret) == Wire::Json {
293            "py: Python<'_>, "
294        } else {
295            ""
296        };
297        let _ = writeln!(
298            out,
299            "fn {}({py_param}{}) -> PyResult<{}> {{",
300            f.rust_name,
301            params.join(", "),
302            py_ret(f)
303        );
304        let _ = writeln!(out, "    {inner}({}){}\n}}", args.join(", "), py_out(f));
305        registrations.push(format!(
306            "    m.add_function(wrap_pyfunction!({}, m)?)?;",
307            f.rust_name
308        ));
309    }
310    for c in &api.classes {
311        let (name, js) = (&c.rust_name, &c.js_name);
312        let snake = crate::bridge::snake_case(name);
313        let ctor_params: Vec<String> = c
314            .constructor
315            .params
316            .iter()
317            .map(|(n, t)| format!("{n}: {}", binding_type(t)))
318            .collect();
319        let ctor_args: Vec<&str> = c
320            .constructor
321            .params
322            .iter()
323            .map(|(n, _)| n.as_str())
324            .collect();
325        let _ = writeln!(
326            out,
327            "\nfn {snake}_new_inner({}) -> Result<port::{name}, String> {{\n{}}}",
328            ctor_params.join(", "),
329            body(&c.constructor, &format!("port::{name}::new"), true)
330        );
331        for (method, mutable) in &c.methods {
332            let receiver = if *mutable {
333                format!("inner: &mut port::{name}")
334            } else {
335                format!("inner: &port::{name}")
336            };
337            let params: Vec<String> = std::iter::once(receiver)
338                .chain(
339                    method
340                        .params
341                        .iter()
342                        .map(|(n, t)| format!("{n}: {}", binding_type(t))),
343                )
344                .collect();
345            let _ = writeln!(
346                out,
347                "\nfn {snake}_{}_inner({}) -> Result<{}, String> {{\n{}}}",
348                method.rust_name.trim_start_matches("r#"),
349                params.join(", "),
350                ret(method),
351                body(method, &format!("inner.{}", method.rust_name), false)
352            );
353        }
354        let _ = writeln!(
355            out,
356            "\n/// Class `{js}`.\n#[pyclass(name = \"{js}\")]\npub struct {name} {{\n    inner: port::{name},\n}}\n"
357        );
358        let _ = writeln!(out, "#[pymethods]\nimpl {name} {{");
359        let _ = writeln!(
360            out,
361            "    #[new]\n    #[pyo3(signature = ({}))]\n    fn new({}) -> PyResult<Self> {{\n        \
362             {snake}_new_inner({}).map(|inner| Self {{ inner }}).map_err(error)\n    }}",
363            signature(&c.constructor, params_of(m, &c.constructor, Some(js))),
364            ctor_params.join(", "),
365            ctor_args.join(", ")
366        );
367        for (method, mutable) in &c.methods {
368            let receiver = if *mutable { "&mut self" } else { "&self" };
369            let params: Vec<String> = method
370                .params
371                .iter()
372                .map(|(n, t)| format!("{n}: {}", binding_type(t)))
373                .collect();
374            let sig = std::iter::once(receiver.to_string())
375                .chain(params)
376                .collect::<Vec<_>>()
377                .join(", ");
378            let borrow = if *mutable {
379                "&mut self.inner"
380            } else {
381                "&self.inner"
382            };
383            let args = std::iter::once(borrow)
384                .chain(method.params.iter().map(|(n, _)| n.as_str()))
385                .collect::<Vec<_>>();
386            let sig = if wire(&method.ret) == Wire::Json {
387                sig.replacen("self", "self, py: Python<'_>", 1)
388            } else {
389                sig
390            };
391            let _ = writeln!(
392                out,
393                "\n    #[pyo3(name = \"{}\", signature = ({}))]\n    fn {}({sig}) -> PyResult<{}> {{\n        \
394                 {snake}_{}_inner({}){}\n    }}",
395                method.js_name,
396                signature(method, params_of(m, method, Some(js))),
397                method.rust_name,
398                py_ret(method),
399                method.rust_name.trim_start_matches("r#"),
400                args.join(", "),
401                py_out(method)
402            );
403        }
404        out.push_str("}\n");
405        registrations.push(format!("    m.add_class::<{name}>()?;"));
406    }
407    if !m.batches.is_empty() {
408        match crate::codegen_batch::py_rs(m, api) {
409            Ok((code, classes)) => {
410                out.push_str(&code);
411                for c in classes {
412                    registrations.push(format!("    m.add_class::<{c}>()?;"));
413                }
414            }
415            Err(e) => {
416                let _ = writeln!(out, "\ncompile_error!({e:?});");
417            }
418        }
419    }
420    let _ = writeln!(
421        out,
422        "\n#[pymodule]\n#[pyo3(name = \"_native\")]\nfn native_module(m: &Bound<'_, PyModule>) -> PyResult<()> {{\n{}\n    Ok(())\n}}",
423        registrations.join("\n")
424    );
425    out
426}
427
428/// The wrapper package: imports `_native`, converting structured values.
429pub fn package_init(m: &Manifest, api: &PortApi) -> String {
430    // Structured values are converted in Rust (`pyconv.rs`): every export is the native one.
431    let structured = |_: &PortFn| -> (Vec<String>, bool) { (Vec::new(), false) };
432    let mut out = format!(
433        "\"\"\"Rust port of `{}`, generated by rust-anything. Import this package where the code\n\
434         imported the original module.\"\"\"\n\nfrom . import _native\n{CODEC_PY}\n",
435        m.unit
436    );
437    let mut names = Vec::new();
438    for f in &api.functions {
439        let (json_params, json_ret) = structured(f);
440        let positions: Vec<String> = f
441            .params
442            .iter()
443            .enumerate()
444            .filter(|(_, (_, t))| wire(t) == Wire::Json)
445            .map(|(i, _)| i.to_string())
446            .collect();
447        if json_params.is_empty() && !json_ret {
448            let _ = writeln!(out, "{} = _native.{}", f.js_name, f.js_name);
449        } else {
450            let _ = writeln!(
451                out,
452                "{name} = _wrap(_native.{name}, ({positions}), ({names_list}), {json_ret})",
453                name = f.js_name,
454                positions = positions
455                    .iter()
456                    .map(|p| format!("{p},"))
457                    .collect::<String>(),
458                names_list = json_params
459                    .iter()
460                    .map(|n| format!("'{n}',"))
461                    .collect::<String>(),
462                json_ret = if json_ret { "True" } else { "False" }
463            );
464        }
465        names.push(f.js_name.clone());
466    }
467    for c in &api.classes {
468        let needs = std::iter::once(&c.constructor)
469            .chain(c.methods.iter().map(|(x, _)| x))
470            .any(|f| {
471                let (p, r) = structured(f);
472                !p.is_empty() || r
473            });
474        if !needs {
475            let _ = writeln!(out, "{} = _native.{}", c.js_name, c.js_name);
476        } else {
477            let methods: String = c
478                .methods
479                .iter()
480                .map(|(method, _)| {
481                    let (params, json_ret) = structured(method);
482                    let positions: String = method
483                        .params
484                        .iter()
485                        .enumerate()
486                        .filter(|(_, (_, t))| wire(t) == Wire::Json)
487                        .map(|(i, _)| format!("{i},"))
488                        .collect();
489                    format!(
490                        "    {name} = _method('{name}', ({positions}), ({params}), {ret})\n",
491                        name = method.js_name,
492                        params = params.iter().map(|n| format!("'{n}',")).collect::<String>(),
493                        ret = if json_ret { "True" } else { "False" }
494                    )
495                })
496                .collect();
497            let (ctor_params, _) = structured(&c.constructor);
498            let ctor_positions: String = c
499                .constructor
500                .params
501                .iter()
502                .enumerate()
503                .filter(|(_, (_, t))| wire(t) == Wire::Json)
504                .map(|(i, _)| format!("{i},"))
505                .collect();
506            let _ = writeln!(
507                out,
508                "\nclass {js}:\n    def __init__(self, *args, **kwargs):\n        \
509                 args, kwargs = _encode_args(args, kwargs, ({ctor_positions}), ({}))\n        \
510                 self._inner = _native.{js}(*args, **kwargs)\n{methods}",
511                ctor_params
512                    .iter()
513                    .map(|n| format!("'{n}',"))
514                    .collect::<String>(),
515                js = c.js_name
516            );
517        }
518        names.push(c.js_name.clone());
519    }
520    for b in &m.batches {
521        let class = format!("{}Batch", crate::codegen_batch::pascal(&b.function));
522        let _ = writeln!(out, "{class} = _native.{class}");
523        names.push(class);
524    }
525    let _ = writeln!(
526        out,
527        "\n__all__ = [{}]",
528        names
529            .iter()
530            .map(|n| format!("'{n}'"))
531            .collect::<Vec<_>>()
532            .join(", ")
533    );
534    out
535}
536
537const CODEC_PY: &str = r#"
538import json as _json
539import math as _math
540
541# Structured values cross as JSON text. JSON has no NaN, tuples, sets, bytes, big ints or
542# non-string keys: those travel as markers (see `js.rs`) and come back as Python values.
543_BIG = 2 ** 53
544
545
546def _enc(v):
547    if v is None or isinstance(v, (bool, str)):
548        return v
549    if isinstance(v, int):
550        return v if -_BIG <= v <= _BIG else {"$int": str(v)}
551    if isinstance(v, float):
552        if _math.isnan(v):
553            return {"$num": "NaN"}
554        if _math.isinf(v):
555            return {"$num": "Infinity" if v > 0 else "-Infinity"}
556        if v == 0 and _math.copysign(1, v) < 0:
557            return {"$num": "-0"}
558        return v
559    if isinstance(v, list):
560        return [_enc(x) for x in v]
561    if isinstance(v, tuple):
562        return {"$tuple": [_enc(x) for x in v]}
563    if isinstance(v, (set, frozenset)):
564        return {"$set": sorted((_enc(x) for x in v), key=_json.dumps)}
565    if isinstance(v, (bytes, bytearray)):
566        return {"$bytes": list(v)}
567    if isinstance(v, dict):
568        if all(isinstance(k, str) for k in v):
569            return {k: _enc(x) for k, x in v.items()}
570        return {"$dict": [[_enc(k), _enc(x)] for k, x in v.items()]}
571    return {"$repr": repr(v)}
572
573
574def _dec(v):
575    if isinstance(v, list):
576        return [_dec(x) for x in v]
577    if not isinstance(v, dict):
578        return v
579    if len(v) == 1:
580        (key, inner), = v.items()
581        if key == "$undefined":
582            return None
583        if key == "$num":
584            return {"NaN": _math.nan, "Infinity": _math.inf, "-Infinity": -_math.inf, "-0": -0.0}[inner]
585        if key == "$int":
586            return int(inner)
587        if key == "$tuple":
588            return tuple(_dec(x) for x in inner)
589        if key == "$set":
590            return {_dec(x) for x in inner}
591        if key == "$bytes":
592            return bytes(inner)
593        if key == "$dict":
594            return {_dec(k): _dec(x) for k, x in inner}
595    return {k: _dec(x) for k, x in v.items()}
596
597
598def _encode_args(args, kwargs, positions, names):
599    args = tuple(_json.dumps(_enc(a)) if i in positions else a for i, a in enumerate(args))
600    kwargs = {k: (_json.dumps(_enc(a)) if k in names else a) for k, a in kwargs.items()}
601    return args, kwargs
602
603
604def _wrap(fn, positions, names, json_result):
605    def call(*args, **kwargs):
606        args, kwargs = _encode_args(args, kwargs, positions, names)
607        out = fn(*args, **kwargs)
608        return _dec(_json.loads(out)) if json_result else out
609    call.__name__ = fn.__name__
610    call.__doc__ = fn.__doc__
611    return call
612
613
614def _method(name, positions, names, json_result):
615    def call(self, *args, **kwargs):
616        args, kwargs = _encode_args(args, kwargs, positions, names)
617        out = getattr(self._inner, name)(*args, **kwargs)
618        return _dec(_json.loads(out)) if json_result else out
619    call.__name__ = name
620    return call
621"#;
622
623/// `src/pyconv.rs`: Python objects to `serde_json::Value` and back, in Rust, without JSON text.
624/// Values the JSON model lacks use the same markers as recorded cases: `$tuple`, `$set`,
625/// `$bytes`, `$int` (beyond i64), `$dict` (non-string keys), `$num` (NaN, infinities, -0).
626pub const PYCONV_RS: &str = r#"//! Python objects to `serde_json::Value` and back, in Rust. Generated by rust-anything.
627
628#![forbid(unsafe_code)]
629
630use pyo3::prelude::*;
631use pyo3::types::{PyBool, PyBytes, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PySet, PyString, PyTuple};
632use serde_json::{Map, Value, json};
633
634fn type_error(obj: &Bound<'_, PyAny>) -> String {
635    let name = obj.get_type().name().map(|n| n.to_string()).unwrap_or_default();
636    format!("TypeError: unsupported argument type {name}")
637}
638
639fn float(x: f64) -> Value {
640    if x.is_nan() {
641        json!({"$num": "NaN"})
642    } else if x.is_infinite() {
643        json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
644    } else if x == 0.0 && x.is_sign_negative() {
645        json!({"$num": "-0"})
646    } else {
647        json!(x)
648    }
649}
650
651fn items(obj: &Bound<'_, PyAny>) -> Result<Vec<Value>, String> {
652    let mut out = Vec::new();
653    for item in obj.try_iter().map_err(|e| e.to_string())? {
654        out.push(from_py(&item.map_err(|e| e.to_string())?)?);
655    }
656    Ok(out)
657}
658
659/// A Python object as a JSON value.
660pub fn from_py(obj: &Bound<'_, PyAny>) -> Result<Value, String> {
661    if obj.is_none() {
662        return Ok(Value::Null);
663    }
664    if obj.is_instance_of::<PyBool>() {
665        return Ok(Value::Bool(obj.extract::<bool>().map_err(|e| e.to_string())?));
666    }
667    if obj.is_instance_of::<PyInt>() {
668        return Ok(match obj.extract::<i64>() {
669            Ok(i) => json!(i),
670            Err(_) => json!({"$int": obj.str().map_err(|e| e.to_string())?.to_string()}),
671        });
672    }
673    if obj.is_instance_of::<PyFloat>() {
674        return Ok(float(obj.extract::<f64>().map_err(|e| e.to_string())?));
675    }
676    if obj.is_instance_of::<PyString>() {
677        return Ok(Value::String(obj.extract::<String>().map_err(|e| e.to_string())?));
678    }
679    if obj.is_instance_of::<PyList>() {
680        return Ok(Value::Array(items(obj)?));
681    }
682    if obj.is_instance_of::<PyTuple>() {
683        return Ok(json!({"$tuple": items(obj)?}));
684    }
685    if obj.is_instance_of::<PyDict>() {
686        let dict = obj.cast::<PyDict>().map_err(|e| e.to_string())?;
687        let mut map = Map::new();
688        let mut pairs = Vec::new();
689        let mut string_keys = true;
690        for (k, v) in dict.iter() {
691            let value = from_py(&v)?;
692            if let Ok(key) = k.extract::<String>() {
693                map.insert(key.clone(), value.clone());
694                pairs.push(json!([key, value]));
695            } else {
696                string_keys = false;
697                pairs.push(json!([from_py(&k)?, value]));
698            }
699        }
700        return Ok(if string_keys { Value::Object(map) } else { json!({"$dict": pairs}) });
701    }
702    if obj.is_instance_of::<PySet>() || obj.is_instance_of::<PyFrozenSet>() {
703        return Ok(json!({"$set": items(obj)?}));
704    }
705    if obj.is_instance_of::<PyBytes>() {
706        return Ok(json!({"$bytes": obj.extract::<Vec<u8>>().map_err(|e| e.to_string())?}));
707    }
708    Err(type_error(obj))
709}
710
711/// A structured argument, converted to the port's parameter type.
712pub fn arg<T: serde::de::DeserializeOwned>(obj: &Bound<'_, PyAny>) -> Result<T, String> {
713    serde_json::from_value(from_py(obj)?).map_err(|e| format!("TypeError: {e}"))
714}
715
716/// A Python argument as a Rust value, without going through JSON.
717pub trait FromPy: Sized {
718    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String>;
719}
720
721/// A Rust result as a Python object, without going through JSON.
722pub trait ToPy {
723    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>>;
724}
725
726macro_rules! extract {
727    ($($t:ty),*) => {$(
728        impl FromPy for $t {
729            fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
730                obj.extract::<$t>().map_err(|_| type_error(obj))
731            }
732        }
733        impl ToPy for $t {
734            fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
735                Ok(self.clone().into_pyobject(py)?.to_owned().into_any().unbind())
736            }
737        }
738    )*};
739}
740extract!(i64, bool, String);
741
742impl FromPy for f64 {
743    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
744        if obj.is_instance_of::<PyFloat>() || obj.is_instance_of::<PyInt>() {
745            obj.extract::<f64>().map_err(|_| type_error(obj))
746        } else {
747            Err(type_error(obj))
748        }
749    }
750}
751
752impl ToPy for f64 {
753    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
754        Ok(PyFloat::new(py, *self).into_any().unbind())
755    }
756}
757
758impl FromPy for crate::pynum::Num {
759    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
760        use crate::pynum::Num;
761        if obj.is_instance_of::<PyFloat>() {
762            return obj.extract::<f64>().map(Num::Float).map_err(|_| type_error(obj));
763        }
764        if obj.is_instance_of::<PyInt>() {
765            return obj
766                .extract::<i64>()
767                .map(Num::Int)
768                .map_err(|_| "OverflowError: int too large for the port".to_string());
769        }
770        Err(type_error(obj))
771    }
772}
773
774impl ToPy for crate::pynum::Num {
775    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
776        match *self {
777            crate::pynum::Num::Int(i) => i.to_py(py),
778            crate::pynum::Num::Float(x) => x.to_py(py),
779        }
780    }
781}
782
783impl FromPy for Value {
784    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
785        from_py(obj)
786    }
787}
788
789impl ToPy for Value {
790    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
791        to_py(py, self)
792    }
793}
794
795impl<T: FromPy> FromPy for Option<T> {
796    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
797        if obj.is_none() { Ok(None) } else { T::from_py(obj).map(Some) }
798    }
799}
800
801impl<T: ToPy> ToPy for Option<T> {
802    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
803        match self {
804            Some(v) => v.to_py(py),
805            None => Ok(py.None()),
806        }
807    }
808}
809
810impl<T: FromPy> FromPy for Vec<T> {
811    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
812        if !obj.is_instance_of::<PyList>() && !obj.is_instance_of::<PyTuple>() {
813            return Err(type_error(obj));
814        }
815        let mut out = Vec::new();
816        for item in obj.try_iter().map_err(|e| e.to_string())? {
817            out.push(T::from_py(&item.map_err(|e| e.to_string())?)?);
818        }
819        Ok(out)
820    }
821}
822
823impl<T: ToPy> ToPy for Vec<T> {
824    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
825        let items: PyResult<Vec<Py<PyAny>>> = self.iter().map(|x| x.to_py(py)).collect();
826        Ok(PyList::new(py, items?)?.into_any().unbind())
827    }
828}
829
830impl<T: FromPy> FromPy for std::collections::HashMap<String, T> {
831    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
832        let dict = obj.cast::<PyDict>().map_err(|_| type_error(obj))?;
833        let mut out = Self::new();
834        for (k, v) in dict.iter() {
835            out.insert(k.extract::<String>().map_err(|_| type_error(&k))?, T::from_py(&v)?);
836        }
837        Ok(out)
838    }
839}
840
841impl<T: ToPy> ToPy for std::collections::HashMap<String, T> {
842    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
843        let dict = PyDict::new(py);
844        for (k, v) in self {
845            dict.set_item(k, v.to_py(py)?)?;
846        }
847        Ok(dict.into_any().unbind())
848    }
849}
850
851macro_rules! tuples {
852    ($(($($t:ident $i:tt),+)),*) => {$(
853        impl<$($t: FromPy),+> FromPy for ($($t,)+) {
854            fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
855                let t = obj.cast::<PyTuple>().map_err(|_| type_error(obj))?;
856                Ok(($($t::from_py(&t.get_item($i).map_err(|e| e.to_string())?)?,)+))
857            }
858        }
859        impl<$($t: ToPy),+> ToPy for ($($t,)+) {
860            fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
861                Ok(PyTuple::new(py, [$(self.$i.to_py(py)?),+])?.into_any().unbind())
862            }
863        }
864    )*};
865}
866tuples!((A 0, B 1), (A 0, B 1, C 2), (A 0, B 1, C 2, D 3));
867
868/// A JSON value as a Python object; markers become the Python types they stand for.
869pub fn to_py(py: Python<'_>, v: &Value) -> PyResult<Py<PyAny>> {
870    let list = |items: &[Value]| -> PyResult<Vec<Py<PyAny>>> { items.iter().map(|x| to_py(py, x)).collect() };
871    Ok(match v {
872        Value::Null => py.None(),
873        Value::Bool(b) => PyBool::new(py, *b).to_owned().into_any().unbind(),
874        Value::Number(n) => match n.as_i64() {
875            Some(i) if !n.is_f64() => i.into_pyobject(py)?.into_any().unbind(),
876            _ => match n.as_u64() {
877                Some(u) if !n.is_f64() => u.into_pyobject(py)?.into_any().unbind(),
878                _ => PyFloat::new(py, n.as_f64().unwrap_or(f64::NAN)).into_any().unbind(),
879            },
880        },
881        Value::String(s) => PyString::new(py, s).into_any().unbind(),
882        Value::Array(items) => PyList::new(py, list(items)?)?.into_any().unbind(),
883        Value::Object(o) if o.len() == 1 => {
884            let (key, inner) = o.iter().next().expect("one entry");
885            let items = || inner.as_array().map(Vec::as_slice).unwrap_or_default();
886            match key.as_str() {
887                "$tuple" => PyTuple::new(py, list(items())?)?.into_any().unbind(),
888                "$set" => PySet::new(py, list(items())?)?.into_any().unbind(),
889                "$bytes" => {
890                    let bytes: Vec<u8> = items().iter().filter_map(|b| b.as_u64()).map(|b| b as u8).collect();
891                    PyBytes::new(py, &bytes).into_any().unbind()
892                }
893                "$int" => py
894                    .import("builtins")?
895                    .getattr("int")?
896                    .call1((inner.as_str().unwrap_or("0"),))?
897                    .unbind(),
898                "$float" => PyFloat::new(py, inner.as_str().and_then(|s| s.parse().ok()).unwrap_or(f64::NAN)).into_any().unbind(),
899                "$num" => PyFloat::new(
900                    py,
901                    match inner.as_str() {
902                        Some("Infinity") => f64::INFINITY,
903                        Some("-Infinity") => f64::NEG_INFINITY,
904                        Some("-0") => -0.0,
905                        _ => f64::NAN,
906                    },
907                )
908                .into_any()
909                .unbind(),
910                "$dict" => {
911                    let dict = PyDict::new(py);
912                    for pair in items() {
913                        if let Some([k, v]) = pair.as_array().map(Vec::as_slice) {
914                            dict.set_item(to_py(py, k)?, to_py(py, v)?)?;
915                        }
916                    }
917                    dict.into_any().unbind()
918                }
919                _ => {
920                    let dict = PyDict::new(py);
921                    dict.set_item(key, to_py(py, inner)?)?;
922                    dict.into_any().unbind()
923                }
924            }
925        }
926        Value::Object(o) => {
927            let dict = PyDict::new(py);
928            for (k, x) in o {
929                dict.set_item(k, to_py(py, x)?)?;
930            }
931            dict.into_any().unbind()
932        }
933    })
934}
935"#;
936
937/// `src/pynum.rs`: Python's int-or-float, for ports of code that takes either.
938pub const PYNUM_RS: &str = r#"//! Python numbers: an int stays an int through `+`, `-`, `*`, `//` and `%`; `/` gives a float.
939//! Generated by rust-anything. Ints beyond i64 become floats (Python would keep a big int).
940
941#![forbid(unsafe_code)]
942
943use std::cmp::Ordering;
944use std::ops::{Add, Mul, Neg, Sub};
945
946#[derive(Clone, Copy, Debug)]
947pub enum Num {
948    Int(i64),
949    Float(f64),
950}
951
952impl Num {
953    pub fn f(self) -> f64 {
954        match self {
955            Self::Int(i) => i as f64,
956            Self::Float(x) => x,
957        }
958    }
959
960    fn op(self, o: Self, int: fn(i64, i64) -> Option<i64>, float: fn(f64, f64) -> f64) -> Self {
961        match (self, o) {
962            (Self::Int(a), Self::Int(b)) => int(a, b).map_or_else(|| Self::Float(float(a as f64, b as f64)), Self::Int),
963            (a, b) => Self::Float(float(a.f(), b.f())),
964        }
965    }
966
967    /// `/`: always a float; `ZeroDivisionError` for zero.
968    pub fn true_div(self, o: Self) -> Result<Self, String> {
969        match (self, o) {
970            (_, o) if o.f() == 0.0 => Err(match (self, o) {
971                (Self::Int(_), Self::Int(_)) => "ZeroDivisionError: division by zero".into(),
972                _ => "ZeroDivisionError: float division by zero".into(),
973            }),
974            (a, b) => Ok(Self::Float(a.f() / b.f())),
975        }
976    }
977
978    /// `%`: the result takes the divisor's sign.
979    pub fn modulo(self, o: Self) -> Result<Self, String> {
980        match (self, o) {
981            (Self::Int(_), Self::Int(0)) => Err("ZeroDivisionError: integer modulo by zero".into()),
982            (Self::Int(a), Self::Int(b)) => {
983                let r = a.wrapping_rem(b);
984                Ok(Self::Int(if r != 0 && (r < 0) != (b < 0) { r + b } else { r }))
985            }
986            (a, b) => {
987                let (x, y) = (a.f(), b.f());
988                if y == 0.0 {
989                    return Err("ZeroDivisionError: float modulo".into());
990                }
991                let m = x % y;
992                Ok(Self::Float(if m != 0.0 {
993                    if (y < 0.0) != (m < 0.0) { m + y } else { m }
994                } else {
995                    0.0_f64.copysign(y)
996                }))
997            }
998        }
999    }
1000
1001    /// Python's `max(a, b, ...)`: the first value no later value is greater than.
1002    pub fn max(values: &[Self]) -> Self {
1003        values[1..].iter().fold(values[0], |m, &x| if x > m { x } else { m })
1004    }
1005
1006    /// Python's `min(a, b, ...)`.
1007    pub fn min(values: &[Self]) -> Self {
1008        values[1..].iter().fold(values[0], |m, &x| if x < m { x } else { m })
1009    }
1010}
1011
1012impl From<f64> for Num {
1013    fn from(x: f64) -> Self {
1014        Self::Float(x)
1015    }
1016}
1017
1018impl From<i64> for Num {
1019    fn from(i: i64) -> Self {
1020        Self::Int(i)
1021    }
1022}
1023
1024impl Add for Num {
1025    type Output = Self;
1026    fn add(self, o: Self) -> Self {
1027        self.op(o, i64::checked_add, |a, b| a + b)
1028    }
1029}
1030
1031impl Sub for Num {
1032    type Output = Self;
1033    fn sub(self, o: Self) -> Self {
1034        self.op(o, i64::checked_sub, |a, b| a - b)
1035    }
1036}
1037
1038impl Mul for Num {
1039    type Output = Self;
1040    fn mul(self, o: Self) -> Self {
1041        self.op(o, i64::checked_mul, |a, b| a * b)
1042    }
1043}
1044
1045impl Neg for Num {
1046    type Output = Self;
1047    fn neg(self) -> Self {
1048        match self {
1049            Self::Int(i) => i.checked_neg().map_or(Self::Float(-(i as f64)), Self::Int),
1050            Self::Float(x) => Self::Float(-x),
1051        }
1052    }
1053}
1054
1055impl PartialEq for Num {
1056    fn eq(&self, o: &Self) -> bool {
1057        match (*self, *o) {
1058            (Self::Int(a), Self::Int(b)) => a == b,
1059            (a, b) => a.f() == b.f(),
1060        }
1061    }
1062}
1063
1064impl PartialOrd for Num {
1065    fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
1066        match (*self, *o) {
1067            (Self::Int(a), Self::Int(b)) => a.partial_cmp(&b),
1068            (a, b) => a.f().partial_cmp(&b.f()),
1069        }
1070    }
1071}
1072"#;
1073
1074#[cfg(test)]
1075mod tests {
1076    use super::*;
1077    use crate::bridge::{Kind, Manifest};
1078    use crate::codegen::{Modules, PortApi, PortFn};
1079    use crate::lang::Lang;
1080    use crate::ts::exports::{ExportedFn, Param};
1081
1082    #[test]
1083    fn converts_python_literals() {
1084        assert_eq!(rust_literal("'-'").as_deref(), Some("String::from(\"-\")"));
1085        assert_eq!(rust_literal("8").as_deref(), Some("8"));
1086        assert_eq!(rust_literal("1_000").as_deref(), Some("1000"));
1087        assert_eq!(rust_literal("0.5").as_deref(), Some("0.5"));
1088        assert_eq!(rust_literal("True").as_deref(), Some("true"));
1089        assert_eq!(rust_literal("None"), None);
1090        assert_eq!(rust_literal("[]"), None);
1091        assert_eq!(rust_literal("'a\\nb'"), None);
1092    }
1093
1094    #[test]
1095    fn optional_object_params_bind_as_option_bound() {
1096        // `thresholds=None` must bind as `Option<Bound>` so PyO3 accepts `None`;
1097        // required structured parameters stay a plain `Bound`, native options are untouched.
1098        assert_eq!(
1099            binding_type("Option<serde_json::Value>").as_str(),
1100            "Option<Bound<'_, PyAny>>"
1101        );
1102        assert_eq!(
1103            binding_type("serde_json::Value").as_str(),
1104            "Bound<'_, PyAny>"
1105        );
1106        assert_eq!(binding_type("Option<i64>").as_str(), "Option<i64>");
1107        assert_eq!(binding_type("String").as_str(), "String");
1108    }
1109
1110    fn verdict_port() -> PortFn {
1111        PortFn {
1112            js_name: "verdict".into(),
1113            rust_name: "verdict".into(),
1114            params: vec![
1115                ("readings".into(), "serde_json::Value".into()),
1116                ("thresholds".into(), "Option<serde_json::Value>".into()),
1117            ],
1118            ret: "serde_json::Value".into(),
1119            fallible: true,
1120            is_async: false,
1121        }
1122    }
1123
1124    fn verdict_manifest() -> Manifest {
1125        let param = |name: &str, ts_type: &str, optional: bool, default: Option<&str>| Param {
1126            name: name.into(),
1127            ts_type: ts_type.into(),
1128            optional,
1129            default: default.map(str::to_string),
1130            ..Default::default()
1131        };
1132        Manifest {
1133            schema: "1".into(),
1134            root: std::path::PathBuf::from("/tmp"),
1135            root_written: None,
1136            unit: "hpdet/".into(),
1137            language: Lang::Python,
1138            kind: Kind::Pyo3,
1139            crate_name: "hpdet-rs".into(),
1140            exports: vec![ExportedFn {
1141                name: "verdict".into(),
1142                file: "hpdet/verdict.py".into(),
1143                line: 1,
1144                params: vec![
1145                    param("readings", "Record<string, number>", false, None),
1146                    param("thresholds", "Thresholds | undefined", true, Some("None")),
1147                ],
1148                returns: "Record<string, number>".into(),
1149                ..Default::default()
1150            }],
1151            classes: Vec::new(),
1152            js_only: Vec::new(),
1153            batches: Vec::new(),
1154            float_tolerance: None,
1155        }
1156    }
1157
1158    #[test]
1159    fn optional_object_wrapper_accepts_none() {
1160        let api = PortApi {
1161            functions: vec![verdict_port()],
1162            ..Default::default()
1163        };
1164        let modules = Modules {
1165            utf16: false,
1166            js: false,
1167        };
1168        let lib = lib_rs(&verdict_manifest(), &api, &modules);
1169        // The signature still defaults to `None`, and the Rust parameter takes `Option`.
1170        assert!(
1171            lib.contains("#[pyo3(name = \"verdict\", signature = (readings, thresholds=None))]"),
1172            "{lib}"
1173        );
1174        assert!(
1175            lib.contains(
1176                "fn verdict_inner(readings: Bound<'_, PyAny>, \
1177                 thresholds: Option<Bound<'_, PyAny>>)"
1178            ),
1179            "{lib}"
1180        );
1181        // `None` converts to `None`; a value converts through the port's type.
1182        assert!(lib.contains("match &thresholds"), "{lib}");
1183        assert!(lib.contains("None => None,"), "{lib}");
1184    }
1185}