Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

93.5 KB
Raw Blame
//! PyO3 bindings and the Python wrapper package for a bridge crate.
//!
//! Like the JS side, the binding layer follows `port.rs`: strings, ints, floats, bools and
//! lists or options of those cross natively; anything structured crosses as JSON text, which
//! the wrapper package (`python/<lib>/__init__.py`) encodes and decodes with Python markers.

use std::fmt::Write as _;

use crate::bridge::Manifest;
use crate::codegen::{Modules, PortApi, PortFn, Wire, wire};
use crate::ts::exports::Param;

/// A Python signature for `#[pyo3(signature = ...)]`: optional parameters default to `None`,
/// keyword-only ones follow `*`, the rest parameter is `*name`.
fn signature(f: &PortFn, source: &[Param]) -> String {
    let mut parts = Vec::new();
    let mut keyword_only = false;
    for (name, ty) in &f.params {
        let param = source
            .iter()
            .find(|p| crate::bridge::snake_case(&p.name) == *name);
        if param.is_some_and(|p| p.keyword_only) && !keyword_only {
            keyword_only = true;
            parts.push("*".to_string());
        }
        // A raw identifier (`r#type`) stays raw: the signature is Rust, and PyO3 shows the
        // parameter to Python without the `r#`.
        let py_name = name.as_str();
        match param {
            Some(p) if p.optional => match p.default.as_deref().and_then(rust_literal) {
                Some(literal) => {
                    let literal = if ty == "f64"
                        && let Ok(integer) = literal.parse::<i64>()
                    {
                        format!("{integer}_f64")
                    } else {
                        literal
                    };
                    parts.push(format!("{py_name}={literal}"));
                }
                None => parts.push(format!("{py_name}=None")),
            },
            _ => parts.push(py_name.to_string()),
        }
    }
    parts.join(", ")
}

/// A Python literal default as a Rust expression, for `#[pyo3(signature = ...)]`: strings,
/// numbers and booleans. `None` and other expressions return `None` (the parameter is an
/// `Option`, and `None` stands for the default).
pub fn rust_literal(default: &str) -> Option<String> {
    let d = default.trim();
    match d {
        // Python's `True`; Ruby's and Java's `true`.
        "True" | "true" => return Some("true".into()),
        "False" | "false" => return Some("false".into()),
        "None" => return None,
        _ => {}
    }
    let digits = d.replace('_', "");
    if digits.parse::<i64>().is_ok() {
        return Some(digits);
    }
    if (digits.contains('.') || digits.contains('e')) && digits.parse::<f64>().is_ok() {
        return Some(if digits.contains('.') {
            digits
        } else {
            format!("{digits}_f64")
        });
    }
    let quote = d.chars().next().filter(|c| *c == '"' || *c == '\'')?;
    let inner = d.strip_prefix(quote)?.strip_suffix(quote)?;
    // Plain literals only: escapes and quotes inside would need Python's own parser.
    if inner.contains('\\') || inner.contains('"') || inner.contains('\'') {
        return None;
    }
    Some(format!("String::from(\"{inner}\")"))
}

/// Whether a parameter keeps Python's literal default (and is a plain, non-`Option` type).
pub fn has_literal_default(p: &Param) -> bool {
    p.optional && p.default.as_deref().and_then(rust_literal).is_some()
}

fn params_of<'m>(m: &'m Manifest, f: &PortFn, class: Option<&str>) -> &'m [Param] {
    match class {
        Some(c) => m
            .classes
            .iter()
            .find(|k| k.name == c)
            .map(|k| {
                if f.rust_name == "new" {
                    k.constructor.as_slice()
                } else {
                    k.methods
                        .iter()
                        .find(|x| x.name == f.js_name)
                        .map_or(&[][..], |x| x.params.as_slice())
                }
            })
            .unwrap_or(&[]),
        None => m
            .exports
            .iter()
            .find(|e| e.name == f.js_name)
            .map_or(&[][..], |e| e.params.as_slice()),
    }
}

/// The inner type of `Option<...>`, if that is what the port declares.
fn option_inner(ty: &str) -> Option<&str> {
    ty.strip_prefix("Option<").and_then(|t| t.strip_suffix('>'))
}

/// Whether the binding for a port parameter is `Option<Bound>`: an optional parameter whose
/// default is `None` and whose value crosses as a Python object. PyO3 needs `Option<...>` to
/// accept `None`; a plain `Bound` rejects it and the generated crate does not compile
/// (`E0308: expected Bound<'_, PyAny>, found Option<_>`). What decides is how the whole
/// `Option<...>` crosses: `Vec<String>` is native on its own, `Option<Vec<String>>` is not.
fn is_option_bound(ty: &str) -> bool {
    option_inner(ty).is_some() && wire(ty) == Wire::Json
}

fn binding_type(ty: &str) -> String {
    if is_option_bound(ty) {
        return "Option<Bound<'_, PyAny>>".to_string();
    }
    match wire(ty) {
        // Structured values arrive as Python objects and are converted in Rust: no JSON text.
        Wire::Json => "Bound<'_, PyAny>".to_string(),
        _ => ty.to_string(),
    }
}

/// The `#[pyfunction]` parameters. An `Option<Bound>` one whose Python default is not `None`
/// (`lat=LAT`) is read with `pyconv::given`: an explicit `None` reaches the port as a value
/// (`Some(Value::Null)`), and only an argument left out is `None` (issue #1157).
fn py_params(m: &Manifest, f: &PortFn, source: &[Param]) -> Vec<String> {
    f.params
        .iter()
        .map(|(n, t)| {
            let explicit_none = m.language == crate::lang::Lang::Python
                && is_option_bound(t)
                && source.iter().any(|p| {
                    crate::bridge::snake_case(&p.name) == *n
                        && p.optional
                        && p.default.as_deref().is_some_and(|d| d.trim() != "None")
                });
            let from = if explicit_none {
                "#[pyo3(from_py_with = crate::pyconv::given)] ".to_string()
            } else if let Some(reader) = str_reader(t) {
                format!(
                    "#[pyo3(from_py_with = crate::py_str::{reader}_{})] ",
                    n.trim_start_matches("r#")
                )
            } else {
                String::new()
            };
            format!("{from}{n}: {}", binding_type(t))
        })
        .collect()
}

/// The `py_str` reader for a parameter that crosses as a native Rust `String` (alone, optional or
/// in a list), so a lone surrogate is refused by the parameter's name (issue #1074).
fn str_reader(ty: &str) -> Option<&'static str> {
    let compact: String = ty.chars().filter(|c| !c.is_whitespace()).collect();
    match compact.as_str() {
        "String" => Some("one"),
        "Option<String>" => Some("optional"),
        "Vec<String>" => Some("list"),
        _ => None,
    }
}

/// `py_str`, in `lib.rs` when a parameter crosses as a native `String`: PyO3's own extraction
/// fails on a lone surrogate (from `errors="surrogateescape"`) with a bare `UnicodeEncodeError`.
/// These raise a `TypeError` naming the parameter instead, the same message `pyconv` gives for a
/// string inside a structured value. PyO3 hands a reader only the object, so each parameter gets
/// its own (`one_<name>`, `optional_<name>`, `list_<name>`).
const PY_STR: &str = r#"
mod py_str {
    use pyo3::prelude::*;
    use pyo3::types::PyString;

    fn lone(obj: &Bound<'_, PyAny>) -> bool {
        obj.is_instance_of::<PyString>() && obj.extract::<String>().is_err()
    }

    fn refused(name: &str) -> PyErr {
        pyo3::exceptions::PyTypeError::new_err(format!(
            "argument '{name}': str holds a lone surrogate, which a Rust String cannot hold"
        ))
    }

    #[allow(dead_code)]
    fn one(obj: &Bound<'_, PyAny>, name: &str) -> PyResult<String> {
        obj.extract::<String>()
            .map_err(|e| if lone(obj) { refused(name) } else { e })
    }

    #[allow(dead_code)]
    fn optional(obj: &Bound<'_, PyAny>, name: &str) -> PyResult<Option<String>> {
        if obj.is_none() { Ok(None) } else { one(obj, name).map(Some) }
    }

    #[allow(dead_code)]
    fn list(obj: &Bound<'_, PyAny>, name: &str) -> PyResult<Vec<String>> {
        obj.extract::<Vec<String>>().map_err(|e| {
            let holds_lone = !obj.is_instance_of::<PyString>()
                && obj.try_iter().is_ok_and(|items| items.flatten().any(|x| lone(&x)));
            if holds_lone { refused(name) } else { e }
        })
    }
"#;

/// The `py_str` module: the shared readers, then one per `(reader, parameter)` the bindings use.
fn py_str_module(api: &PortApi) -> Option<String> {
    let readers: std::collections::BTreeSet<(&str, &str)> = api
        .all()
        .flat_map(|f| f.visible())
        .filter_map(|(n, t, _)| Some((str_reader(t)?, n.trim_start_matches("r#"))))
        .collect();
    if readers.is_empty() {
        return None;
    }
    let mut out = PY_STR.to_string();
    for (reader, name) in readers {
        let ty = match reader {
            "one" => "String",
            "optional" => "Option<String>",
            _ => "Vec<String>",
        };
        let _ = write!(
            out,
            "\n    pub fn {reader}_{name}(obj: &Bound<'_, PyAny>) -> PyResult<{ty}> {{\n        {reader}(obj, {name:?})\n    }}\n"
        );
    }
    out.push_str("}\n");
    Some(out)
}

/// Whether `FromPy`/`ToPy` in `pyconv.rs` cover a type: then it converts directly, without
/// building a `serde_json::Value` first.
fn direct(ty: &str) -> bool {
    const KNOWN: &[&str] = &[
        "Vec",
        "Option",
        "HashMap",
        "std",
        "collections",
        "String",
        "f64",
        "i64",
        "bool",
        "serde_json",
        "Value",
        "Num",
        "crate",
        "pynum",
        "path",
        "PathBuf",
    ];
    let compact: String = ty.chars().filter(|c| !c.is_whitespace()).collect();
    let normalized = compact.replace("Vec<u8>", "String");
    normalized
        .split(|c: char| !(c.is_alphanumeric() || c == '_'))
        .filter(|w| !w.is_empty())
        .all(|w| KNOWN.contains(&w))
}

fn body(f: &PortFn, target: &str, constructor: bool) -> String {
    let mut body = String::new();
    for (n, t) in &f.params {
        body.push_str(&convert(n, t, false));
    }
    let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
    let call = format!(
        "{target}({}){}",
        args.join(", "),
        if f.fallible { "?" } else { "" }
    );
    if !constructor && f.ret.trim() == "()" {
        let _ = writeln!(body, "    {call};\n    Ok(())");
        return body;
    }
    let _ = writeln!(body, "    let out = {call};");
    let _ = writeln!(
        body,
        "    {}",
        if !constructor && wire(&f.ret) == Wire::Json && !direct(&f.ret) {
            "serde_json::to_value(&out).map_err(|e| e.to_string())"
        } else {
            "Ok(out)"
        }
    );
    body
}

/// The `_inner` function's success type: structured results as a `serde_json::Value`.
fn ret(f: &PortFn) -> String {
    match wire(&f.ret) {
        Wire::Json if direct(&f.ret) => f.ret.clone(),
        Wire::Json => "serde_json::Value".into(),
        _ => f.ret.clone(),
    }
}

/// The `#[pyfunction]`'s success type: structured results as a Python object.
fn py_ret(f: &PortFn) -> String {
    match wire(&f.ret) {
        Wire::Json => "Py<PyAny>".into(),
        _ => f.ret.clone(),
    }
}

/// How the `#[pyfunction]` hands back the `_inner` result.
fn py_out(f: &PortFn) -> &'static str {
    match wire(&f.ret) {
        Wire::Json => ".map_err(error).and_then(|v| crate::pyconv::ToPy::into_py(v, py))",
        _ => ".map_err(error)",
    }
}

