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