Skip to main content

rust_anything/
codegen_java.rs

1//! Java: the JNI wrapper (the original classes' static methods over the Rust library), a small
2//! JSON codec with no dependencies, and the reflection driver for record, diff and bench.
3
4use std::fmt::Write as _;
5
6use crate::bridge::Manifest;
7use crate::codegen_ffi::java_native_class;
8use crate::lang::java::receiver;
9
10/// `rustanything/RustAnythingJson.java`: JSON text to Java values and back, conversion to declared
11/// generic types, and the markers for floats JSON cannot carry.
12pub const JSON_JAVA: &str = r#"package rustanything;
13
14import java.lang.reflect.Array;
15import java.lang.reflect.GenericArrayType;
16import java.lang.reflect.ParameterizedType;
17import java.lang.reflect.Type;
18import java.math.BigInteger;
19import java.util.ArrayList;
20import java.util.Collection;
21import java.util.LinkedHashMap;
22import java.util.List;
23import java.util.Map;
24import java.util.Optional;
25
26/** Generated by rust-anything: a dependency-free JSON codec for the bridge. */
27public final class RustAnythingJson {
28    private RustAnythingJson() {}
29
30    /** Captures a generic type: {@code new TypeRef<List<String>>() {}.type()}. */
31    public abstract static class TypeRef<T> {
32        public Type type() {
33            return ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
34        }
35    }
36
37    /** A value that does not fit the declared type. */
38    public static final class Mismatch extends RuntimeException {
39        public Mismatch(String message) {
40            super(message);
41        }
42    }
43
44    // ---- parse ----
45
46    public static Object parse(String text) {
47        int[] pos = {0};
48        Object value = value(text, pos);
49        skip(text, pos);
50        if (pos[0] != text.length()) {
51            throw new IllegalArgumentException("trailing JSON at " + pos[0]);
52        }
53        return value;
54    }
55
56    private static void skip(String s, int[] pos) {
57        while (pos[0] < s.length() && Character.isWhitespace(s.charAt(pos[0]))) {
58            pos[0]++;
59        }
60    }
61
62    private static Object value(String s, int[] pos) {
63        skip(s, pos);
64        char c = s.charAt(pos[0]);
65        if (c == '{') {
66            Map<String, Object> map = new LinkedHashMap<>();
67            pos[0]++;
68            skip(s, pos);
69            if (s.charAt(pos[0]) == '}') {
70                pos[0]++;
71                return map;
72            }
73            while (true) {
74                skip(s, pos);
75                String key = string(s, pos);
76                skip(s, pos);
77                pos[0]++; // ':'
78                map.put(key, value(s, pos));
79                skip(s, pos);
80                if (s.charAt(pos[0]++) == '}') {
81                    return map;
82                }
83            }
84        }
85        if (c == '[') {
86            List<Object> list = new ArrayList<>();
87            pos[0]++;
88            skip(s, pos);
89            if (s.charAt(pos[0]) == ']') {
90                pos[0]++;
91                return list;
92            }
93            while (true) {
94                list.add(value(s, pos));
95                skip(s, pos);
96                if (s.charAt(pos[0]++) == ']') {
97                    return list;
98                }
99            }
100        }
101        if (c == '"') {
102            return string(s, pos);
103        }
104        if (s.startsWith("true", pos[0])) {
105            pos[0] += 4;
106            return Boolean.TRUE;
107        }
108        if (s.startsWith("false", pos[0])) {
109            pos[0] += 5;
110            return Boolean.FALSE;
111        }
112        if (s.startsWith("null", pos[0])) {
113            pos[0] += 4;
114            return null;
115        }
116        int start = pos[0];
117        while (pos[0] < s.length() && "+-0123456789.eE".indexOf(s.charAt(pos[0])) >= 0) {
118            pos[0]++;
119        }
120        String number = s.substring(start, pos[0]);
121        if (number.contains(".") || number.contains("e") || number.contains("E")) {
122            return Double.parseDouble(number);
123        }
124        BigInteger big = new BigInteger(number);
125        return big.bitLength() < 64 ? (Object) big.longValue() : big;
126    }
127
128    private static String string(String s, int[] pos) {
129        StringBuilder out = new StringBuilder();
130        pos[0]++; // opening quote
131        while (true) {
132            char c = s.charAt(pos[0]++);
133            if (c == '"') {
134                return out.toString();
135            }
136            if (c != '\\') {
137                out.append(c);
138                continue;
139            }
140            char e = s.charAt(pos[0]++);
141            switch (e) {
142                case 'n': out.append('\n'); break;
143                case 't': out.append('\t'); break;
144                case 'r': out.append('\r'); break;
145                case 'b': out.append('\b'); break;
146                case 'f': out.append('\f'); break;
147                case 'u':
148                    out.append((char) Integer.parseInt(s.substring(pos[0], pos[0] + 4), 16));
149                    pos[0] += 4;
150                    break;
151                default: out.append(e);
152            }
153        }
154    }
155
156    // ---- write ----
157
158    /** JSON text of a Java value; floats JSON cannot carry become {"$num": ...}. */
159    public static String write(Object v) {
160        StringBuilder out = new StringBuilder();
161        write(out, v);
162        return out.toString();
163    }
164
165    private static void write(StringBuilder out, Object v) {
166        if (v == null) {
167            out.append("null");
168        } else if (v instanceof String || v instanceof Character) {
169            quote(out, v.toString());
170        } else if (v instanceof Double || v instanceof Float) {
171            double d = ((Number) v).doubleValue();
172            if (Double.isNaN(d)) {
173                out.append("{\"$num\":\"NaN\"}");
174            } else if (Double.isInfinite(d)) {
175                out.append(d > 0 ? "{\"$num\":\"Infinity\"}" : "{\"$num\":\"-Infinity\"}");
176            } else if (d == 0 && 1 / d < 0) {
177                out.append("{\"$num\":\"-0\"}");
178            } else if (d == Math.rint(d) && Math.abs(d) < 1e16) {
179                out.append(Long.toString((long) d)).append(".0");
180            } else {
181                out.append(Double.toString(d).replace("E", "e"));
182            }
183        } else if (v instanceof Number || v instanceof Boolean) {
184            out.append(v.toString());
185        } else if (v instanceof Optional) {
186            write(out, ((Optional<?>) v).orElse(null));
187        } else if (v instanceof Map) {
188            out.append('{');
189            boolean first = true;
190            for (Map.Entry<?, ?> e : ((Map<?, ?>) v).entrySet()) {
191                if (!first) {
192                    out.append(',');
193                }
194                first = false;
195                quote(out, String.valueOf(e.getKey()));
196                out.append(':');
197                write(out, e.getValue());
198            }
199            out.append('}');
200        } else if (v instanceof Collection) {
201            out.append('[');
202            boolean first = true;
203            for (Object x : (Collection<?>) v) {
204                if (!first) {
205                    out.append(',');
206                }
207                first = false;
208                write(out, x);
209            }
210            out.append(']');
211        } else if (v.getClass().isArray()) {
212            List<Object> items = new ArrayList<>();
213            for (int i = 0; i < Array.getLength(v); i++) {
214                items.add(Array.get(v, i));
215            }
216            write(out, items);
217        } else {
218            out.append("{\"$object\":");
219            quote(out, v.getClass().getName());
220            out.append('}');
221        }
222    }
223
224    private static void quote(StringBuilder out, String s) {
225        out.append('"');
226        for (int i = 0; i < s.length(); i++) {
227            char c = s.charAt(i);
228            switch (c) {
229                case '"': out.append("\\\""); break;
230                case '\\': out.append("\\\\"); break;
231                case '\n': out.append("\\n"); break;
232                case '\t': out.append("\\t"); break;
233                case '\r': out.append("\\r"); break;
234                default:
235                    if (c < 0x20 || Character.isSurrogate(c)) {
236                        // Escaped surrogates keep lone halves intact through any UTF-8 layer.
237                        out.append(String.format("\\u%04x", (int) c));
238                    } else {
239                        out.append(c);
240                    }
241            }
242        }
243        out.append('"');
244    }
245
246    // ---- convert ----
247
248    private static double number(Object v) {
249        if (v instanceof Number) {
250            return ((Number) v).doubleValue();
251        }
252        if (v instanceof Map && ((Map<?, ?>) v).containsKey("$num")) {
253            switch (String.valueOf(((Map<?, ?>) v).get("$num"))) {
254                case "NaN": return Double.NaN;
255                case "Infinity": return Double.POSITIVE_INFINITY;
256                case "-Infinity": return Double.NEGATIVE_INFINITY;
257                case "-0": return -0.0;
258                default: break;
259            }
260        }
261        throw new Mismatch("not a number: " + v);
262    }
263
264    private static long integer(Object v, long min, long max) {
265        if (v instanceof Long || v instanceof Integer) {
266            long n = ((Number) v).longValue();
267            if (n >= min && n <= max) {
268                return n;
269            }
270        }
271        throw new Mismatch("not an integer in range: " + v);
272    }
273
274    /** Converts a parsed JSON value to {@code type}. */
275    public static Object convert(Object v, Type type) {
276        if (type instanceof ParameterizedType) {
277            ParameterizedType p = (ParameterizedType) type;
278            Class<?> raw = (Class<?>) p.getRawType();
279            Type[] args = p.getActualTypeArguments();
280            if (Optional.class.equals(raw)) {
281                return v == null ? Optional.empty() : Optional.of(convert(v, args[0]));
282            }
283            if (v == null) {
284                return null;
285            }
286            if (Map.class.isAssignableFrom(raw)) {
287                if (!(v instanceof Map)) {
288                    throw new Mismatch("not an object");
289                }
290                Map<String, Object> out = new LinkedHashMap<>();
291                for (Map.Entry<?, ?> e : ((Map<?, ?>) v).entrySet()) {
292                    out.put((String) e.getKey(), convert(e.getValue(), args[1]));
293                }
294                return out;
295            }
296            if (Iterable.class.isAssignableFrom(raw)) {
297                if (!(v instanceof List)) {
298                    throw new Mismatch("not an array");
299                }
300                List<Object> out = new ArrayList<>();
301                for (Object x : (List<?>) v) {
302                    out.add(convert(x, args[0]));
303                }
304                return out;
305            }
306            throw new Mismatch("unsupported type " + type);
307        }
308        if (type instanceof GenericArrayType) {
309            return array(v, ((GenericArrayType) type).getGenericComponentType());
310        }
311        Class<?> c = (Class<?>) type;
312        if (c.isArray()) {
313            return array(v, c.getComponentType());
314        }
315        if (v == null) {
316            if (c.isPrimitive()) {
317                throw new Mismatch("null for " + c);
318            }
319            return null;
320        }
321        if (c == String.class || c == CharSequence.class) {
322            if (!(v instanceof String)) {
323                throw new Mismatch("not a string");
324            }
325            return v;
326        }
327        if (c == int.class || c == Integer.class) {
328            return (int) integer(v, Integer.MIN_VALUE, Integer.MAX_VALUE);
329        }
330        if (c == long.class || c == Long.class) {
331            return integer(v, Long.MIN_VALUE, Long.MAX_VALUE);
332        }
333        if (c == short.class || c == Short.class) {
334            return (short) integer(v, Short.MIN_VALUE, Short.MAX_VALUE);
335        }
336        if (c == byte.class || c == Byte.class) {
337            return (byte) integer(v, Byte.MIN_VALUE, Byte.MAX_VALUE);
338        }
339        if (c == double.class || c == Double.class) {
340            return number(v);
341        }
342        if (c == float.class || c == Float.class) {
343            return (float) number(v);
344        }
345        if (c == boolean.class || c == Boolean.class) {
346            if (!(v instanceof Boolean)) {
347                throw new Mismatch("not a boolean");
348            }
349            return v;
350        }
351        if (c == Object.class) {
352            return v;
353        }
354        throw new Mismatch("unsupported type " + c);
355    }
356
357    private static Object array(Object v, Type component) {
358        if (!(v instanceof List)) {
359            throw new Mismatch("not an array");
360        }
361        List<?> list = (List<?>) v;
362        Class<?> raw = component instanceof Class ? (Class<?>) component : (Class<?>) ((ParameterizedType) component).getRawType();
363        Object out = Array.newInstance(raw, list.size());
364        for (int i = 0; i < list.size(); i++) {
365            Array.set(out, i, convert(list.get(i), component));
366        }
367        return out;
368    }
369}
370"#;
371
372/// Boxes a primitive type for generics: `int` to `Integer`.
373fn boxed(t: &str) -> String {
374    match t.trim() {
375        "int" => "Integer".into(),
376        "long" => "Long".into(),
377        "short" => "Short".into(),
378        "byte" => "Byte".into(),
379        "double" => "Double".into(),
380        "float" => "Float".into(),
381        "boolean" => "Boolean".into(),
382        "char" => "Character".into(),
383        other => other.into(),
384    }
385}
386
387/// The native class: loads the Rust library and calls the dispatcher.
388pub fn native_class(m: &Manifest, api: &crate::codegen::PortApi) -> String {
389    let class = java_native_class(m);
390    let lib = m.lib_name();
391    format!(
392        r#"package rustanything;
393
394import java.lang.reflect.Type;
395import java.util.*;
396
397/** Generated by rust-anything: calls the Rust port of `{unit}` through JNI. */
398public final class {class} {{
399    private {class}() {{}}
400
401    static {{
402        String path = System.getProperty("rust-anything.lib.{lib}");
403        if (path != null) {{
404            System.load(path);
405        }} else {{
406            System.loadLibrary("{lib}");
407        }}
408    }}
409
410    private static native String call(String name, String args);
411
412    // Typed methods: primitives and strings cross JNI directly, without JSON.
413{typed}{calls}
414
415    /** Calls the port of {{@code name}}; its answer is converted to {{@code type}}. */
416    public static Object invoke(String name, Type type, Object... args) {{
417        String answer = call(name, RustAnythingJson.write(java.util.Arrays.asList(args)));
418        @SuppressWarnings("unchecked")
419        Map<String, Object> parsed = (Map<String, Object>) RustAnythingJson.parse(answer);
420        if (parsed.containsKey("ok")) {{
421            return type == void.class ? null : RustAnythingJson.convert(parsed.get("ok"), type);
422        }}
423        String message = parsed.containsKey("error")
424            ? String.valueOf(parsed.get("error"))
425            : "Rust panic: " + parsed.get("panic");
426        throw exception(message);
427    }}
428
429    /** {{@code "IllegalArgumentException: msg"}} becomes that exception; anything else a RuntimeException. */
430    private static RuntimeException exception(String message) {{
431        int colon = message.indexOf(": ");
432        if (colon > 0) {{
433            String type = message.substring(0, colon);
434            String rest = message.substring(colon + 2);
435            for (String prefix : new String[] {{"", "java.lang.", "java.util.", "java.io.", "java.time."}}) {{
436                try {{
437                    Class<?> c = Class.forName(prefix + type);
438                    if (RuntimeException.class.isAssignableFrom(c)) {{
439                        return (RuntimeException) c.getConstructor(String.class).newInstance(rest);
440                    }}
441                }} catch (ReflectiveOperationException e) {{
442                    // try the next package
443                }}
444            }}
445        }}
446        return new RuntimeException(message);
447    }}
448}}
449"#,
450        unit = m.unit,
451        typed = typed_declarations(m, api),
452        calls = call_methods(m, api),
453    )
454}
455
456/// The wrapper classes: `(path, source)` for each class of the unit with ported methods.
457pub fn wrappers(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<(String, String)> {
458    let typed = direct_names(m, api);
459    let native = java_native_class(m);
460    let mut classes: Vec<(String, Vec<String>)> = Vec::new();
461    for f in &m.exports {
462        let (class, name) = receiver(f);
463        let ret = f.native_return.as_deref().unwrap_or("void");
464        let params: Vec<String> = f
465            .params
466            .iter()
467            .map(|p| {
468                format!(
469                    "{} {}",
470                    p.native_type.as_deref().unwrap_or("Object"),
471                    p.name
472                )
473            })
474            .collect();
475        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
476        let args = if args.is_empty() {
477            String::new()
478        } else {
479            format!(", {}", args.join(", "))
480        };
481        let direct = format!(
482            "rustanything.{native}.call_{}({})",
483            f.name,
484            f.params
485                .iter()
486                .map(|p| p.name.as_str())
487                .collect::<Vec<_>>()
488                .join(", ")
489        );
490        let body = if typed.contains(&f.name) {
491            if ret == "void" {
492                format!("{direct};")
493            } else {
494                format!("return {direct};")
495            }
496        } else if ret == "void" {
497            format!(
498                "rustanything.{native}.invoke(\"{}\", void.class{args});",
499                f.name
500            )
501        } else {
502            format!(
503                "return ({}) rustanything.{native}.invoke(\"{}\", new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type(){args});",
504                boxed(ret),
505                f.name,
506                boxed(ret)
507            )
508        };
509        let method = format!(
510            "    /** The Rust port of `{}` (`{}:{}`). */\n    @SuppressWarnings(\"unchecked\")\n    public static {ret} {name}({}) {{\n        {body}\n    }}\n",
511            f.prototype.as_deref().unwrap_or(&f.name),
512            f.file,
513            f.line,
514            params.join(", ")
515        );
516        match classes.iter_mut().find(|(c, _)| *c == class) {
517            Some((_, methods)) => methods.push(method),
518            None => classes.push((class, vec![method])),
519        }
520    }
521    let imports = imports_of(m);
522    classes
523        .into_iter()
524        .map(|(class, methods)| {
525            let (package, simple) = class.rsplit_once('.').unwrap_or(("", class.as_str()));
526            let path = if package.is_empty() {
527                format!("java/{simple}.java")
528            } else {
529                format!("java/{}/{simple}.java", package.replace('.', "/"))
530            };
531            let mut out = String::new();
532            if !package.is_empty() {
533                let _ = writeln!(out, "package {package};\n");
534            }
535            out.push_str(&imports);
536            let _ = write!(
537                out,
538                "/** The Rust port of `{simple}`, generated by rust-anything: the same static methods. */\n\
539                 public final class {simple} {{\n    private {simple}() {{}}\n\n{}}}\n",
540                methods.join("\n")
541            );
542            (path, out)
543        })
544        .collect()
545}
546
547/// The `java.util` imports the original signatures need.
548fn imports_of(m: &Manifest) -> String {
549    let mut names: Vec<&str> = Vec::new();
550    for f in &m.exports {
551        let types = f
552            .params
553            .iter()
554            .filter_map(|p| p.native_type.as_deref())
555            .chain(f.native_return.as_deref());
556        for t in types {
557            for name in ["List", "Map", "Optional", "Collection", "Set"] {
558                if t.split(|c: char| !c.is_alphanumeric()).any(|w| w == name)
559                    && !names.contains(&name)
560                {
561                    names.push(name);
562                }
563            }
564        }
565    }
566    names.sort_unstable();
567    let mut out: String = names
568        .iter()
569        .map(|n| format!("import java.util.{n};\n"))
570        .collect();
571    if !out.is_empty() {
572        out.push('\n');
573    }
574    out
575}
576
577/// `{ name: [class, method] }` for the driver.
578pub fn targets(m: &Manifest) -> serde_json::Value {
579    serde_json::Value::Object(
580        m.exports
581            .iter()
582            .map(|f| {
583                let (class, name) = receiver(f);
584                (f.name.clone(), serde_json::json!([class, name]))
585            })
586            .collect(),
587    )
588}
589
590/// `rustanything/RustAnythingDriver.java`: calls static methods by name for record, diff and bench.
591pub const DRIVER_JAVA: &str = r#"package rustanything;
592
593import java.io.BufferedWriter;
594import java.lang.reflect.InvocationTargetException;
595import java.lang.reflect.Method;
596import java.lang.reflect.Modifier;
597import java.lang.reflect.Type;
598import java.nio.charset.StandardCharsets;
599import java.nio.file.Files;
600import java.nio.file.Path;
601import java.util.ArrayList;
602import java.util.LinkedHashMap;
603import java.util.List;
604import java.util.Map;
605
606/** Generated by rust-anything: calls the unit's static methods by name. */
607public final class RustAnythingDriver {
608    private RustAnythingDriver() {}
609
610    private static final Map<String, Method> METHODS = new LinkedHashMap<>();
611
612    @SuppressWarnings("unchecked")
613    private static void load(String targetsPath) throws Exception {
614        Map<String, Object> targets = (Map<String, Object>) RustAnythingJson.parse(Files.readString(Path.of(targetsPath)));
615        for (Map.Entry<String, Object> e : targets.entrySet()) {
616            List<Object> t = (List<Object>) e.getValue();
617            try {
618                Class<?> c = Class.forName((String) t.get(0));
619                for (Method m : c.getMethods()) {
620                    if (m.getName().equals(t.get(1)) && Modifier.isStatic(m.getModifiers())) {
621                        METHODS.put(e.getKey(), m);
622                    }
623                }
624            } catch (ClassNotFoundException ex) {
625                // missing: reported per case
626            }
627        }
628    }
629
630    /** {"ok": v} | {"error": msg, "error_type": name} | {"invalid": true} | {"missing": true}. */
631    @SuppressWarnings("unchecked")
632    private static Map<String, Object> call(Map<String, Object> c) {
633        Map<String, Object> out = new LinkedHashMap<>();
634        Method m = METHODS.get((String) c.get("fn"));
635        if (m == null) {
636            out.put("missing", true);
637            return out;
638        }
639        List<Object> args = (List<Object>) c.get("args");
640        Type[] types = m.getGenericParameterTypes();
641        Object[] values = new Object[types.length];
642        try {
643            for (int i = 0; i < types.length; i++) {
644                Object raw = i < args.size() ? args.get(i) : null;
645                if (raw instanceof Map && ((Map<?, ?>) raw).containsKey("$undefined")) {
646                    raw = null;
647                }
648                values[i] = RustAnythingJson.convert(raw, types[i]);
649            }
650        } catch (RustAnythingJson.Mismatch e) {
651            out.put("invalid", true);
652            return out;
653        }
654        try {
655            Object result = m.invoke(null, values);
656            out.put("ok", RustAnythingJson.parse(RustAnythingJson.write(result)));
657        } catch (InvocationTargetException e) {
658            Throwable cause = e.getCause();
659            out.put("error", String.valueOf(cause.getMessage()));
660            out.put("error_type", cause.getClass().getSimpleName());
661        } catch (ReflectiveOperationException e) {
662            out.put("error", e.toString());
663            out.put("error_type", "ReflectiveOperationException");
664        } catch (StackOverflowError e) {
665            out.put("error", "stack overflow");
666            out.put("error_type", "StackOverflowError");
667        }
668        return out;
669    }
670
671    @SuppressWarnings("unchecked")
672    private static List<Map<String, Object>> lines(String path) throws Exception {
673        List<Map<String, Object>> out = new ArrayList<>();
674        for (String line : Files.readAllLines(Path.of(path), StandardCharsets.UTF_8)) {
675            if (!line.isBlank()) {
676                out.add((Map<String, Object>) RustAnythingJson.parse(line));
677            }
678        }
679        return out;
680    }
681
682    private static boolean same(Map<String, Object> expected, Map<String, Object> got) {
683        if (String.valueOf(got.get("error")).contains("Rust panic:")) {
684            return false;
685        }
686        if (expected.containsKey("error")) {
687            return got.containsKey("error") && String.valueOf(expected.get("error_type")).equals(String.valueOf(got.get("error_type")));
688        }
689        return expected.containsKey("ok") && got.containsKey("ok")
690            && RustAnythingJson.write(expected.get("ok")).equals(RustAnythingJson.write(got.get("ok")));
691    }
692
693    @SuppressWarnings("unchecked")
694    public static void main(String[] argv) throws Exception {
695        String mode = argv[0];
696        load(argv[1]);
697        String casesPath = argv[2];
698        Path outPath = Path.of(argv[3]);
699        if (mode.equals("record")) {
700            List<Object> cases = (List<Object>) RustAnythingJson.parse(Files.readString(Path.of(casesPath)));
701            String progress = System.getenv("RUST_ANYTHING_PROGRESS");
702            try (BufferedWriter w = Files.newBufferedWriter(outPath, StandardCharsets.UTF_8)) {
703                for (int index = 0; index < cases.size(); index++) {
704                    if (progress != null) {
705                        Files.writeString(Path.of(progress), index + "\n", StandardCharsets.UTF_8,
706                            java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.APPEND);
707                    }
708                    Map<String, Object> c = (Map<String, Object>) cases.get(index);
709                    Map<String, Object> result = call(c);
710                    if (result.containsKey("invalid") || result.containsKey("missing")) {
711                        continue;
712                    }
713                    Map<String, Object> line = new LinkedHashMap<>();
714                    line.put("fn", c.get("fn"));
715                    line.put("args", c.get("args"));
716                    line.putAll(result);
717                    w.write(RustAnythingJson.write(line));
718                    w.write("\n");
719                    w.flush();
720                }
721            }
722        } else if (mode.equals("diff")) {
723            int total = 0, passed = 0, failed = 0;
724            List<Object> missing = new ArrayList<>();
725            List<Object> mismatches = new ArrayList<>();
726            for (Map<String, Object> c : lines(casesPath)) {
727                total++;
728                Map<String, Object> got = call(c);
729                if (got.containsKey("missing")) {
730                    failed++;
731                    if (!missing.contains(c.get("fn"))) {
732                        missing.add(c.get("fn"));
733                    }
734                    continue;
735                }
736                Map<String, Object> expected = new LinkedHashMap<>();
737                for (String k : new String[] {"ok", "error", "error_type"}) {
738                    if (c.containsKey(k)) {
739                        expected.put(k, c.get(k));
740                    }
741                }
742                if (same(expected, got)) {
743                    passed++;
744                } else {
745                    failed++;
746                    Map<String, Object> m = new LinkedHashMap<>();
747                    m.put("fn", c.get("fn"));
748                    m.put("args", c.get("args"));
749                    m.put("expected", expected);
750                    m.put("actual", got);
751                    mismatches.add(m);
752                }
753            }
754            Map<String, Object> summary = new LinkedHashMap<>();
755            summary.put("total", total);
756            summary.put("passed", passed);
757            summary.put("failed", failed);
758            summary.put("missing", missing);
759            summary.put("mismatches", mismatches);
760            Files.writeString(outPath, RustAnythingJson.write(summary));
761        } else if (mode.equals("bench")) {
762            long minMs = Long.parseLong(argv[4]);
763            Map<String, List<Map<String, Object>>> groups = new LinkedHashMap<>();
764            for (Map<String, Object> c : lines(casesPath)) {
765                groups.computeIfAbsent((String) c.get("fn"), k -> new ArrayList<>()).add(c);
766            }
767            Map<String, Object> result = new LinkedHashMap<>();
768            for (Map.Entry<String, List<Map<String, Object>>> g : groups.entrySet()) {
769                List<Map<String, Object>> cases = g.getValue();
770                // Arguments are converted once: only the calls are timed.
771                Method m = METHODS.get(g.getKey());
772                if (m == null) {
773                    continue;
774                }
775                Type[] types = m.getGenericParameterTypes();
776                List<Object[]> prepared = new ArrayList<>();
777                for (Map<String, Object> c : cases) {
778                    List<Object> args = (List<Object>) c.get("args");
779                    Object[] values = new Object[types.length];
780                    try {
781                        for (int i = 0; i < types.length; i++) {
782                            Object raw = i < args.size() ? args.get(i) : null;
783                            if (raw instanceof Map && ((Map<?, ?>) raw).containsKey("$undefined")) {
784                                raw = null;
785                            }
786                            values[i] = RustAnythingJson.convert(raw, types[i]);
787                        }
788                        prepared.add(values);
789                    } catch (RustAnythingJson.Mismatch e) {
790                        // not a valid call
791                    }
792                }
793                if (prepared.isEmpty()) {
794                    continue;
795                }
796                Runnable pass = () -> {
797                    for (Object[] values : prepared) {
798                        try {
799                            m.invoke(null, values);
800                        } catch (ReflectiveOperationException | RuntimeException e) {
801                            // errors count as calls
802                        }
803                    }
804                };
805                // Warm up the JIT before timing.
806                long warm = System.nanoTime();
807                while (System.nanoTime() - warm < minMs * 1_000_000L / 2) {
808                    pass.run();
809                }
810                long passes = 0;
811                long start = System.nanoTime();
812                while (true) {
813                    pass.run();
814                    passes++;
815                    long elapsed = System.nanoTime() - start;
816                    if (elapsed / 1_000_000 >= minMs) {
817                        Map<String, Object> row = new LinkedHashMap<>();
818                        row.put("cases", prepared.size());
819                        row.put("ns", (double) elapsed / (passes * prepared.size()));
820                        result.put(g.getKey(), row);
821                        break;
822                    }
823                }
824            }
825            Files.writeString(outPath, RustAnythingJson.write(result));
826        }
827    }
828}
829"#;
830
831/// Shadow classes, `<Class>Shadow` beside each original class: the same static methods,
832/// running the original and the Rust port, returning the original's result and counting
833/// mismatches. `-Drust-anything.mode=old` runs the original only, `new` the port only.
834pub fn shadows(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<(String, String)> {
835    let typed = direct_names(m, api);
836    let native = java_native_class(m);
837    let mut classes: Vec<(String, Vec<String>)> = Vec::new();
838    for f in &m.exports {
839        let (class, name) = receiver(f);
840        let simple = class.rsplit('.').next().unwrap_or(&class).to_string();
841        let ret = f.native_return.as_deref().unwrap_or("void");
842        let params: Vec<String> = f
843            .params
844            .iter()
845            .map(|p| {
846                format!(
847                    "{} {}",
848                    p.native_type.as_deref().unwrap_or("Object"),
849                    p.name
850                )
851            })
852            .collect();
853        let names: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
854        let call_args = names.join(", ");
855        let native_args = if names.is_empty() {
856            String::new()
857        } else {
858            format!(", {call_args}")
859        };
860        let type_ref = if ret == "void" {
861            "void.class".to_string()
862        } else {
863            format!(
864                "new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type()",
865                boxed(ret)
866            )
867        };
868        let port = if typed.contains(&f.name) {
869            format!("rustanything.{native}.call_{}({call_args})", f.name)
870        } else {
871            format!(
872                "rustanything.{native}.invoke(\"{}\", {type_ref}{native_args})",
873                f.name
874            )
875        };
876        let method = if ret == "void" {
877            format!(
878                "    @SuppressWarnings(\"unchecked\")\n    public static void {name}({params}) {{\n        if (MODE.equals(\"new\")) {{\n            {port};\n            return;\n        }}\n\
879                 \x20       {simple}.{name}({call_args});\n        if (!MODE.equals(\"old\")) {{\n            try {{\n                {port};\n                compare(\"{name}\", null, null);\n\
880                 \x20           }} catch (RuntimeException e) {{\n                compare(\"{name}\", null, e);\n            }}\n        }}\n    }}\n",
881                params = params.join(", "),
882            )
883        } else {
884            format!(
885                "    @SuppressWarnings(\"unchecked\")\n    public static {ret} {name}({params}) {{\n        if (MODE.equals(\"new\")) {{\n            return ({b}) {port};\n        }}\n\
886                 \x20       {ret} expected = {simple}.{name}({call_args});\n        if (!MODE.equals(\"old\")) {{\n            Object actual;\n            try {{\n                actual = {port};\n\
887                 \x20           }} catch (RuntimeException e) {{\n                actual = e;\n            }}\n            compare(\"{name}\", expected, actual);\n        }}\n        return expected;\n    }}\n",
888                params = params.join(", "),
889                b = boxed(ret),
890            )
891        };
892        match classes.iter_mut().find(|(c, _)| *c == class) {
893            Some((_, methods)) => methods.push(method),
894            None => classes.push((class, vec![method])),
895        }
896    }
897    let imports = imports_of(m);
898    classes
899        .into_iter()
900        .map(|(class, methods)| {
901            let (package, simple) = class.rsplit_once('.').unwrap_or(("", class.as_str()));
902            let path = if package.is_empty() {
903                format!("shadow/{simple}Shadow.java")
904            } else {
905                format!("shadow/{}/{simple}Shadow.java", package.replace('.', "/"))
906            };
907            let mut out = String::new();
908            if !package.is_empty() {
909                let _ = writeln!(out, "package {package};\n");
910            }
911            out.push_str("import java.util.concurrent.atomic.AtomicLong;\n");
912            out.push_str(&imports.replace("\n\n", "\n"));
913            let _ = write!(
914                out,
915                "\n/** Runs `{simple}` and its Rust port side by side. Generated by rust-anything: call it in place of `{simple}`. */\n\
916                 public final class {simple}Shadow {{\n    private {simple}Shadow() {{}}\n\n\
917                 \x20   private static final String MODE = System.getProperty(\"rust-anything.mode\", \"shadow\");\n\
918                 \x20   public static final AtomicLong CALLS = new AtomicLong();\n    public static final AtomicLong MISMATCHES = new AtomicLong();\n\n\
919                 \x20   private static void compare(String name, Object expected, Object actual) {{\n        CALLS.incrementAndGet();\n\
920                 \x20       if (actual instanceof Throwable || !rustanything.RustAnythingJson.write(expected).equals(rustanything.RustAnythingJson.write(actual))) {{\n\
921                 \x20           if (MISMATCHES.incrementAndGet() <= 10) {{\n                System.err.println(\"[rust-anything] mismatch in \" + name + \": expected \" + expected + \", got \" + actual);\n            }}\n        }}\n    }}\n\n{}}}\n",
922                methods.join("\n")
923            );
924            (path, out)
925        })
926        .collect()
927}
928
929/// A Java type that crosses JNI without JSON: the JNI type, the port type it must match, how
930/// the argument becomes the port's value, how the port's result becomes the JNI value, and the
931/// value returned while an exception is pending.
932struct Jni {
933    jni: &'static str,
934    port: &'static str,
935    arg: fn(&str) -> String,
936    out: &'static str,
937    default: &'static str,
938}
939
940fn jni(java: &str) -> Option<Jni> {
941    let int = |jni, out| Jni {
942        jni,
943        port: "i64",
944        arg: |n| format!("i64::from({n})"),
945        out,
946        default: "0",
947    };
948    Some(match java.trim() {
949        "int" => int("jni::sys::jint", "out as jni::sys::jint"),
950        "short" => int("jni::sys::jshort", "out as jni::sys::jshort"),
951        "byte" => int("jni::sys::jbyte", "out as jni::sys::jbyte"),
952        "long" => Jni {
953            jni: "jni::sys::jlong",
954            port: "i64",
955            arg: |n| n.to_string(),
956            out: "out",
957            default: "0",
958        },
959        "double" => Jni {
960            jni: "jni::sys::jdouble",
961            port: "f64",
962            arg: |n| n.to_string(),
963            out: "out",
964            default: "0.0",
965        },
966        "float" => Jni {
967            jni: "jni::sys::jfloat",
968            port: "f64",
969            arg: |n| format!("f64::from({n})"),
970            out: "out as jni::sys::jfloat",
971            default: "0.0",
972        },
973        "boolean" => Jni {
974            jni: "jni::sys::jboolean",
975            port: "bool",
976            arg: |n| format!("{n} != 0"),
977            out: "jni::sys::jboolean::from(out)",
978            default: "0",
979        },
980        "String" => Jni {
981            jni: "jni::objects::JString<'local>",
982            port: "String",
983            arg: |n| n.to_string(),
984            out: "java_string(&mut env, &out)",
985            default: "std::ptr::null_mut()",
986        },
987        _ => return None,
988    })
989}
990
991/// Whether a function crosses as a typed JNI method: every parameter and the result are
992/// primitives or `String`, and the port kept the matching Rust types.
993fn typed<'m>(
994    m: &'m Manifest,
995    f: &crate::codegen::PortFn,
996) -> Option<&'m crate::ts::exports::ExportedFn> {
997    let e = m.exports.iter().find(|e| e.name == f.js_name)?;
998    if e.params.len() != f.params.len() {
999        return None;
1000    }
1001    for (p, (_, port_ty)) in e.params.iter().zip(&f.params) {
1002        if jni(p.native_type.as_deref()?)?.port != port_ty {
1003            return None;
1004        }
1005    }
1006    match e.native_return.as_deref()? {
1007        "void" => (f.ret == "()").then_some(e),
1008        r => (jni(r)?.port == f.ret).then_some(e),
1009    }
1010}
1011
1012/// Escape one component of a JNI symbol. Non-ASCII characters are encoded one UTF-16 unit at a time.
1013pub(crate) fn mangle_jni_component(s: &str) -> String {
1014    let mut out = String::new();
1015    for unit in s.encode_utf16() {
1016        match unit {
1017            0x30..=0x39 | 0x41..=0x5a | 0x61..=0x7a => out.push(char::from(unit as u8)),
1018            0x5f => out.push_str("_1"),
1019            _ => {
1020                let _ = write!(out, "_0{unit:04x}");
1021            }
1022        }
1023    }
1024    out
1025}
1026
1027/// Typed JNI functions for `lib.rs`, appended after the JSON dispatcher.
1028pub fn typed_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1029    let class = java_native_class(m);
1030    let mut out = String::from(
1031        r#"
1032/// `rustanything.RustAnythingError` and its `(String, String)` constructor, resolved once per process.
1033type Exception = (jni::objects::GlobalRef, jni::objects::JMethodID);
1034static RUST_ANYTHING_ERROR: std::sync::OnceLock<Option<Exception>> = std::sync::OnceLock::new();
1035
1036fn rust_anything_error(env: &mut jni::JNIEnv) -> Option<Exception> {
1037    RUST_ANYTHING_ERROR
1038        .get_or_init(|| {
1039            let class = env.find_class("rustanything/RustAnythingError").ok()?;
1040            let ctor = env
1041                .get_method_id(&class, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V")
1042                .ok()?;
1043            Some((env.new_global_ref(class).ok()?, ctor))
1044        })
1045        .clone()
1046}
1047
1048/// Splits `"Type: message"`; anything else is a RuntimeException with the whole message.
1049fn split_error(message: &str) -> (&str, &str) {
1050    message
1051        .split_once(": ")
1052        .filter(|(k, _)| {
1053            k.starts_with(|c: char| c.is_ascii_alphabetic())
1054                && k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '$'))
1055        })
1056        .unwrap_or(("RuntimeException", message))
1057}
1058
1059#[allow(dead_code)]
1060/// Hands an error back through the caller's `String[2]` slot: type and message. The Java side
1061/// throws it, which is much cheaper than an exception raised from native code.
1062fn report(env: &mut jni::JNIEnv, slot: &jni::objects::JObjectArray, message: &str) {
1063    let (kind, text) = split_error(message);
1064    if let (Ok(kind), Ok(text)) = (env.new_string(kind), env.new_string(text)) {
1065        let _ = env.set_object_array_element(slot, 0, &kind);
1066        let _ = env.set_object_array_element(slot, 1, &text);
1067    }
1068}
1069
1070#[allow(dead_code)]
1071/// Throws `"Type: message"` as a `RustAnythingError` without a stack trace, which is cheap from
1072/// native code; the generated Java turns it into a `Type` exception, built in Java.
1073fn throw(env: &mut jni::JNIEnv, message: &str) {
1074    let (kind, text) = split_error(message);
1075    let Some((class, ctor)) = rust_anything_error(env) else {
1076        let _ = env.exception_clear();
1077        let _ = env.throw_new("java/lang/RuntimeException", message);
1078        return;
1079    };
1080    let (Ok(kind), Ok(text)) = (env.new_string(kind), env.new_string(text)) else {
1081        return;
1082    };
1083    let class: &jni::objects::JClass = class.as_obj().into();
1084    let args = [
1085        jni::objects::JValue::Object(&kind).as_jni(),
1086        jni::objects::JValue::Object(&text).as_jni(),
1087    ];
1088    // SAFETY: `ctor` is the `(String, String)` constructor of `class`, looked up together, and
1089    // both arguments are Strings.
1090    if let Ok(object) = unsafe { env.new_object_unchecked(class, ctor, &args) } {
1091        let _ = env.throw(jni::objects::JThrowable::from(object));
1092    }
1093}
1094
1095/// Runs the port; a panic becomes an error instead of unwinding into the JVM.
1096#[allow(dead_code)]
1097fn run<T>(f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
1098    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|panic| {
1099        let text = panic
1100            .downcast_ref::<&str>()
1101            .map(ToString::to_string)
1102            .or_else(|| panic.downcast_ref::<String>().cloned())
1103            .unwrap_or_default();
1104        Err(format!("RuntimeException: Rust panic: {text}"))
1105    })
1106}
1107
1108/// A `String` argument; `None` (with a NullPointerException thrown) for null.
1109#[allow(dead_code)]
1110fn string_arg(env: &mut jni::JNIEnv, s: &jni::objects::JString) -> Option<String> {
1111    if s.is_null() {
1112        let _ = env.throw_new("java/lang/NullPointerException", "null String argument");
1113        return None;
1114    }
1115    let raw = env.get_raw();
1116    let mut stack = [0u16; 128];
1117    // SAFETY: `raw` is this thread's JNIEnv and `s` a live, non-null String reference; the JVM
1118    // fills every entry of the function table.
1119    let len = unsafe { ((**raw).GetStringLength?)(raw, s.as_raw()) };
1120    let n = usize::try_from(len).unwrap_or(0);
1121    let mut heap = Vec::new();
1122    let units: &mut [u16] = if n <= stack.len() {
1123        &mut stack[..n]
1124    } else {
1125        heap.resize(n, 0);
1126        &mut heap
1127    };
1128    // SAFETY: as above; `units` holds exactly `len` UTF-16 code units.
1129    unsafe { ((**raw).GetStringRegion?)(raw, s.as_raw(), 0, len, units.as_mut_ptr()) };
1130    // UTF-16 straight from the String: no modified UTF-8 in between.
1131    Some(String::from_utf16_lossy(units))
1132}
1133
1134/// A Java String from Rust text, built from UTF-16 (`NewString`), not modified UTF-8.
1135#[allow(dead_code)]
1136fn java_string(env: &mut jni::JNIEnv, text: &str) -> jni::sys::jstring {
1137    let mut stack = [0u16; 128];
1138    let mut heap = Vec::new();
1139    let units: &[u16] = if text.len() <= stack.len() {
1140        let mut n = 0;
1141        for u in text.encode_utf16() {
1142            stack[n] = u;
1143            n += 1;
1144        }
1145        &stack[..n]
1146    } else {
1147        heap.extend(text.encode_utf16());
1148        &heap
1149    };
1150    let Ok(len) = jni::sys::jsize::try_from(units.len()) else {
1151        return std::ptr::null_mut();
1152    };
1153    let raw = env.get_raw();
1154    // SAFETY: `raw` is this thread's JNIEnv, valid for the call.
1155    let Some(new_string) = (unsafe { (**raw).NewString }) else {
1156        return std::ptr::null_mut();
1157    };
1158    // SAFETY: `units` holds `len` UTF-16 code units, read during the call only.
1159    unsafe { new_string(raw, units.as_ptr(), len) }
1160}
1161"#,
1162    );
1163    for f in &api.functions {
1164        let Some(e) = typed(m, f) else { continue };
1165        let ret_java = e.native_return.as_deref().unwrap_or("void");
1166        let ret = if ret_java == "void" {
1167            None
1168        } else {
1169            jni(ret_java)
1170        };
1171        let mut params = vec![
1172            "mut env: jni::JNIEnv<'local>".to_string(),
1173            "_class: jni::objects::JClass<'local>".to_string(),
1174        ];
1175        let mut prelude = String::new();
1176        let mut args = Vec::new();
1177        let default = ret.as_ref().map_or("", |r| r.default);
1178        for (p, (name, _)) in e.params.iter().zip(&f.params) {
1179            let t = jni(p.native_type.as_deref().unwrap_or_default()).expect("typed");
1180            params.push(format!("{name}: {}", t.jni));
1181            if t.port == "String" {
1182                let _ = writeln!(
1183                    prelude,
1184                    "    let Some({name}) = string_arg(&mut env, &{name}) else {{\n        return {default};\n    }};"
1185                );
1186                args.push(name.clone());
1187            } else {
1188                args.push((t.arg)(name));
1189            }
1190        }
1191        params.push("slot: jni::objects::JObjectArray<'local>".to_string());
1192        let call = format!("port::{}({})", f.rust_name, args.join(", "));
1193        let call = if f.fallible {
1194            call
1195        } else {
1196            format!("Ok({call})")
1197        };
1198        let (ret_ty, ok) = match &ret {
1199            Some(r) => (
1200                format!(
1201                    " -> {}",
1202                    r.jni
1203                        .replace("JString<'local>", "jstring")
1204                        .replace("jni::objects::jstring", "jni::sys::jstring")
1205                ),
1206                r.out.to_string(),
1207            ),
1208            None => (String::new(), "()".to_string()),
1209        };
1210        let _ = writeln!(
1211            out,
1212            "\n/// `{proto}`: typed, no JSON.\n// SAFETY: the JNI symbol of `rustanything.{class}.n_{js}`; nothing else defines it.\n\
1213             #[unsafe(no_mangle)]\npub extern \"system\" fn Java_rustanything_{mclass}_n_1{mjs}<'local>({params}){ret_ty} {{\n\
1214             {prelude}    match run(|| {call}) {{\n        Ok(out) => {ok},\n        Err(message) => {{\n            \
1215             report(&mut env, &slot, &message);\n            {default}\n        }}\n    }}\n}}",
1216            proto = e.prototype.as_deref().unwrap_or(&e.name),
1217            js = f.js_name,
1218            mclass = mangle_jni_component(&class),
1219            mjs = mangle_jni_component(&f.js_name),
1220            params = params.join(", "),
1221        );
1222    }
1223    out
1224}
1225
1226/// The exports that cross as typed JNI methods.
1227fn typed_names(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<String> {
1228    api.functions
1229        .iter()
1230        .filter(|f| typed(m, f).is_some())
1231        .map(|f| f.js_name.clone())
1232        .collect()
1233}
1234
1235/// The `static native` declarations of the typed methods.
1236fn typed_declarations(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1237    let mut out = String::new();
1238    for f in &api.functions {
1239        let Some(e) = typed(m, f) else { continue };
1240        let params: Vec<String> = e
1241            .params
1242            .iter()
1243            .map(|p| {
1244                format!(
1245                    "{} {}",
1246                    p.native_type.as_deref().unwrap_or("Object"),
1247                    p.name
1248                )
1249            })
1250            .collect();
1251        let mut params = params;
1252        params.push("String[] slot".into());
1253        let _ = writeln!(
1254            out,
1255            "    public static native {} n_{}({});",
1256            e.native_return.as_deref().unwrap_or("void"),
1257            f.js_name,
1258            params.join(", ")
1259        );
1260    }
1261    out
1262}
1263
1264// ---- the binary wire: lists, arrays, maps, boxed and optional values, without JSON ----------
1265
1266use crate::wire::Ty;
1267
1268fn split_generic(t: &str) -> Option<(&str, Vec<String>)> {
1269    let i = t.find('<')?;
1270    let inner = t.strip_suffix('>')?.get(i + 1..)?;
1271    let mut args = Vec::new();
1272    let mut depth = 0;
1273    let mut cur = String::new();
1274    for c in inner.chars() {
1275        match c {
1276            '<' => depth += 1,
1277            '>' => depth -= 1,
1278            ',' if depth == 0 => {
1279                args.push(cur.trim().to_string());
1280                cur.clear();
1281                continue;
1282            }
1283            _ => {}
1284        }
1285        cur.push(c);
1286    }
1287    args.push(cur.trim().to_string());
1288    Some((t[..i].trim(), args))
1289}
1290
1291/// The wire type of a Java type; `None` for types the wire does not carry.
1292fn java_ty(t: &str) -> Option<Ty> {
1293    let t = t.trim();
1294    let boxed = |inner: Ty| Ty::Opt {
1295        inner: Box::new(inner),
1296        native: t.to_string(),
1297    };
1298    Some(match t {
1299        "int" | "long" | "short" | "byte" => Ty::I64(t.into()),
1300        "double" | "float" => Ty::F64(t.into()),
1301        "boolean" => Ty::Bool,
1302        "String" | "CharSequence" => Ty::Str,
1303        "Integer" => boxed(Ty::I64("int".into())),
1304        "Long" => boxed(Ty::I64("long".into())),
1305        "Short" => boxed(Ty::I64("short".into())),
1306        "Byte" => boxed(Ty::I64("byte".into())),
1307        "Double" => boxed(Ty::F64("double".into())),
1308        "Float" => boxed(Ty::F64("float".into())),
1309        "Boolean" => boxed(Ty::Bool),
1310        _ => {
1311            if let Some(item) = t.strip_suffix("[]") {
1312                let item_ty = java_ty(item)?;
1313                // Primitive arrays need a helper; reference arrays use a generic one.
1314                if matches!(item_ty, Ty::I64(_) | Ty::F64(_) | Ty::Bool)
1315                    && !matches!(item.trim(), "int" | "long" | "double" | "boolean")
1316                {
1317                    return None;
1318                }
1319                return Some(Ty::List {
1320                    item: Box::new(item_ty),
1321                    native: t.into(),
1322                    array: true,
1323                });
1324            }
1325            let (head, args) = split_generic(t)?;
1326            match head.rsplit('.').next().unwrap_or(head) {
1327                "List" | "ArrayList" | "Collection" | "Iterable" | "LinkedList" => Ty::List {
1328                    item: Box::new(java_ty(args.first()?)?),
1329                    native: t.into(),
1330                    array: false,
1331                },
1332                "Map" | "LinkedHashMap" | "HashMap" | "TreeMap" if args.first()? == "String" => {
1333                    Ty::Map {
1334                        value: Box::new(java_ty(args.get(1)?)?),
1335                        native: t.into(),
1336                    }
1337                }
1338                "Optional" => Ty::Opt {
1339                    inner: Box::new(java_ty(args.first()?)?),
1340                    native: t.into(),
1341                },
1342                _ => return None,
1343            }
1344        }
1345    })
1346}
1347
1348/// Java statements writing `expr` of type `t` to writer `w`.
1349fn java_enc(expr: &str, t: &Ty, depth: usize) -> String {
1350    let d = depth;
1351    match t {
1352        Ty::I64(_) => format!("w.i64({expr});"),
1353        Ty::F64(_) => format!("w.f64({expr});"),
1354        Ty::Bool => format!("w.bool({expr});"),
1355        Ty::Str => format!("w.str({expr});"),
1356        Ty::Opt { inner, native } if native.starts_with("Optional") => format!(
1357            "{{ var o{d} = {expr}; if (o{d} == null || o{d}.isEmpty()) {{ w.tag(0); }} else {{ w.tag(1); {} }} }}",
1358            java_enc(&format!("o{d}.get()"), inner, d + 1)
1359        ),
1360        Ty::Opt { inner, .. } => format!(
1361            "{{ var o{d} = {expr}; if (o{d} == null) {{ w.tag(0); }} else {{ w.tag(1); {} }} }}",
1362            java_enc(&format!("o{d}"), inner, d + 1)
1363        ),
1364        Ty::List { item, array, .. } => format!(
1365            "{{ var a{d} = {expr}; if (a{d} == null) {{ w.tag(0); }} else {{ w.tag(1); w.len(a{d}.{}); for (var v{d} : a{d}) {{ {} }} }} }}",
1366            if *array { "length" } else { "size()" },
1367            java_enc(&format!("v{d}"), item, d + 1)
1368        ),
1369        Ty::Map { value, .. } => format!(
1370            "{{ var m{d} = {expr}; if (m{d} == null) {{ w.tag(0); }} else {{ w.tag(1); w.len(m{d}.size()); for (var e{d} : m{d}.entrySet()) {{ w.str(e{d}.getKey()); {} }} }} }}",
1371            java_enc(&format!("e{d}.getValue()"), value, d + 1)
1372        ),
1373        _ => String::new(),
1374    }
1375}
1376
1377/// A Java expression reading a value of type `t` from reader `r`.
1378fn java_dec(t: &Ty) -> Option<String> {
1379    Some(match t {
1380        Ty::I64(n) => match n.as_str() {
1381            "long" => "r.i64()".into(),
1382            other => format!("(({other}) r.i64())"),
1383        },
1384        Ty::F64(n) => match n.as_str() {
1385            "float" => "((float) r.f64())".into(),
1386            _ => "r.f64()".into(),
1387        },
1388        Ty::Bool => "r.bool()".into(),
1389        Ty::Str => "r.str()".into(),
1390        Ty::Opt { inner, native } if native.starts_with("Optional") => {
1391            let arg = split_generic(native)?.1.first()?.clone();
1392            format!(
1393                "(r.tag() == 0 ? java.util.Optional.<{arg}>empty() : java.util.Optional.of({}))",
1394                java_dec(inner)?
1395            )
1396        }
1397        Ty::Opt { inner, native } => {
1398            format!("(r.tag() == 0 ? null : ({native}) {})", java_dec(inner)?)
1399        }
1400        Ty::List {
1401            item,
1402            native,
1403            array: true,
1404        } => match native.trim_end_matches("[]") {
1405            "int" => "r.ints()".into(),
1406            "long" => "r.longs()".into(),
1407            "double" => "r.doubles()".into(),
1408            "boolean" => "r.booleans()".into(),
1409            elem => format!("r.array(() -> {}, {elem}[]::new)", java_dec(item)?),
1410        },
1411        Ty::List { item, .. } => format!("r.list(() -> {})", java_dec(item)?),
1412        Ty::Map { value, .. } => format!("r.map(() -> {})", java_dec(value)?),
1413        _ => return None,
1414    })
1415}
1416
1417/// `rustanything/RustAnythingError.java`: the error the Rust side throws, turned into the real
1418/// exception type in Java.
1419pub const ERROR_JAVA: &str = r#"package rustanything;
1420
1421import java.lang.invoke.MethodHandle;
1422import java.lang.invoke.MethodHandles;
1423import java.lang.invoke.MethodType;
1424import java.util.Optional;
1425import java.util.concurrent.ConcurrentHashMap;
1426
1427/** Generated by rust-anything: a port's error, thrown from Rust without a stack trace (cheap from native code). */
1428public final class RustAnythingError extends RuntimeException {
1429    private static final long serialVersionUID = 1L;
1430    private static final ConcurrentHashMap<String, Optional<MethodHandle>> CONSTRUCTORS = new ConcurrentHashMap<>();
1431
1432    public final String type;
1433
1434    public RustAnythingError(String type, String message) {
1435        super(message, null, false, false);
1436        this.type = type;
1437    }
1438
1439    private static Optional<MethodHandle> constructor(String type) {
1440        for (String prefix : new String[] {"java.lang.", "java.util.", "java.io.", ""}) {
1441            try {
1442                Class<?> c = Class.forName(prefix + type);
1443                if (RuntimeException.class.isAssignableFrom(c)) {
1444                    return Optional.of(MethodHandles.publicLookup()
1445                        .findConstructor(c, MethodType.methodType(void.class, String.class))
1446                        .asType(MethodType.methodType(RuntimeException.class, String.class)));
1447                }
1448            } catch (ReflectiveOperationException | IllegalArgumentException e) {
1449                // try the next package
1450            }
1451        }
1452        return Optional.empty();
1453    }
1454
1455    /** The exception the original throws: `type` with the message, else a RuntimeException. */
1456    public RuntimeException real() {
1457        return make(type, getMessage());
1458    }
1459
1460    private static final ThreadLocal<String[]> SLOTS = ThreadLocal.withInitial(() -> new String[2]);
1461
1462    /** This thread's error slot: the Rust side writes a failed call's type and message there. */
1463    public static String[] slot() {
1464        return SLOTS.get();
1465    }
1466
1467    /** Throws the error a call left in `slot`, if any. */
1468    public static void check(String[] slot) {
1469        if (slot[0] != null) {
1470            String type = slot[0];
1471            String message = slot[1];
1472            slot[0] = null;
1473            slot[1] = null;
1474            throw make(type, message);
1475        }
1476    }
1477
1478    private static RuntimeException make(String type, String message) {
1479        Optional<MethodHandle> ctor = CONSTRUCTORS.computeIfAbsent(type, RustAnythingError::constructor);
1480        if (ctor.isPresent()) {
1481            try {
1482                return (RuntimeException) ctor.get().invokeExact(message);
1483            } catch (Throwable e) {
1484                // fall through
1485            }
1486        }
1487        return new RuntimeException(type + ": " + message);
1488    }
1489}
1490"#;
1491
1492/// `rustanything/RustAnythingWire.java`: the Java half of the binary wire.
1493pub const WIRE_JAVA: &str = r#"package rustanything;
1494
1495import java.io.ByteArrayOutputStream;
1496import java.nio.charset.StandardCharsets;
1497import java.util.ArrayList;
1498import java.util.LinkedHashMap;
1499import java.util.List;
1500import java.util.Map;
1501import java.util.function.IntFunction;
1502import java.util.function.Supplier;
1503
1504/** Generated by rust-anything: the binary wire to the Rust port. Little endian; nullable values start with 0 for null. */
1505public final class RustAnythingWire {
1506    private RustAnythingWire() {}
1507
1508    public static final class Writer {
1509        private byte[] buf = new byte[64];
1510        private int n;
1511
1512        private void ensure(int more) {
1513            if (n + more > buf.length) {
1514                buf = java.util.Arrays.copyOf(buf, Math.max(buf.length * 2, n + more));
1515            }
1516        }
1517
1518        public void tag(int t) {
1519            ensure(1);
1520            buf[n++] = (byte) t;
1521        }
1522
1523        public void len(int v) {
1524            ensure(4);
1525            for (int i = 0; i < 4; i++) {
1526                buf[n++] = (byte) (v >>> (8 * i));
1527            }
1528        }
1529
1530        public void i64(long v) {
1531            ensure(8);
1532            for (int i = 0; i < 8; i++) {
1533                buf[n++] = (byte) (v >>> (8 * i));
1534            }
1535        }
1536
1537        public void f64(double v) {
1538            i64(Double.doubleToRawLongBits(v));
1539        }
1540
1541        public void bool(boolean v) {
1542            tag(v ? 1 : 0);
1543        }
1544
1545        public void str(String s) {
1546            if (s == null) {
1547                tag(0);
1548                return;
1549            }
1550            byte[] b = s.getBytes(StandardCharsets.UTF_8);
1551            tag(1);
1552            len(b.length);
1553            ensure(b.length);
1554            System.arraycopy(b, 0, buf, n, b.length);
1555            n += b.length;
1556        }
1557
1558        public byte[] bytes() {
1559            return java.util.Arrays.copyOf(buf, n);
1560        }
1561    }
1562
1563    public static final class Reader {
1564        private final byte[] b;
1565        private int i;
1566
1567        public Reader(byte[] b) {
1568            this.b = b;
1569        }
1570
1571        public int tag() {
1572            return b[i++] & 0xff;
1573        }
1574
1575        public int len() {
1576            int v = 0;
1577            for (int k = 0; k < 4; k++) {
1578                v |= (b[i++] & 0xff) << (8 * k);
1579            }
1580            return v;
1581        }
1582
1583        public long i64() {
1584            long v = 0;
1585            for (int k = 0; k < 8; k++) {
1586                v |= (long) (b[i++] & 0xff) << (8 * k);
1587            }
1588            return v;
1589        }
1590
1591        public double f64() {
1592            return Double.longBitsToDouble(i64());
1593        }
1594
1595        public boolean bool() {
1596            return tag() != 0;
1597        }
1598
1599        public String str() {
1600            if (tag() == 0) {
1601                return null;
1602            }
1603            int n = len();
1604            String s = new String(b, i, n, StandardCharsets.UTF_8);
1605            i += n;
1606            return s;
1607        }
1608
1609        public <T> List<T> list(Supplier<T> item) {
1610            if (tag() == 0) {
1611                return null;
1612            }
1613            int n = len();
1614            List<T> out = new ArrayList<>(n);
1615            for (int k = 0; k < n; k++) {
1616                out.add(item.get());
1617            }
1618            return out;
1619        }
1620
1621        public <T> T[] array(Supplier<T> item, IntFunction<T[]> make) {
1622            List<T> items = list(item);
1623            return items == null ? null : items.toArray(make.apply(items.size()));
1624        }
1625
1626        public <T> Map<String, T> map(Supplier<T> item) {
1627            if (tag() == 0) {
1628                return null;
1629            }
1630            int n = len();
1631            Map<String, T> out = new LinkedHashMap<>();
1632            for (int k = 0; k < n; k++) {
1633                String key = str();
1634                out.put(key, item.get());
1635            }
1636            return out;
1637        }
1638
1639        public int[] ints() {
1640            if (tag() == 0) {
1641                return null;
1642            }
1643            int[] out = new int[len()];
1644            for (int k = 0; k < out.length; k++) {
1645                out[k] = (int) i64();
1646            }
1647            return out;
1648        }
1649
1650        public long[] longs() {
1651            if (tag() == 0) {
1652                return null;
1653            }
1654            long[] out = new long[len()];
1655            for (int k = 0; k < out.length; k++) {
1656                out[k] = i64();
1657            }
1658            return out;
1659        }
1660
1661        public double[] doubles() {
1662            if (tag() == 0) {
1663                return null;
1664            }
1665            double[] out = new double[len()];
1666            for (int k = 0; k < out.length; k++) {
1667                out[k] = f64();
1668            }
1669            return out;
1670        }
1671
1672        public boolean[] booleans() {
1673            if (tag() == 0) {
1674                return null;
1675            }
1676            boolean[] out = new boolean[len()];
1677            for (int k = 0; k < out.length; k++) {
1678                out[k] = bool();
1679            }
1680            return out;
1681        }
1682    }
1683}
1684"#;
1685
1686/// The exports that cross the binary wire, with their Java body and Rust code.
1687fn java_wire_fns<'m>(
1688    m: &'m Manifest,
1689    api: &crate::codegen::PortApi,
1690) -> Vec<(&'m crate::ts::exports::ExportedFn, String, String)> {
1691    let class = java_native_class(m);
1692    let mut out = Vec::new();
1693    for f in &api.functions {
1694        if typed(m, f).is_some() {
1695            continue;
1696        }
1697        let Some(e) = m.exports.iter().find(|e| e.name == f.js_name) else {
1698            continue;
1699        };
1700        if e.params.len() != f.params.len() {
1701            continue;
1702        }
1703        let Some(params) = e
1704            .params
1705            .iter()
1706            .map(|p| Some((p.name.clone(), java_ty(p.native_type.as_deref()?)?)))
1707            .collect::<Option<Vec<_>>>()
1708        else {
1709            continue;
1710        };
1711        let ret_java = e.native_return.as_deref().unwrap_or("void");
1712        let result = if ret_java == "void" {
1713            None
1714        } else {
1715            java_ty(ret_java)
1716        };
1717        if ret_java != "void" && result.is_none() {
1718            continue;
1719        }
1720        // Java body of `call_<name>`.
1721        let mut java =
1722            String::from("        RustAnythingWire.Writer w = new RustAnythingWire.Writer();\n");
1723        for (name, t) in &params {
1724            let _ = writeln!(java, "        {}", java_enc(name, t, 0));
1725        }
1726        let _ = writeln!(
1727            java,
1728            "        String[] slot = RustAnythingError.slot();\n        byte[] out = w_{}(w.bytes(), slot);\n        RustAnythingError.check(slot);",
1729            f.js_name
1730        );
1731        if let Some(t) = &result {
1732            let Some(dec) = java_dec(t) else { continue };
1733            let _ = writeln!(
1734                java,
1735                "        RustAnythingWire.Reader r = new RustAnythingWire.Reader(out);\n        return {dec};"
1736            );
1737        }
1738        // Rust JNI function.
1739        let mut statics = String::new();
1740        let prefix = format!("S_{}", f.js_name.to_uppercase());
1741        let Some(reads) = crate::wire::rust_read_args(&params, &f.params, &prefix, &mut statics)
1742        else {
1743            continue;
1744        };
1745        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
1746        let call = format!("port::{}({})", f.rust_name, args.join(", "));
1747        let call = if f.fallible { format!("{call}?") } else { call };
1748        let write = match &result {
1749            None if f.ret == "()" => format!("        let () = {call};\n"),
1750            None => continue,
1751            Some(t) => {
1752                let schema = format!("{prefix}_OUT");
1753                let Some(w) = crate::wire::rust_write(t, &f.ret, "out", &schema, 0) else {
1754                    continue;
1755                };
1756                if w.contains(&schema) {
1757                    let _ = writeln!(
1758                        statics,
1759                        "static {schema}: wire::Schema = {};",
1760                        crate::wire::schema_expr(t)
1761                    );
1762                }
1763                format!("        let out = &{call};\n        {w}\n")
1764            }
1765        };
1766        let rust = format!(
1767            "\n{statics}\n/// `{proto}`: binary wire.\n// SAFETY: the JNI symbol of `rustanything.{class}.w_{js}`; nothing else defines it.\n\
1768             #[unsafe(no_mangle)]\npub extern \"system\" fn Java_rustanything_{mclass}_w_1{mjs}<'local>(mut env: jni::JNIEnv<'local>, \
1769             _class: jni::objects::JClass<'local>, args: jni::objects::JByteArray<'local>, slot: jni::objects::JObjectArray<'local>) -> jni::sys::jbyteArray {{\n    \
1770             let Ok(input) = env.convert_byte_array(&args) else {{\n        return std::ptr::null_mut();\n    }};\n    \
1771             let result = run(|| {{\n        let r = &mut wire::Reader::new(&input);\n{reads}        let w = &mut wire::Writer::default();\n{write}        \
1772             Ok(std::mem::take(&mut w.0))\n    }});\n    match result {{\n        \
1773             Ok(bytes) => env.byte_array_from_slice(&bytes).map_or(std::ptr::null_mut(), jni::objects::JByteArray::into_raw),\n        \
1774             Err(message) => {{\n            report(&mut env, &slot, &message);\n            std::ptr::null_mut()\n        }}\n    }}\n}}",
1775            proto = e.prototype.as_deref().unwrap_or(&e.name),
1776            js = f.js_name,
1777            mclass = mangle_jni_component(&class),
1778            mjs = mangle_jni_component(&f.js_name),
1779        );
1780        out.push((e, java, rust));
1781    }
1782    out
1783}
1784
1785/// Rust code of every wire export, for `lib.rs`.
1786pub fn wire_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1787    java_wire_fns(m, api)
1788        .into_iter()
1789        .map(|(_, _, rust)| rust)
1790        .collect()
1791}
1792
1793/// `call_<name>` methods of the native class: the one entry point wrappers and shadows use.
1794fn call_methods(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1795    let mut out = String::new();
1796    let sig = |e: &crate::ts::exports::ExportedFn| {
1797        e.params
1798            .iter()
1799            .map(|p| {
1800                format!(
1801                    "{} {}",
1802                    p.native_type.as_deref().unwrap_or("Object"),
1803                    p.name
1804                )
1805            })
1806            .collect::<Vec<_>>()
1807            .join(", ")
1808    };
1809    for f in &api.functions {
1810        let Some(e) = typed(m, f) else { continue };
1811        let ret = e.native_return.as_deref().unwrap_or("void");
1812        let args = e
1813            .params
1814            .iter()
1815            .map(|p| p.name.as_str())
1816            .collect::<Vec<_>>()
1817            .join(", ");
1818        let call_args = if args.is_empty() {
1819            "slot".to_string()
1820        } else {
1821            format!("{args}, slot")
1822        };
1823        let body = if ret == "void" {
1824            format!(
1825                "String[] slot = RustAnythingError.slot();\n            n_{}({call_args});\n            RustAnythingError.check(slot);",
1826                f.js_name
1827            )
1828        } else {
1829            format!(
1830                "String[] slot = RustAnythingError.slot();\n            {ret} out = n_{}({call_args});\n            RustAnythingError.check(slot);\n            return out;",
1831                f.js_name
1832            )
1833        };
1834        let _ = writeln!(
1835            out,
1836            "\n    public static {ret} call_{}({}) {{\n        try {{\n            {body}\n        }} catch (RustAnythingError e) {{\n            throw e.real();\n        }}\n    }}",
1837            f.js_name,
1838            sig(e)
1839        );
1840    }
1841    for (e, body, _) in java_wire_fns(m, api) {
1842        let ret = e.native_return.as_deref().unwrap_or("void");
1843        let _ = writeln!(
1844            out,
1845            "\n    private static native byte[] w_{name}(byte[] args, String[] slot);\n\n    @SuppressWarnings(\"unchecked\")\n    public static {ret} call_{name}({}) {{\n        try {{\n{body}        }} catch (RustAnythingError e) {{\n            throw e.real();\n        }}\n    }}",
1846            sig(e),
1847            name = e.name,
1848        );
1849    }
1850    out
1851}
1852
1853/// The exports with a `call_<name>` method (typed or wire).
1854fn direct_names(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<String> {
1855    let mut names = typed_names(m, api);
1856    names.extend(
1857        java_wire_fns(m, api)
1858            .into_iter()
1859            .map(|(e, ..)| e.name.clone()),
1860    );
1861    names
1862}
1863
1864#[cfg(test)]
1865mod tests {
1866    use super::*;
1867
1868    #[test]
1869    fn jni_symbols_match_javac_for_non_ascii_identifiers() {
1870        assert_eq!(mangle_jni_component("n_café"), "n_1caf_000e9");
1871        assert_eq!(mangle_jni_component("w_get$Value"), "w_1get_00024Value");
1872        assert_eq!(mangle_jni_component("n_𐐀"), "n_1_0d801_0dc00");
1873    }
1874}