/// A port's `Err("KeyError: missing")` raises that built-in exception type with the message, and
/// so does any other built-in exception's name (`Err("FileNotFoundError: x")`). The original's own
/// classes go by their dotted path, `Err("sqlparse.exceptions.SQLParseError: x")`: the module is
/// imported and the class raised, so the caller (and `diff`) sees the class the original raises,
/// also when its constructor takes other arguments than the message (`ParseError(position, token)`).
/// Anything else, or a name that is not an `Exception` subclass, is a `ValueError` with the whole
/// message. Panics become `PanicException`.
const PY_ERROR: &str = r#"
fn error(message: String) -> PyErr {
    use pyo3::exceptions as e;
    const ORIGINAL_PACKAGES: &[&str] = &ORIGINAL_PACKAGES_LIST;
    /// The subclass that prints the message, made once per original class and kept, so every raise
    /// of the class gives the same type. It pickles through `_unpickled_error`, since pickle looks the
    /// name up and finds the original.
    fn printing<'py>(
        py: Python<'py>,
        class: &Bound<'py, pyo3::types::PyType>,
        base_str: &Bound<'py, PyAny>,
    ) -> Option<Bound<'py, pyo3::types::PyType>> {
        static MADE: pyo3::sync::PyOnceLock<Py<pyo3::types::PyDict>> = pyo3::sync::PyOnceLock::new();
        let made = MADE.get_or_init(py, || pyo3::types::PyDict::new(py).unbind()).bind(py);
        if let Ok(Some(found)) = made.get_item(class) {
            return found.cast_into().ok();
        }
        let attrs = pyo3::types::PyDict::new(py);
        attrs.set_item("__str__", base_str).ok()?;
        for key in ["__module__", "__qualname__", "__doc__"] {
            attrs.set_item(key, class.getattr(key).ok()?).ok()?;
        }
        static REDUCE: pyo3::sync::PyOnceLock<Option<Py<PyAny>>> = pyo3::sync::PyOnceLock::new();
        let reduce = REDUCE.get_or_init(py, || {
            let rebuild = NATIVE.get(py)?.bind(py).getattr("_unpickled_error").ok()?;
            let globals = pyo3::types::PyDict::new(py);
            py.run(
                cr"
def make(rebuild):
    def __reduce__(self):
        kind = f'{type(self).__module__}.{type(self).__name__}'
        state = getattr(self, '__dict__', None)
        return (rebuild, (kind, str(self)), state) if state else (rebuild, (kind, str(self)))
    return __reduce__
",
                Some(&globals),
                None,
            )
            .ok()?;
            Some(globals.get_item("make").ok()??.call1((rebuild,)).ok()?.unbind())
        });
        if let Some(reduce) = reduce {
            attrs.set_item("__reduce__", reduce.bind(py)).ok()?;
        }
        let built = py
            .import("builtins")
            .ok()?
            .getattr("type")
            .ok()?
            .call1((class.name().ok()?, (class,), attrs))
            .ok()?;
        let kept = made.call_method1("setdefault", (class, &built)).unwrap_or(built);
        kept.cast_into().ok()
    }
    /// The class made without running its `__init__`, for a constructor that takes other arguments
    /// than the message (or none): `__new__` keeps the message as the exception's `args`. A class
    /// whose own `__str__` reads what its `__init__` would have set is raised through a subclass of
    /// the same name and module that prints the message, so `except` on the class still catches it.
    fn without_init<'py>(
        py: Python<'py>,
        class: &Bound<'py, pyo3::types::PyType>,
        text: &str,
    ) -> Option<Bound<'py, PyAny>> {
        let builtins = py.import("builtins").ok()?;
        let base_str = builtins.getattr("BaseException").ok()?.getattr("__str__").ok()?;
        let target = if class.getattr("__str__").ok()?.is(&base_str) {
            class.clone()
        } else {
            printing(py, class, &base_str)?
        };
        let value = target.call_method1("__new__", (&target, text)).ok()?;
        // A `__new__` of the class's own may hand back another object: leave that one alone.
        if !value.is_instance(class).ok()? {
            return None;
        }
        // It may also drop its arguments: the message goes in `args` either way, through
        // `BaseException.args` itself, since the class may override `__setattr__`.
        builtins
            .getattr("BaseException")
            .ok()?
            .getattr("args")
            .ok()?
            .call_method1("__set__", (&value, (text,)))
            .ok()?;
        Some(value)
    }
    /// `Err("Kind: text")` for a `Kind` the match below does not know: a built-in exception's name or
    /// `package.module.Class`, called with the text, or made without its `__init__` when that takes
    /// other arguments. None when it names no `Exception` subclass or no instance can be made.
    fn named_error(kind: &str, text: &str) -> Option<PyErr> {
        Python::attach(|py| {
            // Each dotted part must be a Python identifier, by Python's own rules (`str.isidentifier`).
            let identifier = |part: &str| {
                pyo3::types::PyString::new(py, part)
                    .call_method0("isidentifier")
                    .and_then(|ok| ok.extract::<bool>())
                    .unwrap_or(false)
            };
            if !kind.split('.').all(identifier) {
                return None;
            }
            let (module, name) = kind.rsplit_once('.').unwrap_or(("builtins", kind));
            let target_mod = if module == "builtins" {
                py.import("builtins").ok()?.into_any()
            } else {
                let sys_modules = py.import("sys").ok()?.getattr("modules").ok()?;
                let top = module.split('.').next().unwrap_or(module);
                match sys_modules.get_item(module) {
                    Ok(loaded) => loaded,
                    Err(_) if ORIGINAL_PACKAGES.contains(&top) => py.import(module).ok()?.into_any(),
                    Err(_) => return None,
                }
            };
            let class = target_mod.getattr(name).ok()?;
            let class = class.cast_into::<pyo3::types::PyType>().ok()?;
            if !class.is_subclass_of::<pyo3::exceptions::PyException>().ok()? {
                return None;
            }
            let value = match class.call1((text,)) {
                Ok(value) if value.is_instance(&class).ok()? => value,
                _ => without_init(py, &class, text)?,
            };
            Some(PyErr::from_value(value))
        })
    }
    let (kind, text) = message.split_once(": ").unwrap_or(("", message.as_str()));
    let text = text.to_string();
    match kind {
        "TypeError" => e::PyTypeError::new_err(text),
        "KeyError" => e::PyKeyError::new_err(text),
        "IndexError" => e::PyIndexError::new_err(text),
        "OverflowError" => e::PyOverflowError::new_err(text),
        "ZeroDivisionError" => e::PyZeroDivisionError::new_err(text),
        "AttributeError" => e::PyAttributeError::new_err(text),
        "RuntimeError" => e::PyRuntimeError::new_err(text),
        "NotImplementedError" => e::PyNotImplementedError::new_err(text),
        "LookupError" => e::PyLookupError::new_err(text),
        "ArithmeticError" => e::PyArithmeticError::new_err(text),
        "UnicodeError" => e::PyUnicodeError::new_err(text),
        "ValueError" => e::PyValueError::new_err(text),
        _ => named_error(kind, &text).unwrap_or_else(|| e::PyValueError::new_err(message)),
    }
}

/// The native module, kept so `error()` can name `_unpickled_error` for pickle.
static NATIVE: pyo3::sync::PyOnceLock<Py<PyModule>> = pyo3::sync::PyOnceLock::new();

/// What unpickling (or copying) an error of an original class calls: the error `error()` raises
/// for `kind: text`.
#[pyfunction]
#[pyo3(name = "_unpickled_error")]
fn unpickled_error(py: Python<'_>, kind: &str, text: &str) -> Py<PyAny> {
    error(format!("{kind}: {text}")).value(py).clone().into_any().unbind()
}
"#;

/// A Rust value as a Python object, for the result and the arguments handed back: directly when
/// `pyconv` covers the type, else through a `serde_json::Value`.
fn to_py_expr(ty: &str, x: &str) -> String {
    if ty.trim() == "()" {
        return "Ok(py.None())".into();
    }
    if wire(ty) != Wire::Json || direct(ty) {
        format!("crate::pyconv::ToPy::into_py({x}, py).map_err(|e| e.to_string())")
    } else {
        format!(
            "serde_json::to_value(&{x}).map_err(|e| e.to_string()).and_then(|v| crate::pyconv::into_py(py, v).map_err(|e| e.to_string()))"
        )
    }
}

/// The binding of a function whose port changes arguments in place or prints. It answers with a
/// tuple `(result, [each changed argument after the call], printed text, exception or None)`:
/// the package's `_effects` wrapper writes the arguments back into the caller's objects, prints,
/// then returns the result or raises the exception (built here, by the same rules as any other
/// error).
fn effects_binding(m: &Manifest, f: &PortFn) -> String {
    let visible = f.visible();
    let view = PortFn {
        params: visible
            .iter()
            .map(|(n, t, _)| ((*n).to_string(), (*t).to_string()))
            .collect(),
        ..f.clone()
    };
    let params: Vec<String> = view
        .params
        .iter()
        .map(|(n, t)| format!("{n}: {}", binding_type(t)))
        .collect();
    let inner = format!("{}_inner", f.rust_name.trim_start_matches("r#"));
    let mut body = String::new();
    for (n, t, mutable) in &visible {
        body.push_str(&convert(n, t, *mutable));
    }
    if f.prints() {
        body.push_str("    let mut stdout = String::new();\n");
    }
    let args: Vec<String> = f
        .params
        .iter()
        .map(|(n, t)| {
            if t.trim_start().starts_with("&mut ") {
                format!("&mut {n}")
            } else {
                n.clone()
            }
        })
        .collect();
    let call = format!("port::{}({})", f.rust_name, args.join(", "));
    let call = if f.fallible {
        call
    } else {
        format!("Ok::<_, String>({call})")
    };
    let ret = f.ret.trim();
    let _ = writeln!(
        body,
        "    let (ret, failure): (Py<PyAny>, Option<String>) = match {call} {{\n        Ok({}) => ({}, None),\n        Err(e) => (py.None(), Some(e)),\n    }};",
        if ret == "()" { "_" } else { "out" },
        if ret == "()" {
            "py.None()".to_string()
        } else {
            format!("{}?", to_py_expr(ret, "out"))
        }
    );
    let after: Vec<String> = visible
        .iter()
        .filter(|(_, _, mutable)| *mutable)
        .map(|(n, t, _)| format!("{}?", to_py_expr(t, n)))
        .collect();
    let _ = writeln!(
        body,
        "    let after: Vec<Py<PyAny>> = vec![{}];",
        after.join(", ")
    );
    let printed = if f.prints() { "&stdout" } else { "\"\"" };
    body.push_str(&format!(
        "    let exception: Py<PyAny> = match failure {{\n        Some(e) => error(e).into_value(py).into_any(),\n        None => py.None(),\n    }};\n    \
         let items = [\n        ret,\n        pyo3::types::PyList::new(py, after).map_err(|e| e.to_string())?.into_any().unbind(),\n        \
         pyo3::types::PyString::new(py, {printed}).into_any().unbind(),\n        exception,\n    ];\n    \
         pyo3::types::PyTuple::new(py, items).map(|t| t.into_any().unbind()).map_err(|e| e.to_string())\n"
    ));
    let names: Vec<&str> = view.params.iter().map(|(n, _)| n.as_str()).collect();
    format!(
        "\nfn {inner}(py: Python<'_>, {}) -> Result<Py<PyAny>, String> {{\n{body}}}\n\n\
         /// `{js}`.\n#[pyfunction]\n#[pyo3(name = \"{js}\", signature = ({sig}))]\n\
         fn {name}_py(py: Python<'_>, {}) -> PyResult<Py<PyAny>> {{\n    {inner}(py, {}).map_err(error)\n}}\n",
        params.join(", "),
        py_params(m, &view, params_of(m, &view, None)).join(", "),
        names.join(", "),
        js = f.js_name,
        sig = signature(&view, params_of(m, &view, None)),
        name = f.rust_name.trim_start_matches("r#"),
    )
}

