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