rust-anything 4.1.0

Rewrite your app in Rust, one piece at a time, checked against the original's recorded behavior at every step. TypeScript/JavaScript, Python, C, Go, Ruby, Java, Kotlin, PHP, C# and PowerShell
Documentation
mod common;

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

use rust_anything::{
    bridge,
    codegen_java::{DRIVER_JAVA, ERROR_JAVA, JSON_JAVA, WIRE_JAVA},
    harness::DiffOutcome,
};

#[test]
fn java_replay_distinguishes_null_from_a_rejected_argument() {
    if !common::have("java") || !common::have("javac") {
        return;
    }

    let root = std::env::temp_dir().join(format!("rust-anything-java-null-{}", std::process::id()));
    std::fs::create_dir_all(&root).unwrap();
    let result = replay(&root);
    std::fs::remove_dir_all(root).unwrap();

    let diff = result.unwrap();
    assert_eq!((diff.passed, diff.failed), (1, 1));
    assert_eq!(diff.mismatches[0]["actual"]["invalid"], true);
}

#[test]
fn java_replay_and_wrapper_handle_extends_wildcard_parameters() {
    if !common::have("java") || !common::have("javac") {
        return;
    }

    let root = std::env::temp_dir().join(format!(
        "rust-anything-java-wildcard-{}",
        std::process::id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).unwrap();
    let result = replay_wildcards(&root);
    let _ = std::fs::remove_dir_all(&root);
    result.unwrap();
}

fn replay_wildcards(root: &Path) -> anyhow::Result<()> {
    let src = r#"package acme;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class Wildcards {
    public static int count(List<? extends CharSequence> xs) {
        int total = 0;
        for (CharSequence s : xs) total += s.length();
        return total;
    }
    public static int sumValues(Map<String, ? extends Integer> m) {
        int total = 0;
        for (Integer v : m.values()) total += v;
        return total;
    }
    public static int firstLen(Optional<? extends CharSequence> opt) {
        return opt.map(CharSequence::length).orElse(-1);
    }
    public static int nested(List<? extends List<? extends CharSequence>> rows) {
        int total = 0;
        for (List<? extends CharSequence> row : rows) total += row.size();
        return total;
    }
    public static int nestedGenericArray(List<? extends List<String>[][]> grids) {
        List<String>[][] first = grids.get(0);
        return grids.size() + first.length + first[0].length;
    }
    public static Map<CharSequence, Integer> echoCharSeqMap(Map<CharSequence, Integer> m) {
        return m;
    }
}
"#;
    std::fs::create_dir_all(root.join("acme"))?;
    std::fs::write(root.join("acme/Wildcards.java"), src)?;

    // Bridge the class and compile the generated Java wrapper + wire classes with javac.
    let out = root.join("port");
    bridge::bridge(&bridge::Options {
        root,
        unit: "acme/Wildcards.java",
        kind: None,
        out: Some(out.clone()),
        name: Some("wildcards-rs".into()),
        force: false,
        keep: Vec::new(),
        lang: Some(rust_anything::lang::Lang::Java),
        batch: Vec::new(),
        as_json: Vec::new(),
        allocator: Default::default(),
    })?;

    let java_dir = out.join("java");
    let compile_dir = root.join("wrapper-classes");
    std::fs::create_dir_all(&compile_dir)?;
    let mut javac = Command::new("javac");
    javac.args(["-d", compile_dir.to_str().unwrap()]);
    for rel in [
        "rustanything/RustAnythingJson.java",
        "rustanything/RustAnythingWire.java",
        "rustanything/RustAnythingError.java",
        "rustanything/WildcardsRsNative.java",
        "acme/Wildcards.java",
    ] {
        javac.arg(java_dir.join(rel));
    }
    run(&mut javac)?;

    // Compile the original class with the driver and run diff across valid and invalid inputs.
    let run_dir = root.join("driver-run");
    std::fs::create_dir_all(run_dir.join("acme"))?;
    std::fs::write(run_dir.join("RustAnythingDriver.java"), DRIVER_JAVA)?;
    std::fs::write(run_dir.join("RustAnythingJson.java"), JSON_JAVA)?;
    std::fs::write(run_dir.join("RustAnythingWire.java"), WIRE_JAVA)?;
    std::fs::write(run_dir.join("RustAnythingError.java"), ERROR_JAVA)?;
    std::fs::write(run_dir.join("acme/Wildcards.java"), src)?;
    std::fs::write(
        run_dir.join("targets.json"),
        r#"{"count":["acme.Wildcards","count"],"sumValues":["acme.Wildcards","sumValues"],"firstLen":["acme.Wildcards","firstLen"],"nested":["acme.Wildcards","nested"],"nestedGenericArray":["acme.Wildcards","nestedGenericArray"],"echoCharSeqMap":["acme.Wildcards","echoCharSeqMap"]}"#,
    )?;
    std::fs::write(
        run_dir.join("cases.jsonl"),
        concat!(
            r#"{"fn":"count","args":[["hi","there"]],"ok":7}"#,
            "\n",
            r#"{"fn":"sumValues","args":[{"a":2,"b":5}],"ok":7}"#,
            "\n",
            r#"{"fn":"firstLen","args":["rust"],"ok":4}"#,
            "\n",
            r#"{"fn":"firstLen","args":[null],"ok":-1}"#,
            "\n",
            r#"{"fn":"nested","args":[[["a","b"],["c"]]],"ok":3}"#,
            "\n",
            r#"{"fn":"nestedGenericArray","args":[[[[["a"]]]]],"ok":3}"#,
            "\n",
            r#"{"fn":"echoCharSeqMap","args":[{"k":9}],"ok":{"k":9}}"#,
            "\n",
            r#"{"fn":"count","args":[[123]],"ok":0}"#,
            "\n",
        ),
    )?;

    run(Command::new("javac").current_dir(&run_dir).args([
        "-d",
        ".",
        "RustAnythingDriver.java",
        "RustAnythingJson.java",
        "RustAnythingWire.java",
        "RustAnythingError.java",
        "acme/Wildcards.java",
    ]))?;
    run(Command::new("java").current_dir(&run_dir).args([
        "-cp",
        ".",
        "rustanything.RustAnythingDriver",
        "diff",
        "targets.json",
        "cases.jsonl",
        "diff.json",
    ]))?;
    let diff: DiffOutcome = serde_json::from_slice(&std::fs::read(run_dir.join("diff.json"))?)?;
    assert_eq!((diff.passed, diff.failed), (7, 1), "{diff:?}");
    assert_eq!(diff.mismatches[0]["actual"]["invalid"], true, "{diff:?}");
    Ok(())
}