/// The conversion of one argument to the port's type: structured ones from the Python object,
/// native ones as they came; `mutable` for an argument the port changes.
fn convert(n: &str, t: &str, mutable: bool) -> String {
    let keyword = if mutable { "mut " } else { "" };
    if wire(t) != Wire::Json {
        return if mutable {
            format!("    let mut {n} = {n};\n")
        } else {
            String::new()
        };
    }
    let named = if direct(t) && !t.contains("String") {
        String::new()
    } else {
        format!(
            ".map_err(|e| crate::pyconv::argument({:?}, e))",
            n.trim_start_matches("r#")
        )
    };
    if is_option_bound(t) {
        if direct(t) {
            format!(
                "    let {keyword}{n}: {t} = match &{n} {{\n        None => None,\n        Some(v) => Some(crate::pyconv::FromPy::from_py(v){named}?),\n    }};\n"
            )
        } else {
            format!(
                "    let {keyword}{n} = match &{n} {{\n        None => None,\n        Some(v) => Some(crate::pyconv::arg(v){named}?),\n    }};\n"
            )
        }
    } else if direct(t) {
        format!("    let {keyword}{n}: {t} = crate::pyconv::FromPy::from_py(&{n}){named}?;\n")
    } else {
        format!("    let {keyword}{n} = crate::pyconv::arg(&{n}){named}?;\n")
    }
}

fn original_packages(m: &Manifest) -> Vec<String> {
    let files = m
        .exports
        .iter()
        .map(|f| f.file.as_str())
        .chain(m.classes.iter().map(|c| c.file.as_str()));
    let mut packages = std::collections::BTreeSet::new();
    for file in files {
        let path = m.root.join(file);
        let mut top = path.file_stem().map(|s| s.to_string_lossy().into_owned());
        let mut dir = path.parent();
        while let Some(d) = dir.filter(|d| d.join("__init__.py").is_file()) {
            top = d.file_name().map(|s| s.to_string_lossy().into_owned());
            dir = d.parent();
        }
        packages.extend(top.filter(|t| t != "__init__"));
    }
    packages.into_iter().collect()
}

pub fn lib_rs(m: &Manifest, api: &PortApi, modules: &Modules) -> String {
    let mut out = format!(
        "//! Python bindings for `{}`: generated from the signatures in `port.rs` by rust-anything.\n\
         //! Regenerate with `rust-anything refresh` after changing them.\n\n\
         #![allow(clippy::too_many_arguments)]\n\
         // Without the module (a front door links the crate as a plain library) nothing calls these.\n\
         #![cfg_attr(not(feature = \"python-module\"), allow(dead_code, unused_imports))]\n\n\
         use pyo3::prelude::*;\n\n",
        m.unit
    );
    if modules.js {
        out.push_str("pub mod js;\n");
    }
    out.push_str("pub mod port;\n");
    if api.needs_json() {
        out.push_str(
            "pub mod pyconv;\npub mod pynum;\n\n#[allow(unused_imports)]\nuse pynum::Num;\n",
        );
    }
    if modules.utf16 {
        out.push_str("pub mod utf16;\n");
    }
    out.push_str(&PY_ERROR.replace(
        "ORIGINAL_PACKAGES_LIST",
        &format!("{:?}", original_packages(m)),
    ));
    if let Some(module) = py_str_module(api) {
        out.push_str(&module);
    }
    let mut registrations = vec![
        "    let _ = crate::NATIVE.set(m.py(), m.clone().unbind());".to_string(),
        "    m.add_function(wrap_pyfunction!(crate::unpickled_error, m)?)?;".to_string(),
    ];
    for f in &api.functions {
        if f.has_effects() {
            out.push_str(&effects_binding(m, f));
            registrations.push(format!(
                "    m.add_function(wrap_pyfunction!(crate::{}_py, m)?)?;",
                f.rust_name.trim_start_matches("r#")
            ));
            continue;
        }
        let params: Vec<String> = f
            .params
            .iter()
            .map(|(n, t)| format!("{n}: {}", binding_type(t)))
            .collect();
        let base_name = f.rust_name.trim_start_matches("r#");
        let inner = format!("{}_inner", base_name);
        let wrapper = format!("{}_py", base_name);
        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
        let _ = writeln!(
            out,
            "\nfn {inner}({}) -> Result<{}, String> {{\n{}}}\n",
            params.join(", "),
            ret(f),
            body(f, &format!("port::{}", f.rust_name), false)
        );
        let _ = writeln!(out, "/// `{}`.", f.js_name);
        let _ = writeln!(out, "#[pyfunction]");
        let _ = writeln!(
            out,
            "#[pyo3(name = \"{}\", signature = ({}))]",
            f.js_name,
            signature(f, params_of(m, f, None))
        );
        let py_param = if wire(&f.ret) == Wire::Json {
            "py: Python<'_>, "
        } else {
            ""
        };
        let _ = writeln!(
            out,
            "fn {wrapper}({py_param}{}) -> PyResult<{}> {{",
            py_params(m, f, params_of(m, f, None)).join(", "),
            py_ret(f)
        );
        let _ = writeln!(out, "    {inner}({}){}\n}}", args.join(", "), py_out(f));
        registrations.push(format!(
            "    m.add_function(wrap_pyfunction!(crate::{}, m)?)?;",
            wrapper
        ));
    }
    for c in &api.classes {
        let (name, js) = (&c.rust_name, &c.js_name);
        let snake = crate::bridge::snake_case(name);
        let ctor_params: Vec<String> = c
            .constructor
            .params
            .iter()
            .map(|(n, t)| format!("{n}: {}", binding_type(t)))
            .collect();
        let ctor_args: Vec<&str> = c
            .constructor
            .params
            .iter()
            .map(|(n, _)| n.as_str())
            .collect();
        let _ = writeln!(
            out,
            "\nfn {snake}_new_inner({}) -> Result<port::{name}, String> {{\n{}}}",
            ctor_params.join(", "),
            body(&c.constructor, &format!("port::{name}::new"), true)
        );
        for (method, mutable) in &c.methods {
            let receiver = if *mutable {
                format!("inner: &mut port::{name}")
            } else {
                format!("inner: &port::{name}")
            };
            let params: Vec<String> = std::iter::once(receiver)
                .chain(
                    method
                        .params
                        .iter()
                        .map(|(n, t)| format!("{n}: {}", binding_type(t))),
                )
                .collect();
            let _ = writeln!(
                out,
                "\nfn {snake}_{}_inner({}) -> Result<{}, String> {{\n{}}}",
                method.rust_name.trim_start_matches("r#"),
                params.join(", "),
                ret(method),
                body(method, &format!("inner.{}", method.rust_name), false)
            );
        }
        let _ = writeln!(
            out,
            "\n/// Class `{js}`.\n#[pyclass(name = \"{js}\")]\npub struct {name} {{\n    inner: port::{name},\n}}\n"
        );
        let _ = writeln!(out, "#[pymethods]\nimpl {name} {{");
        let _ = writeln!(
            out,
            "    #[new]\n    #[pyo3(signature = ({}))]\n    fn new({}) -> PyResult<Self> {{\n        \
             {snake}_new_inner({}).map(|inner| Self {{ inner }}).map_err(error)\n    }}",
            signature(&c.constructor, params_of(m, &c.constructor, Some(js))),
            py_params(m, &c.constructor, params_of(m, &c.constructor, Some(js))).join(", "),
            ctor_args.join(", ")
        );
        for (method, mutable) in &c.methods {
            let receiver = if *mutable { "&mut self" } else { "&self" };
            let params = py_params(m, method, params_of(m, method, Some(js)));
            let sig = std::iter::once(receiver.to_string())
                .chain(params)
                .collect::<Vec<_>>()
                .join(", ");
            let borrow = if *mutable {
                "&mut self.inner"
            } else {
                "&self.inner"
            };
            let args = std::iter::once(borrow)
                .chain(method.params.iter().map(|(n, _)| n.as_str()))
                .collect::<Vec<_>>();
            let sig = if wire(&method.ret) == Wire::Json {
                sig.replacen("self", "self, py: Python<'_>", 1)
            } else {
                sig
            };
            let method_wrapper = format!("{}_py", method.rust_name.trim_start_matches("r#"));
            let _ = writeln!(
                out,
                "\n    #[pyo3(name = \"{}\", signature = ({}))]\n    fn {method_wrapper}({sig}) -> PyResult<{}> {{\n        \
                 {snake}_{}_inner({}){}\n    }}",
                method.js_name,
                signature(method, params_of(m, method, Some(js))),
                py_ret(method),
                method.rust_name.trim_start_matches("r#"),
                args.join(", "),
                py_out(method)
            );
        }
        out.push_str("}\n");
        registrations.push(format!("    m.add_class::<crate::{name}>()?;"));
    }
    if !m.batches.is_empty() {
        match crate::codegen_batch::py_rs(m, api) {
            Ok((code, classes)) => {
                out.push_str(&code);
                for c in classes {
                    registrations.push(format!("    m.add_class::<crate::{c}>()?;"));
                }
            }
            Err(e) => {
                let _ = writeln!(out, "\ncompile_error!({e:?});");
            }
        }
    }
    let _ = writeln!(
        out,
        "\n#[cfg(feature = \"python-module\")]\n#[pymodule]\n#[pyo3(name = \"_native\")]\nfn native_module(m: &Bound<'_, PyModule>) -> PyResult<()> {{\n{}\n    Ok(())\n}}",
        registrations.join("\n")
    );
    out
}

/// Passes keyword arguments named as in the original (`maxLen=5`) under the binding's
/// snake_case names (`max_len`), which PyO3 takes them by.
const KEYWORDS_PY: &str = r#"
def _keywords(fn, names):
    import functools

    @functools.wraps(fn)
    def call(*args, **kwargs):
        given = {}
        for k, v in kwargs.items():
            name = names.get(k, k)
            if name in given:
                raise TypeError(f"{fn.__name__}() got multiple values for argument '{k}'")
            given[name] = v
        return fn(*args, **given)

    return call

"#;

/// The original's parameter names that the binding renamed, with the binding's name:
/// `maxLen` -> `max_len`, `N` -> `n`. A name that is already snake_case is not listed.
fn renamed_keywords(m: &Manifest, f: &PortFn) -> Vec<(String, String)> {
    let Some(export) = m.exports.iter().find(|e| e.name == f.js_name) else {
        return Vec::new();
    };
    export
        .params
        .iter()
        .filter_map(|p| {
            let binding = crate::bridge::snake_case(&p.name);
            // PyO3 shows a raw identifier (`r#type`) without its `r#`.
            let binding = binding.trim_start_matches("r#");
            (binding != p.name).then(|| (p.name.clone(), binding.to_string()))
        })
        .collect()
}

