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.

103 KB
Raw Blame
//! Bridges built for real: compile the generated crate, load it from the original language and
//! replay the recording. Run on every CI platform, since linking differs between them.

mod common;

use std::path::{Path, PathBuf};
use std::process::Command;

use rust_anything::bridge::{self, Kind};
use rust_anything::harness::{self, DiffOptions, RecordOptions};

fn project(name: &str, files: &[(&str, &str)]) -> common::Scratch {
    let root = common::Scratch::new(std::env::temp_dir().join(format!(
        "rust-anything-native-{name}-{}",
        std::process::id()
    )));
    for (path, text) in files {
        let path = root.join(path);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, text).unwrap();
    }
    root
}

/// Bridge `unit`, record the original, port `name` with `body`, build, and replay.
fn round_trip(root: &Path, unit: &str, crate_name: &str, kind: Kind, name: &str, body: &str) {
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root,
        unit,
        kind: Some(kind),
        out: Some(dir.clone()),
        name: Some(crate_name.to_string()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 0, "{recorded:?}");

    let port_path = dir.join("src/port.rs");
    let port = std::fs::read_to_string(&port_path).unwrap();
    let start = port
        .find(&format!("pub fn {name}("))
        .unwrap_or_else(|| panic!("no {name} in\n{port}"));
    let open = start + port[start..].find('{').unwrap();
    let close = open + port[open..].find("\n}").unwrap();
    let ported = format!("{}{{\n    {body}{}", &port[..open], &port[close..]);
    std::fs::write(&port_path, ported).unwrap();

    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap();
    assert_eq!(
        (outcome.failed, outcome.passed),
        (0, outcome.total),
        "{:#?}",
        outcome.mismatches
    );

    std::fs::write(&port_path, std::fs::read(&port_path).unwrap()).unwrap();
    let stale = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap_err();
    assert!(
        format!("{stale:#}").contains("rust-anything build"),
        "{stale:#}"
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn napi_addon_builds_loads_and_matches_in_space_and_unicode_path() {
    if !common::have("node") {
        return;
    }
    let root = project(
        "napi path with spaces ünïcøde",
        &[
            ("package.json", r#"{"name":"shout","version":"0.1.0"}"#),
            (
                "src/shout.ts",
                "export function shout(text: string): string {\n  return text + \"!\";\n}\n",
            ),
        ],
    );
    round_trip(
        &root,
        "src/shout.ts",
        "shout-napi-rs",
        Kind::Napi,
        "shout",
        "Ok(format!(\"{text}!\"))",
    );
}

#[test]
fn pyo3_extension_builds_imports_and_matches() {
    if common::python().is_none() {
        return;
    }
    let root = project(
        "pyo3",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"shout\"\nversion = \"0.1.0\"\n",
            ),
            (
                "shout/__init__.py",
                "def shout(text: str) -> str:\n    return text + \"!\"\n",
            ),
        ],
    );
    round_trip(
        &root,
        "shout/",
        "shout-pyo3-rs",
        Kind::Pyo3,
        "shout",
        "Ok(format!(\"{text}!\"))",
    );
}

#[test]
fn pyo3_bytes_bridge_accepts_bytes_bytearray_memoryview_and_returns_bytes() {
    let Some(python) = common::python() else {
        return;
    };
    let root = project(
        "pyo3-bytes",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"crc\"\nversion = \"0.1.0\"\n",
            ),
            (
                "crc/__init__.py",
                "def xor_bytes(data: bytes, mask: int) -> bytes:\n\
                 \x20   return bytes((b ^ (mask & 0xFF)) for b in data)\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "crc/",
        kind: Some(Kind::Pyo3),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();

    let port_path = dir.join("src/port.rs");
    let port = std::fs::read_to_string(&port_path).unwrap();
    assert!(
        port.contains("pub fn xor_bytes(data: Vec<u8>, mask: i64) -> Result<Vec<u8>, String>"),
        "{port}"
    );

    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 20,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 0, "{recorded:?}");

    let start = port.find("pub fn xor_bytes(").unwrap();
    let open = start + port[start..].find('{').unwrap();
    let close = open + port[open..].find("\n}").unwrap();
    let ported = format!(
        "{}{{\n    Ok(data.into_iter().map(|b| b ^ (mask as u8)).collect()){}",
        &port[..open],
        &port[close..]
    );
    std::fs::write(&port_path, ported).unwrap();

    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap();
    assert_eq!(
        (outcome.failed, outcome.passed),
        (0, outcome.total),
        "{:#?}",
        outcome.mismatches
    );

    let check = Command::new(python)
        .env("PYTHONPATH", dir.join("python"))
        .args([
            "-c",
            "import crc_rs as m\n\
             for inp in (b'abc', bytearray(b'abc'), memoryview(b'abc'), memoryview(b'axbxc')[::2]):\n\
             \x20   out = m.xor_bytes(inp, 1)\n\
             \x20   assert type(out) is bytes, type(out)\n\
             \x20   assert out == bytes(b ^ 1 for b in b'abc'), out\n",
        ])
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "stdout: {}\nstderr: {}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr)
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn pyo3_path_bridge_takes_and_returns_pathlib_paths() {
    let Some(python) = common::python() else {
        return;
    };
    let root = project(
        "pyo3-path",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"pathkit\"\nversion = \"0.1.0\"\n",
            ),
            (
                "pathkit/__init__.py",
                "from __future__ import annotations\n\nfrom pathlib import Path\n\n\n\
                 def stem_of(file: Path) -> str:\n\
                 \x20   return file.stem\n\n\n\
                 def same(file: Path) -> Path:\n\
                 \x20   return file\n\n\n\
                 def maybe(file: Path | None) -> Path | None:\n\
                 \x20   return file\n\n\n\
                 def tagged(info: dict) -> dict:\n\
                 \x20   return info\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "pathkit/",
        kind: Some(Kind::Pyo3),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();

    let port_path = dir.join("src/port.rs");
    let mut port = std::fs::read_to_string(&port_path).unwrap();
    for signature in [
        "pub fn stem_of(file: std::path::PathBuf) -> Result<String, String>",
        "pub fn same(file: std::path::PathBuf) -> Result<std::path::PathBuf, String>",
        "pub fn maybe(file: Option<std::path::PathBuf>) -> Result<Option<std::path::PathBuf>, String>",
    ] {
        assert!(port.contains(signature), "{signature}\n{port}");
    }

    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 20,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 0, "{recorded:?}");
    // Every case calls the original with a real path, and a returned path keeps its text. The
    // path checked has no separator: Windows records `src\main.py` for `src/main.py`.
    // `post` says the line also holds what the call changed and printed: nothing, here.
    let cases = std::fs::read_to_string(dir.join("cases.jsonl"))
        .unwrap()
        .replace(r#", "post": true"#, "");
    assert!(!cases.contains("AttributeError"), "{cases}");
    assert!(!cases.contains("$repr"), "{cases}");
    assert!(
        cases.contains(
            r#"{"fn": "same", "args": [{"$path": "notes.txt"}], "ok": {"$path": "notes.txt"}}"#
        ),
        "{cases}"
    );
    assert!(
        cases.contains(
            r#"{"fn": "stem_of", "args": [{"$path": "/tmp/report.tar.gz"}], "ok": "report.tar"}"#
        ),
        "{cases}"
    );

    for (name, body) in [
        (
            "stem_of",
            "Ok(file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default())",
        ),
        ("same", "Ok(file)"),
        ("maybe", "Ok(file)"),
        ("tagged", "Ok(info)"),
    ] {
        let start = port.find(&format!("pub fn {name}(")).unwrap();
        let open = start + port[start..].find('{').unwrap();
        let close = open + port[open..].find("\n}").unwrap();
        port = format!("{}{{\n    {body}{}", &port[..open], &port[close..]);
    }
    std::fs::write(&port_path, port).unwrap();

    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap();
    assert_eq!(
        (outcome.failed, outcome.passed),
        (0, outcome.total),
        "{:#?}",
        outcome.mismatches
    );

    let check = Command::new(python)
        .env("PYTHONPATH", dir.join("python"))
        .args([
            "-c",
            "import pathkit_rs as m\n\
             from pathlib import Path, PurePosixPath\n\
             out = m.same(Path('a') / 'b.txt')\n\
             assert isinstance(out, Path) and out == Path('a/b.txt'), out\n\
             assert m.stem_of(PurePosixPath('x/y.tar.gz')) == 'y.tar'\n\
             assert m.maybe(None) is None\n\
             import os\n\
             if os.name == 'posix':\n\
             \x20   odd = Path(os.fsdecode(b'bad-\\xff.txt'))\n\
             \x20   assert m.same(odd) == odd, m.same(odd)\n\
             \x20   assert m.tagged({'file': odd}) == {'file': odd}\n\
             assert m.tagged({'file': Path('a.txt')}) == {'file': Path('a.txt')}\n\
             try:\n\
             \x20   m.stem_of('a.txt')\n\
             except TypeError as error:\n\
             \x20   assert 'str' in str(error), error\n\
             else:\n\
             \x20   raise AssertionError('a str is not a path')\n",
        ])
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "stdout: {}\nstderr: {}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr)
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn pyo3_lone_surrogates_round_trip_through_utf16_marker() {
    let Some(python) = common::python() else {
        return;
    };
    let root = project(
        "pyo3-utf16",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"surrokit\"\nversion = \"0.1.0\"\n",
            ),
            (
                "surrokit/__init__.py",
                "def echo(s):\n\
                 \x20   return s\n\n\n\
                 def decode_surrogateescape(data: bytes):\n\
                 \x20   return data.decode(\"utf-8\", errors=\"surrogateescape\")\n\n\n\
                 def tagged(info: dict) -> dict:\n\
                 \x20   return info\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "surrokit/",
        kind: Some(Kind::Pyo3),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();

    let inputs = root.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\": \"echo\", \"args\": [{\"$utf16\": [97, 56553, 98]}]}\n\
         {\"fn\": \"decode_surrogateescape\", \"args\": [{\"$bytes\": [97, 233, 98]}]}\n\
         {\"fn\": \"tagged\", \"args\": [{\"$dict\": [[{\"$utf16\": [56553]}, {\"$utf16\": [55296]}]]}]}\n",
    )
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 0,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert_eq!(recorded.cases, 3, "{recorded:?}");
    let cases = std::fs::read_to_string(dir.join("cases.jsonl")).unwrap();
    assert!(
        cases.contains(r#""ok": {"$utf16": [97, 56553, 98]}"#),
        "{cases}"
    );
    assert!(
        cases.contains(r#""ok": {"$dict": [[{"$utf16": [56553]}, {"$utf16": [55296]}]]}"#),
        "{cases}"
    );

    let port_path = dir.join("src/port.rs");
    let mut port = std::fs::read_to_string(&port_path).unwrap();
    let decode_body = "let mut units = Vec::new();\n    \
                       for chunk in data.utf8_chunks() {\n        \
                           units.extend(chunk.valid().encode_utf16());\n        \
                           for &b in chunk.invalid() {\n            \
                               units.push(0xDC00 + u16::from(b));\n        \
                           }\n    \
                       }\n    \
                       Ok(crate::js::utf16_string(&units))";
    for (name, body) in [
        ("echo", "Ok(s)"),
        ("decode_surrogateescape", decode_body),
        ("tagged", "Ok(info)"),
    ] {
        let start = port.find(&format!("pub fn {name}(")).unwrap();
        let open = start + port[start..].find('{').unwrap();
        let close = open + port[open..].find("\n}").unwrap();
        port = format!("{}{{\n    {body}{}", &port[..open], &port[close..]);
    }
    std::fs::write(&port_path, port).unwrap();

    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap();
    assert_eq!(
        (outcome.failed, outcome.passed),
        (0, outcome.total),
        "{:#?}",
        outcome.mismatches
    );

    let check = Command::new(python)
        .env("PYTHONPATH", dir.join("python"))
        .args([
            "-c",
            "import surrokit_rs as m\n\
             odd = b'hi-\\xe9-\\xff'.decode('utf-8', 'surrogateescape')\n\
             assert type(m.echo(odd)) is str and m.echo(odd) == odd, repr(m.echo(odd))\n\
             mixed = 'a\\U0001f600\\udce9\\ud800b'\n\
             assert m.echo(mixed) == mixed, repr(m.echo(mixed))\n\
             assert m.decode_surrogateescape(b'hi-\\xe9-\\xff') == odd\n\
             assert m.tagged({odd: [mixed, (odd,)]}) == {odd: [mixed, (odd,)]}\n\
             assert m.tagged({'$utf16': 'literal'}) == {'$utf16': 'literal'}\n\
             assert m.tagged({'$utf16': [97]}) == 'a'\n\
             for bad in ([70000], [-1], [True], [70000, 'x']):\n\
             \x20   got = m.tagged({'$utf16': bad})\n\
             \x20   assert got == {'$utf16': bad}, (bad, got)\n\
             assert m.tagged({'$tuple': [1, 'a']}) == (1, 'a')\n\
             for same in ({'k': (1, [2, (3, 'x')]), 'n': None}, {1: 'a', 'b': (2,)}, {'one': ({'s'},)},\n\
             \x20            [{'x'}, b'ab', 2 ** 70, -1.5, True], [(i, str(i)) for i in range(3000)]):\n\
             \x20   got = m.tagged(same)\n\
             \x20   assert got == same and repr(got) == repr(same), (same, got)\n",
        ])
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "stdout: {}\nstderr: {}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr)
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn pyo3_a_surrogate_pair_of_code_points_stays_apart_from_the_astral_character() {
    // Issue #1477: "\udc00\ud800\udc00" (three code points) and "\udc00\U00010000" (two) have
    // the same UTF-16 units, so `$utf16` recorded and bridged them alike.
    let Some(python) = common::python() else {
        return;
    };
    let root = project(
        "pyo3-codepoints",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"pairkit\"\nversion = \"0.1.0\"\n",
            ),
            ("pairkit/__init__.py", "def echo(s):\n    return s\n"),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "pairkit/",
        kind: Some(Kind::Pyo3),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();

    let inputs = root.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\": \"echo\", \"args\": [{\"$codepoints\": [56320, 55296, 56320]}]}\n\
         {\"fn\": \"echo\", \"args\": [{\"$utf16\": [56320, 55296, 56320]}]}\n",
    )
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 0,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert_eq!(recorded.cases, 2, "{recorded:?}");
    let cases = std::fs::read_to_string(dir.join("cases.jsonl")).unwrap();
    assert!(
        cases.contains(r#""ok": {"$codepoints": [56320, 55296, 56320]}"#),
        "{cases}"
    );
    assert!(
        cases.contains(r#""ok": {"$utf16": [56320, 55296, 56320]}"#),
        "{cases}"
    );

    let port_path = dir.join("src/port.rs");
    let original = std::fs::read_to_string(&port_path).unwrap();
    let with_body = |body: &str| {
        let start = original.find("pub fn echo(").unwrap();
        let open = start + original[start..].find('{').unwrap();
        let close = open + original[open..].find("\n}").unwrap();
        format!("{}{{\n    {body}{}", &original[..open], &original[close..])
    };
    let diff = || {
        harness::build(&dir).unwrap();
        harness::diff(&DiffOptions {
            crate_dir: &dir,
            module: None,
            ignore_key_order: false,
            node_args: &[],
            float_tolerance: None,
        })
        .unwrap()
    };

    std::fs::write(&port_path, with_body("Ok(s)")).unwrap();
    let outcome = diff();
    assert_eq!(
        (outcome.failed, outcome.passed),
        (0, 2),
        "{:#?}",
        outcome.mismatches
    );

    let check = Command::new(python)
        .env("PYTHONPATH", dir.join("python"))
        .args([
            "-c",
            "import pairkit_rs as m\n\
             pair = chr(0xDC00) + chr(0xD800) + chr(0xDC00)\n\
             astral = chr(0xDC00) + chr(0x10000)\n\
             assert [ord(c) for c in m.echo(pair)] == [0xDC00, 0xD800, 0xDC00], repr(m.echo(pair))\n\
             assert [ord(c) for c in m.echo(astral)] == [0xDC00, 0x10000], repr(m.echo(astral))\n",
        ])
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "stdout: {}\nstderr: {}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr)
    );

    // A port that folds the code points into UTF-16 units, as the bridge used to, is not exact.
    let folding = "Ok(match s.get(\"$codepoints\").and_then(|v| v.as_array()) {\n        \
                   Some(points) => {\n            \
                       let mut units: Vec<u64> = Vec::new();\n            \
                       for p in points.iter().filter_map(|p| p.as_u64()) {\n                \
                           if p > 0xFFFF {\n                    \
                               units.push(0xD800 + ((p - 0x10000) >> 10));\n                    \
                               units.push(0xDC00 + ((p - 0x10000) & 0x3FF));\n                \
                           } else {\n                    \
                               units.push(p);\n                \
                           }\n            \
                       }\n            \
                       serde_json::json!({ \"$utf16\": units })\n        \
                   }\n        \
                   None => s,\n    \
                   })";
    std::fs::write(&port_path, with_body(folding)).unwrap();
    let outcome = diff();
    assert_eq!(
        (outcome.failed, outcome.passed),
        (1, 1),
        "{:#?}",
        outcome.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn pyo3_lone_surrogate_in_a_string_parameter_is_refused_by_name() {
    let Some(python) = common::python() else {
        return;
    };
    let root = project(
        "pyo3-utf16-typed",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"scorekit\"\nversion = \"0.1.0\"\n",
            ),
            (
                "scorekit/__init__.py",
                "def score(a: str, b: str) -> int:\n\
                 \x20   return len(a) + len(b)\n\n\n\
                 def total(words: list[str]) -> int:\n\
                 \x20   return len(words)\n\n\n\
                 def size(counts: dict[str, int]) -> int:\n\
                 \x20   return len(counts)\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "scorekit/",
        kind: Some(Kind::Pyo3),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();

    let inputs = root.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\": \"score\", \"args\": [\"ab\", \"c\"]}\n\
         {\"fn\": \"score\", \"args\": [{\"$utf16\": [97, 56553]}, \"c\"]}\n\
         {\"fn\": \"total\", \"args\": [[\"x\", {\"$utf16\": [55296]}]]}\n\
         {\"fn\": \"size\", \"args\": [{\"$dict\": [[{\"$utf16\": [56553]}, 1]]}]}\n",
    )
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 0,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert_eq!(recorded.cases, 4, "{recorded:?}");

    let port_path = dir.join("src/port.rs");
    let mut port = std::fs::read_to_string(&port_path).unwrap();
    for (name, body) in [
        (
            "score",
            "Ok((a.chars().count() + b.chars().count()) as i64)",
        ),
        ("total", "Ok(words.len() as i64)"),
        ("size", "Ok(counts.len() as i64)"),
    ] {
        let start = port.find(&format!("pub fn {name}(")).unwrap();
        let open = start + port[start..].find('{').unwrap();
        let close = open + port[open..].find("\n}").unwrap();
        port = format!("{}{{\n    {body}{}", &port[..open], &port[close..]);
    }
    assert!(port.contains("counts: serde_json::Value"), "{port}");
    let port = port.replacen(
        "counts: serde_json::Value",
        "counts: std::collections::HashMap<String, i64>",
        1,
    );
    std::fs::write(&port_path, port).unwrap();
    bridge::refresh(&dir).unwrap();

    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap();
    assert_eq!((outcome.passed, outcome.failed), (1, 3), "{outcome:#?}");
    let shown = serde_json::to_string(&outcome.mismatches).unwrap();
    for name in ["'a'", "'words'", "'counts'"] {
        assert!(
            shown.contains(&format!(
                "argument {name}: str holds a lone surrogate, which a Rust String cannot hold"
            )),
            "{shown}"
        );
    }

    let check = Command::new(python)
        .env("PYTHONPATH", dir.join("python"))
        .args([
            "-c",
            "import scorekit_rs as m\n\
             odd = b'hi-\\xe9'.decode('utf-8', 'surrogateescape')\n\
             assert m.score('ab', 'c') == 3\n\
             for call, name in ((lambda: m.score('x', odd), 'b'), (lambda: m.total(['x', odd]), 'words'), (lambda: m.size({odd: 1}), 'counts')):\n\
             \x20   try:\n\
             \x20       call()\n\
             \x20   except TypeError as e:\n\
             \x20       want = f\"argument '{name}': str holds a lone surrogate, which a Rust String cannot hold\"\n\
             \x20       assert str(e).startswith(want), str(e)\n\
             \x20   else:\n\
             \x20       raise AssertionError(name)\n",
        ])
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "stdout: {}\nstderr: {}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr)
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn pyo3_required_optional_parameter_is_passed_none_not_left_out() {
    if common::python().is_none() {
        return;
    }
    let root = project(
        "pyo3-required-optional",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"pickkit\"\nversion = \"0.1.0\"\n",
            ),
            (
                "pickkit/__init__.py",
                "from __future__ import annotations\n\n\n\
                 def pick(text: str, fallback: str | None) -> str:\n\
                 \x20   return text if fallback is None else fallback\n\n\n\
                 def tag(name: str, suffix: str | None = None) -> str:\n\
                 \x20   return name + (\"\" if suffix is None else suffix)\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "pickkit/",
        kind: Some(Kind::Pyo3),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 20,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    // `pick` has no default for `fallback`: the original is called with `None`, not without it.
    let cases = std::fs::read_to_string(dir.join("cases.jsonl")).unwrap();
    assert!(!cases.contains("missing 1 required positional"), "{cases}");
    let none_passed = cases.lines().any(|line| {
        line.contains(r#""fn": "pick""#) && line.contains(r#"{"$undefined": true}], "ok""#)
    });
    assert!(none_passed, "no `pick(text, None)` case:\n{cases}");

    let port_path = dir.join("src/port.rs");
    let mut port = std::fs::read_to_string(&port_path).unwrap();
    for (name, body) in [
        ("pick", "Ok(fallback.unwrap_or(text))"),
        (
            "tag",
            "Ok(format!(\"{name}{}\", suffix.unwrap_or_default()))",
        ),
    ] {
        let start = port.find(&format!("pub fn {name}(")).unwrap();
        let open = start + port[start..].find('{').unwrap();
        let close = open + port[open..].find("\n}").unwrap();
        port = format!("{}{{\n    {body}{}", &port[..open], &port[close..]);
    }
    std::fs::write(&port_path, port).unwrap();
    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap();
    assert_eq!(
        (outcome.failed, outcome.passed),
        (0, outcome.total),
        "{:#?}",
        outcome.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn pyo3_dataclass_argument_crosses_as_its_fields() {
    let Some(python) = common::python() else {
        return;
    };
    let root = project(
        "pyo3-dataclass",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"shop\"\nversion = \"0.1.0\"\n",
            ),
            (
                "shop/__init__.py",
                "from dataclasses import dataclass\n\n\n\
                 @dataclass\nclass Item:\n    name: str\n    count: int\n\n\n\
                 def label(item: Item) -> str:\n    return f\"{item.count} x {item.name}\"\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "shop/",
        kind: Some(Kind::Pyo3),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();

    let port_path = dir.join("src/port.rs");
    let port = std::fs::read_to_string(&port_path).unwrap();
    let start = port
        .find("pub fn label(item: serde_json::Value) -> Result<String, String>")
        .unwrap_or_else(|| panic!("{port}"));
    let open = start + port[start..].find('{').unwrap();
    let close = open + port[open..].find("\n}").unwrap();
    // The recorder writes an instance as `{"$object": name, "attrs": {...}}`; the port reads that.
    let ported = format!(
        "{}{{\n    let attrs = &item[\"attrs\"];\n    Ok(format!(\"{{}} x {{}}\", attrs[\"count\"], attrs[\"name\"].as_str().unwrap_or_default())){}",
        &port[..open],
        &port[close..]
    );
    std::fs::write(&port_path, ported).unwrap();
    harness::build(&dir).unwrap();

    // What a caller of the shadow module passes is the instance itself.
    let paths = std::env::join_paths([dir.join("python"), root.to_path_buf()]).unwrap();
    let check = Command::new(python)
        .env("PYTHONPATH", paths)
        .args([
            "-c",
            "import shop_rs as m\nfrom shop import Item\n\
             out = m.label(Item('nut', 3))\nassert out == '3 x nut', out\n\
             loop = Item('nut', 3)\nloop.name = loop  # a field that refers back to its object\n\
             out = m.label(loop)\nassert out == '3 x ', out\n\
             shared = Item('nut', 3)\npair = Item(shared, 3)\npair.count = shared  # twice, no cycle\n\
             assert m.label(pair).endswith(' x '), m.label(pair)\n",
        ])
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "stdout: {}\nstderr: {}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr)
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn pyo3_float_param_with_integer_default_builds_and_matches() {
    if common::python().is_none() {
        return;
    }
    let root = project(
        "pyo3-float-default",
        &[(
            "scale.py",
            "def scale(x: float, factor: float = 2) -> float:\n    return float(x) * float(factor)\n",
        )],
    );
    round_trip(
        &root,
        "scale.py",
        "scale-rs",
        Kind::Pyo3,
        "scale",
        "Ok(x * factor)",
    );
}

#[test]
fn pyo3_explicit_none_for_a_non_none_default_reaches_the_port_as_null() {
    if common::python().is_none() {
        return;
    }
    let root = project(
        "pyo3-explicit-none",
        &[(
            "sky.py",
            "import math\nLAT = 44.0\n\n\n\
             def to_az_el(dec: float, ha: float, lat=LAT) -> float:\n\
             \x20   p = math.radians(lat)\n\
             \x20   return math.sin(p) * dec + ha\n",
        )],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "sky.py",
        kind: Some(Kind::Pyo3),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    let cases = std::fs::read_to_string(dir.join("cases.jsonl")).unwrap();
    assert!(
        cases.contains(r#"null], "error": "TypeError: must be real number, not NoneType""#),
        "no `to_az_el(dec, ha, None)` case:\n{cases}"
    );
    let omitted = cases.lines().any(|line| {
        let case: serde_json::Value = serde_json::from_str(line).unwrap();
        let args = case["args"].as_array().unwrap();
        case.get("ok").is_some()
            && (args.len() == 2 || args[2] == serde_json::json!({"$undefined": true}))
    });
    assert!(omitted, "no `to_az_el(dec, ha)` case:\n{cases}");

    let port_path = dir.join("src/port.rs");
    let port = std::fs::read_to_string(&port_path).unwrap();
    let start = port
        .find("pub fn to_az_el(dec: f64, ha: f64, lat: Option<serde_json::Value>)")
        .unwrap_or_else(|| panic!("{port}"));
    let open = start + port[start..].find('{').unwrap();
    let close = open + port[open..].find("\n}").unwrap();
    let body = "use serde_json::Value;\n    \
        let lat = match lat {\n        \
            None => 44.0,\n        \
            Some(Value::Bool(b)) => f64::from(u8::from(b)),\n        \
            Some(Value::Number(n)) => n.as_f64().unwrap_or_default(),\n        \
            Some(other) => {\n            \
                let kind = match other {\n                \
                    Value::Null => \"NoneType\",\n                \
                    Value::String(_) => \"str\",\n                \
                    Value::Array(_) => \"list\",\n                \
                    _ => \"dict\",\n            \
                };\n            \
                return Err(format!(\"TypeError: must be real number, not {kind}\"));\n        \
            }\n    \
        };\n    \
        Ok(lat.to_radians().sin() * dec + ha)";
    std::fs::write(
        &port_path,
        format!("{}{{\n    {body}{}", &port[..open], &port[close..]),
    )
    .unwrap();
    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap();
    assert_eq!(
        (outcome.failed, outcome.passed),
        (0, outcome.total),
        "{:#?}",
        outcome.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}

/// A freshly bridged crate is all `unimplemented!` stubs: replaying it must pass no case, even
/// where the original throws the same kind of error a panic turns into.
fn stubs_fail(root: &Path, unit: &str, name: &str, kind: Option<Kind>, program: &str) {
    if !common::have(program) {
        return;
    }
    let dir = std::env::temp_dir().join(format!(
        "rust-anything-stubs-{}-{}",
        root.file_name().unwrap().to_string_lossy(),
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&dir);
    let _gone = common::Scratch(dir.clone());
    bridge::bridge(&bridge::Options {
        root,
        unit,
        kind,
        out: Some(dir.clone()),
        name: Some(name.to_string()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 20,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(
        recorded.errors > 0,
        "{}: no recorded case throws, so this proves nothing",
        root.display()
    );
    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap();
    std::fs::remove_dir_all(&dir).unwrap();
    assert_eq!(outcome.passed, 0, "a stub matched {outcome:#?}");
}

fn fixture(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(name)
}

#[test]
fn unported_stubs_never_match_in_typescript() {
    stubs_fail(
        &fixture("classes"),
        "src/stats.ts",
        "stats-rs",
        Some(Kind::Napi),
        "node",
    );
}

#[test]
fn unported_stubs_never_match_in_python() {
    let Some(python) = common::python() else {
        return;
    };
    stubs_fail(
        &fixture("python"),
        "src/textkit/",
        "textkit-rs",
        None,
        python,
    );
}

#[test]
fn unported_stubs_never_match_a_ruby_runtime_error() {
    if cfg!(windows) {
        eprintln!(
            "skipped: RubyInstaller's Ruby is built with MinGW, and an MSVC Rust extension cannot load into it"
        );
        return;
    }
    if !common::have_ruby_3() {
        return;
    }
    let root = project(
        "stubs-ruby",
        &[
            ("shout.gemspec", ""),
            (
                "lib/shout.rb",
                "module Shout\n  def self.shout(s)\n    raise \"empty\" if s.empty?\n    s + \"!\"\n  end\nend\n",
            ),
        ],
    );
    stubs_fail(&root, "lib/shout.rb", "shout-ruby-rs", None, "ruby");
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn unported_stubs_never_match_a_java_runtime_exception() {
    let root = project(
        "stubs-java",
        &[
            (
                "pom.xml",
                "<project xmlns=\"http://maven.apache.org/POM/4.0.0\">\n  <modelVersion>4.0.0</modelVersion>\n  <groupId>com.example</groupId>\n  <artifactId>shout</artifactId>\n  <version>0.1.0</version>\n</project>\n",
            ),
            (
                "src/main/java/com/example/shout/Shout.java",
                "package com.example.shout;\n\npublic final class Shout {\n    public static String shout(String s) {\n        if (s.isEmpty()) {\n            throw new RuntimeException(\"empty\");\n        }\n        return s + \"!\";\n    }\n}\n",
            ),
        ],
    );
    stubs_fail(
        &root,
        "src/main/java/com/example/shout/",
        "shout-java-rs",
        None,
        "java",
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn unported_stubs_never_match_a_go_panic() {
    let root = project(
        "stubs-go",
        &[
            ("go.mod", "module example.com/shout\n\ngo 1.22\n"),
            (
                "shout/shout.go",
                "package shout\n\nfunc Shout(s string) string {\n\tif s == \"\" {\n\t\tpanic(\"empty\")\n\t}\n\treturn s + \"!\"\n}\n",
            ),
        ],
    );
    stubs_fail(&root, "shout/", "shout-go-rs", None, "go");
    std::fs::remove_dir_all(root).unwrap();
}

/// A `uint64` parameter crosses as JSON, not through the typed entry points: a Rust panic there
/// used to carry no `Rust panic:` text, so it matched a recorded Go panic.
#[test]
fn unported_stubs_never_match_a_go_panic_on_the_json_path() {
    let root = project(
        "stubs-go-json",
        &[
            ("go.mod", "module example.com/bang\n\ngo 1.22\n"),
            (
                "bang/bang.go",
                "package bang\n\nfunc Bang(n uint64) string {\n\tif n == 0 {\n\t\tpanic(\"zero\")\n\t}\n\treturn \"!\"\n}\n",
            ),
        ],
    );
    stubs_fail(&root, "bang/", "bang-rs", None, "go");
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn napi_errors_keep_their_class_and_async_exports_reject() {
    if !common::have("node") {
        return;
    }
    let root = project(
        "napi-errors",
        &[
            ("package.json", r#"{"name":"guard","version":"0.1.0"}"#),
            (
                "src/guard.ts",
                "export function check(text: string): string {\n  if (text === '') throw new TypeError('empty');\n  return text;\n}\n\
                 export async function later(text: string): Promise<string> {\n  return text;\n}\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/guard.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: Some("guard-napi-rs".to_string()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    let port = port
        .replacen(
            "unimplemented!(\"port `check` from src/guard.ts\")",
            "if text.is_empty() { return Err(\"TypeError: empty\".into()); }\n    Ok(text)",
            1,
        )
        .replacen(
            "unimplemented!(\"port `later` from src/guard.ts\")",
            "panic!(\"boom\")",
            1,
        );
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    harness::build(&dir).unwrap();
    let script = r#"
const m = require(process.argv[1])
const out = []
try { m.check('') } catch (e) { out.push(e instanceof TypeError, e.message) }
try { m.check('a\uD800') } catch (e) { out.push(e instanceof TypeError && /lone surrogate/.test(e.message)) }
let threw = false
const p = (() => { try { return m.later(5) } catch { threw = true } })()
out.push(!threw && p instanceof Promise)
;(p ? p.catch(e => e.name) : Promise.resolve(null)).then(name => {
  out.push(name)
  return m.later('x').catch(e => e.code)
}).then(code => { out.push(code); console.log(JSON.stringify(out)) })
"#;
    let output = Command::new("node")
        .args(["-e", script])
        .arg(dir.join("index.cjs"))
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(
        stdout.trim(),
        r#"[true,"empty",true,true,"TypeError","RUST_PANIC"]"#,
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn napi_wire_survives_a_second_load_a_reentrant_getter_and_a_proto_key() {
    if !common::have("node") {
        return;
    }
    let root = project(
        "napi-wire-state",
        &[
            ("package.json", r#"{"name":"geo","version":"0.1.0"}"#),
            (
                "src/geo.ts",
                "export interface Rect { w: number; h: number }\n\
                 export function area(r: Rect): number {\n  return r.w * r.h\n}\n\
                 export function tally(words: string[]): Record<string, number> {\n  \
                 const out: Record<string, number> = Object.create(null)\n  \
                 for (const w of words) out[w] = (out[w] ?? 0) + 1\n  return out\n}\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/geo.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let mut port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    for (name, body) in [
        (
            "area",
            "Ok(r[\"w\"].as_f64().unwrap_or(f64::NAN) * r[\"h\"].as_f64().unwrap_or(f64::NAN))",
        ),
        (
            "tally",
            "let mut m = serde_json::Map::new();\n    \
             for w in words {\n        \
             let n = m.get(&w).and_then(|v| v.as_f64()).unwrap_or(0.0) + 1.0;\n        \
             m.insert(w, serde_json::json!(n));\n    }\n    \
             Ok(serde_json::Value::Object(m))",
        ),
    ] {
        let stub = format!("unimplemented!(\"port `{name}` from src/geo.ts\")");
        assert!(port.contains(&stub), "{port}");
        port = port.replacen(&stub, body, 1);
    }
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    harness::build(&dir).unwrap();
    let script = r#"
const idx = require.resolve(process.argv[1])
const a = require(idx)
delete require.cache[idx]
const b = require(idx)
const out = [b.area({ w: 10, h: 10 }), a.area({ w: 4, h: 5 }), b.area({ w: 3, h: 3 })]
const arg = { get w() { a.area({ w: 5, h: 7 }); return 2 }, h: 3 }
out.push(a.area(arg))
const t = a.tally(['__proto__', 'a', '__proto__'])
out.push(Object.keys(t).join(','), t['__proto__'], Object.getPrototypeOf(t) === Object.prototype)
console.log(JSON.stringify(out))
"#;
    let output = Command::new("node")
        .args(["-e", script])
        .arg(dir.join("index.cjs"))
        .output()
        .unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        r#"[100,20,9,6,"__proto__,a",2,true]"#,
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn napi_carries_bytes_maps_sets_dates_and_bigints() {
    if !common::have("node") {
        return;
    }
    let root = project(
        "napi-types",
        &[
            ("package.json", r#"{"name":"types","version":"0.1.0"}"#),
            (
                "src/types.ts",
                "export function size(m: Map<string, number>): number { return m.size }\n\
                 export function echo(b: Uint8Array): Uint8Array { return b }\n\
                 export function big(n: bigint): bigint { return n * 2n }\n\
                 export function day(d: Date): Date { return d }\n\
                 export function keys(s: Set<string>): Set<string> { return s }\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/types.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let mut port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    for (name, body) in [
        (
            "size",
            "Ok(m[\"$map\"].as_array().map_or(0, Vec::len) as f64)",
        ),
        ("echo", "Ok(b)"),
        (
            "big",
            "let n: i128 = n[\"$bigint\"].as_str().ok_or(\"not a bigint\")?.parse().map_err(|e| format!(\"{e}\"))?;\n    Ok(serde_json::json!({ \"$bigint\": (n * 2).to_string() }))",
        ),
        ("day", "Ok(d)"),
        ("keys", "Ok(s)"),
    ] {
        let stub = format!("unimplemented!(\"port `{name}` from src/types.ts\")");
        assert!(port.contains(&stub), "{port}");
        port = port.replacen(&stub, body, 1);
    }
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    harness::build(&dir).unwrap();
    let script = r#"
const m = require(process.argv[1])
const bytes = m.echo(new Uint8Array([0, 7, 255]))
const buffer = m.echo(Buffer.from('hi'))
const when = new Date('2024-02-29T12:00:00.000Z')
console.log(JSON.stringify([
  m.size(new Map([['a', 1], ['b', 2]])),
  bytes instanceof Uint8Array && [...bytes].join(','),
  Buffer.isBuffer(buffer) && buffer.toString(),
  String(m.big(9007199254740993n)),
  m.day(when) instanceof Date && m.day(when).getTime() === when.getTime(),
  [...m.keys(new Set(['x', 'y']))].join(','),
]))
"#;
    let output = Command::new("node")
        .args(["-e", script])
        .arg(dir.join("index.cjs"))
        .output()
        .unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        r#"[2,"0,7,255","hi","18014398509481986",true,"x,y"]"#,
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn java_records_with_the_bridge_crate_inside_the_project() {
    if !common::have("javac") {
        return;
    }
    let root = project(
        "java-default-out",
        &[
            (
                "pom.xml",
                "<project xmlns=\"http://maven.apache.org/POM/4.0.0\">\n  <modelVersion>4.0.0</modelVersion>\n  <groupId>com.example</groupId>\n  <artifactId>smoke</artifactId>\n  <version>0.1.0</version>\n</project>\n",
            ),
            (
                "src/main/java/com/example/smoke/TextKit.java",
                "package com.example.smoke;\n\npublic final class TextKit {\n    public static int wordCount(String s) {\n        return s.isBlank() ? 0 : s.trim().split(\"\\\\s+\").length;\n    }\n}\n",
            ),
        ],
    );
    let outcome = bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/main/java/com/example/smoke/",
        kind: None,
        out: None,
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    assert!(outcome.crate_dir.ends_with("rust/smoke-rs"), "{outcome:?}");
    let recorded = harness::record(&RecordOptions {
        crate_dir: &outcome.crate_dir,
        count: 10,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert!(recorded.cases > 0, "{recorded:?}");
}

fn bridge_python(root: &Path, unit: &str) -> anyhow::Result<bridge::Outcome> {
    bridge::bridge(&bridge::Options {
        root,
        unit,
        kind: None,
        out: Some(root.join("port")),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
}

#[test]
fn a_name_defined_twice_in_a_unit_is_refused() {
    let root = project(
        "twice",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"hp\"\nversion = \"0.1.0\"\n",
            ),
            (
                "hp/__init__.py",
                "from . import verdict as _v\n\ndef verdict(*args, **options):\n    return _v.verdict(*args, **options)\n",
            ),
            (
                "hp/verdict.py",
                "def verdict(score: int) -> str:\n    return \"ok\" if score > 0 else \"no\"\n",
            ),
        ],
    );
    let err = bridge_python(&root, "hp/").unwrap_err();
    std::fs::remove_dir_all(&root).unwrap();
    let text = format!("{err:#}");
    assert!(text.contains("`verdict` is defined twice"), "{text}");
    assert!(
        text.contains("hp/__init__.py") && text.contains("hp/verdict.py"),
        "{text}"
    );
}

#[test]
fn cli_entry_points_stay_in_python() {
    let root = project(
        "entry",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"tool\"\nversion = \"0.1.0\"\n",
            ),
            (
                "tool/cli.py",
                "import argparse\n\n\
                 def build_parser() -> argparse.ArgumentParser:\n    return argparse.ArgumentParser()\n\n\
                 def shout(text: str) -> str:\n    return text.upper()\n\n\
                 def main() -> int:\n    build_parser().parse_args()\n    return 0\n\n\
                 if __name__ == \"__main__\":\n    raise SystemExit(main())\n",
            ),
        ],
    );
    let outcome = bridge_python(&root, "tool/").unwrap();
    let manifest = rust_anything::bridge::Manifest::load(&outcome.crate_dir).unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(outcome.exports, ["shout"]);
    let kept: Vec<&str> = manifest.js_only.iter().map(|j| j.name.as_str()).collect();
    assert_eq!(kept, ["build_parser", "main"]);
    assert!(
        manifest.js_only[0]
            .reason
            .contains("command-line entry point")
    );
}

#[test]
fn dataclass_parameters_get_real_instances() {
    if !common::have("python3") {
        return;
    }
    let root = project(
        "dataclass",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"clip\"\nversion = \"0.1.0\"\n",
            ),
            ("clip/__init__.py", ""),
            (
                "clip/models.py",
                "from dataclasses import dataclass\n\n\
                 @dataclass\nclass Limits:\n    low: int\n    high: int = 10\n",
            ),
            (
                "clip/ops.py",
                "from .models import Limits\n\n\
                 def clamp(value: int, limits: Limits) -> int:\n    return max(limits.low, min(value, limits.high))\n",
            ),
        ],
    );
    let outcome = bridge_python(&root, "clip/").unwrap();
    harness::record(&RecordOptions {
        crate_dir: &outcome.crate_dir,
        count: 40,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    let cases = std::fs::read_to_string(outcome.crate_dir.join("cases.jsonl")).unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    let with_instance = cases
        .lines()
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .filter(|c| c["fn"] == "clamp")
        .filter(|c| c["args"][1]["$object"] == "Limits" && c.get("ok").is_some())
        .count();
    assert!(
        with_instance >= 5,
        "only {with_instance} clamp cases ran with a real Limits instance:\n{cases}"
    );
}

#[test]
fn one_file_of_a_unit_can_be_bridged_alone() {
    if !common::have("python3") {
        return;
    }
    let root = project(
        "one-file",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"pkg\"\nversion = \"0.1.0\"\n",
            ),
            ("pkg/__init__.py", ""),
            (
                "pkg/core.py",
                "def score(text: str) -> int:\n    return len(text.split())\n",
            ),
            (
                "pkg/tool.py",
                "def helper(path: str) -> str:\n    return open(path).read()\n",
            ),
        ],
    );
    let outcome = bridge_python(&root, "pkg/core.py").unwrap();
    assert_eq!(outcome.exports, ["score"]);
    let manifest = rust_anything::bridge::Manifest::load(&outcome.crate_dir).unwrap();
    assert_eq!(manifest.unit, "pkg/core.py");
    let recorded = harness::record(&RecordOptions {
        crate_dir: &outcome.crate_dir,
        count: 10,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    let missing = bridge_python(&root, "pkg/nope.py").unwrap_err();
    std::fs::remove_dir_all(&root).unwrap();
    assert!(recorded.cases > 0, "{recorded:?}");
    assert!(format!("{missing:#}").contains("no unit or source file"));
}

#[test]
fn napi_batches_take_structured_parameters() {
    if !common::have("node") {
        return;
    }
    let root = project(
        "batch-options",
        &[
            ("package.json", r#"{"name":"fmt","version":"0.1.0"}"#),
            (
                "src/fmt.ts",
                "export function label(n: number, options?: { long?: boolean }): string {\n  return options?.long ? `${n} units` : `${n}u`;\n}\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/fmt.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: vec!["label:n".into()],
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    let port = port.replacen(
        "unimplemented!(\"port `label` from src/fmt.ts\")",
        "let long = options\n        .as_ref()\n        .and_then(|o| o.get(\"long\"))\n        .and_then(serde_json::Value::as_bool)\n        .unwrap_or(false);\n    Ok(if long { format!(\"{n} units\") } else { format!(\"{n}u\") })",
        1,
    );
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    harness::build(&dir).unwrap();
    let script = r#"
const { LabelBatch } = require(process.argv[1])
const batch = new LabelBatch([1, 2])
const refused = [() => new LabelBatch(3), () => new LabelBatch([1, '2'])].map(f => { try { f(); return 'no' } catch (e) { return e.name } })
console.log(JSON.stringify([batch.run(), batch.run({ long: true }), batch instanceof LabelBatch, refused]))
"#;
    let output = Command::new("node")
        .args(["-e", script])
        .arg(dir.join("index.cjs"))
        .output()
        .unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        r#"[["1u","2u"],["1 units","2 units"],true,["TypeError","TypeError"]]"#,
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn napi_string_batches_cross_joined() {
    if !common::have("node") {
        return;
    }
    let root = project(
        "batch-strings",
        &[
            ("package.json", r#"{"name":"wrap","version":"0.1.0"}"#),
            (
                "src/wrap.ts",
                "export function wrap(s: string): string {\n  return `<${s}>`;\n}\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/wrap.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: vec!["wrap:s".into()],
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    let port = port.replacen(
        "unimplemented!(\"port `wrap` from src/wrap.ts\")",
        "Ok(format!(\"<{s}>\"))",
        1,
    );
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    harness::build(&dir).unwrap();
    let script = r#"
const { WrapBatch } = require(process.argv[1])
const items = ['', 'a', 'é', '😀x', '日本', 'b\uD800c', 'ascii only']
const batch = new WrapBatch(items)
const refused = [() => new WrapBatch('ab'), () => new WrapBatch(['a', 1])].map(f => { try { f(); return 'no' } catch (e) { return e.name } })
console.log(JSON.stringify([batch.run(), batch instanceof WrapBatch, refused, new WrapBatch([]).run()]))
"#;
    let output = Command::new("node")
        .args(["-e", script])
        .arg(dir.join("index.cjs"))
        .output()
        .unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        r#"[["<>","<a>","<é>","<😀x>","<日本>","<b�c>","<ascii only>"],true,["TypeError","TypeError"],[]]"#,
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn python_batches_build_and_run_on_rusty_alloc() {
    if !common::have("python3") {
        return;
    }
    let root = project(
        "rusty-alloc",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"tally\"\nversion = \"0.1.0\"\n",
            ),
            ("tally/__init__.py", ""),
            (
                "tally/words.py",
                "def shout(text: str) -> str:\n    return \" \".join(w.upper() + \"!\" for w in text.split())\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "tally/",
        kind: None,
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: vec!["shout:text".into()],
        as_json: Vec::new(),
        allocator: bridge::Allocator::RustyAlloc,
    })
    .unwrap();
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    let port = port.replacen(
        "unimplemented!(\"port `shout` from tally/words.py\")",
        "Ok(text\n        .split_whitespace()\n        .map(|w| format!(\"{}!\", w.to_uppercase()))\n        .collect::<Vec<_>>()\n        .join(\" \"))",
        1,
    );
    assert!(port.contains("to_uppercase"), "{port}");
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    harness::build(&dir).unwrap();
    let script = r#"
import sys
sys.path[:0] = [sys.argv[1] + "/python", sys.argv[2]]
from tally_rs import ShoutBatch
from tally.words import shout
items = [f"item {i} of the batch, {'x' * (i % 50)}" for i in range(5000)]
print(ShoutBatch(items).run() == [shout(t) for t in items])
"#;
    let output = Command::new("python3")
        .args(["-c", script])
        .arg(&dir)
        .arg(&*root)
        .output()
        .unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "True",
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn a_bridged_pyo3_crate_passes_clippy() {
    // `gate` runs `cargo clippy --all-targets -- -D warnings` on the crate, generated code included.
    if common::python().is_none() || !common::have("cargo") {
        return;
    }
    let root = project(
        "pyo3-clippy",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"lint\"\nversion = \"0.1.0\"\n",
            ),
            (
                "lint/__init__.py",
                "def same(data: dict) -> dict:\n    return data\n\n\n\
                 def greet(name: str, note: str | None = None) -> str:\n    return name\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "lint/",
        kind: Some(Kind::Pyo3),
        out: Some(dir.clone()),
        name: Some("lint-pyo3-rs".to_string()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let port = std::fs::read_to_string(dir.join("src/port.rs"))
        .unwrap()
        .replacen(
            "unimplemented!(\"port `same` from lint/__init__.py\")",
            "Ok(data)",
            1,
        )
        .replacen(
            "unimplemented!(\"port `greet` from lint/__init__.py\")",
            "Ok(note.unwrap_or(name))",
            1,
        );
    assert!(port.contains("Ok(note.unwrap_or(name))"), "{port}");
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(lib.contains("pub fn optional_note("), "{lib}");
    assert!(
        dir.join("src/pyconv.rs").exists(),
        "a JSON-valued unit uses pyconv"
    );
    let output = Command::new("cargo")
        .args(["clippy", "--all-targets", "--", "-D", "warnings"])
        .current_dir(&dir)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn python_errors_raise_the_originals_own_classes() {
    let Some(python) = common::python() else {
        return;
    };
    let root = project(
        "pyo3-errors",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"guard\"\nversion = \"0.1.0\"\n",
            ),
            (
                "guard/errors.py",
                "class GuardError(Exception):\n    \"\"\"The package's own error.\"\"\"\n\n\n\
                 class q\u{301}Error(Exception):\n    \"\"\"A name Python allows: a combining mark after q.\"\"\"\n\n\n\
                 class FieldError(Exception):\n    def __init__(self, field, reason):\n        \
                 super().__init__(field, reason)\n        self.field = field\n        self.reason = reason\n\n    \
                 def __str__(self):\n        return f\"{self.field}: {self.reason}\"\n\n\n\
                 class EmptyError(Exception):\n    def __init__(self):\n        super().__init__(\"nothing given\")\n\n\n\
                 class DroppedError(Exception):\n    def __new__(cls, *args):\n        return super().__new__(cls)\n\n    \
                 def __init__(self):\n        super().__init__(\"dropped\")\n\n\n\
                 class FrozenError(Exception):\n    def __init__(self):\n        super().__init__(\"fixed\")\n\n    \
                 def __setattr__(self, name, value):\n        raise AttributeError(\"read-only\")\n\n\n\
                 SAVED = ValueError(\"keep\")\n\n\n\
                 class RedirectError(Exception):\n    def __new__(cls, *args):\n        return SAVED\n",
            ),
            (
                "guard/__init__.py",
                "from guard.errors import EmptyError, FieldError, GuardError\n\n\n\
                 def check(text: str) -> str:\n    if not text:\n        raise GuardError(\"blank\")\n    return text\n\n\n\
                 def need(text: str) -> str:\n    if not text:\n        raise FileNotFoundError(\"nothing to open\")\n    return text\n\n\n\
                 def name_of(text: str) -> str:\n    if not text:\n        raise EmptyError()\n    \
                 if len(text) > 3:\n        raise FieldError(\"name\", \"too long\")\n    return text\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "guard/",
        kind: Some(Kind::Pyo3),
        out: Some(dir.clone()),
        name: Some("guard-pyo3-rs".to_string()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let inputs = dir.join("inputs.jsonl");
    std::fs::write(
        &inputs,
        "{\"fn\": \"check\", \"args\": [\"\"]}\n{\"fn\": \"check\", \"args\": [\"ok\"]}\n\
         {\"fn\": \"need\", \"args\": [\"\"]}\n{\"fn\": \"name_of\", \"args\": [\"\"]}\n\
         {\"fn\": \"name_of\", \"args\": [\"long name\"]}\n{\"fn\": \"name_of\", \"args\": [\"ok\"]}\n",
    )
    .unwrap();
    harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: Some(&inputs),
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    let port = port
        .replacen(
            "unimplemented!(\"port `check` from guard/__init__.py\")",
            "if text.is_empty() {\n        return Err(\"guard.errors.GuardError: blank\".into());\n    }\n    Ok(text)",
            1,
        )
        .replacen(
            "unimplemented!(\"port `need` from guard/__init__.py\")",
            "if text.is_empty() {\n        return Err(\"FileNotFoundError: nothing to open\".into());\n    }\n    \
             match text.as_str() {\n        \
             \"not-a-class\" => Err(\"os.path: a module\".into()),\n        \
             \"not-an-error\" => Err(\"builtins.int: a class, not an exception\".into()),\n        \
             \"no-module\" => Err(\"no_such_module.Error: gone\".into()),\n        \
             \"sentence\" => Err(\"Could not open it: no such file\".into()),\n        \
             \"combining\" => Err(\"guard.errors.q\u{301}Error: marked\".into()),\n        \
             \"needs-more\" => Err(\"json.decoder.JSONDecodeError: takes a document and a position\".into()),\n        \
             \"args-dropped\" => Err(\"guard.errors.DroppedError: dropped\".into()),\n        \
             \"frozen\" => Err(\"guard.errors.FrozenError: fixed\".into()),\n        \
             \"redirect\" => Err(\"guard.errors.RedirectError: moved\".into()),\n        \
             _ => Ok(text),\n    }",
            1,
        )
        .replacen(
            "unimplemented!(\"port `name_of` from guard/__init__.py\")",
            "if text.is_empty() {\n        return Err(\"guard.errors.EmptyError: nothing given\".into());\n    }\n    \
             if text.chars().count() > 3 {\n        return Err(\"guard.errors.FieldError: name: too long\".into());\n    }\n    Ok(text)",
            1,
        );
    assert!(port.contains("guard.errors.GuardError"), "{port}");
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap();
    assert_eq!(
        (outcome.failed, outcome.passed),
        (0, outcome.total),
        "{:#?}",
        outcome.mismatches
    );
    // A class whose constructor wants more than the message (or nothing) is raised as itself,
    // printing the message, and `except` on it catches it. Names that are not an exception class
    // keep today's ValueError with the whole message.
    let script = r#"
import sys
sys.path[:0] = [sys.argv[1] + "/python", sys.argv[2]]
from guard_pyo3_rs import check, name_of, need
from guard.errors import FieldError, GuardError
out = []
try:
    name_of("long name")
except FieldError as e:
    out.append(f"caught {type(e).__name__}: {e}")
for f, arg in [(check, ""), (need, ""), (need, "not-a-class"), (need, "not-an-error"),
               (need, "no-module"), (need, "sentence"), (need, "needs-more"),
               (need, "combining"), (name_of, ""), (name_of, "long name"),
               (need, "args-dropped"), (need, "frozen"), (need, "redirect")]:
    try:
        f(arg)
    except Exception as e:
        name = type(e).__name__.encode("ascii", "backslashreplace").decode()
        out.append(f"{type(e).__module__}.{name}: {e}")
import pickle
raised = []
for _ in range(2):
    try:
        name_of("long name")
    except FieldError as e:
        raised.append(e)
first, second = raised
out.append(f"one class for every raise: {type(first) is type(second)}")
out.append(f"still a FieldError: {isinstance(first, FieldError)}")
first.attempt = 3
loaded = pickle.loads(pickle.dumps(first))
out.append(f"pickled: {type(loaded) is type(first)} {isinstance(loaded, FieldError)} {loaded} {loaded.args == first.args} {loaded.attempt}")
import copy, os, subprocess
out.append(f"copied: {copy.copy(first)} {copy.deepcopy(first).attempt}")
fresh = subprocess.run(
    [sys.executable, "-c", "import pickle, sys; e = pickle.loads(sys.stdin.buffer.read()); print(type(e).__name__, e)"],
    input=pickle.dumps(first), capture_output=True, env={**os.environ, "PYTHONPATH": os.pathsep.join([sys.argv[1] + "/python", sys.argv[2]])},
)
out.append(f"fresh process: {fresh.stdout.decode().strip()} {fresh.stderr.decode().strip()}")
from guard.errors import SAVED
out.append(f"saved: {SAVED}")
print("\n".join(out))
"#;
    let output = Command::new(python)
        .args(["-c", script])
        .arg(&dir)
        .arg(&*root)
        .output()
        .unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&output.stdout)
            .replace("\r\n", "\n")
            .trim(),
        "caught FieldError: name: too long\n\
         guard.errors.GuardError: blank\n\
         builtins.FileNotFoundError: nothing to open\n\
         builtins.ValueError: os.path: a module\n\
         builtins.ValueError: builtins.int: a class, not an exception\n\
         builtins.ValueError: no_such_module.Error: gone\n\
         builtins.ValueError: Could not open it: no such file\n\
         json.decoder.JSONDecodeError: takes a document and a position\n\
         guard.errors.q\\u0301Error: marked\n\
         guard.errors.EmptyError: nothing given\n\
         guard.errors.FieldError: name: too long\n\
         guard.errors.DroppedError: dropped\n\
         guard.errors.FrozenError: fixed\n\
         builtins.ValueError: guard.errors.RedirectError: moved\n\
         one class for every raise: True\n\
         still a FieldError: True\n\
         pickled: True True name: too long True 3\n\
         copied: name: too long 3\n\
         fresh process: FieldError name: too long \n\
         saved: keep",
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn napi_none_answers_null_where_the_source_declares_null() {
    // A call the binary wire refuses (`null` for an optional array, which is not `T | null`) takes the JSON path, and
    // async calls always do: `None` must still reach JS as the `null` the source declares,
    // through a type alias and `Promise` too, and stay `undefined` where it says `undefined`.
    if !common::have("node") {
        return;
    }
    let root = project(
        "napi-none",
        &[
            ("package.json", r#"{"name":"none","version":"0.1.0"}"#),
            (
                "src/none.ts",
                "type Verdict = \"named\" | null\n\
                 export function direct(names?: string[]): \"named\" | null { return names?.length ? \"named\" : null }\n\
                 export function aliased(names?: string[]): Verdict { return names?.length ? \"named\" : null }\n\
                 export async function later(names?: string[]): Promise<\"named\" | null> { return names?.length ? \"named\" : null }\n\
                 export function loose(names?: string[]): \"named\" | undefined { return names?.length ? \"named\" : undefined }\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/none.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let body = "Ok(names.filter(|n| !n.is_empty()).map(|_| \"named\".to_string()))";
    let mut port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    for name in ["direct", "aliased", "later", "loose"] {
        let stub = format!("unimplemented!(\"port `{name}` from src/none.ts\")");
        assert!(port.contains(&stub), "{port}");
        port = port.replacen(&stub, body, 1);
    }
    std::fs::write(dir.join("src/port.rs"), &port).unwrap();
    harness::build(&dir).unwrap();
    let script = r#"
const m = require(process.argv[1])
const show = v => v === null ? 'null' : v === undefined ? 'undefined' : v
Promise.all([m.direct(null), m.aliased(null), m.later(null), m.loose(null), m.direct(['a'])])
  .then(vs => console.log(vs.map(show).join(',')))
"#;
    let output = Command::new("node")
        .args(["-e", script])
        .arg(dir.join("index.cjs"))
        .output()
        .unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "null,null,null,undefined,named",
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn napi_async_call_without_an_optional_array_gets_none() {
    if !common::have("node") {
        return;
    }
    let root = project(
        "napi-omitted",
        &[
            ("package.json", r#"{"name":"omitted","version":"0.1.0"}"#),
            (
                "src/refusal.ts",
                "export async function refusalAsync(raw: string, names: readonly string[] | undefined): Promise<\"long\" | \"named\" | null> {\n\
                 \x20 if (raw.length > 5) return \"long\"\n\
                 \x20 return names?.some((n) => raw.includes(n)) ? \"named\" : null\n\
                 }\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/refusal.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let body = "if raw.encode_utf16().count() > 5 { return Ok(Some(\"long\".into())); }\n    \
                Ok(names.unwrap_or_default().iter().any(|n| raw.contains(n.as_str())).then(|| \"named\".into()))";
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    let stub = "unimplemented!(\"port `refusalAsync` from src/refusal.ts\")";
    assert!(port.contains(stub), "{port}");
    std::fs::write(dir.join("src/port.rs"), port.replacen(stub, body, 1)).unwrap();
    harness::build(&dir).unwrap();
    let script = r#"
const m = require(process.argv[1])
const show = v => v === null ? 'null' : v === undefined ? 'undefined' : v
Promise.all([m.refusalAsync('HELLO'), m.refusalAsync('HELLO', undefined), m.refusalAsync('HELLO', null), m.refusalAsync('HELLO', ['ELL']), m.refusalAsync('LONGER')])
  .then(vs => console.log(vs.map(show).join(',')), e => console.log('error: ' + e.message))
"#;
    let output = Command::new("node")
        .args(["-e", script])
        .arg(dir.join("index.cjs"))
        .output()
        .unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "null,null,null,named,long",
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn napi_substring_keeps_half_a_surrogate_pair() {
    // JS `slice` can cut a surrogate pair and hand back the lone half. A port that follows the
    // bridge's advice for string offsets must give the same string, not U+FFFD.
    if !common::have("node") {
        return;
    }
    let root = project(
        "napi-utf16",
        &[
            ("package.json", r#"{"name":"head","version":"0.1.0"}"#),
            (
                "src/head.ts",
                "export function head(s: string): string { return s.slice(0, 1) }\n",
            ),
        ],
    );
    let dir = root.join("port");
    let outcome = bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/head.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    assert!(
        outcome.notes.iter().any(|n| n.contains("slice_units")),
        "{:#?}",
        outcome.notes
    );
    // Port it as the note says: the result becomes a `serde_json::Value` that can hold a lone
    // surrogate, and `refresh` regenerates the binding for the new signature.
    let port = std::fs::read_to_string(dir.join("src/port.rs")).unwrap();
    let stub = "-> Result<String, String> {\n    let _ = &s;\n    \
                unimplemented!(\"port `head` from src/head.ts\")";
    assert!(port.contains(stub), "{port}");
    let port = port.replacen(
        stub,
        "-> Result<serde_json::Value, String> {\n    \
         Ok(crate::js::utf16_string(crate::utf16::slice_units(&crate::utf16::units(&s), 0, 1)))",
        1,
    );
    std::fs::write(dir.join("src/port.rs"), port).unwrap();
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    let script = r#"
const m = require(process.argv[1])
const units = r => Array.from({ length: r.length }, (_, i) => r.charCodeAt(i))
console.log(JSON.stringify(['\uD83D\uDE00', 'a\uD83D\uDE00', ''].map(s => units(m.head(s)))))
"#;
    let output = Command::new("node")
        .args(["-e", script])
        .arg(dir.join("index.cjs"))
        .output()
        .unwrap();
    std::fs::remove_dir_all(&root).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&output.stdout).trim(),
        "[[55357],[97],[]]",
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn napi_plain_marker_object_round_trips_through_record_and_diff() {
    if !common::have("node") {
        return;
    }
    let root = project(
        "napi-plain-marker",
        &[
            ("package.json", r#"{"name":"marker","version":"0.1.0"}"#),
            (
                "src/marker.ts",
                "export function markerObject(flag: boolean): { $map: [string, boolean][] } {\n\
                   return { $map: [['ok', flag]] }\n\
                 }\n",
            ),
        ],
    );
    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "src/marker.ts",
        kind: Some(Kind::Napi),
        out: Some(dir.clone()),
        name: None,
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 10,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 0, "{recorded:?}");

    let port_path = dir.join("src/port.rs");
    let port = std::fs::read_to_string(&port_path).unwrap();
    let stub = "-> Result<serde_json::Value, String> {\n    let _ = &flag;\n    \
                unimplemented!(\"port `markerObject` from src/marker.ts\")";
    assert!(port.contains(stub), "{port}");
    let ported = port.replacen(
        stub,
        "-> Result<std::collections::HashMap<String, Vec<(String, bool)>>, String> {\n    \
         Ok(std::collections::HashMap::from([(\"$map\".to_string(), vec![(\"ok\".to_string(), flag)])]))",
        1,
    );
    std::fs::write(&port_path, ported).unwrap();
    bridge::refresh(&dir).unwrap();
    let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
    assert!(lib.contains("crate::js::to_plain_json(&out)"), "{lib}");

    harness::build(&dir).unwrap();
    let outcome = harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap();
    assert_eq!(
        (outcome.failed, outcome.passed),
        (0, outcome.total),
        "{:#?}",
        outcome.mismatches
    );
    std::fs::remove_dir_all(&root).unwrap();
}

#[test]
fn napi_plain_marker_objects_round_trip_nested_and_side_by_side() {
    if !common::have("node") {
        return;
    }
    let root = project(
        "napi-plain-marker-nested",
        &[
            ("package.json", r#"{"name":"marker","version":"0.1.0"}"#),
            (
                "src/marker.ts",
                "export function nested(flag: boolean): { $map: { $set: { a: boolean } } } {\n\
                   return { $map: { $set: { a: flag } } }\n\
                 }\n\
                 export function mixed(flag: boolean): Record<string, Record<string, Record<string, boolean>[]>> {\n\
                   return { $map: { $set: [{ $date: flag }, { a: flag }, { $num: flag, b: flag }] }, c: { $bytes: [] } }\n\
                 }\n",
            ),
        ],
    );
    let port = "#![forbid(unsafe_code)]\n\nuse std::collections::BTreeMap;\n\n\
        /// Port of `nested` (`marker.ts:1`).\n\
        pub fn nested(flag: bool) -> Result<BTreeMap<String, BTreeMap<String, BTreeMap<String, bool>>>, String> {\n    \
        let set = BTreeMap::from([(\"$set\".to_string(), BTreeMap::from([(\"a\".to_string(), flag)]))]);\n    \
        Ok(BTreeMap::from([(\"$map\".to_string(), set)]))\n}\n\n\
        /// Port of `mixed` (`marker.ts:4`).\n\
        pub fn mixed(flag: bool) -> Result<BTreeMap<String, BTreeMap<String, Vec<BTreeMap<String, bool>>>>, String> {\n    \
        let one = |k: &str| BTreeMap::from([(k.to_string(), flag)]);\n    \
        let two = BTreeMap::from([(\"$num\".to_string(), flag), (\"b\".to_string(), flag)]);\n    \
        Ok(BTreeMap::from([\n        \
        (\"$map\".to_string(), BTreeMap::from([(\"$set\".to_string(), vec![one(\"$date\"), one(\"a\"), two])])),\n        \
        (\"c\".to_string(), BTreeMap::from([(\"$bytes\".to_string(), vec![])])),\n    \
        ]))\n}\n";
    let outcome = build_and_diff(&root, "src/marker.ts", "marker-rs", Kind::Napi, port);
    let lib = std::fs::read_to_string(root.join("port/src/lib.rs")).unwrap();
    assert!(lib.contains("crate::js::to_plain_json(&out)"), "{lib}");
    assert_eq!(
        (outcome.failed, outcome.passed),
        (0, outcome.total),
        "{:#?}",
        outcome.mismatches
    );
    std::fs::remove_dir_all(&root).unwrap();
}

/// Bridges `unit`, records the original, writes `port` as `src/port.rs`, builds and replays.
fn build_and_diff(
    root: &Path,
    unit: &str,
    name: &str,
    kind: Kind,
    port: &str,
) -> harness::DiffOutcome {
    let dir = root.join("port");
    if !dir.exists() {
        bridge::bridge(&bridge::Options {
            root,
            unit,
            kind: Some(kind),
            out: Some(dir.clone()),
            name: Some(name.to_string()),
            force: false,
            keep: Vec::new(),
            lang: None,
            batch: Vec::new(),
            as_json: Vec::new(),
            allocator: Default::default(),
        })
        .unwrap();
        let recorded = harness::record(&RecordOptions {
            crate_dir: &dir,
            count: 30,
            inputs: None,
            module: None,
            resolve_from: None,
            node_args: &[],
            sandbox: false,
        })
        .unwrap();
        assert!(recorded.cases > 0, "{recorded:?}");
    }
    std::fs::write(dir.join("src/port.rs"), port).unwrap();
    // The signatures of the stubs `bridge` wrote are the bindings' source: regenerate them.
    bridge::refresh(&dir).unwrap();
    harness::build(&dir).unwrap();
    harness::diff(&DiffOptions {
        crate_dir: &dir,
        module: None,
        ignore_key_order: false,
        node_args: &[],
        float_tolerance: None,
    })
    .unwrap()
}

fn names_failing(outcome: &harness::DiffOutcome) -> Vec<String> {
    // The groups cover every mismatch; `mismatches` keeps only the first few.
    let mut names: Vec<String> = outcome
        .groups
        .iter()
        .filter_map(|g| g.function.clone())
        .collect();
    names.sort();
    names.dedup();
    names
}

#[test]
fn napi_addon_changes_the_callers_arguments_and_prints_through_the_caller() {
    if !common::have("node") {
        return;
    }
    let root = project(
        "napi-effects",
        &[
            ("package.json", r#"{"name":"fx","version":"0.1.0"}"#),
            (
                "src/fx.ts",
                "export function sortInPlace(xs: number[]): void { xs.sort((a, b) => a - b) }\n\
                 export function say(s: string): number { console.log(s); return s.length }\n",
            ),
        ],
    );
    let header = "#![forbid(unsafe_code)]\n\n/// Port of `sortInPlace` (`fx.ts:1`).\n";
    let say = "\n/// Port of `say` (`fx.ts:2`).\npub fn say(s: String, stdout: &mut String) -> Result<f64, String> {\n";
    let faithful = format!(
        "{header}pub fn sort_in_place(xs: &mut Vec<f64>) -> Result<(), String> {{\n    \
         xs.sort_by(|a, b| a.total_cmp(b));\n    Ok(())\n}}\n{say}    \
         stdout.push_str(&s);\n    stdout.push('\\n');\n    Ok(s.encode_utf16().count() as f64)\n}}\n"
    );
    let no_op = format!(
        "{header}pub fn sort_in_place(xs: &mut Vec<f64>) -> Result<(), String> {{\n    \
         let _ = xs;\n    Ok(())\n}}\n{say}    let _ = stdout;\n    Ok(s.encode_utf16().count() as f64)\n}}\n"
    );
    let ok = build_and_diff(&root, "src/fx.ts", "fx-napi-rs", Kind::Napi, &faithful);
    // `total_cmp` orders -0 before 0 and NaN last, where `a - b` leaves NaN where it is: judge the
    // cases that do not hold those. The point is that mutation and output arrive at all.
    let wrong: Vec<_> = ok.mismatches.iter().filter(|m| m["fn"] == "say").collect();
    assert!(wrong.is_empty(), "{wrong:#?}");
    assert!(ok.passed > ok.failed, "{:#?}", ok.mismatches);
    let bad = build_and_diff(&root, "src/fx.ts", "fx-napi-rs", Kind::Napi, &no_op);
    assert_eq!(
        names_failing(&bad),
        ["say", "sortInPlace"],
        "{:#?}",
        bad.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn pyo3_extension_changes_the_callers_arguments_and_prints_through_the_caller() {
    if common::python().is_none() {
        return;
    }
    let root = project(
        "pyo3-effects",
        &[
            (
                "pyproject.toml",
                "[project]\nname = \"fx\"\nversion = \"0.1.0\"\n",
            ),
            (
                "fx.py",
                "def sort_in_place(xs: list[int]) -> None:\n    xs.sort()\n\n\n\
                 def say(s: str) -> int:\n    print(s)\n    return len(s)\n",
            ),
        ],
    );
    let header = "#![forbid(unsafe_code)]\n\n/// Port of `sort_in_place` (`fx.py:1`).\n";
    let say = "\n/// Port of `say` (`fx.py:5`).\npub fn say(s: String, stdout: &mut String) -> Result<i64, String> {\n";
    let faithful = format!(
        "{header}pub fn sort_in_place(xs: &mut Vec<i64>) -> Result<(), String> {{\n    xs.sort();\n    Ok(())\n}}\n\
         {say}    stdout.push_str(&s);\n    stdout.push('\\n');\n    Ok(s.chars().count() as i64)\n}}\n"
    );
    let no_op = format!(
        "{header}pub fn sort_in_place(xs: &mut Vec<i64>) -> Result<(), String> {{\n    let _ = xs;\n    Ok(())\n}}\n\
         {say}    let _ = stdout;\n    Ok(s.chars().count() as i64)\n}}\n"
    );
    let ok = build_and_diff(&root, "fx.py", "fx-pyo3-rs", Kind::Pyo3, &faithful);
    assert_eq!(ok.failed, 0, "{:#?}", ok.mismatches);
    let bad = build_and_diff(&root, "fx.py", "fx-pyo3-rs", Kind::Pyo3, &no_op);
    assert_eq!(
        names_failing(&bad),
        ["say", "sort_in_place"],
        "{:#?}",
        bad.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn magnus_extension_changes_the_callers_arguments_and_prints_through_the_caller() {
    if cfg!(windows) {
        eprintln!(
            "skipped: RubyInstaller's Ruby is built with MinGW, and an MSVC Rust extension cannot load into it"
        );
        return;
    }
    if !common::have_ruby_3() {
        return;
    }
    let root = project(
        "magnus-effects",
        &[(
            "fx.rb",
            "module Fx\n  # @param xs [Array<Integer>]\n  # @return [nil]\n  def self.sort_in_place(xs)\n    xs.sort!\n    nil\n  end\n\n  \
             # @param s [String]\n  # @return [Integer]\n  def self.mark(s)\n    s << \"!\"\n    s.length\n  end\n\n  \
             # @param s [String]\n  # @return [Integer]\n  def self.say(s)\n    puts s\n    s.length\n  end\nend\n",
        )],
    );
    let port = |sort: &str, mark: &str, say: &str| {
        format!(
            "#![forbid(unsafe_code)]\n\n/// Port of `sort_in_place` (`fx.rb:4`).\n\
             pub fn sort_in_place(xs: &mut Vec<i64>) -> Result<(), String> {{\n    {sort}\n    Ok(())\n}}\n\n\
             /// Port of `mark` (`fx.rb:10`).\npub fn mark(s: &mut String) -> Result<i64, String> {{\n    {mark}\n    \
             Ok(s.chars().count() as i64)\n}}\n\n/// Port of `say` (`fx.rb:16`).\n\
             pub fn say(s: String, stdout: &mut String) -> Result<i64, String> {{\n    {say}\n    Ok(s.chars().count() as i64)\n}}\n"
        )
    };
    let faithful = port(
        "xs.sort();",
        "s.push('!');",
        "stdout.push_str(&s); stdout.push('\\n');",
    );
    let no_op = port("let _ = xs;", "let _ = s;", "let _ = stdout;");
    let ok = build_and_diff(&root, "fx.rb", "fx-magnus-rs", Kind::Ffi, &faithful);
    assert_eq!(ok.failed, 0, "{:#?}", ok.mismatches);
    let bad = build_and_diff(&root, "fx.rb", "fx-magnus-rs", Kind::Ffi, &no_op);
    assert_eq!(
        names_failing(&bad),
        ["mark", "say", "sort_in_place"],
        "{:#?}",
        bad.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn go_cgo_library_changes_the_callers_slice_and_prints_through_the_caller() {
    if !common::have("go") {
        return;
    }
    let root = project(
        "go-effects",
        &[
            ("go.mod", "module example.com/fx\n\ngo 1.22\n"),
            (
                "fx/fx.go",
                "package fx\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\n\
                 func SortInPlace(xs []int) { sort.Ints(xs) }\n\n\
                 func Say(s string) int {\n\tfmt.Println(s)\n\treturn len(s)\n}\n",
            ),
        ],
    );
    let port = |sort: &str, say: &str| {
        format!(
            "#![forbid(unsafe_code)]\n\n/// Port of `SortInPlace` (`fx.go:9`).\n\
             pub fn sort_in_place(xs: &mut Vec<i64>) -> Result<(), String> {{\n    {sort}\n    Ok(())\n}}\n\n\
             /// Port of `Say` (`fx.go:11`).\npub fn say(s: String, stdout: &mut String) -> Result<i64, String> {{\n    {say}\n    \
             Ok(s.len() as i64)\n}}\n"
        )
    };
    let faithful = port("xs.sort();", "stdout.push_str(&s); stdout.push('\\n');");
    let no_op = port("let _ = xs;", "let _ = stdout;");
    let ok = build_and_diff(&root, "fx/", "fx-go-rs", Kind::Ffi, &faithful);
    assert_eq!(ok.failed, 0, "{:#?}", ok.mismatches);
    let bad = build_and_diff(&root, "fx/", "fx-go-rs", Kind::Ffi, &no_op);
    assert_eq!(
        names_failing(&bad),
        ["Say", "SortInPlace"],
        "{:#?}",
        bad.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn go_port_rebuilt_after_its_name_owner_leaves_runs_the_new_library() {
    if !common::have("go") {
        return;
    }
    let root = project(
        "go-owner",
        &[
            ("go.mod", "module example.com/fx\n\ngo 1.22\n"),
            (
                "fx/fx.go",
                "package fx\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\n\
                 func SortInPlace(xs []int) { sort.Ints(xs) }\n\n\
                 func Say(s string) int {\n\tfmt.Println(s)\n\treturn len(s)\n}\n",
            ),
        ],
    );
    let shared = root.join("shared");
    let other = root.join("other-owner");
    std::fs::create_dir_all(&other).unwrap();
    std::fs::write(
        other.join("Cargo.toml"),
        "[package]\nname = \"fx-owner-rs\"\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    assert!(
        rust_anything::cache::target_in(&shared, &other)
            .unwrap()
            .shared
    );

    let dir = root.join("port");
    bridge::bridge(&bridge::Options {
        root: &root,
        unit: "fx/",
        kind: Some(Kind::Ffi),
        out: Some(dir.clone()),
        name: Some("fx-owner-rs".to_string()),
        force: false,
        keep: Vec::new(),
        lang: None,
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })
    .unwrap();
    let recorded = harness::record(&RecordOptions {
        crate_dir: &dir,
        count: 30,
        inputs: None,
        module: None,
        resolve_from: None,
        node_args: &[],
        sandbox: false,
    })
    .unwrap();
    assert!(recorded.cases > 0, "{recorded:?}");
    let port = |sort: &str, say: &str| {
        format!(
            "#![forbid(unsafe_code)]\n\n/// Port of `SortInPlace` (`fx.go:9`).\n\
             pub fn sort_in_place(xs: &mut Vec<i64>) -> Result<(), String> {{\n    {sort}\n    Ok(())\n}}\n\n\
             /// Port of `Say` (`fx.go:11`).\npub fn say(s: String, stdout: &mut String) -> Result<i64, String> {{\n    {say}\n    \
             Ok(s.len() as i64)\n}}\n"
        )
    };
    let build_and_diff = |port: &str| -> serde_json::Value {
        std::fs::write(dir.join("src/port.rs"), port).unwrap();
        bridge::refresh(&dir).unwrap();
        let cli = |args: &[&str]| {
            common::cli()
                .args(args)
                .arg(&dir)
                .env("CARGO_TARGET_DIR", &shared)
                .output()
                .unwrap()
        };
        let built = cli(&["build"]);
        assert!(built.status.success(), "{built:?}");
        let diffed = cli(&["diff", "--json"]);
        serde_json::from_slice(&diffed.stdout).unwrap_or_else(|e| panic!("{e}: {diffed:?}"))
    };
    let failing = |outcome: &serde_json::Value| {
        let mut names: Vec<String> = outcome["groups"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|g| g["fn"].as_str().map(str::to_string))
            .collect();
        names.sort();
        names.dedup();
        names
    };

    let ok = build_and_diff(&port(
        "xs.sort();",
        "stdout.push_str(&s); stdout.push('\\n');",
    ));
    assert_eq!(ok["failed"], 0, "{ok:#}");
    std::fs::remove_dir_all(&other).unwrap();
    let bad = build_and_diff(&port("let _ = xs;", "let _ = stdout;"));
    assert_eq!(
        failing(&bad),
        ["Say", "SortInPlace"],
        "the no-op port passed: the Go driver ran the library of the build before: {bad:#}"
    );
}

#[test]
fn jni_library_changes_the_callers_collection_and_prints_through_the_caller() {
    if !common::have("java") || !common::have("javac") {
        return;
    }
    let root = project(
        "java-effects",
        &[
            (
                "pom.xml",
                "<project><modelVersion>4.0.0</modelVersion><groupId>com.acme</groupId><artifactId>fx</artifactId><version>1</version></project>",
            ),
            (
                "src/main/java/com/acme/Fx.java",
                "package com.acme;\n\nimport java.util.*;\n\npublic final class Fx {\n    \
                 public static void sortInPlace(List<Integer> xs) { Collections.sort(xs); }\n    \
                 public static int say(String s) { System.out.println(s); return s.length(); }\n}\n",
            ),
        ],
    );
    let port = |sort: &str, say: &str| {
        format!(
            "#![forbid(unsafe_code)]\n\n/// Port of `sortInPlace` (`Fx.java:5`).\n\
             pub fn sort_in_place(xs: &mut Vec<i64>) -> Result<(), String> {{\n    {sort}\n    Ok(())\n}}\n\n\
             /// Port of `say` (`Fx.java:6`).\npub fn say(s: String, stdout: &mut String) -> Result<i64, String> {{\n    {say}\n    \
             Ok(s.encode_utf16().count() as i64)\n}}\n"
        )
    };
    let faithful = port("xs.sort();", "stdout.push_str(&s); stdout.push('\\n');");
    let no_op = port("let _ = xs;", "let _ = stdout;");
    let unit = "src/main/java/com/acme/Fx.java";
    let ok = build_and_diff(&root, unit, "fx-jni-rs", Kind::Ffi, &faithful);
    assert_eq!(ok.failed, 0, "{:#?}", ok.mismatches);
    let bad = build_and_diff(&root, unit, "fx-jni-rs", Kind::Ffi, &no_op);
    assert_eq!(
        names_failing(&bad),
        ["say", "sortInPlace"],
        "{:#?}",
        bad.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn php_ffi_library_changes_the_callers_reference_and_prints_through_the_caller() {
    if !common::have_with(
        "php",
        &[
            "-d",
            "ffi.enable=1",
            "-r",
            "exit(class_exists('FFI') ? 0 : 1);",
        ],
        "is missing or has no FFI extension",
    ) {
        return;
    }
    let root = project(
        "php-effects",
        &[(
            "fx.php",
            "<?php\n\n/**\n * @param int[] $xs\n */\nfunction sort_in_place(array &$xs): void\n{\n    sort($xs);\n}\n\n\
             function say(string $s): int\n{\n    echo $s, \"\\n\";\n    return strlen($s);\n}\n",
        )],
    );
    let port = |sort: &str, say: &str| {
        format!(
            "#![forbid(unsafe_code)]\n\n/// Port of `sort_in_place` (`fx.php:6`).\n\
             pub fn sort_in_place(xs: &mut Vec<i64>) -> Result<(), String> {{\n    {sort}\n    Ok(())\n}}\n\n\
             /// Port of `say` (`fx.php:11`).\npub fn say(s: String, stdout: &mut String) -> Result<i64, String> {{\n    {say}\n    \
             Ok(s.len() as i64)\n}}\n"
        )
    };
    let faithful = port("xs.sort();", "stdout.push_str(&s); stdout.push('\\n');");
    let no_op = port("let _ = xs;", "let _ = stdout;");
    let ok = build_and_diff(&root, "fx.php", "fx-php-rs", Kind::Ffi, &faithful);
    assert_eq!(ok.failed, 0, "{:#?}", ok.mismatches);
    let bad = build_and_diff(&root, "fx.php", "fx-php-rs", Kind::Ffi, &no_op);
    assert_eq!(
        names_failing(&bad),
        ["say", "sort_in_place"],
        "{:#?}",
        bad.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn csharp_pinvoke_library_changes_the_callers_list_and_prints_through_the_caller() {
    if !common::have("dotnet") {
        return;
    }
    let root = project(
        "csharp-effects",
        &[(
            "Fx.cs",
            "using System;\nusing System.Collections.Generic;\n\nnamespace Acme\n{\n    public static class Fx\n    {\n        \
             public static void SortInPlace(List<int> xs) { xs.Sort(); }\n        \
             public static int Say(string s) { Console.WriteLine(s); return s.Length; }\n    }\n}\n",
        )],
    );
    let port = |sort: &str, say: &str| {
        format!(
            "#![forbid(unsafe_code)]\n\n/// Port of `SortInPlace` (`Fx.cs:7`).\n\
             pub fn sort_in_place(xs: &mut Vec<i64>) -> Result<(), String> {{\n    {sort}\n    Ok(())\n}}\n\n\
             /// Port of `Say` (`Fx.cs:8`).\npub fn say(s: String, stdout: &mut String) -> Result<i64, String> {{\n    {say}\n    \
             Ok(s.encode_utf16().count() as i64)\n}}\n"
        )
    };
    let faithful = port("xs.sort();", "stdout.push_str(&s); stdout.push('\\n');");
    let no_op = port("let _ = xs;", "let _ = stdout;");
    let ok = build_and_diff(&root, "Fx.cs", "fx-csharp-rs", Kind::Ffi, &faithful);
    assert_eq!(ok.failed, 0, "{:#?}", ok.mismatches);
    let bad = build_and_diff(&root, "Fx.cs", "fx-csharp-rs", Kind::Ffi, &no_op);
    assert_eq!(
        names_failing(&bad),
        ["Say", "SortInPlace"],
        "{:#?}",
        bad.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}

#[test]
fn kotlin_jni_library_changes_the_callers_list_and_prints_through_the_caller() {
    if !common::have("kotlinc") || !common::have("java") {
        return;
    }
    let root = project(
        "kotlin-effects",
        &[(
            "Fx.kt",
            "package acme\n\nfun sortInPlace(xs: MutableList<Int>) { xs.sort() }\n\n\
             fun say(s: String): Int {\n    println(s)\n    return s.length\n}\n",
        )],
    );
    let port = |sort: &str, say: &str| {
        format!(
            "#![forbid(unsafe_code)]\n\n/// Port of `sortInPlace` (`Fx.kt:3`).\n\
             pub fn sort_in_place(xs: &mut Vec<i64>) -> Result<(), String> {{\n    {sort}\n    Ok(())\n}}\n\n\
             /// Port of `say` (`Fx.kt:5`).\npub fn say(s: String, stdout: &mut String) -> Result<i64, String> {{\n    {say}\n    \
             Ok(s.encode_utf16().count() as i64)\n}}\n"
        )
    };
    let faithful = port("xs.sort();", "stdout.push_str(&s); stdout.push('\\n');");
    let no_op = port("let _ = xs;", "let _ = stdout;");
    let ok = build_and_diff(&root, "Fx.kt", "fx-kotlin-rs", Kind::Ffi, &faithful);
    assert_eq!(ok.failed, 0, "{:#?}", ok.mismatches);
    let bad = build_and_diff(&root, "Fx.kt", "fx-kotlin-rs", Kind::Ffi, &no_op);
    assert_eq!(
        names_failing(&bad),
        ["say", "sortInPlace"],
        "{:#?}",
        bad.mismatches
    );
    std::fs::remove_dir_all(root).unwrap();
}