#[test]
fn java_error_lookup_matches_across_json_typed_and_wire_paths() {
    if !common::have("java") || !common::have("javac") {
        return;
    }

    let root = std::env::temp_dir().join(format!("rust-anything-java-err-{}", std::process::id()));
    std::fs::create_dir_all(&root).unwrap();
    let result = check_error_lookup(&root);
    std::fs::remove_dir_all(root).unwrap();
    result.unwrap();
}

fn check_error_lookup(root: &Path) -> anyhow::Result<()> {
    std::fs::write(root.join("RustAnythingError.java"), ERROR_JAVA)?;
    std::fs::write(
        root.join("CheckErrors.java"),
        r#"import rustanything.RustAnythingError;

public class CheckErrors {
    private static void checkBoth(String type, String msg, Class<?> expected) {
        RuntimeException fromJson = RustAnythingError.from(type + ": " + msg);
        RuntimeException fromReal = new RustAnythingError(type, msg).real();
        RuntimeException fromSlot;
        try {
            String[] slot = RustAnythingError.slot();
            slot[0] = type;
            slot[1] = msg;
            RustAnythingError.check(slot);
            throw new AssertionError("expected exception for " + type);
        } catch (RuntimeException e) {
            fromSlot = e;
        }
        if (fromJson.getClass() != expected || fromReal.getClass() != expected || fromSlot.getClass() != expected) {
            throw new AssertionError("class mismatch for " + type + ": "
                + fromJson.getClass() + " / " + fromReal.getClass() + " / " + fromSlot.getClass());
        }
        if (!fromJson.getMessage().equals(fromReal.getMessage())
            || !fromJson.getMessage().equals(fromSlot.getMessage())) {
            throw new AssertionError("message mismatch for " + type);
        }
    }

    public static void main(String[] args) {
        checkBoth("IllegalArgumentException", "bad", IllegalArgumentException.class);
        checkBoth("NoSuchElementException", "missing", java.util.NoSuchElementException.class);
        checkBoth("DateTimeException", "empty year", java.time.DateTimeException.class);
        checkBoth("java.time.DateTimeException", "empty year", java.time.DateTimeException.class);
        checkBoth("RejectedExecutionException", "busy", java.util.concurrent.RejectedExecutionException.class);
        checkBoth("NoSuchException", "oops", RuntimeException.class);
        RuntimeException plain = RustAnythingError.from("bad input: 42");
        if (plain.getClass() != RuntimeException.class || !plain.getMessage().equals("bad input: 42")) {
            throw new AssertionError("unexpected plain error: " + plain);
        }
    }
}
"#,
    )?;

    run(Command::new("javac").current_dir(root).args([
        "-d",
        ".",
        "RustAnythingError.java",
        "CheckErrors.java",
    ]))?;
    run(Command::new("java")
        .current_dir(root)
        .args(["-cp", ".", "CheckErrors"]))?;
    Ok(())
}

fn replay(root: &Path) -> anyhow::Result<DiffOutcome> {
    std::fs::write(root.join("RustAnythingDriver.java"), DRIVER_JAVA)?;
    std::fs::write(root.join("RustAnythingJson.java"), JSON_JAVA)?;
    std::fs::write(
        root.join("Port.java"),
        "public class Port { public static String value(int input) { return null; } }",
    )?;
    std::fs::write(root.join("targets.json"), r#"{"value":["Port","value"]}"#)?;
    std::fs::write(
        root.join("cases.jsonl"),
        r#"{"fn":"value","args":[1],"ok":null}
{"fn":"value","args":["previously accepted"],"ok":null}
"#,
    )?;

    run(Command::new("javac").current_dir(root).args([
        "-d",
        ".",
        "RustAnythingDriver.java",
        "RustAnythingJson.java",
        "Port.java",
    ]))?;
    run(Command::new("java").current_dir(root).args([
        "-cp",
        ".",
        "rustanything.RustAnythingDriver",
        "diff",
        "targets.json",
        "cases.jsonl",
        "diff.json",
    ]))?;
    Ok(serde_json::from_slice(&std::fs::read(
        root.join("diff.json"),
    )?)?)
}

fn run(cmd: &mut Command) -> anyhow::Result<()> {
    let output = cmd.output()?;
    anyhow::ensure!(
        output.status.success(),
        "{cmd:?} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    Ok(())
}