/// The wrapper package: imports `_native`, converting structured values.
pub fn package_init(m: &Manifest, api: &PortApi) -> String {
    // Structured values are converted in Rust (`pyconv.rs`): every export is the native one.
    let structured = |_: &PortFn| -> (Vec<String>, bool) { (Vec::new(), false) };
    let mut out = format!(
        "\"\"\"Rust port of `{}`, generated by rust-anything. Import this package where the code\n\
         imported the original module.\"\"\"\n\nfrom . import _native\n{CODEC_PY}\n",
        m.unit
    );
    if api
        .functions
        .iter()
        .any(|f| !renamed_keywords(m, f).is_empty())
    {
        out.push_str(KEYWORDS_PY);
    }
    let mut names = Vec::new();
    for f in &api.functions {
        let (json_params, json_ret) = structured(f);
        let positions: Vec<String> = f
            .params
            .iter()
            .enumerate()
            .filter(|(_, (_, t))| wire(t) == Wire::Json)
            .map(|(i, _)| i.to_string())
            .collect();
        if f.has_effects() {
            let changed: String = f
                .visible()
                .iter()
                .enumerate()
                .filter(|(_, (_, _, mutable))| *mutable)
                .map(|(i, (n, _, _))| format!("({i}, '{}'), ", n.trim_start_matches("r#")))
                .collect();
            let _ = writeln!(
                out,
                "{name} = _effects(_native.{name}, ({changed}))",
                name = f.js_name
            );
        } else if json_params.is_empty() && !json_ret {
            let _ = writeln!(out, "{} = _native.{}", f.js_name, f.js_name);
        } else {
            let _ = writeln!(
                out,
                "{name} = _wrap(_native.{name}, ({positions}), ({names_list}), {json_ret})",
                name = f.js_name,
                positions = positions
                    .iter()
                    .map(|p| format!("{p},"))
                    .collect::<String>(),
                names_list = json_params
                    .iter()
                    .map(|n| format!("'{n}',"))
                    .collect::<String>(),
                json_ret = if json_ret { "True" } else { "False" }
            );
        }
        let renamed = renamed_keywords(m, f);
        if !renamed.is_empty() {
            let map: Vec<String> = renamed
                .iter()
                .map(|(from, to)| format!("'{from}': '{to}'"))
                .collect();
            let _ = writeln!(
                out,
                "{name} = _keywords({name}, {{{}}})",
                map.join(", "),
                name = f.js_name
            );
        }
        names.push(f.js_name.clone());
    }
    for c in &api.classes {
        let needs = std::iter::once(&c.constructor)
            .chain(c.methods.iter().map(|(x, _)| x))
            .any(|f| {
                let (p, r) = structured(f);
                !p.is_empty() || r
            });
        if !needs {
            let _ = writeln!(out, "{} = _native.{}", c.js_name, c.js_name);
        } else {
            let methods: String = c
                .methods
                .iter()
                .map(|(method, _)| {
                    let (params, json_ret) = structured(method);
                    let positions: String = method
                        .params
                        .iter()
                        .enumerate()
                        .filter(|(_, (_, t))| wire(t) == Wire::Json)
                        .map(|(i, _)| format!("{i},"))
                        .collect();
                    format!(
                        "    {name} = _method('{name}', ({positions}), ({params}), {ret})\n",
                        name = method.js_name,
                        params = params.iter().map(|n| format!("'{n}',")).collect::<String>(),
                        ret = if json_ret { "True" } else { "False" }
                    )
                })
                .collect();
            let (ctor_params, _) = structured(&c.constructor);
            let ctor_positions: String = c
                .constructor
                .params
                .iter()
                .enumerate()
                .filter(|(_, (_, t))| wire(t) == Wire::Json)
                .map(|(i, _)| format!("{i},"))
                .collect();
            let _ = writeln!(
                out,
                "\nclass {js}:\n    def __init__(self, *args, **kwargs):\n        \
                 args, kwargs = _encode_args(args, kwargs, ({ctor_positions}), ({}))\n        \
                 self._inner = _native.{js}(*args, **kwargs)\n{methods}",
                ctor_params
                    .iter()
                    .map(|n| format!("'{n}',"))
                    .collect::<String>(),
                js = c.js_name
            );
        }
        names.push(c.js_name.clone());
    }
    for b in &m.batches {
        let class = format!("{}Batch", crate::codegen_batch::pascal(&b.function));
        let _ = writeln!(out, "{class} = _native.{class}");
        names.push(class);
    }
    let _ = writeln!(
        out,
        "\n__all__ = [{}]",
        names
            .iter()
            .map(|n| format!("'{n}'"))
            .collect::<Vec<_>>()
            .join(", ")
    );
    out
}

const CODEC_PY: &str = r#"
import json as _json
import math as _math
import sys as _sys

# Structured values cross as JSON text. JSON has no NaN, tuples, sets, bytes, big ints or
# non-string keys: those travel as markers (see `js.rs`) and come back as Python values.
_BIG = 2 ** 53


def _enc(v):
    if v is None or isinstance(v, (bool, str)):
        return v
    if isinstance(v, int):
        return v if -_BIG <= v <= _BIG else {"$int": str(v)}
    if isinstance(v, float):
        if _math.isnan(v):
            return {"$num": "NaN"}
        if _math.isinf(v):
            return {"$num": "Infinity" if v > 0 else "-Infinity"}
        if v == 0 and _math.copysign(1, v) < 0:
            return {"$num": "-0"}
        return v
    if isinstance(v, list):
        return [_enc(x) for x in v]
    if isinstance(v, tuple):
        return {"$tuple": [_enc(x) for x in v]}
    if isinstance(v, (set, frozenset)):
        return {"$set": sorted((_enc(x) for x in v), key=_json.dumps)}
    if isinstance(v, (bytes, bytearray, memoryview)):
        return {"$bytes": list(bytes(v))}
    if isinstance(v, dict):
        if all(isinstance(k, str) for k in v):
            return {k: _enc(x) for k, x in v.items()}
        return {"$dict": [[_enc(k), _enc(x)] for k, x in v.items()]}
    return {"$repr": repr(v)}


def _dec(v):
    if isinstance(v, list):
        return [_dec(x) for x in v]
    if not isinstance(v, dict):
        return v
    if len(v) == 1:
        (key, inner), = v.items()
        if key == "$undefined":
            return None
        if key == "$num":
            return {"NaN": _math.nan, "Infinity": _math.inf, "-Infinity": -_math.inf, "-0": -0.0}[inner]
        if key == "$int":
            return int(inner)
        if key == "$tuple":
            return tuple(_dec(x) for x in inner)
        if key == "$set":
            return {_dec(x) for x in inner}
        if key == "$bytes":
            return bytes(inner)
        if key == "$dict":
            return {_dec(k): _dec(x) for k, x in inner}
    return {k: _dec(x) for k, x in v.items()}


def _encode_args(args, kwargs, positions, names):
    args = tuple(_json.dumps(_enc(a)) if i in positions else a for i, a in enumerate(args))
    kwargs = {k: (_json.dumps(_enc(a)) if k in names else a) for k, a in kwargs.items()}
    return args, kwargs


def _wrap(fn, positions, names, json_result):
    def call(*args, **kwargs):
        args, kwargs = _encode_args(args, kwargs, positions, names)
        out = fn(*args, **kwargs)
        return _dec(_json.loads(out)) if json_result else out
    call.__name__ = fn.__name__
    call.__doc__ = fn.__doc__
    return call


def _merge(old, fresh):
    if type(old) is type(fresh) and _copy_back(old, fresh):
        return old
    return fresh


def _copy_back(target, source):
    """Writes `source` into `target`, so the caller's own object changes; nested containers keep
    their identity where the shape did not change. False for what cannot change in place."""
    if isinstance(target, list) and isinstance(source, list):
        old = list(target)
        target[:] = [_merge(old[i], x) if i < len(old) else x for i, x in enumerate(source)]
        return True
    if isinstance(target, dict) and isinstance(source, dict):
        old = dict(target)
        target.clear()
        for k, x in source.items():
            target[k] = _merge(old[k], x) if k in old else x
        return True
    if isinstance(target, set) and isinstance(source, set):
        target.clear()
        target.update(source)
        return True
    if isinstance(target, bytearray) and isinstance(source, (bytes, bytearray)):
        target[:] = source
        return True
    return False


def _effects(fn, changed):
    """A function the port runs for its effect on the arguments and the output: the binding answers
    `(result, changed arguments, printed text, exception)`; the arguments go back into the caller's
    objects, the text to `sys.stdout`, then the result is returned or the exception raised."""
    def call(*args, **kwargs):
        ret, after, text, exc = fn(*args, **kwargs)
        for (position, name), value in zip(changed, after):
            target = args[position] if position < len(args) else kwargs.get(name)
            if target is not None:
                _copy_back(target, value)
        if text:
            _sys.stdout.write(text)
        if exc is not None:
            raise exc
        return ret
    call.__name__ = fn.__name__
    call.__doc__ = fn.__doc__
    return call


def _method(name, positions, names, json_result):
    def call(self, *args, **kwargs):
        args, kwargs = _encode_args(args, kwargs, positions, names)
        out = getattr(self._inner, name)(*args, **kwargs)
        return _dec(_json.loads(out)) if json_result else out
    call.__name__ = name
    return call
"#;

/// `src/pyconv.rs`: Python objects to `serde_json::Value` and back, in Rust, without JSON text.
/// Values the JSON model lacks use the same markers as recorded cases: `$tuple`, `$set`,
/// `$bytes`, `$path` (a `pathlib` path), `$int` (beyond i64), `$dict` (non-string keys), `$num`
/// (NaN, infinities, -0), `$utf16` (strings with lone surrogates), `$codepoints` (those whose
/// UTF-16 units would read back as another string).
pub const PYCONV_RS: &str = r#"//! Python objects to `serde_json::Value` and back, in Rust. Generated by rust-anything.

#![forbid(unsafe_code)]

use pyo3::prelude::*;
use pyo3::types::{
    PyBool, PyByteArray, PyBytes, PyDict, PyFloat, PyFrozenSet, PyInt, PyList, PyMemoryView,
    PySet, PyString, PyTuple,
};
use serde_json::{Map, Value, json};

fn type_error(obj: &Bound<'_, PyAny>) -> String {
    let name = obj.get_type().name().map(|n| n.to_string()).unwrap_or_default();
    format!("TypeError: unsupported argument type {name}")
}

/// A `str` with a lone surrogate where the port takes a Rust `String`, which has no room for one;
/// an untyped parameter or a `Value` carries it as `$utf16` instead.
const LONE_SURROGATE: &str = "TypeError: str holds a lone surrogate, which a Rust String cannot hold";

/// An argument's conversion error, named after the parameter when it is a lone surrogate, as
/// PyO3 names a top-level `str` parameter.
pub fn argument(name: &str, error: String) -> String {
    match error.strip_prefix("TypeError: ") {
        Some(rest) if error == LONE_SURROGATE => format!("TypeError: argument '{name}': {rest}"),
        _ => error,
    }
}

fn holds_utf16(v: &Value) -> bool {
    match v {
        Value::Array(items) => items.iter().any(holds_utf16),
        Value::Object(o) => {
            o.contains_key("$utf16") || o.contains_key("$codepoints") || o.values().any(holds_utf16)
        }
        _ => false,
    }
}

fn float(x: f64) -> Value {
    if x.is_nan() {
        json!({"$num": "NaN"})
    } else if x.is_infinite() {
        json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
    } else if x == 0.0 && x.is_sign_negative() {
        json!({"$num": "-0"})
    } else {
        json!(x)
    }
}

/// `{key: inner}`, without the copy `json!` makes of a value put in it.
fn marked(key: &str, inner: Value) -> Value {
    Value::Object(Map::from_iter([(key.to_string(), inner)]))
}

