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.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
//! `record --messages` (#1073): without it a port that throws the recorded class with another
//! message passes `diff`, and the verdict says messages were not compared; with it that port
//! fails and one with the recorded message passes.
mod common;
use std::path::Path;
use std::process::Command;
use rust_anything::bridge::{self, Kind};
use rust_anything::harness;
fn project(name: &str, files: &[(&str, &str)]) -> common::Scratch {
let root = common::Scratch::new(std::env::temp_dir().join(format!(
"rust-anything-messages-{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
}
fn bridged(root: &Path, unit: &str, kind: Kind, name: &str) -> std::path::PathBuf {
let dir = root.join("port");
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();
dir
}
fn port_with(dir: &Path, stub: &str, body: &str) {
let path = dir.join("src/port.rs");
let port = std::fs::read_to_string(&path).unwrap();
assert!(port.contains(stub), "{port}");
std::fs::write(&path, port.replacen(stub, body, 1)).unwrap();
harness::build(dir).unwrap();
}
fn record(dir: &Path, inputs: &Path, extra: &[&str]) {
let out = common::cli()
.arg("record")
.arg(dir)
.args(["--count", "0", "--inputs"])
.arg(inputs)
.args(extra)
.output()
.unwrap();
assert!(
out.status.success(),
"{}\n{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
);
}
/// `diff --json` and the text `diff` prints.
fn diff(dir: &Path) -> (serde_json::Value, String) {
let json = common::cli()
.arg("diff")
.arg(dir)
.arg("--json")
.output()
.unwrap();
let report: serde_json::Value = serde_json::from_slice(&json.stdout).unwrap_or_else(|e| {
panic!(
"{e}: {}\n{}",
String::from_utf8_lossy(&json.stdout),
String::from_utf8_lossy(&json.stderr)
)
});
let text = common::cli().arg("diff").arg(dir).output().unwrap();
(report, String::from_utf8_lossy(&text.stdout).into_owned())
}
const NOT_COMPARED: &str = "error messages not compared: 1 recorded error checked by class only";
/// The round both languages share: the port in `dir` throws the recorded class with the wrong
/// message, and `right` is the stub replaced by one that throws the recorded message.
fn wrong_then_right(dir: &Path, inputs: &Path, wrong: (&str, &str), right: &str) {
port_with(dir, wrong.0, wrong.1);
record(dir, inputs, &[]);
let (report, text) = diff(dir);
assert_eq!(
(report["passed"].as_u64(), report["failed"].as_u64()),
(Some(2), Some(0)),
"{report:#}"
);
assert_eq!(report["comparison"]["messages"], false, "{report:#}");
assert_eq!(report["comparison"]["unchecked_messages"], 1, "{report:#}");
assert!(text.contains(NOT_COMPARED), "{text}");
record(dir, inputs, &["--messages"]);
let saved = std::fs::read_to_string(dir.join(bridge::MANIFEST)).unwrap();
assert!(saved.contains("\"messages\": true"), "{saved}");
let recorded_from =
std::fs::read_to_string(dir.join(rust_anything::recording::RECORDED_FROM)).unwrap();
assert!(
recorded_from.contains("\"messages\": true"),
"{recorded_from}"
);
let (report, text) = diff(dir);
assert_eq!(
(report["passed"].as_u64(), report["failed"].as_u64()),
(Some(1), Some(1)),
"{report:#}"
);
assert_eq!(report["comparison"]["messages"], true, "{report:#}");
assert!(!text.contains("error messages not compared"), "{text}");
port_with(dir, wrong.1, right);
let (report, _) = diff(dir);
assert_eq!(
(report["passed"].as_u64(), report["failed"].as_u64()),
(Some(2), Some(0)),
"{report:#}"
);
// `--no-messages` goes back to the class alone, and says so again.
record(dir, inputs, &["--no-messages"]);
let (_, text) = diff(dir);
assert!(text.contains(NOT_COMPARED), "{text}");
}
#[test]
fn napi_ports_are_held_to_the_recorded_message_only_with_messages() {
if !common::have("node") {
return;
}
let root = project(
"napi",
&[
("package.json", r#"{"name":"guard","version":"0.1.0"}"#),
(
"src/guard.ts",
"export function check(n: number): number {\n if (n < 0) throw new RangeError('negative input');\n return n;\n}\n",
),
],
);
let dir = bridged(&root, "src/guard.ts", Kind::Napi, "guard-messages-rs");
let inputs = root.join("inputs.jsonl");
std::fs::write(
&inputs,
"{\"fn\": \"check\", \"args\": [-1]}\n{\"fn\": \"check\", \"args\": [2]}\n",
)
.unwrap();
wrong_then_right(
&dir,
&inputs,
(
"unimplemented!(\"port `check` from src/guard.ts\")",
"if n < 0.0 { return Err(\"RangeError: wrong text\".into()); }\n Ok(n)",
),
"if n < 0.0 { return Err(\"RangeError: negative input\".into()); }\n Ok(n)",
);
}
#[test]
fn python_ports_are_held_to_the_recorded_message_only_with_messages() {
if common::python().is_none() {
return;
}
let root = project(
"pyo3",
&[
(
"pyproject.toml",
"[project]\nname = \"guard\"\nversion = \"0.1.0\"\n",
),
(
"guard/__init__.py",
"def check(text: str) -> str:\n if not text:\n raise ValueError(\"empty input\")\n return text\n",
),
],
);
let dir = bridged(&root, "guard/", Kind::Pyo3, "guard-messages-pyo3-rs");
let inputs = root.join("inputs.jsonl");
std::fs::write(
&inputs,
"{\"fn\": \"check\", \"args\": [\"\"]}\n{\"fn\": \"check\", \"args\": [\"ok\"]}\n",
)
.unwrap();
wrong_then_right(
&dir,
&inputs,
(
"unimplemented!(\"port `check` from guard/__init__.py\")",
"if text.is_empty() {\n return Err(\"ValueError: wrong text\".into());\n }\n Ok(text)",
),
"if text.is_empty() {\n return Err(\"ValueError: empty input\".into());\n }\n Ok(text)",
);
}
/// Two recorded errors of one class, the port throwing it with the first case's message: every
/// case passes on the class alone, the second fails once messages count.
const CASES: &str = "{\"fn\":\"check\",\"args\":[1],\"error\":\"right text\",\"error_type\":\"TYPE\"}\n\
{\"fn\":\"check\",\"args\":[2],\"error\":\"other text\",\"error_type\":\"TYPE\"}\n";
fn cases(dir: &Path, error_type: &str) -> std::path::PathBuf {
let path = dir.join("cases.jsonl");
std::fs::write(&path, CASES.replace("TYPE", error_type)).unwrap();
path
}
/// Runs `cmd` without and with `RUST_ANYTHING_MESSAGES=1` and returns `(passed, failed)` of each.
fn both_ways(mut cmd: impl FnMut() -> Command, out: &Path) -> ((u64, u64), (u64, u64)) {
let mut run = |messages: bool| {
let mut c = cmd();
if messages {
c.env("RUST_ANYTHING_MESSAGES", "1");
} else {
c.env_remove("RUST_ANYTHING_MESSAGES");
}
let output = c.output().unwrap();
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value =
serde_json::from_slice(&std::fs::read(out).unwrap()).unwrap();
(
report["passed"].as_u64().unwrap(),
report["failed"].as_u64().unwrap(),
)
};
(run(false), run(true))
}
#[test]
fn the_ruby_driver_compares_messages_when_asked() {
if !common::have("ruby") {
return;
}
let dir = project(
"ruby",
&[(
"thrower.rb",
"module Thrower\n def self.check(*_args)\n raise ArgumentError, \"right text\"\n end\nend\n",
)],
);
let cases = cases(&dir, "ArgumentError");
std::fs::write(dir.join("targets.json"), r#"{"check":["Thrower","check"]}"#).unwrap();
let out = dir.join("diff.json");
let counts = both_ways(
|| {
let mut c = Command::new("ruby");
c.arg("-e")
.arg(rust_anything::codegen_ruby::driver())
.arg("diff")
.arg(dir.join("targets.json"))
.arg(&cases)
.arg(&out)
.arg("0")
.arg(dir.join("thrower.rb"));
c
},
&out,
);
assert_eq!(counts, ((2, 0), (1, 1)));
}
#[test]
fn the_php_driver_compares_messages_when_asked() {
if !common::have("php") {
return;
}
let dir = project(
"php",
&[(
"unit.php",
"<?php\nfunction check($n) { throw new \\InvalidArgumentException('right text'); }\n",
)],
);
let cases = cases(&dir, "InvalidArgumentException");
std::fs::write(dir.join("driver.php"), rust_anything::codegen_php::driver()).unwrap();
std::fs::write(dir.join("targets.json"), r#"{"check": "check"}"#).unwrap();
let out = dir.join("diff.json");
let counts = both_ways(
|| {
let mut c = Command::new("php");
c.arg(dir.join("driver.php"))
.arg("diff")
.arg(dir.join("targets.json"))
.arg(&cases)
.arg(&out)
.arg("0")
.arg(dir.join("unit.php"));
c
},
&out,
);
assert_eq!(counts, ((2, 0), (1, 1)));
}
#[test]
fn the_powershell_driver_compares_messages_when_asked() {
if !common::have("pwsh") {
return;
}
let dir = project(
"pwsh",
&[(
"Tools.ps1",
"function Test-Check { param([int]$n) throw [System.ArgumentException]::new('right text') }\n",
)],
);
let cases = dir.join("cases.jsonl");
std::fs::write(
&cases,
CASES
.replace("TYPE", "System.ArgumentException")
.replace("check", "Test-Check"),
)
.unwrap();
std::fs::write(
dir.join("driver.ps1"),
rust_anything::codegen_powershell::driver(),
)
.unwrap();
std::fs::write(
dir.join("targets.json"),
r#"{"Test-Check": {"params": ["n"]}}"#,
)
.unwrap();
let out = dir.join("diff.json");
let counts = both_ways(
|| {
let mut c = Command::new("pwsh");
c.args(["-NoProfile", "-NonInteractive", "-File"])
.arg(dir.join("driver.ps1"))
.arg("diff")
.arg(dir.join("targets.json"))
.arg(&cases)
.arg(&out)
.arg("0")
.arg(dir.join("Tools.ps1"));
c
},
&out,
);
assert_eq!(counts, ((2, 0), (1, 1)));
}
#[test]
fn the_java_driver_compares_messages_when_asked() {
if !common::have("java") || !common::have("javac") {
return;
}
let dir = project(
"java",
&[
(
"RustAnythingDriver.java",
rust_anything::codegen_java::DRIVER_JAVA,
),
(
"RustAnythingJson.java",
rust_anything::codegen_java::JSON_JAVA,
),
(
"Thrower.java",
"public class Thrower { public static int check(int n) { throw new IllegalArgumentException(\"right text\"); } }",
),
("targets.json", r#"{"check":["Thrower","check"]}"#),
],
);
cases(&dir, "IllegalArgumentException");
let compiled = Command::new("javac")
.current_dir(&dir)
.args([
"-d",
".",
"RustAnythingDriver.java",
"RustAnythingJson.java",
"Thrower.java",
])
.output()
.unwrap();
assert!(
compiled.status.success(),
"{}",
String::from_utf8_lossy(&compiled.stderr)
);
let out = dir.join("diff.json");
let run = |property: Option<&str>| {
let mut c = Command::new("java");
c.current_dir(&dir);
c.args(property);
c.args([
"-cp",
".",
"rustanything.RustAnythingDriver",
"diff",
"targets.json",
"cases.jsonl",
"diff.json",
]);
let output = c.output().unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: harness::DiffOutcome =
serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap();
(report.passed, report.failed)
};
assert_eq!(run(None), (2, 0));
assert_eq!(run(Some("-Drust-anything.messages=true")), (1, 1));
}
#[test]
fn the_csharp_driver_compares_messages_when_asked() {
if !common::have("dotnet") {
return;
}
let dir = project("csharp", &[]);
let dotnet = || {
let mut c = Command::new("dotnet");
c.env("DOTNET_CLI_TELEMETRY_OPTOUT", "1")
.env("DOTNET_NOLOGO", "1")
.env("DOTNET_SKIP_FIRST_TIME_EXPERIENCE", "1");
c
};
let version = dotnet().arg("--version").output().unwrap();
let major = String::from_utf8_lossy(&version.stdout)
.trim()
.split('.')
.next()
.unwrap()
.to_string();
std::fs::write(
dir.join("Driver.cs"),
rust_anything::codegen_csharp::driver(),
)
.unwrap();
std::fs::write(
dir.join("Thrower.cs"),
"namespace Acme\n{\n public static class Thrower\n {\n \
public static int Check(int n) => throw new global::System.ArgumentException(\"right text\");\n }\n}\n",
)
.unwrap();
std::fs::write(
dir.join("Check.csproj"),
format!(
"<Project Sdk=\"Microsoft.NET.Sdk\">\n <PropertyGroup>\n <OutputType>Exe</OutputType>\n \
<TargetFramework>net{major}.0</TargetFramework>\n <Nullable>enable</Nullable>\n \
<LangVersion>latest</LangVersion>\n <AllowUnsafeBlocks>true</AllowUnsafeBlocks>\n \
</PropertyGroup>\n</Project>\n"
),
)
.unwrap();
std::fs::write(
dir.join("targets.json"),
r#"{"check": {"original": "Acme.Thrower", "rust": "Acme.Rust.Thrower", "method": "Check"}}"#,
)
.unwrap();
let cases = cases(&dir, "System.ArgumentException");
let built = dotnet()
.current_dir(&dir)
.args(["build", "Check.csproj", "-o", "bin", "--nologo", "-v", "q"])
.output()
.unwrap();
assert!(
built.status.success(),
"{}",
String::from_utf8_lossy(&built.stdout)
);
let out = dir.join("diff.json");
let counts = both_ways(
|| {
let mut c = dotnet();
c.arg(dir.join("bin").join("Check.dll"))
.arg("diff")
.arg(dir.join("targets.json"))
.arg(&cases)
.arg(&out)
.arg("0");
c
},
&out,
);
assert_eq!(counts, ((2, 0), (1, 1)));
}