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
fix(java): write a lone surrogate as a $utf16 marker so record, diff and gate can read it (#1298)
Alexc61d0419840b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bc204769..af3b5862 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,14 @@## Unreleased+- Java: a string with a lone UTF-16 surrogate (such as `substring` cutting an emoji in half) is+ now written as `{"$utf16": [code units]}`, as the other languages do, and the driver accepts+ that marker as a `String` argument. Before, the driver wrote `\ud83d` on its own, which a strict+ JSON reader refuses, so `record` ended with `unexpected end of hex escape` and `diff` and+ `gate` could not read the recording back. This covers a `String`, a `char`, and values inside+ lists and maps (Kotlin and Android use the same driver). An exception message and a map key+ stay text, with a lone surrogate replaced by U+FFFD. A recording made before this change still+ holds the old escapes: record it again (#1291).- Ruby: a crate bridged without `--batch` passes `gate`'s clippy check. The generated `src/lib.rs`imported magnus's `Object` and `method`, which only the batch classes use, so clippy with`-D warnings` failed on `unused imports: Object and method` in generated code the port's authordiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex cb230313..cccb0d0f 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -113,6 +113,8 @@ paths in what you commit. CI runs it on every file.- `tests/go_unsigned.rs`: Go `uint64`, `uint` and `uintptr` keep their range in the port.- `tests/java_package_declaration.rs` and `tests/java_replay.rs`: Java recording with comments inthe package declaration, and replay that tells `null` from a rejected argument.+ - `tests/java_lone_surrogate.rs`: Java strings holding a lone UTF-16 surrogate, recorded and+ replayed as `{"$utf16": [...]}`.- `tests/ruby_recording.rs`: Ruby results that cannot be encoded.- `tests/powershell.rs`: a PowerShell module bridged, recorded, diffed, gated and enabled;skipped without `pwsh` 7.4+.diff --git a/src/codegen_java.rs b/src/codegen_java.rsindex b51a41b9..6b5f86cf 100644--- a/src/codegen_java.rs+++ b/src/codegen_java.rs@@ -173,7 +173,21 @@ public final class RustAnythingJson {if (v == null) {out.append("null");} else if (v instanceof CharSequence || v instanceof Character) {- quote(out, v.toString());+ String s = v.toString();+ if (hasLoneSurrogate(s)) {+ // JSON text cannot carry a lone half (a strict reader rejects "\ud83d" on its own),+ // so the string goes as its UTF-16 code units, as the other languages do.+ out.append("{\"$utf16\":[");+ for (int i = 0; i < s.length(); i++) {+ if (i > 0) {+ out.append(',');+ }+ out.append((int) s.charAt(i));+ }+ out.append("]}");+ } else {+ quote(out, s);+ }} else if (v instanceof Double || v instanceof Float) {double d = ((Number) v).doubleValue();if (Double.isNaN(d)) {@@ -199,7 +213,8 @@ public final class RustAnythingJson {out.append(',');}first = false;- quote(out, String.valueOf(e.getKey()));+ // A key cannot be a {"$utf16": ...} object: a lone half in it becomes U+FFFD.+ quote(out, message(String.valueOf(e.getKey())));out.append(':');write(out, e.getValue());}@@ -228,6 +243,55 @@ public final class RustAnythingJson {}}+ /** An error message as JSON text can hold it: a lone surrogate becomes U+FFFD. */+ public static String message(String s) {+ StringBuilder sb = new StringBuilder();+ for (int i = 0; i < s.length(); i++) {+ char c = s.charAt(i);+ if (Character.isHighSurrogate(c) && i + 1 < s.length() && Character.isLowSurrogate(s.charAt(i + 1))) {+ sb.append(c).append(s.charAt(++i));+ } else {+ sb.append(Character.isSurrogate(c) ? (char) 0xFFFD : c);+ }+ }+ return sb.toString();+ }++ private static boolean hasLoneSurrogate(String s) {+ for (int i = 0; i < s.length(); i++) {+ char c = s.charAt(i);+ if (Character.isHighSurrogate(c) && i + 1 < s.length() && Character.isLowSurrogate(s.charAt(i + 1))) {+ i++;+ } else if (Character.isSurrogate(c)) {+ return true;+ }+ }+ return false;+ }++ /** The string a {"$utf16": [code units]} marker stands for, or null when v is not one. */+ private static String utf16(Object v) {+ if (!(v instanceof Map) || !((Map<?, ?>) v).containsKey("$utf16")) {+ return null;+ }+ Object units = ((Map<?, ?>) v).get("$utf16");+ if (((Map<?, ?>) v).size() != 1 || !(units instanceof List)) {+ return null;+ }+ StringBuilder sb = new StringBuilder();+ for (Object u : (List<?>) units) {+ if (!(u instanceof Long || u instanceof Integer)) {+ return null;+ }+ long unit = ((Number) u).longValue();+ if (unit < 0 || unit > 0xffff) {+ return null;+ }+ sb.append((char) unit);+ }+ return sb.toString();+ }+private static void quote(StringBuilder out, String s) {out.append('"');for (int i = 0; i < s.length(); i++) {@@ -369,6 +433,10 @@ public final class RustAnythingJson {return null;}if (c == String.class || c == CharSequence.class) {+ String units = utf16(v);+ if (units != null) {+ return units;+ }if (!(v instanceof String)) {throw new Mismatch("not a string");}@@ -841,10 +909,10 @@ public final class RustAnythingDriver {out.put("ok", RustAnythingJson.parse(RustAnythingJson.write(result)));} catch (InvocationTargetException e) {Throwable cause = e.getCause();- out.put("error", String.valueOf(cause.getMessage()));+ out.put("error", RustAnythingJson.message(String.valueOf(cause.getMessage())));out.put("error_type", cause.getClass().getSimpleName());} catch (ReflectiveOperationException e) {- out.put("error", e.toString());+ out.put("error", RustAnythingJson.message(e.toString()));out.put("error_type", "ReflectiveOperationException");} catch (StackOverflowError e) {out.put("error", "stack overflow");diff --git a/tests/java_lone_surrogate.rs b/tests/java_lone_surrogate.rsnew file mode 100644index 00000000..213706d1--- /dev/null+++ b/tests/java_lone_surrogate.rs@@ -0,0 +1,141 @@+mod common;++use std::{path::Path, process::Command};++use rust_anything::{+ codegen_java::{DRIVER_JAVA, ERROR_JAVA, JSON_JAVA, WIRE_JAVA},+ harness::DiffOutcome,+};+use serde_json::{Value, json};++#[test]+fn java_record_and_diff_keep_a_lone_surrogate_readable() {+ if !common::have("java") || !common::have("javac") {+ return;+ }++ let root = std::env::temp_dir().join(format!(+ "rust-anything-java-surrogate-{}",+ std::process::id()+ ));+ let _ = std::fs::remove_dir_all(&root);+ std::fs::create_dir_all(&root).unwrap();+ let result = record_and_diff(&root);+ let _ = std::fs::remove_dir_all(&root);+ result.unwrap();+}++fn record_and_diff(root: &Path) -> anyhow::Result<()> {+ std::fs::create_dir_all(root.join("acme"))?;+ std::fs::write(+ root.join("acme/Quoted.java"),+ r#"package acme;+public class Quoted {+ public static String unquote(String name) {+ return name.substring(1, name.length() - 1).replace("\"\"", "\"");+ }+ public static int length(String s) {+ return s.length();+ }+ public static String fail(String s) {+ throw new IllegalArgumentException("bad:" + s.substring(0, 2));+ }+ public static java.util.List<String> halves(String s) {+ return java.util.Arrays.asList(s.substring(1), s.substring(0, 1));+ }+ public static java.util.Map<String, Integer> keyed(String s) {+ return java.util.Collections.singletonMap(s.substring(0, 1), 1);+ }+}+"#,+ )?;+ std::fs::write(root.join("RustAnythingDriver.java"), DRIVER_JAVA)?;+ std::fs::write(root.join("RustAnythingJson.java"), JSON_JAVA)?;+ std::fs::write(root.join("RustAnythingWire.java"), WIRE_JAVA)?;+ std::fs::write(root.join("RustAnythingError.java"), ERROR_JAVA)?;+ std::fs::write(+ root.join("targets.json"),+ r#"{"unquote":["acme.Quoted","unquote"],"length":["acme.Quoted","length"],"fail":["acme.Quoted","fail"],"halves":["acme.Quoted","halves"],"keyed":["acme.Quoted","keyed"]}"#,+ )?;+ // The first case cuts the surrogate pair of the emoji in two, so the result ends in a lone high+ // surrogate; the second hands such a string in; the third keeps the pair whole.+ std::fs::write(+ root.join("inputs.json"),+ r#"[{"fn":"unquote","args":["abcπ"]},+ {"fn":"length","args":[{"$utf16":[97,55357]}]},+ {"fn":"unquote","args":["\"aπ\""]},+ {"fn":"fail","args":["aπ"]},+ {"fn":"halves","args":["π"]},+ {"fn":"keyed","args":["π"]},+ {"fn":"length","args":[{"$utf16":[97],"extra":1}]},+ {"fn":"length","args":[{"$utf16":[97.5]}]}]"#,+ )?;+ run(Command::new("javac").current_dir(root).args([+ "-d",+ ".",+ "RustAnythingDriver.java",+ "RustAnythingJson.java",+ "RustAnythingWire.java",+ "RustAnythingError.java",+ "acme/Quoted.java",+ ]))?;++ run(Command::new("java").current_dir(root).args([+ "-cp",+ ".",+ "rustanything.RustAnythingDriver",+ "record",+ "targets.json",+ "inputs.json",+ "cases.jsonl",+ ]))?;++ // Rust reads every recorded line as strict JSON, and a lone half must not break that.+ let text = std::fs::read_to_string(root.join("cases.jsonl"))?;+ let lines: Vec<Value> = text+ .lines()+ .map(serde_json::from_str)+ .collect::<Result<_, _>>()?;+ // The two malformed markers are refused as invalid arguments, so they are not recorded.+ assert_eq!(lines.len(), 6, "{text}");+ assert_eq!(+ lines[0]["ok"],+ json!({"$utf16": [98, 99, 0xd83d]}),+ "{text}"+ );+ assert_eq!(lines[1]["ok"], json!(2), "{text}");+ assert_eq!(lines[2]["ok"], json!("a\u{1f600}"), "{text}");+ // An error message stays text, with the lone half replaced.+ assert_eq!(lines[3]["error"], json!("bad:a\u{fffd}"), "{text}");+ // The two halves of a pair, each alone, in a list.+ assert_eq!(+ lines[4]["ok"],+ json!([{"$utf16": [0xde00]}, {"$utf16": [0xd83d]}]),+ "{text}"+ );+ // A map key stays a string, with the lone half replaced.+ assert_eq!(lines[5]["ok"], json!({"\u{fffd}": 1}), "{text}");++ run(Command::new("java").current_dir(root).args([+ "-cp",+ ".",+ "rustanything.RustAnythingDriver",+ "diff",+ "targets.json",+ "cases.jsonl",+ "diff.json",+ ]))?;+ let diff: DiffOutcome = serde_json::from_slice(&std::fs::read(root.join("diff.json"))?)?;+ assert_eq!((diff.passed, diff.failed), (6, 0), "{diff:?}");+ Ok(())+}++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(())+}