fn items(obj: &Bound<'_, PyAny>) -> Result<Vec<Value>, String> {
    let size = match obj.cast::<PyList>() {
        Ok(list) => list.len(),
        Err(_) => obj.cast::<PyTuple>().map_or(0, |t| t.len()),
    };
    let mut out = Vec::with_capacity(size);
    for item in obj.try_iter().map_err(|e| e.to_string())? {
        out.push(from_py(&item.map_err(|e| e.to_string())?)?);
    }
    Ok(out)
}

fn extract_bytes(obj: &Bound<'_, PyAny>) -> Option<Result<Vec<u8>, String>> {
    if obj.is_instance_of::<PyBytes>() {
        return Some(
            obj.cast::<PyBytes>()
                .map(|b| b.as_bytes().to_vec())
                .map_err(|e| e.to_string()),
        );
    }
    if obj.is_instance_of::<PyByteArray>() {
        return Some(
            obj.cast::<PyByteArray>()
                .map(|b| b.to_vec())
                .map_err(|e| e.to_string()),
        );
    }
    if obj.is_instance_of::<PyMemoryView>() {
        return Some(
            obj.call_method0("tobytes")
                .and_then(|b| {
                    b.cast::<PyBytes>()
                        .map(|b| b.as_bytes().to_vec())
                        .map_err(Into::into)
                })
                .map_err(|e| e.to_string()),
        );
    }
    None
}

thread_local! {
    /// The instances being converted on this thread, outermost first. One that refers back to
    /// itself, directly or through its fields, becomes `{"$cycle": true}`; the same instance
    /// in two separate fields is converted twice.
    static CONVERTING: std::cell::RefCell<Vec<usize>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

fn py_string_value(obj: &Bound<'_, PyAny>) -> Result<Value, String> {
    if let Ok(s) = obj.extract::<String>() {
        return Ok(Value::String(s));
    }
    // Lone surrogates (e.g. from `errors="surrogateescape"`) cannot become Rust UTF-8 `String`:
    // encode their UTF-16 code units with the same `$utf16` marker recordings use. A high then a
    // low surrogate code point would read back as one character, so a string with that pair keeps
    // its code points instead (`$codepoints`), as the recorder does.
    let encoded = obj
        .call_method1("encode", ("utf-32-le", "surrogatepass"))
        .map_err(|e| e.to_string())?;
    let bytes = encoded
        .cast::<PyBytes>()
        .map_err(|e| e.to_string())?
        .as_bytes();
    let points: Vec<u32> = bytes
        .as_chunks::<4>()
        .0
        .iter()
        .map(|c| u32::from_le_bytes(*c))
        .collect();
    let paired = points
        .windows(2)
        .any(|w| (0xD800..0xDC00).contains(&w[0]) && (0xDC00..0xE000).contains(&w[1]));
    if paired {
        return Ok(json!({"$codepoints": points}));
    }
    let mut units: Vec<u16> = Vec::with_capacity(points.len());
    for point in points {
        match char::from_u32(point) {
            Some(c) => units.extend(c.encode_utf16(&mut [0; 2]).iter()),
            None => units.push(point as u16),
        }
    }
    Ok(json!({"$utf16": units}))
}

/// A Python object as a JSON value.
pub fn from_py(obj: &Bound<'_, PyAny>) -> Result<Value, String> {
    if obj.is_none() {
        return Ok(Value::Null);
    }
    if obj.is_instance_of::<PyBool>() {
        return Ok(Value::Bool(obj.extract::<bool>().map_err(|e| e.to_string())?));
    }
    if obj.is_instance_of::<PyInt>() {
        return Ok(match obj.extract::<i64>() {
            Ok(i) => json!(i),
            Err(_) => json!({"$int": obj.str().map_err(|e| e.to_string())?.to_string()}),
        });
    }
    if obj.is_instance_of::<PyFloat>() {
        return Ok(float(obj.extract::<f64>().map_err(|e| e.to_string())?));
    }
    if obj.is_instance_of::<PyString>() {
        return py_string_value(obj);
    }
    struct CycleGuard;
    impl Drop for CycleGuard {
        fn drop(&mut self) {
            CONVERTING.with(|active| {
                active.borrow_mut().pop();
            });
        }
    }
    let enter_cycle = |id: usize| -> Option<CycleGuard> {
        let seen = CONVERTING.with(|active| active.borrow().contains(&id));
        if seen {
            return None;
        }
        CONVERTING.with(|active| active.borrow_mut().push(id));
        Some(CycleGuard)
    };
    if obj.is_instance_of::<PyList>() {
        let Some(_guard) = enter_cycle(obj.as_ptr() as usize) else {
            return Ok(json!({"$cycle": true}));
        };
        return Ok(Value::Array(items(obj)?));
    }
    if obj.is_instance_of::<PyTuple>() {
        let Some(_guard) = enter_cycle(obj.as_ptr() as usize) else {
            return Ok(json!({"$cycle": true}));
        };
        return Ok(marked("$tuple", Value::Array(items(obj)?)));
    }
    if obj.is_instance_of::<PyDict>() {
        let Some(_guard) = enter_cycle(obj.as_ptr() as usize) else {
            return Ok(json!({"$cycle": true}));
        };
        let dict = obj.cast::<PyDict>().map_err(|e| e.to_string())?;
        let mut entries: Vec<(Result<String, Value>, Value)> = Vec::with_capacity(dict.len());
        for (k, v) in dict.iter() {
            let value = from_py(&v)?;
            let key = match k.extract::<String>() {
                Ok(key) => Ok(key),
                Err(_) => Err(from_py(&k)?),
            };
            entries.push((key, value));
        }
        return Ok(if entries.iter().all(|(k, _)| k.is_ok()) {
            Value::Object(entries.into_iter().filter_map(|(k, v)| Some((k.ok()?, v))).collect::<Map<_, _>>())
        } else {
            let pairs: Vec<Value> = entries
                .into_iter()
                .map(|(k, v)| Value::Array(vec![k.map_or_else(|k| k, Value::String), v]))
                .collect();
            marked("$dict", Value::Array(pairs))
        });
    }
    if obj.is_instance_of::<PySet>() || obj.is_instance_of::<PyFrozenSet>() {
        return Ok(marked("$set", Value::Array(items(obj)?)));
    }
    if let Some(bytes) = extract_bytes(obj) {
        return Ok(json!({"$bytes": bytes?}));
    }
    if let Some(bytes) = path_bytes(obj) {
        // The path's text; a name that is not UTF-8 keeps its bytes instead.
        return Ok(match String::from_utf8(bytes) {
            Ok(text) => json!({"$path": text}),
            Err(not_utf8) => json!({"$path": {"$bytes": not_utf8.into_bytes()}}),
        });
    }
    // An instance that keeps its fields in `__dict__` (a dataclass, a plain class): its class
    // name and fields, the shape the recorder writes for it.
    if let Ok(fields) = obj.getattr("__dict__")
        && fields.is_instance_of::<PyDict>()
    {
        // An instance reached again through its own fields is written as the recorder writes
        // it; without this the conversion would never end.
        let Some(_guard) = enter_cycle(obj.as_ptr() as usize) else {
            return Ok(json!({"$cycle": true}));
        };
        let attrs = from_py(&fields)?;
        let name = obj.get_type().name().map_err(|e| e.to_string())?;
        return Ok(Value::Object(Map::from_iter([
            ("$object".to_string(), Value::String(name.to_string())),
            ("attrs".to_string(), attrs),
        ])));
    }
    Err(type_error(obj))
}

/// The file-system bytes of an `os.PathLike` object (`pathlib.Path` and friends), from
/// `os.fsencode`, so a name that is not valid Unicode keeps its bytes. A `str` is not a path.
fn path_bytes(obj: &Bound<'_, PyAny>) -> Option<Vec<u8>> {
    let os = obj.py().import("os").ok()?;
    if !obj.is_instance(&os.getattr("PathLike").ok()?).ok()? {
        return None;
    }
    let encoded = os.getattr("fsencode").ok()?.call1((obj,)).ok()?;
    Some(encoded.cast::<PyBytes>().ok()?.as_bytes().to_vec())
}

fn new_path(py: Python<'_>, text: &str) -> PyResult<Py<PyAny>> {
    Ok(py.import("pathlib")?.getattr("Path")?.call1((text,))?.unbind())
}

/// The path a `$path` marker stands for: its text, or `{"$bytes": [...]}` for a name that is
/// not UTF-8.
fn marked_path(py: Python<'_>, inner: &Value) -> PyResult<Py<PyAny>> {
    match inner.get("$bytes").and_then(Value::as_array) {
        Some(bytes) => {
            let bytes: Vec<u8> = bytes.iter().filter_map(|b| b.as_u64()).map(|b| b as u8).collect();
            path_to_py(py, &path_from_bytes(bytes))
        }
        None => new_path(py, inner.as_str().unwrap_or_default()),
    }
}

#[cfg(unix)]
fn path_from_bytes(bytes: Vec<u8>) -> std::path::PathBuf {
    use std::os::unix::ffi::OsStringExt;
    std::ffi::OsString::from_vec(bytes).into()
}

#[cfg(not(unix))]
fn path_from_bytes(bytes: Vec<u8>) -> std::path::PathBuf {
    String::from_utf8_lossy(&bytes).into_owned().into()
}

/// A `pathlib.Path` for a Rust path. On Unix the bytes go through `os.fsdecode`, so a name
/// that is not UTF-8 comes back as the same file name, not with U+FFFD in it.
#[cfg(unix)]
fn path_to_py(py: Python<'_>, path: &std::path::Path) -> PyResult<Py<PyAny>> {
    use std::os::unix::ffi::OsStrExt;
    let bytes = PyBytes::new(py, path.as_os_str().as_bytes());
    let text = py.import("os")?.getattr("fsdecode")?.call1((bytes,))?;
    Ok(py.import("pathlib")?.getattr("Path")?.call1((text,))?.unbind())
}

#[cfg(not(unix))]
fn path_to_py(py: Python<'_>, path: &std::path::Path) -> PyResult<Py<PyAny>> {
    new_path(py, &path.to_string_lossy())
}

/// A structured argument, converted to the port's parameter type.
pub fn arg<T: serde::de::DeserializeOwned>(obj: &Bound<'_, PyAny>) -> Result<T, String> {
    let value = from_py(obj)?;
    let lone = holds_utf16(&value);
    serde_json::from_value(value).map_err(|e| {
        if lone && e.to_string().starts_with("invalid type: map, expected a string") {
            LONE_SURROGATE.to_string()
        } else {
            format!("TypeError: {e}")
        }
    })
}

/// An argument whose Python default is not `None`, as `#[pyo3(from_py_with = ...)]`: whatever the
/// caller passed, `None` too, so only an argument left out is `None` in Rust.
pub fn given<'py>(obj: &Bound<'py, PyAny>) -> PyResult<Option<Bound<'py, PyAny>>> {
    Ok(Some(obj.clone()))
}

/// A Python argument as a Rust value, without going through JSON.
pub trait FromPy: Sized {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String>;
}

/// A Rust result as a Python object, without going through JSON.
pub trait ToPy {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>>;

    /// `to_py` for a value the caller is done with: each part is freed as soon as it is converted.
    fn into_py(self, py: Python<'_>) -> PyResult<Py<PyAny>>
    where
        Self: Sized,
    {
        self.to_py(py)
    }
}

macro_rules! extract {
    ($($t:ty),*) => {$(
        impl FromPy for $t {
            fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
                obj.extract::<$t>().map_err(|_| type_error(obj))
            }
        }
        impl ToPy for $t {
            fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
                Ok(self.clone().into_pyobject(py)?.to_owned().into_any().unbind())
            }
        }
    )*};
}
extract!(i64, bool);

impl FromPy for String {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        obj.extract::<String>().map_err(|_| {
            if obj.is_instance_of::<PyString>() {
                LONE_SURROGATE.to_string()
            } else {
                type_error(obj)
            }
        })
    }
}

impl ToPy for String {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        Ok(PyString::new(py, self).into_any().unbind())
    }
}

impl FromPy for f64 {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        if obj.is_instance_of::<PyFloat>() || obj.is_instance_of::<PyInt>() {
            obj.extract::<f64>().map_err(|_| type_error(obj))
        } else {
            Err(type_error(obj))
        }
    }
}

impl ToPy for f64 {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        Ok(PyFloat::new(py, *self).into_any().unbind())
    }
}

impl FromPy for crate::pynum::Num {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        use crate::pynum::Num;
        if obj.is_instance_of::<PyFloat>() {
            return obj.extract::<f64>().map(Num::Float).map_err(|_| type_error(obj));
        }
        if obj.is_instance_of::<PyInt>() {
            return obj
                .extract::<i64>()
                .map(Num::Int)
                .map_err(|_| "OverflowError: int too large for the port".to_string());
        }
        Err(type_error(obj))
    }
}

impl ToPy for crate::pynum::Num {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        match *self {
            crate::pynum::Num::Int(i) => i.to_py(py),
            crate::pynum::Num::Float(x) => x.to_py(py),
        }
    }
}

impl FromPy for Value {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        from_py(obj)
    }
}

impl ToPy for Value {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        to_py(py, self)
    }

    fn into_py(self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        into_py(py, self)
    }
}

impl<T: FromPy> FromPy for Option<T> {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        if obj.is_none() { Ok(None) } else { T::from_py(obj).map(Some) }
    }
}

impl<T: ToPy> ToPy for Option<T> {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        match self {
            Some(v) => v.to_py(py),
            None => Ok(py.None()),
        }
    }

    fn into_py(self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        match self {
            Some(v) => v.into_py(py),
            None => Ok(py.None()),
        }
    }
}

impl FromPy for Vec<u8> {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        extract_bytes(obj).unwrap_or_else(|| Err(type_error(obj)))
    }
}

impl ToPy for Vec<u8> {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        Ok(PyBytes::new(py, self).into_any().unbind())
    }
}

impl FromPy for std::path::PathBuf {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        path_bytes(obj).map(path_from_bytes).ok_or_else(|| type_error(obj))
    }
}

impl ToPy for std::path::PathBuf {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        path_to_py(py, self)
    }
}

impl<T: FromPy> FromPy for Vec<T> {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        if !obj.is_instance_of::<PyList>() && !obj.is_instance_of::<PyTuple>() {
            return Err(type_error(obj));
        }
        let mut out = Vec::new();
        for item in obj.try_iter().map_err(|e| e.to_string())? {
            out.push(T::from_py(&item.map_err(|e| e.to_string())?)?);
        }
        Ok(out)
    }
}

impl<T: ToPy> ToPy for Vec<T> {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let items: PyResult<Vec<Py<PyAny>>> = self.iter().map(|x| x.to_py(py)).collect();
        Ok(PyList::new(py, items?)?.into_any().unbind())
    }

    fn into_py(self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let items: PyResult<Vec<Py<PyAny>>> = self.into_iter().map(|x| x.into_py(py)).collect();
        Ok(PyList::new(py, items?)?.into_any().unbind())
    }
}

impl<T: FromPy> FromPy for std::collections::HashMap<String, T> {
    fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
        let dict = obj.cast::<PyDict>().map_err(|_| type_error(obj))?;
        let mut out = Self::new();
        for (k, v) in dict.iter() {
            out.insert(String::from_py(&k)?, T::from_py(&v)?);
        }
        Ok(out)
    }
}

impl<T: ToPy> ToPy for std::collections::HashMap<String, T> {
    fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let dict = PyDict::new(py);
        for (k, v) in self {
            dict.set_item(k, v.to_py(py)?)?;
        }
        Ok(dict.into_any().unbind())
    }

    fn into_py(self, py: Python<'_>) -> PyResult<Py<PyAny>> {
        let dict = PyDict::new(py);
        for (k, v) in self {
            dict.set_item(k, v.into_py(py)?)?;
        }
        Ok(dict.into_any().unbind())
    }
}

macro_rules! tuples {
    ($(($($t:ident $i:tt),+)),*) => {$(
        impl<$($t: FromPy),+> FromPy for ($($t,)+) {
            fn from_py(obj: &Bound<'_, PyAny>) -> Result<Self, String> {
                let t = obj.cast::<PyTuple>().map_err(|_| type_error(obj))?;
                Ok(($($t::from_py(&t.get_item($i).map_err(|e| e.to_string())?)?,)+))
            }
        }
        impl<$($t: ToPy),+> ToPy for ($($t,)+) {
            fn to_py(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
                Ok(PyTuple::new(py, [$(self.$i.to_py(py)?),+])?.into_any().unbind())
            }
        }
    )*};
}
tuples!((A 0, B 1), (A 0, B 1, C 2), (A 0, B 1, C 2, D 3));

/// A tuple element, converted as `PyTuple::new` fills the tuple.
struct Item<'a>(&'a Value);

impl<'py> IntoPyObject<'py> for Item<'_> {
    type Target = PyAny;
    type Output = Bound<'py, PyAny>;
    type Error = PyErr;

    fn into_pyobject(self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        to_py(py, self.0).map(|o| o.into_bound(py))
    }
}

/// An owned tuple element, freed once converted.
struct Owned(Value);

impl<'py> IntoPyObject<'py> for Owned {
    type Target = PyAny;
    type Output = Bound<'py, PyAny>;
    type Error = PyErr;

    fn into_pyobject(self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        into_py(py, self.0).map(|o| o.into_bound(py))
    }
}

/// A JSON value as a Python object; markers become the Python types they stand for.
pub fn to_py(py: Python<'_>, v: &Value) -> PyResult<Py<PyAny>> {
    let list = |items: &[Value]| -> PyResult<Vec<Py<PyAny>>> { items.iter().map(|x| to_py(py, x)).collect() };
    Ok(match v {
        Value::Null => py.None(),
        Value::Bool(b) => PyBool::new(py, *b).to_owned().into_any().unbind(),
        Value::Number(n) => match n.as_i64() {
            Some(i) if !n.is_f64() => i.into_pyobject(py)?.into_any().unbind(),
            _ => match n.as_u64() {
                Some(u) if !n.is_f64() => u.into_pyobject(py)?.into_any().unbind(),
                _ => PyFloat::new(py, n.as_f64().unwrap_or(f64::NAN)).into_any().unbind(),
            },
        },
        Value::String(s) => PyString::new(py, s).into_any().unbind(),
        Value::Array(items) => PyList::new(py, list(items)?)?.into_any().unbind(),
        Value::Object(o) if o.len() == 1 => {
            let (key, inner) = o.iter().next().expect("one entry");
            entry(py, key, inner)?
        }
        Value::Object(o) => {
            let dict = PyDict::new(py);
            for (k, x) in o {
                dict.set_item(k, to_py(py, x)?)?;
            }
            dict.into_any().unbind()
        }
    })
}

/// A one-entry object: a marker's Python value, or a dict with that entry.
fn entry(py: Python<'_>, key: &str, inner: &Value) -> PyResult<Py<PyAny>> {
    let list = |items: &[Value]| -> PyResult<Vec<Py<PyAny>>> { items.iter().map(|x| to_py(py, x)).collect() };
    let items = || inner.as_array().map(Vec::as_slice).unwrap_or_default();
    Ok(match key {
        "$tuple" => PyTuple::new(py, items().iter().map(Item))?.into_any().unbind(),
        "$set" => PySet::new(py, list(items())?)?.into_any().unbind(),
        "$bytes" => {
            let bytes: Vec<u8> = items().iter().filter_map(|b| b.as_u64()).map(|b| b as u8).collect();
            PyBytes::new(py, &bytes).into_any().unbind()
        }
        "$path" => marked_path(py, inner)?,
        "$int" => py
            .import("builtins")?
            .getattr("int")?
            .call1((inner.as_str().unwrap_or("0"),))?
            .unbind(),
        "$float" => PyFloat::new(py, inner.as_str().and_then(|s| s.parse().ok()).unwrap_or(f64::NAN)).into_any().unbind(),
        "$num" => PyFloat::new(
            py,
            match inner.as_str() {
                Some("Infinity") => f64::INFINITY,
                Some("-Infinity") => f64::NEG_INFINITY,
                Some("-0") => -0.0,
                _ => f64::NAN,
            },
        )
        .into_any()
        .unbind(),
        "$dict" => {
            let dict = PyDict::new(py);
            for pair in items() {
                if let Some([k, v]) = pair.as_array().map(Vec::as_slice) {
                    dict.set_item(to_py(py, k)?, to_py(py, v)?)?;
                }
            }
            dict.into_any().unbind()
        }
        "$utf16" => match inner.as_array() {
            Some(units) if units.iter().all(|u| u.as_u64().is_some_and(|u| u <= 0xFFFF)) => {
                let mut raw = Vec::with_capacity(units.len() * 2);
                for unit in units {
                    raw.extend_from_slice(&(unit.as_u64().expect("checked") as u16).to_le_bytes());
                }
                PyBytes::new(py, &raw)
                    .call_method1("decode", ("utf-16-le", "surrogatepass"))?
                    .unbind()
            }
            _ => {
                let dict = PyDict::new(py);
                dict.set_item(key, to_py(py, inner)?)?;
                dict.into_any().unbind()
            }
        },
        "$codepoints" => match inner.as_array() {
            Some(points) if points.iter().all(|c| c.as_u64().is_some_and(|c| c <= 0x10FFFF)) => {
                let mut raw = Vec::with_capacity(points.len() * 4);
                for point in points {
                    raw.extend_from_slice(&(point.as_u64().expect("checked") as u32).to_le_bytes());
                }
                PyBytes::new(py, &raw)
                    .call_method1("decode", ("utf-32-le", "surrogatepass"))?
                    .unbind()
            }
            _ => {
                let dict = PyDict::new(py);
                dict.set_item(key, to_py(py, inner)?)?;
                dict.into_any().unbind()
            }
        },
        _ => {
            let dict = PyDict::new(py);
            dict.set_item(key, to_py(py, inner)?)?;
            dict.into_any().unbind()
        }
    })
}

/// `to_py` for a value the caller is done with: each part is freed as soon as it is converted,
/// while it is still in the cache, instead of in a separate pass over the whole tree.
pub fn into_py(py: Python<'_>, v: Value) -> PyResult<Py<PyAny>> {
    Ok(match v {
        Value::Array(items) => {
            let items: PyResult<Vec<Py<PyAny>>> = items.into_iter().map(|x| into_py(py, x)).collect();
            PyList::new(py, items?)?.into_any().unbind()
        }
        Value::Object(o) if o.len() == 1 => {
            let (key, inner) = o.into_iter().next().expect("one entry");
            match (key.as_str(), inner) {
                ("$tuple", Value::Array(items)) => PyTuple::new(py, items.into_iter().map(Owned))?.into_any().unbind(),
                (marker, inner) if marker.starts_with('$') => entry(py, marker, &inner)?,
                (_, inner) => {
                    let dict = PyDict::new(py);
                    dict.set_item(&key, into_py(py, inner)?)?;
                    dict.into_any().unbind()
                }
            }
        }
        Value::Object(o) => {
            let dict = PyDict::new(py);
            for (k, x) in o {
                dict.set_item(k, into_py(py, x)?)?;
            }
            dict.into_any().unbind()
        }
        v => to_py(py, &v)?,
    })
}
"#;

/// `src/pynum.rs`: Python's int-or-float, for ports of code that takes either.
pub const PYNUM_RS: &str = r#"//! Python numbers: an int stays an int through `+`, `-`, `*`, `//` and `%`; `/` gives a float.
//! Generated by rust-anything. Ints beyond i64 become floats (Python would keep a big int).

#![forbid(unsafe_code)]

use std::cmp::Ordering;
use std::ops::{Add, Mul, Neg, Sub};

#[derive(Clone, Copy, Debug)]
pub enum Num {
    Int(i64),
    Float(f64),
}

impl Num {
    pub fn f(self) -> f64 {
        match self {
            Self::Int(i) => i as f64,
            Self::Float(x) => x,
        }
    }

    fn op(self, o: Self, int: fn(i64, i64) -> Option<i64>, float: fn(f64, f64) -> f64) -> Self {
        match (self, o) {
            (Self::Int(a), Self::Int(b)) => int(a, b).map_or_else(|| Self::Float(float(a as f64, b as f64)), Self::Int),
            (a, b) => Self::Float(float(a.f(), b.f())),
        }
    }

    /// `/`: always a float; `ZeroDivisionError` for zero.
    pub fn true_div(self, o: Self) -> Result<Self, String> {
        match (self, o) {
            (_, o) if o.f() == 0.0 => Err(match (self, o) {
                (Self::Int(_), Self::Int(_)) => "ZeroDivisionError: division by zero".into(),
                _ => "ZeroDivisionError: float division by zero".into(),
            }),
            (a, b) => Ok(Self::Float(a.f() / b.f())),
        }
    }

    /// `%`: the result takes the divisor's sign.
    pub fn modulo(self, o: Self) -> Result<Self, String> {
        match (self, o) {
            (Self::Int(_), Self::Int(0)) => Err("ZeroDivisionError: integer modulo by zero".into()),
            (Self::Int(a), Self::Int(b)) => {
                let r = a.wrapping_rem(b);
                Ok(Self::Int(if r != 0 && (r < 0) != (b < 0) { r + b } else { r }))
            }
            (a, b) => {
                let (x, y) = (a.f(), b.f());
                if y == 0.0 {
                    return Err("ZeroDivisionError: float modulo".into());
                }
                let m = x % y;
                Ok(Self::Float(if m != 0.0 {
                    if (y < 0.0) != (m < 0.0) { m + y } else { m }
                } else {
                    0.0_f64.copysign(y)
                }))
            }
        }
    }

    /// Python's `max(a, b, ...)`: the first value no later value is greater than;
    /// `ValueError` for no values.
    pub fn max(values: &[Self]) -> Result<Self, String> {
        let (&first, rest) = values
            .split_first()
            .ok_or_else(|| "ValueError: max() iterable argument is empty".to_string())?;
        Ok(rest.iter().fold(first, |m, &x| if x > m { x } else { m }))
    }

    /// Python's `min(a, b, ...)`; `ValueError` for no values.
    pub fn min(values: &[Self]) -> Result<Self, String> {
        let (&first, rest) = values
            .split_first()
            .ok_or_else(|| "ValueError: min() iterable argument is empty".to_string())?;
        Ok(rest.iter().fold(first, |m, &x| if x < m { x } else { m }))
    }
}

impl From<f64> for Num {
    fn from(x: f64) -> Self {
        Self::Float(x)
    }
}

impl From<i64> for Num {
    fn from(i: i64) -> Self {
        Self::Int(i)
    }
}

impl Add for Num {
    type Output = Self;
    fn add(self, o: Self) -> Self {
        self.op(o, i64::checked_add, |a, b| a + b)
    }
}

impl Sub for Num {
    type Output = Self;
    fn sub(self, o: Self) -> Self {
        self.op(o, i64::checked_sub, |a, b| a - b)
    }
}

impl Mul for Num {
    type Output = Self;
    fn mul(self, o: Self) -> Self {
        self.op(o, i64::checked_mul, |a, b| a * b)
    }
}

impl Neg for Num {
    type Output = Self;
    fn neg(self) -> Self {
        match self {
            Self::Int(i) => i.checked_neg().map_or(Self::Float(-(i as f64)), Self::Int),
            Self::Float(x) => Self::Float(-x),
        }
    }
}

impl PartialEq for Num {
    fn eq(&self, o: &Self) -> bool {
        match (*self, *o) {
            (Self::Int(a), Self::Int(b)) => a == b,
            (a, b) => a.f() == b.f(),
        }
    }
}

impl PartialOrd for Num {
    fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
        match (*self, *o) {
            (Self::Int(a), Self::Int(b)) => a.partial_cmp(&b),
            (a, b) => a.f().partial_cmp(&b.f()),
        }
    }
}
"#;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bridge::{Kind, Manifest};
    use crate::codegen::{Modules, PortApi, PortClass, PortFn};
    use crate::lang::Lang;
    use crate::ts::exports::{ExportedFn, Param};

    #[test]
    fn the_module_is_behind_the_feature_so_a_front_door_can_leave_it_out() {
        let api = PortApi {
            functions: vec![verdict_port()],
            ..Default::default()
        };
        let modules = Modules {
            utf16: false,
            js: false,
        };
        let lib = lib_rs(&verdict_manifest(), &api, &modules);
        assert!(
            lib.contains("#[cfg(feature = \"python-module\")]\n#[pymodule]"),
            "{lib}"
        );
        assert!(lib.contains("not(feature = \"python-module\")"), "{lib}");
    }

    #[test]
    fn converts_python_literals() {
        assert_eq!(rust_literal("'-'").as_deref(), Some("String::from(\"-\")"));
        assert_eq!(rust_literal("8").as_deref(), Some("8"));
        assert_eq!(rust_literal("1_000").as_deref(), Some("1000"));
        assert_eq!(rust_literal("0.5").as_deref(), Some("0.5"));
        assert_eq!(rust_literal("True").as_deref(), Some("true"));
        assert_eq!(rust_literal("None"), None);
        assert_eq!(rust_literal("[]"), None);
        assert_eq!(rust_literal("'a\\nb'"), None);
    }

    #[test]
    fn integer_defaults_match_the_rust_parameter_type() {
        let f = PortFn {
            js_name: "scale".into(),
            rust_name: "scale".into(),
            params: vec![
                ("factor".into(), "f64".into()),
                ("count".into(), "i64".into()),
            ],
            ret: "f64".into(),
            fallible: true,
            is_async: false,
        };
        let param = |name: &str, default: &str| Param {
            name: name.into(),
            optional: true,
            default: Some(default.into()),
            ..Default::default()
        };
        let source = [param("factor", "-1_000"), param("count", "2")];
        assert_eq!(signature(&f, &source), "factor=-1000_f64, count=2");
    }

    #[test]
    fn a_parameter_named_like_a_rust_keyword_keeps_its_raw_identifier() {
        // `def tag(type, ref=None)`: the port's parameters are `r#type` and `r#ref`, and the
        // signature has to name them the same way, or `signature = (type, ref=None)` is not
        // Rust. PyO3 shows a raw identifier to Python without its `r#`.
        let f = PortFn {
            js_name: "tag".into(),
            rust_name: "tag".into(),
            params: vec![
                ("r#type".into(), "String".into()),
                ("r#ref".into(), "Option<String>".into()),
            ],
            ret: "String".into(),
            fallible: true,
            is_async: false,
        };
        let source = [
            Param {
                name: "type".into(),
                ..Default::default()
            },
            Param {
                name: "ref".into(),
                optional: true,
                default: Some("None".into()),
                ..Default::default()
            },
        ];
        assert_eq!(signature(&f, &source), "r#type, r#ref=None");
    }

    #[test]
    fn optional_object_params_bind_as_option_bound() {
        // `thresholds=None` must bind as `Option<Bound>` so PyO3 accepts `None`;
        // required structured parameters stay a plain `Bound`, native options are untouched.
        assert_eq!(
            binding_type("Option<serde_json::Value>").as_str(),
            "Option<Bound<'_, PyAny>>"
        );
        assert_eq!(
            binding_type("serde_json::Value").as_str(),
            "Bound<'_, PyAny>"
        );
        assert_eq!(binding_type("Option<i64>").as_str(), "Option<i64>");
        assert_eq!(binding_type("String").as_str(), "String");
        // A list is native on its own but crosses as an object once it is optional
        // (`paths: Sequence[str] = ()`), so it needs `Option<Bound>` for its `=None` too.
        for optional_list in [
            "Option<Vec<String>>",
            "Option<Vec<f64>>",
            "Option<Vec<i64>>",
        ] {
            assert_eq!(binding_type(optional_list), "Option<Bound<'_, PyAny>>");
        }
        let tally = PortFn {
            js_name: "tally".into(),
            rust_name: "tally".into(),
            params: vec![("paths".into(), "Option<Vec<String>>".into())],
            ret: "i64".into(),
            fallible: true,
            is_async: false,
        };
        let converted = body(&tally, "port::tally", false);
        assert!(
            converted.contains("let paths: Option<Vec<String>> = match &paths {"),
            "{converted}"
        );
    }

    fn verdict_port() -> PortFn {
        PortFn {
            js_name: "verdict".into(),
            rust_name: "verdict".into(),
            params: vec![
                ("readings".into(), "serde_json::Value".into()),
                ("thresholds".into(), "Option<serde_json::Value>".into()),
            ],
            ret: "serde_json::Value".into(),
            fallible: true,
            is_async: false,
        }
    }

    fn verdict_manifest() -> Manifest {
        let param = |name: &str, ts_type: &str, optional: bool, default: Option<&str>| Param {
            name: name.into(),
            ts_type: ts_type.into(),
            optional,
            default: default.map(str::to_string),
            ..Default::default()
        };
        Manifest {
            schema: "1".into(),
            root: std::path::PathBuf::from("/tmp"),
            root_written: None,
            unit: "hpdet/".into(),
            language: Lang::Python,
            kind: Kind::Pyo3,
            crate_name: "hpdet-rs".into(),
            exports: vec![ExportedFn {
                name: "verdict".into(),
                file: "hpdet/verdict.py".into(),
                line: 1,
                params: vec![
                    param("readings", "Record<string, number>", false, None),
                    param("thresholds", "Thresholds | undefined", true, Some("None")),
                ],
                returns: "Record<string, number>".into(),
                ..Default::default()
            }],
            classes: Vec::new(),
            js_only: Vec::new(),
            batches: Vec::new(),
            allocator: Default::default(),
            float_tolerance: None,
            ignore_key_order: false,
            messages: false,
            end_state: None,
        }
    }

    #[test]
    fn a_keyword_argument_keeps_its_name_in_the_original() {
        // `def pad(text, maxLen=3, N=0)`: PyO3 takes `max_len` and `n`, and a caller passes
        // `maxLen=5`, so the package maps the original's names before calling `_native`.
        let mut m = verdict_manifest();
        let param = |name: &str| Param {
            name: name.into(),
            ts_type: "int".into(),
            optional: true,
            default: Some("3".into()),
            ..Default::default()
        };
        m.exports = vec![ExportedFn {
            name: "pad".into(),
            file: "cc.py".into(),
            line: 1,
            params: vec![
                Param {
                    name: "text".into(),
                    ts_type: "string".into(),
                    ..Default::default()
                },
                param("maxLen"),
                param("N"),
            ],
            returns: "string".into(),
            ..Default::default()
        }];
        let pad = PortFn {
            js_name: "pad".into(),
            rust_name: "pad".into(),
            params: vec![
                ("text".into(), "String".into()),
                ("max_len".into(), "i64".into()),
                ("n".into(), "i64".into()),
            ],
            ret: "String".into(),
            fallible: true,
            is_async: false,
        };
        let api = PortApi {
            functions: vec![pad],
            ..Default::default()
        };
        let init = package_init(&m, &api);
        assert!(init.contains("def _keywords(fn, names):"), "{init}");
        assert!(
            init.contains(
                "pad = _native.pad\npad = _keywords(pad, {'maxLen': 'max_len', 'N': 'n'})\n"
            ),
            "{init}"
        );
        // Names that are already snake_case generate the code they did.
        let plain = package_init(
            &verdict_manifest(),
            &PortApi {
                functions: vec![verdict_port()],
                ..Default::default()
            },
        );
        assert!(!plain.contains("_keywords"), "{plain}");
    }

    #[test]
    fn a_keyword_given_under_both_names_is_refused() {
        // `pad("a", maxLen=5, max_len=7)` names one parameter twice: the original raises
        // TypeError, and the mapped call must not keep whichever came last.
        let Some(python) = ["python3", "python"].into_iter().find(|p| {
            std::process::Command::new(p)
                .arg("--version")
                .output()
                .is_ok_and(|o| o.status.success())
        }) else {
            return;
        };
        let script = format!(
            "{KEYWORDS_PY}\n\
             def pad(text, max_len=3):\n    return text * max_len\n\
             pad = _keywords(pad, {{'maxLen': 'max_len'}})\n\
             assert pad('a', maxLen=2) == 'aa'\n\
             assert pad('a', max_len=2) == 'aa'\n\
             for kwargs in ({{'maxLen': 5, 'max_len': 7}}, {{'max_len': 7, 'maxLen': 5}}):\n\
             \x20   try:\n\
             \x20       pad('a', **kwargs)\n\
             \x20   except TypeError as e:\n\
             \x20       assert 'multiple values' in str(e), e\n\
             \x20   else:\n\
             \x20       raise SystemExit('accepted ' + repr(kwargs))\n\
             print('ok')\n"
        );
        let out = std::process::Command::new(python)
            .args(["-c", &script])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
    }

    #[test]
    fn registrations_name_the_crate_so_a_same_named_crate_cannot_shadow_them() {
        let constructor = PortFn {
            js_name: "constructor".into(),
            rust_name: "new".into(),
            params: Vec::new(),
            ret: "Self".into(),
            fallible: true,
            is_async: false,
        };
        let api = PortApi {
            functions: vec![verdict_port()],
            classes: vec![PortClass {
                js_name: "Hpdet".into(),
                rust_name: "Hpdet".into(),
                constructor,
                methods: Vec::new(),
            }],
            ..Default::default()
        };
        let modules = Modules {
            utf16: false,
            js: false,
        };
        let lib = lib_rs(&verdict_manifest(), &api, &modules);
        assert!(
            lib.contains("m.add_function(wrap_pyfunction!(crate::verdict_py, m)?)?;"),
            "{lib}"
        );
        assert!(lib.contains("m.add_class::<crate::Hpdet>()?;"), "{lib}");
    }

    #[test]
    fn an_export_named_like_a_generated_item_does_not_clash_with_it() {
        let export = |name: &str, ty: &str| PortFn {
            js_name: name.into(),
            rust_name: name.into(),
            params: vec![("n".into(), ty.into())],
            ret: "i64".into(),
            fallible: false,
            is_async: false,
        };
        let api = PortApi {
            functions: vec![
                export("error", "i64"),
                export("port", "i64"),
                export("native_module", "i64"),
                export("unpickled_error", "&mut Vec<i64>"),
                export("area", "i64"),
                export("area_inner", "i64"),
            ],
            ..Default::default()
        };
        let modules = Modules {
            utf16: false,
            js: false,
        };
        let lib = lib_rs(&verdict_manifest(), &api, &modules);
        let mut names: Vec<&str> = lib
            .lines()
            .filter_map(|l| l.strip_prefix("fn ").or_else(|| l.strip_prefix("pub mod ")))
            .map(|l| l.split(['(', ';', '<']).next().unwrap_or(l))
            .collect();
        names.sort_unstable();
        let before = names.len();
        names.dedup();
        assert_eq!(before, names.len(), "{lib}");
        for name in [
            "error",
            "port",
            "native_module",
            "unpickled_error",
            "area_inner",
        ] {
            assert!(
                lib.contains(&format!("#[pyo3(name = \"{name}\", signature")),
                "{lib}"
            );
        }
    }

    #[test]
    fn optional_object_wrapper_accepts_none() {
        let api = PortApi {
            functions: vec![verdict_port()],
            ..Default::default()
        };
        let modules = Modules {
            utf16: false,
            js: false,
        };
        let lib = lib_rs(&verdict_manifest(), &api, &modules);
        assert!(
            lib.contains("#![allow(clippy::too_many_arguments)]"),
            "{lib}"
        );
        // The signature still defaults to `None`, and the Rust parameter takes `Option`.
        assert!(
            lib.contains("#[pyo3(name = \"verdict\", signature = (readings, thresholds=None))]"),
            "{lib}"
        );
        assert!(
            lib.contains(
                "fn verdict_inner(readings: Bound<'_, PyAny>, \
                 thresholds: Option<Bound<'_, PyAny>>)"
            ),
            "{lib}"
        );
        // `None` converts to `None`; a value converts through the port's type.
        assert!(lib.contains("match &thresholds"), "{lib}");
        assert!(lib.contains("None => None,"), "{lib}");
        assert!(!lib.contains("from_py_with"), "{lib}");
    }

    #[test]
    fn explicit_none_for_a_non_none_default_is_not_an_argument_left_out() {
        let mut manifest = verdict_manifest();
        manifest.exports[0].params[1].default = Some("DEFAULT_THRESHOLDS".into());
        let api = PortApi {
            functions: vec![verdict_port()],
            ..Default::default()
        };
        let modules = Modules {
            utf16: false,
            js: false,
        };
        let lib = lib_rs(&manifest, &api, &modules);
        assert!(
            lib.contains("#[pyo3(name = \"verdict\", signature = (readings, thresholds=None))]"),
            "{lib}"
        );
        assert!(
            lib.contains(
                "fn verdict_py(py: Python<'_>, readings: Bound<'_, PyAny>, \
                 #[pyo3(from_py_with = crate::pyconv::given)] thresholds: Option<Bound<'_, PyAny>>)"
            ),
            "{lib}"
        );
        assert!(
            lib.contains(
                "fn verdict_inner(readings: Bound<'_, PyAny>, \
                 thresholds: Option<Bound<'_, PyAny>>)"
            ),
            "{lib}"
        );
        assert!(PYCONV_RS.contains("pub fn given<'py>"));
    }

    #[test]
    fn bytes_params_and_results_convert_directly_without_json() {
        assert!(direct("Vec<u8>"));
        assert!(direct("Option<Vec<u8>>"));
        assert!(direct("Vec<Vec<u8>>"));
        assert!(!direct("u8"));
        assert!(!direct("Option<u8>"));
        assert_eq!(binding_type("Vec<u8>"), "Bound<'_, PyAny>");
        assert_eq!(binding_type("Option<Vec<u8>>"), "Option<Bound<'_, PyAny>>");

        let crc = PortFn {
            js_name: "crc".into(),
            rust_name: "crc".into(),
            params: vec![("data".into(), "Vec<u8>".into())],
            ret: "Vec<u8>".into(),
            fallible: true,
            is_async: false,
        };
        let mut manifest = verdict_manifest();
        manifest.exports = vec![ExportedFn {
            name: "crc".into(),
            file: "geo/crc.py".into(),
            line: 1,
            params: vec![Param {
                name: "data".into(),
                ts_type: "pybytes".into(),
                ..Default::default()
            }],
            returns: "pybytes".into(),
            ..Default::default()
        }];
        let api = PortApi {
            functions: vec![crc],
            ..Default::default()
        };
        let modules = Modules {
            utf16: false,
            js: false,
        };
        let lib = lib_rs(&manifest, &api, &modules);
        assert!(
            lib.contains("fn crc_inner(data: Bound<'_, PyAny>) -> Result<Vec<u8>, String>"),
            "{lib}"
        );
        assert!(
            lib.contains("let data: Vec<u8> = crate::pyconv::FromPy::from_py(&data)?;"),
            "{lib}"
        );
        assert!(!lib.contains("serde_json::to_value"), "{lib}");
    }

    #[test]
    fn string_params_refuse_a_lone_surrogate_by_name() {
        let tally = PortFn {
            js_name: "tally".into(),
            rust_name: "tally".into(),
            params: vec![
                ("a".into(), "String".into()),
                ("tags".into(), "Vec<String>".into()),
                ("r#type".into(), "Option<String>".into()),
                (
                    "counts".into(),
                    "std::collections::HashMap<String, i64>".into(),
                ),
            ],
            ret: "i64".into(),
            fallible: true,
            is_async: false,
        };
        let mut manifest = verdict_manifest();
        manifest.exports = vec![ExportedFn {
            name: "tally".into(),
            file: "geo/tally.py".into(),
            line: 1,
            params: ["a", "tags", "type", "counts"]
                .iter()
                .map(|n| Param {
                    name: (*n).into(),
                    optional: *n == "type",
                    ..Default::default()
                })
                .collect(),
            returns: "int".into(),
            ..Default::default()
        }];
        let api = PortApi {
            functions: vec![tally],
            ..Default::default()
        };
        let modules = Modules {
            utf16: false,
            js: false,
        };
        let lib = lib_rs(&manifest, &api, &modules);
        for expected in [
            "#[pyo3(from_py_with = crate::py_str::one_a)] a: String",
            "#[pyo3(from_py_with = crate::py_str::list_tags)] tags: Vec<String>",
            "#[pyo3(from_py_with = crate::py_str::optional_type)] r#type: Option<String>",
            "pub fn one_a(obj: &Bound<'_, PyAny>) -> PyResult<String> {\n        one(obj, \"a\")",
            "pub fn optional_type(obj: &Bound<'_, PyAny>) -> PyResult<Option<String>> {",
            "crate::pyconv::FromPy::from_py(&counts).map_err(|e| crate::pyconv::argument(\"counts\", e))?;",
        ] {
            assert!(lib.contains(expected), "{expected}\n{lib}");
        }
        assert!(PYCONV_RS.contains("impl FromPy for String {"));
    }

    #[test]
    fn max_and_min_of_no_values_raise_value_error_instead_of_panicking() {
        let dir = std::env::temp_dir().join(format!("rust-anything-pynum-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("pynum.rs"), PYNUM_RS).unwrap();
        std::fs::write(
            dir.join("main.rs"),
            "mod pynum;\nuse pynum::Num;\nfn main() {\n    \
             assert_eq!(Num::max(&[]).unwrap_err(), \"ValueError: max() iterable argument is empty\");\n    \
             assert_eq!(Num::min(&[]).unwrap_err(), \"ValueError: min() iterable argument is empty\");\n    \
             assert!(matches!(Num::max(&[Num::Int(1), Num::Float(2.5)]), Ok(Num::Float(x)) if x == 2.5));\n    \
             assert!(matches!(Num::min(&[Num::Int(1), Num::Float(2.5)]), Ok(Num::Int(1))));\n}\n",
        )
        .unwrap();
        let bin = dir.join("pynum-check");
        let compiled = std::process::Command::new("rustc")
            .args(["--edition=2024", "-o"])
            .arg(&bin)
            .arg(dir.join("main.rs"))
            .output()
            .expect("rustc must run");
        assert!(
            compiled.status.success(),
            "compiling PYNUM_RS failed:\n{}",
            String::from_utf8_lossy(&compiled.stderr)
        );
        let ran = std::process::Command::new(&bin).output().unwrap();
        let _ = std::fs::remove_dir_all(&dir);
        assert!(
            ran.status.success(),
            "{}",
            String::from_utf8_lossy(&ran.stderr)
        );
    }
}