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            try (BufferedWriter w = Files.newBufferedWriter(outPath, StandardCharsets.UTF_8)) {
702                for (Object o : cases) {
703                    Map<String, Object> c = (Map<String, Object>) o;
704                    Map<String, Object> result = call(c);
705                    if (result.containsKey("invalid") || result.containsKey("missing")) {
706                        continue;
707                    }
708                    Map<String, Object> line = new LinkedHashMap<>();
709                    line.put("fn", c.get("fn"));
710                    line.put("args", c.get("args"));
711                    line.putAll(result);
712                    w.write(RustAnythingJson.write(line));
713                    w.write("\n");
714                }
715            }
716        } else if (mode.equals("diff")) {
717            int total = 0, passed = 0, failed = 0;
718            List<Object> missing = new ArrayList<>();
719            List<Object> mismatches = new ArrayList<>();
720            for (Map<String, Object> c : lines(casesPath)) {
721                total++;
722                Map<String, Object> got = call(c);
723                if (got.containsKey("missing")) {
724                    failed++;
725                    if (!missing.contains(c.get("fn"))) {
726                        missing.add(c.get("fn"));
727                    }
728                    continue;
729                }
730                Map<String, Object> expected = new LinkedHashMap<>();
731                for (String k : new String[] {"ok", "error", "error_type"}) {
732                    if (c.containsKey(k)) {
733                        expected.put(k, c.get(k));
734                    }
735                }
736                if (same(expected, got)) {
737                    passed++;
738                } else {
739                    failed++;
740                    Map<String, Object> m = new LinkedHashMap<>();
741                    m.put("fn", c.get("fn"));
742                    m.put("args", c.get("args"));
743                    m.put("expected", expected);
744                    m.put("actual", got);
745                    mismatches.add(m);
746                }
747            }
748            Map<String, Object> summary = new LinkedHashMap<>();
749            summary.put("total", total);
750            summary.put("passed", passed);
751            summary.put("failed", failed);
752            summary.put("missing", missing);
753            summary.put("mismatches", mismatches);
754            Files.writeString(outPath, RustAnythingJson.write(summary));
755        } else if (mode.equals("bench")) {
756            long minMs = Long.parseLong(argv[4]);
757            Map<String, List<Map<String, Object>>> groups = new LinkedHashMap<>();
758            for (Map<String, Object> c : lines(casesPath)) {
759                groups.computeIfAbsent((String) c.get("fn"), k -> new ArrayList<>()).add(c);
760            }
761            Map<String, Object> result = new LinkedHashMap<>();
762            for (Map.Entry<String, List<Map<String, Object>>> g : groups.entrySet()) {
763                List<Map<String, Object>> cases = g.getValue();
764                // Arguments are converted once: only the calls are timed.
765                Method m = METHODS.get(g.getKey());
766                if (m == null) {
767                    continue;
768                }
769                Type[] types = m.getGenericParameterTypes();
770                List<Object[]> prepared = new ArrayList<>();
771                for (Map<String, Object> c : cases) {
772                    List<Object> args = (List<Object>) c.get("args");
773                    Object[] values = new Object[types.length];
774                    try {
775                        for (int i = 0; i < types.length; i++) {
776                            Object raw = i < args.size() ? args.get(i) : null;
777                            if (raw instanceof Map && ((Map<?, ?>) raw).containsKey("$undefined")) {
778                                raw = null;
779                            }
780                            values[i] = RustAnythingJson.convert(raw, types[i]);
781                        }
782                        prepared.add(values);
783                    } catch (RustAnythingJson.Mismatch e) {
784                        // not a valid call
785                    }
786                }
787                if (prepared.isEmpty()) {
788                    continue;
789                }
790                Runnable pass = () -> {
791                    for (Object[] values : prepared) {
792                        try {
793                            m.invoke(null, values);
794                        } catch (ReflectiveOperationException | RuntimeException e) {
795                            // errors count as calls
796                        }
797                    }
798                };
799                // Warm up the JIT before timing.
800                long warm = System.nanoTime();
801                while (System.nanoTime() - warm < minMs * 1_000_000L / 2) {
802                    pass.run();
803                }
804                long passes = 0;
805                long start = System.nanoTime();
806                while (true) {
807                    pass.run();
808                    passes++;
809                    long elapsed = System.nanoTime() - start;
810                    if (elapsed / 1_000_000 >= minMs) {
811                        Map<String, Object> row = new LinkedHashMap<>();
812                        row.put("cases", prepared.size());
813                        row.put("ns", (double) elapsed / (passes * prepared.size()));
814                        result.put(g.getKey(), row);
815                        break;
816                    }
817                }
818            }
819            Files.writeString(outPath, RustAnythingJson.write(result));
820        }
821    }
822}
823"#;
824
825/// Shadow classes, `<Class>Shadow` beside each original class: the same static methods,
826/// running the original and the Rust port, returning the original's result and counting
827/// mismatches. `-Drust-anything.mode=old` runs the original only, `new` the port only.
828pub fn shadows(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<(String, String)> {
829    let typed = direct_names(m, api);
830    let native = java_native_class(m);
831    let mut classes: Vec<(String, Vec<String>)> = Vec::new();
832    for f in &m.exports {
833        let (class, name) = receiver(f);
834        let simple = class.rsplit('.').next().unwrap_or(&class).to_string();
835        let ret = f.native_return.as_deref().unwrap_or("void");
836        let params: Vec<String> = f
837            .params
838            .iter()
839            .map(|p| {
840                format!(
841                    "{} {}",
842                    p.native_type.as_deref().unwrap_or("Object"),
843                    p.name
844                )
845            })
846            .collect();
847        let names: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
848        let call_args = names.join(", ");
849        let native_args = if names.is_empty() {
850            String::new()
851        } else {
852            format!(", {call_args}")
853        };
854        let type_ref = if ret == "void" {
855            "void.class".to_string()
856        } else {
857            format!(
858                "new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type()",
859                boxed(ret)
860            )
861        };
862        let port = if typed.contains(&f.name) {
863            format!("rustanything.{native}.call_{}({call_args})", f.name)
864        } else {
865            format!(
866                "rustanything.{native}.invoke(\"{}\", {type_ref}{native_args})",
867                f.name
868            )
869        };
870        let method = if ret == "void" {
871            format!(
872                "    @SuppressWarnings(\"unchecked\")\n    public static void {name}({params}) {{\n        if (MODE.equals(\"new\")) {{\n            {port};\n            return;\n        }}\n\
873                 \x20       {simple}.{name}({call_args});\n        if (!MODE.equals(\"old\")) {{\n            try {{\n                {port};\n                compare(\"{name}\", null, null);\n\
874                 \x20           }} catch (RuntimeException e) {{\n                compare(\"{name}\", null, e);\n            }}\n        }}\n    }}\n",
875                params = params.join(", "),
876            )
877        } else {
878            format!(
879                "    @SuppressWarnings(\"unchecked\")\n    public static {ret} {name}({params}) {{\n        if (MODE.equals(\"new\")) {{\n            return ({b}) {port};\n        }}\n\
880                 \x20       {ret} expected = {simple}.{name}({call_args});\n        if (!MODE.equals(\"old\")) {{\n            Object actual;\n            try {{\n                actual = {port};\n\
881                 \x20           }} catch (RuntimeException e) {{\n                actual = e;\n            }}\n            compare(\"{name}\", expected, actual);\n        }}\n        return expected;\n    }}\n",
882                params = params.join(", "),
883                b = boxed(ret),
884            )
885        };
886        match classes.iter_mut().find(|(c, _)| *c == class) {
887            Some((_, methods)) => methods.push(method),
888            None => classes.push((class, vec![method])),
889        }
890    }
891    let imports = imports_of(m);
892    classes
893        .into_iter()
894        .map(|(class, methods)| {
895            let (package, simple) = class.rsplit_once('.').unwrap_or(("", class.as_str()));
896            let path = if package.is_empty() {
897                format!("shadow/{simple}Shadow.java")
898            } else {
899                format!("shadow/{}/{simple}Shadow.java", package.replace('.', "/"))
900            };
901            let mut out = String::new();
902            if !package.is_empty() {
903                let _ = writeln!(out, "package {package};\n");
904            }
905            out.push_str("import java.util.concurrent.atomic.AtomicLong;\n");
906            out.push_str(&imports.replace("\n\n", "\n"));
907            let _ = write!(
908                out,
909                "\n/** Runs `{simple}` and its Rust port side by side. Generated by rust-anything: call it in place of `{simple}`. */\n\
910                 public final class {simple}Shadow {{\n    private {simple}Shadow() {{}}\n\n\
911                 \x20   private static final String MODE = System.getProperty(\"rust-anything.mode\", \"shadow\");\n\
912                 \x20   public static final AtomicLong CALLS = new AtomicLong();\n    public static final AtomicLong MISMATCHES = new AtomicLong();\n\n\
913                 \x20   private static void compare(String name, Object expected, Object actual) {{\n        CALLS.incrementAndGet();\n\
914                 \x20       if (actual instanceof Throwable || !rustanything.RustAnythingJson.write(expected).equals(rustanything.RustAnythingJson.write(actual))) {{\n\
915                 \x20           if (MISMATCHES.incrementAndGet() <= 10) {{\n                System.err.println(\"[rust-anything] mismatch in \" + name + \": expected \" + expected + \", got \" + actual);\n            }}\n        }}\n    }}\n\n{}}}\n",
916                methods.join("\n")
917            );
918            (path, out)
919        })
920        .collect()
921}
922
923/// A Java type that crosses JNI without JSON: the JNI type, the port type it must match, how
924/// the argument becomes the port's value, how the port's result becomes the JNI value, and the
925/// value returned while an exception is pending.
926struct Jni {
927    jni: &'static str,
928    port: &'static str,
929    arg: fn(&str) -> String,
930    out: &'static str,
931    default: &'static str,
932}
933
934fn jni(java: &str) -> Option<Jni> {
935    let int = |jni, out| Jni {
936        jni,
937        port: "i64",
938        arg: |n| format!("i64::from({n})"),
939        out,
940        default: "0",
941    };
942    Some(match java.trim() {
943        "int" => int("jni::sys::jint", "out as jni::sys::jint"),
944        "short" => int("jni::sys::jshort", "out as jni::sys::jshort"),
945        "byte" => int("jni::sys::jbyte", "out as jni::sys::jbyte"),
946        "long" => Jni {
947            jni: "jni::sys::jlong",
948            port: "i64",
949            arg: |n| n.to_string(),
950            out: "out",
951            default: "0",
952        },
953        "double" => Jni {
954            jni: "jni::sys::jdouble",
955            port: "f64",
956            arg: |n| n.to_string(),
957            out: "out",
958            default: "0.0",
959        },
960        "float" => Jni {
961            jni: "jni::sys::jfloat",
962            port: "f64",
963            arg: |n| format!("f64::from({n})"),
964            out: "out as jni::sys::jfloat",
965            default: "0.0",
966        },
967        "boolean" => Jni {
968            jni: "jni::sys::jboolean",
969            port: "bool",
970            arg: |n| format!("{n} != 0"),
971            out: "jni::sys::jboolean::from(out)",
972            default: "0",
973        },
974        "String" => Jni {
975            jni: "jni::objects::JString<'local>",
976            port: "String",
977            arg: |n| n.to_string(),
978            out: "java_string(&mut env, &out)",
979            default: "std::ptr::null_mut()",
980        },
981        _ => return None,
982    })
983}
984
985/// Whether a function crosses as a typed JNI method: every parameter and the result are
986/// primitives or `String`, and the port kept the matching Rust types.
987fn typed<'m>(
988    m: &'m Manifest,
989    f: &crate::codegen::PortFn,
990) -> Option<&'m crate::ts::exports::ExportedFn> {
991    let e = m.exports.iter().find(|e| e.name == f.js_name)?;
992    if e.params.len() != f.params.len() {
993        return None;
994    }
995    for (p, (_, port_ty)) in e.params.iter().zip(&f.params) {
996        if jni(p.native_type.as_deref()?)?.port != port_ty {
997            return None;
998        }
999    }
1000    match e.native_return.as_deref()? {
1001        "void" => (f.ret == "()").then_some(e),
1002        r => (jni(r)?.port == f.ret).then_some(e),
1003    }
1004}
1005
1006/// Escape one component of a JNI symbol. Non-ASCII characters are encoded one UTF-16 unit at a time.
1007pub(crate) fn mangle_jni_component(s: &str) -> String {
1008    let mut out = String::new();
1009    for unit in s.encode_utf16() {
1010        match unit {
1011            0x30..=0x39 | 0x41..=0x5a | 0x61..=0x7a => out.push(char::from(unit as u8)),
1012            0x5f => out.push_str("_1"),
1013            _ => {
1014                let _ = write!(out, "_0{unit:04x}");
1015            }
1016        }
1017    }
1018    out
1019}
1020
1021/// Typed JNI functions for `lib.rs`, appended after the JSON dispatcher.
1022pub fn typed_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1023    let class = java_native_class(m);
1024    let mut out = String::from(
1025        r#"
1026/// `rustanything.RustAnythingError` and its `(String, String)` constructor, resolved once per process.
1027type Exception = (jni::objects::GlobalRef, jni::objects::JMethodID);
1028static RUST_ANYTHING_ERROR: std::sync::OnceLock<Option<Exception>> = std::sync::OnceLock::new();
1029
1030fn rust_anything_error(env: &mut jni::JNIEnv) -> Option<Exception> {
1031    RUST_ANYTHING_ERROR
1032        .get_or_init(|| {
1033            let class = env.find_class("rustanything/RustAnythingError").ok()?;
1034            let ctor = env
1035                .get_method_id(&class, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V")
1036                .ok()?;
1037            Some((env.new_global_ref(class).ok()?, ctor))
1038        })
1039        .clone()
1040}
1041
1042/// Splits `"Type: message"`; anything else is a RuntimeException with the whole message.
1043fn split_error(message: &str) -> (&str, &str) {
1044    message
1045        .split_once(": ")
1046        .filter(|(k, _)| {
1047            k.starts_with(|c: char| c.is_ascii_alphabetic())
1048                && k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '$'))
1049        })
1050        .unwrap_or(("RuntimeException", message))
1051}
1052
1053#[allow(dead_code)]
1054/// Hands an error back through the caller's `String[2]` slot: type and message. The Java side
1055/// throws it, which is much cheaper than an exception raised from native code.
1056fn report(env: &mut jni::JNIEnv, slot: &jni::objects::JObjectArray, message: &str) {
1057    let (kind, text) = split_error(message);
1058    if let (Ok(kind), Ok(text)) = (env.new_string(kind), env.new_string(text)) {
1059        let _ = env.set_object_array_element(slot, 0, &kind);
1060        let _ = env.set_object_array_element(slot, 1, &text);
1061    }
1062}
1063
1064#[allow(dead_code)]
1065/// Throws `"Type: message"` as a `RustAnythingError` without a stack trace, which is cheap from
1066/// native code; the generated Java turns it into a `Type` exception, built in Java.
1067fn throw(env: &mut jni::JNIEnv, message: &str) {
1068    let (kind, text) = split_error(message);
1069    let Some((class, ctor)) = rust_anything_error(env) else {
1070        let _ = env.exception_clear();
1071        let _ = env.throw_new("java/lang/RuntimeException", message);
1072        return;
1073    };
1074    let (Ok(kind), Ok(text)) = (env.new_string(kind), env.new_string(text)) else {
1075        return;
1076    };
1077    let class: &jni::objects::JClass = class.as_obj().into();
1078    let args = [
1079        jni::objects::JValue::Object(&kind).as_jni(),
1080        jni::objects::JValue::Object(&text).as_jni(),
1081    ];
1082    // SAFETY: `ctor` is the `(String, String)` constructor of `class`, looked up together, and
1083    // both arguments are Strings.
1084    if let Ok(object) = unsafe { env.new_object_unchecked(class, ctor, &args) } {
1085        let _ = env.throw(jni::objects::JThrowable::from(object));
1086    }
1087}
1088
1089/// Runs the port; a panic becomes an error instead of unwinding into the JVM.
1090#[allow(dead_code)]
1091fn run<T>(f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
1092    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|panic| {
1093        let text = panic
1094            .downcast_ref::<&str>()
1095            .map(ToString::to_string)
1096            .or_else(|| panic.downcast_ref::<String>().cloned())
1097            .unwrap_or_default();
1098        Err(format!("RuntimeException: Rust panic: {text}"))
1099    })
1100}
1101
1102/// A `String` argument; `None` (with a NullPointerException thrown) for null.
1103#[allow(dead_code)]
1104fn string_arg(env: &mut jni::JNIEnv, s: &jni::objects::JString) -> Option<String> {
1105    if s.is_null() {
1106        let _ = env.throw_new("java/lang/NullPointerException", "null String argument");
1107        return None;
1108    }
1109    let raw = env.get_raw();
1110    let mut stack = [0u16; 128];
1111    // SAFETY: `raw` is this thread's JNIEnv and `s` a live, non-null String reference; the JVM
1112    // fills every entry of the function table.
1113    let len = unsafe { ((**raw).GetStringLength?)(raw, s.as_raw()) };
1114    let n = usize::try_from(len).unwrap_or(0);
1115    let mut heap = Vec::new();
1116    let units: &mut [u16] = if n <= stack.len() {
1117        &mut stack[..n]
1118    } else {
1119        heap.resize(n, 0);
1120        &mut heap
1121    };
1122    // SAFETY: as above; `units` holds exactly `len` UTF-16 code units.
1123    unsafe { ((**raw).GetStringRegion?)(raw, s.as_raw(), 0, len, units.as_mut_ptr()) };
1124    // UTF-16 straight from the String: no modified UTF-8 in between.
1125    Some(String::from_utf16_lossy(units))
1126}
1127
1128/// A Java String from Rust text, built from UTF-16 (`NewString`), not modified UTF-8.
1129#[allow(dead_code)]
1130fn java_string(env: &mut jni::JNIEnv, text: &str) -> jni::sys::jstring {
1131    let mut stack = [0u16; 128];
1132    let mut heap = Vec::new();
1133    let units: &[u16] = if text.len() <= stack.len() {
1134        let mut n = 0;
1135        for u in text.encode_utf16() {
1136            stack[n] = u;
1137            n += 1;
1138        }
1139        &stack[..n]
1140    } else {
1141        heap.extend(text.encode_utf16());
1142        &heap
1143    };
1144    let Ok(len) = jni::sys::jsize::try_from(units.len()) else {
1145        return std::ptr::null_mut();
1146    };
1147    let raw = env.get_raw();
1148    // SAFETY: `raw` is this thread's JNIEnv, valid for the call.
1149    let Some(new_string) = (unsafe { (**raw).NewString }) else {
1150        return std::ptr::null_mut();
1151    };
1152    // SAFETY: `units` holds `len` UTF-16 code units, read during the call only.
1153    unsafe { new_string(raw, units.as_ptr(), len) }
1154}
1155"#,
1156    );
1157    for f in &api.functions {
1158        let Some(e) = typed(m, f) else { continue };
1159        let ret_java = e.native_return.as_deref().unwrap_or("void");
1160        let ret = if ret_java == "void" {
1161            None
1162        } else {
1163            jni(ret_java)
1164        };
1165        let mut params = vec![
1166            "mut env: jni::JNIEnv<'local>".to_string(),
1167            "_class: jni::objects::JClass<'local>".to_string(),
1168        ];
1169        let mut prelude = String::new();
1170        let mut args = Vec::new();
1171        let default = ret.as_ref().map_or("", |r| r.default);
1172        for (p, (name, _)) in e.params.iter().zip(&f.params) {
1173            let t = jni(p.native_type.as_deref().unwrap_or_default()).expect("typed");
1174            params.push(format!("{name}: {}", t.jni));
1175            if t.port == "String" {
1176                let _ = writeln!(
1177                    prelude,
1178                    "    let Some({name}) = string_arg(&mut env, &{name}) else {{\n        return {default};\n    }};"
1179                );
1180                args.push(name.clone());
1181            } else {
1182                args.push((t.arg)(name));
1183            }
1184        }
1185        params.push("slot: jni::objects::JObjectArray<'local>".to_string());
1186        let call = format!("port::{}({})", f.rust_name, args.join(", "));
1187        let call = if f.fallible {
1188            call
1189        } else {
1190            format!("Ok({call})")
1191        };
1192        let (ret_ty, ok) = match &ret {
1193            Some(r) => (
1194                format!(
1195                    " -> {}",
1196                    r.jni
1197                        .replace("JString<'local>", "jstring")
1198                        .replace("jni::objects::jstring", "jni::sys::jstring")
1199                ),
1200                r.out.to_string(),
1201            ),
1202            None => (String::new(), "()".to_string()),
1203        };
1204        let _ = writeln!(
1205            out,
1206            "\n/// `{proto}`: typed, no JSON.\n// SAFETY: the JNI symbol of `rustanything.{class}.n_{js}`; nothing else defines it.\n\
1207             #[unsafe(no_mangle)]\npub extern \"system\" fn Java_rustanything_{mclass}_n_1{mjs}<'local>({params}){ret_ty} {{\n\
1208             {prelude}    match run(|| {call}) {{\n        Ok(out) => {ok},\n        Err(message) => {{\n            \
1209             report(&mut env, &slot, &message);\n            {default}\n        }}\n    }}\n}}",
1210            proto = e.prototype.as_deref().unwrap_or(&e.name),
1211            js = f.js_name,
1212            mclass = mangle_jni_component(&class),
1213            mjs = mangle_jni_component(&f.js_name),
1214            params = params.join(", "),
1215        );
1216    }
1217    out
1218}
1219
1220/// The exports that cross as typed JNI methods.
1221fn typed_names(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<String> {
1222    api.functions
1223        .iter()
1224        .filter(|f| typed(m, f).is_some())
1225        .map(|f| f.js_name.clone())
1226        .collect()
1227}
1228
1229/// The `static native` declarations of the typed methods.
1230fn typed_declarations(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1231    let mut out = String::new();
1232    for f in &api.functions {
1233        let Some(e) = typed(m, f) else { continue };
1234        let params: Vec<String> = e
1235            .params
1236            .iter()
1237            .map(|p| {
1238                format!(
1239                    "{} {}",
1240                    p.native_type.as_deref().unwrap_or("Object"),
1241                    p.name
1242                )
1243            })
1244            .collect();
1245        let mut params = params;
1246        params.push("String[] slot".into());
1247        let _ = writeln!(
1248            out,
1249            "    public static native {} n_{}({});",
1250            e.native_return.as_deref().unwrap_or("void"),
1251            f.js_name,
1252            params.join(", ")
1253        );
1254    }
1255    out
1256}
1257
1258// ---- the binary wire: lists, arrays, maps, boxed and optional values, without JSON ----------
1259
1260use crate::wire::Ty;
1261
1262fn split_generic(t: &str) -> Option<(&str, Vec<String>)> {
1263    let i = t.find('<')?;
1264    let inner = t.strip_suffix('>')?.get(i + 1..)?;
1265    let mut args = Vec::new();
1266    let mut depth = 0;
1267    let mut cur = String::new();
1268    for c in inner.chars() {
1269        match c {
1270            '<' => depth += 1,
1271            '>' => depth -= 1,
1272            ',' if depth == 0 => {
1273                args.push(cur.trim().to_string());
1274                cur.clear();
1275                continue;
1276            }
1277            _ => {}
1278        }
1279        cur.push(c);
1280    }
1281    args.push(cur.trim().to_string());
1282    Some((t[..i].trim(), args))
1283}
1284
1285/// The wire type of a Java type; `None` for types the wire does not carry.
1286fn java_ty(t: &str) -> Option<Ty> {
1287    let t = t.trim();
1288    let boxed = |inner: Ty| Ty::Opt {
1289        inner: Box::new(inner),
1290        native: t.to_string(),
1291    };
1292    Some(match t {
1293        "int" | "long" | "short" | "byte" => Ty::I64(t.into()),
1294        "double" | "float" => Ty::F64(t.into()),
1295        "boolean" => Ty::Bool,
1296        "String" | "CharSequence" => Ty::Str,
1297        "Integer" => boxed(Ty::I64("int".into())),
1298        "Long" => boxed(Ty::I64("long".into())),
1299        "Short" => boxed(Ty::I64("short".into())),
1300        "Byte" => boxed(Ty::I64("byte".into())),
1301        "Double" => boxed(Ty::F64("double".into())),
1302        "Float" => boxed(Ty::F64("float".into())),
1303        "Boolean" => boxed(Ty::Bool),
1304        _ => {
1305            if let Some(item) = t.strip_suffix("[]") {
1306                let item_ty = java_ty(item)?;
1307                // Primitive arrays need a helper; reference arrays use a generic one.
1308                if matches!(item_ty, Ty::I64(_) | Ty::F64(_) | Ty::Bool)
1309                    && !matches!(item.trim(), "int" | "long" | "double" | "boolean")
1310                {
1311                    return None;
1312                }
1313                return Some(Ty::List {
1314                    item: Box::new(item_ty),
1315                    native: t.into(),
1316                    array: true,
1317                });
1318            }
1319            let (head, args) = split_generic(t)?;
1320            match head.rsplit('.').next().unwrap_or(head) {
1321                "List" | "ArrayList" | "Collection" | "Iterable" | "LinkedList" => Ty::List {
1322                    item: Box::new(java_ty(args.first()?)?),
1323                    native: t.into(),
1324                    array: false,
1325                },
1326                "Map" | "LinkedHashMap" | "HashMap" | "TreeMap" if args.first()? == "String" => {
1327                    Ty::Map {
1328                        value: Box::new(java_ty(args.get(1)?)?),
1329                        native: t.into(),
1330                    }
1331                }
1332                "Optional" => Ty::Opt {
1333                    inner: Box::new(java_ty(args.first()?)?),
1334                    native: t.into(),
1335                },
1336                _ => return None,
1337            }
1338        }
1339    })
1340}
1341
1342/// Java statements writing `expr` of type `t` to writer `w`.
1343fn java_enc(expr: &str, t: &Ty, depth: usize) -> String {
1344    let d = depth;
1345    match t {
1346        Ty::I64(_) => format!("w.i64({expr});"),
1347        Ty::F64(_) => format!("w.f64({expr});"),
1348        Ty::Bool => format!("w.bool({expr});"),
1349        Ty::Str => format!("w.str({expr});"),
1350        Ty::Opt { inner, native } if native.starts_with("Optional") => format!(
1351            "{{ var o{d} = {expr}; if (o{d} == null || o{d}.isEmpty()) {{ w.tag(0); }} else {{ w.tag(1); {} }} }}",
1352            java_enc(&format!("o{d}.get()"), inner, d + 1)
1353        ),
1354        Ty::Opt { inner, .. } => format!(
1355            "{{ var o{d} = {expr}; if (o{d} == null) {{ w.tag(0); }} else {{ w.tag(1); {} }} }}",
1356            java_enc(&format!("o{d}"), inner, d + 1)
1357        ),
1358        Ty::List { item, array, .. } => format!(
1359            "{{ 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}) {{ {} }} }} }}",
1360            if *array { "length" } else { "size()" },
1361            java_enc(&format!("v{d}"), item, d + 1)
1362        ),
1363        Ty::Map { value, .. } => format!(
1364            "{{ 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()); {} }} }} }}",
1365            java_enc(&format!("e{d}.getValue()"), value, d + 1)
1366        ),
1367        _ => String::new(),
1368    }
1369}
1370
1371/// A Java expression reading a value of type `t` from reader `r`.
1372fn java_dec(t: &Ty) -> Option<String> {
1373    Some(match t {
1374        Ty::I64(n) => match n.as_str() {
1375            "long" => "r.i64()".into(),
1376            other => format!("(({other}) r.i64())"),
1377        },
1378        Ty::F64(n) => match n.as_str() {
1379            "float" => "((float) r.f64())".into(),
1380            _ => "r.f64()".into(),
1381        },
1382        Ty::Bool => "r.bool()".into(),
1383        Ty::Str => "r.str()".into(),
1384        Ty::Opt { inner, native } if native.starts_with("Optional") => {
1385            let arg = split_generic(native)?.1.first()?.clone();
1386            format!(
1387                "(r.tag() == 0 ? java.util.Optional.<{arg}>empty() : java.util.Optional.of({}))",
1388                java_dec(inner)?
1389            )
1390        }
1391        Ty::Opt { inner, native } => {
1392            format!("(r.tag() == 0 ? null : ({native}) {})", java_dec(inner)?)
1393        }
1394        Ty::List {
1395            item,
1396            native,
1397            array: true,
1398        } => match native.trim_end_matches("[]") {
1399            "int" => "r.ints()".into(),
1400            "long" => "r.longs()".into(),
1401            "double" => "r.doubles()".into(),
1402            "boolean" => "r.booleans()".into(),
1403            elem => format!("r.array(() -> {}, {elem}[]::new)", java_dec(item)?),
1404        },
1405        Ty::List { item, .. } => format!("r.list(() -> {})", java_dec(item)?),
1406        Ty::Map { value, .. } => format!("r.map(() -> {})", java_dec(value)?),
1407        _ => return None,
1408    })
1409}
1410
1411/// `rustanything/RustAnythingError.java`: the error the Rust side throws, turned into the real
1412/// exception type in Java.
1413pub const ERROR_JAVA: &str = r#"package rustanything;
1414
1415import java.lang.invoke.MethodHandle;
1416import java.lang.invoke.MethodHandles;
1417import java.lang.invoke.MethodType;
1418import java.util.Optional;
1419import java.util.concurrent.ConcurrentHashMap;
1420
1421/** Generated by rust-anything: a port's error, thrown from Rust without a stack trace (cheap from native code). */
1422public final class RustAnythingError extends RuntimeException {
1423    private static final long serialVersionUID = 1L;
1424    private static final ConcurrentHashMap<String, Optional<MethodHandle>> CONSTRUCTORS = new ConcurrentHashMap<>();
1425
1426    public final String type;
1427
1428    public RustAnythingError(String type, String message) {
1429        super(message, null, false, false);
1430        this.type = type;
1431    }
1432
1433    private static Optional<MethodHandle> constructor(String type) {
1434        for (String prefix : new String[] {"java.lang.", "java.util.", "java.io.", ""}) {
1435            try {
1436                Class<?> c = Class.forName(prefix + type);
1437                if (RuntimeException.class.isAssignableFrom(c)) {
1438                    return Optional.of(MethodHandles.publicLookup()
1439                        .findConstructor(c, MethodType.methodType(void.class, String.class))
1440                        .asType(MethodType.methodType(RuntimeException.class, String.class)));
1441                }
1442            } catch (ReflectiveOperationException | IllegalArgumentException e) {
1443                // try the next package
1444            }
1445        }
1446        return Optional.empty();
1447    }
1448
1449    /** The exception the original throws: `type` with the message, else a RuntimeException. */
1450    public RuntimeException real() {
1451        return make(type, getMessage());
1452    }
1453
1454    private static final ThreadLocal<String[]> SLOTS = ThreadLocal.withInitial(() -> new String[2]);
1455
1456    /** This thread's error slot: the Rust side writes a failed call's type and message there. */
1457    public static String[] slot() {
1458        return SLOTS.get();
1459    }
1460
1461    /** Throws the error a call left in `slot`, if any. */
1462    public static void check(String[] slot) {
1463        if (slot[0] != null) {
1464            String type = slot[0];
1465            String message = slot[1];
1466            slot[0] = null;
1467            slot[1] = null;
1468            throw make(type, message);
1469        }
1470    }
1471
1472    private static RuntimeException make(String type, String message) {
1473        Optional<MethodHandle> ctor = CONSTRUCTORS.computeIfAbsent(type, RustAnythingError::constructor);
1474        if (ctor.isPresent()) {
1475            try {
1476                return (RuntimeException) ctor.get().invokeExact(message);
1477            } catch (Throwable e) {
1478                // fall through
1479            }
1480        }
1481        return new RuntimeException(type + ": " + message);
1482    }
1483}
1484"#;
1485
1486/// `rustanything/RustAnythingWire.java`: the Java half of the binary wire.
1487pub const WIRE_JAVA: &str = r#"package rustanything;
1488
1489import java.io.ByteArrayOutputStream;
1490import java.nio.charset.StandardCharsets;
1491import java.util.ArrayList;
1492import java.util.LinkedHashMap;
1493import java.util.List;
1494import java.util.Map;
1495import java.util.function.IntFunction;
1496import java.util.function.Supplier;
1497
1498/** Generated by rust-anything: the binary wire to the Rust port. Little endian; nullable values start with 0 for null. */
1499public final class RustAnythingWire {
1500    private RustAnythingWire() {}
1501
1502    public static final class Writer {
1503        private byte[] buf = new byte[64];
1504        private int n;
1505
1506        private void ensure(int more) {
1507            if (n + more > buf.length) {
1508                buf = java.util.Arrays.copyOf(buf, Math.max(buf.length * 2, n + more));
1509            }
1510        }
1511
1512        public void tag(int t) {
1513            ensure(1);
1514            buf[n++] = (byte) t;
1515        }
1516
1517        public void len(int v) {
1518            ensure(4);
1519            for (int i = 0; i < 4; i++) {
1520                buf[n++] = (byte) (v >>> (8 * i));
1521            }
1522        }
1523
1524        public void i64(long v) {
1525            ensure(8);
1526            for (int i = 0; i < 8; i++) {
1527                buf[n++] = (byte) (v >>> (8 * i));
1528            }
1529        }
1530
1531        public void f64(double v) {
1532            i64(Double.doubleToRawLongBits(v));
1533        }
1534
1535        public void bool(boolean v) {
1536            tag(v ? 1 : 0);
1537        }
1538
1539        public void str(String s) {
1540            if (s == null) {
1541                tag(0);
1542                return;
1543            }
1544            byte[] b = s.getBytes(StandardCharsets.UTF_8);
1545            tag(1);
1546            len(b.length);
1547            ensure(b.length);
1548            System.arraycopy(b, 0, buf, n, b.length);
1549            n += b.length;
1550        }
1551
1552        public byte[] bytes() {
1553            return java.util.Arrays.copyOf(buf, n);
1554        }
1555    }
1556
1557    public static final class Reader {
1558        private final byte[] b;
1559        private int i;
1560
1561        public Reader(byte[] b) {
1562            this.b = b;
1563        }
1564
1565        public int tag() {
1566            return b[i++] & 0xff;
1567        }
1568
1569        public int len() {
1570            int v = 0;
1571            for (int k = 0; k < 4; k++) {
1572                v |= (b[i++] & 0xff) << (8 * k);
1573            }
1574            return v;
1575        }
1576
1577        public long i64() {
1578            long v = 0;
1579            for (int k = 0; k < 8; k++) {
1580                v |= (long) (b[i++] & 0xff) << (8 * k);
1581            }
1582            return v;
1583        }
1584
1585        public double f64() {
1586            return Double.longBitsToDouble(i64());
1587        }
1588
1589        public boolean bool() {
1590            return tag() != 0;
1591        }
1592
1593        public String str() {
1594            if (tag() == 0) {
1595                return null;
1596            }
1597            int n = len();
1598            String s = new String(b, i, n, StandardCharsets.UTF_8);
1599            i += n;
1600            return s;
1601        }
1602
1603        public <T> List<T> list(Supplier<T> item) {
1604            if (tag() == 0) {
1605                return null;
1606            }
1607            int n = len();
1608            List<T> out = new ArrayList<>(n);
1609            for (int k = 0; k < n; k++) {
1610                out.add(item.get());
1611            }
1612            return out;
1613        }
1614
1615        public <T> T[] array(Supplier<T> item, IntFunction<T[]> make) {
1616            List<T> items = list(item);
1617            return items == null ? null : items.toArray(make.apply(items.size()));
1618        }
1619
1620        public <T> Map<String, T> map(Supplier<T> item) {
1621            if (tag() == 0) {
1622                return null;
1623            }
1624            int n = len();
1625            Map<String, T> out = new LinkedHashMap<>();
1626            for (int k = 0; k < n; k++) {
1627                String key = str();
1628                out.put(key, item.get());
1629            }
1630            return out;
1631        }
1632
1633        public int[] ints() {
1634            if (tag() == 0) {
1635                return null;
1636            }
1637            int[] out = new int[len()];
1638            for (int k = 0; k < out.length; k++) {
1639                out[k] = (int) i64();
1640            }
1641            return out;
1642        }
1643
1644        public long[] longs() {
1645            if (tag() == 0) {
1646                return null;
1647            }
1648            long[] out = new long[len()];
1649            for (int k = 0; k < out.length; k++) {
1650                out[k] = i64();
1651            }
1652            return out;
1653        }
1654
1655        public double[] doubles() {
1656            if (tag() == 0) {
1657                return null;
1658            }
1659            double[] out = new double[len()];
1660            for (int k = 0; k < out.length; k++) {
1661                out[k] = f64();
1662            }
1663            return out;
1664        }
1665
1666        public boolean[] booleans() {
1667            if (tag() == 0) {
1668                return null;
1669            }
1670            boolean[] out = new boolean[len()];
1671            for (int k = 0; k < out.length; k++) {
1672                out[k] = bool();
1673            }
1674            return out;
1675        }
1676    }
1677}
1678"#;
1679
1680/// The exports that cross the binary wire, with their Java body and Rust code.
1681fn java_wire_fns<'m>(
1682    m: &'m Manifest,
1683    api: &crate::codegen::PortApi,
1684) -> Vec<(&'m crate::ts::exports::ExportedFn, String, String)> {
1685    let class = java_native_class(m);
1686    let mut out = Vec::new();
1687    for f in &api.functions {
1688        if typed(m, f).is_some() {
1689            continue;
1690        }
1691        let Some(e) = m.exports.iter().find(|e| e.name == f.js_name) else {
1692            continue;
1693        };
1694        if e.params.len() != f.params.len() {
1695            continue;
1696        }
1697        let Some(params) = e
1698            .params
1699            .iter()
1700            .map(|p| Some((p.name.clone(), java_ty(p.native_type.as_deref()?)?)))
1701            .collect::<Option<Vec<_>>>()
1702        else {
1703            continue;
1704        };
1705        let ret_java = e.native_return.as_deref().unwrap_or("void");
1706        let result = if ret_java == "void" {
1707            None
1708        } else {
1709            java_ty(ret_java)
1710        };
1711        if ret_java != "void" && result.is_none() {
1712            continue;
1713        }
1714        // Java body of `call_<name>`.
1715        let mut java =
1716            String::from("        RustAnythingWire.Writer w = new RustAnythingWire.Writer();\n");
1717        for (name, t) in &params {
1718            let _ = writeln!(java, "        {}", java_enc(name, t, 0));
1719        }
1720        let _ = writeln!(
1721            java,
1722            "        String[] slot = RustAnythingError.slot();\n        byte[] out = w_{}(w.bytes(), slot);\n        RustAnythingError.check(slot);",
1723            f.js_name
1724        );
1725        if let Some(t) = &result {
1726            let Some(dec) = java_dec(t) else { continue };
1727            let _ = writeln!(
1728                java,
1729                "        RustAnythingWire.Reader r = new RustAnythingWire.Reader(out);\n        return {dec};"
1730            );
1731        }
1732        // Rust JNI function.
1733        let mut statics = String::new();
1734        let prefix = format!("S_{}", f.js_name.to_uppercase());
1735        let Some(reads) = crate::wire::rust_read_args(&params, &f.params, &prefix, &mut statics)
1736        else {
1737            continue;
1738        };
1739        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
1740        let call = format!("port::{}({})", f.rust_name, args.join(", "));
1741        let call = if f.fallible { format!("{call}?") } else { call };
1742        let write = match &result {
1743            None if f.ret == "()" => format!("        let () = {call};\n"),
1744            None => continue,
1745            Some(t) => {
1746                let schema = format!("{prefix}_OUT");
1747                let Some(w) = crate::wire::rust_write(t, &f.ret, "out", &schema, 0) else {
1748                    continue;
1749                };
1750                if w.contains(&schema) {
1751                    let _ = writeln!(
1752                        statics,
1753                        "static {schema}: wire::Schema = {};",
1754                        crate::wire::schema_expr(t)
1755                    );
1756                }
1757                format!("        let out = &{call};\n        {w}\n")
1758            }
1759        };
1760        let rust = format!(
1761            "\n{statics}\n/// `{proto}`: binary wire.\n// SAFETY: the JNI symbol of `rustanything.{class}.w_{js}`; nothing else defines it.\n\
1762             #[unsafe(no_mangle)]\npub extern \"system\" fn Java_rustanything_{mclass}_w_1{mjs}<'local>(mut env: jni::JNIEnv<'local>, \
1763             _class: jni::objects::JClass<'local>, args: jni::objects::JByteArray<'local>, slot: jni::objects::JObjectArray<'local>) -> jni::sys::jbyteArray {{\n    \
1764             let Ok(input) = env.convert_byte_array(&args) else {{\n        return std::ptr::null_mut();\n    }};\n    \
1765             let result = run(|| {{\n        let r = &mut wire::Reader::new(&input);\n{reads}        let w = &mut wire::Writer::default();\n{write}        \
1766             Ok(std::mem::take(&mut w.0))\n    }});\n    match result {{\n        \
1767             Ok(bytes) => env.byte_array_from_slice(&bytes).map_or(std::ptr::null_mut(), jni::objects::JByteArray::into_raw),\n        \
1768             Err(message) => {{\n            report(&mut env, &slot, &message);\n            std::ptr::null_mut()\n        }}\n    }}\n}}",
1769            proto = e.prototype.as_deref().unwrap_or(&e.name),
1770            js = f.js_name,
1771            mclass = mangle_jni_component(&class),
1772            mjs = mangle_jni_component(&f.js_name),
1773        );
1774        out.push((e, java, rust));
1775    }
1776    out
1777}
1778
1779/// Rust code of every wire export, for `lib.rs`.
1780pub fn wire_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1781    java_wire_fns(m, api)
1782        .into_iter()
1783        .map(|(_, _, rust)| rust)
1784        .collect()
1785}
1786
1787/// `call_<name>` methods of the native class: the one entry point wrappers and shadows use.
1788fn call_methods(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1789    let mut out = String::new();
1790    let sig = |e: &crate::ts::exports::ExportedFn| {
1791        e.params
1792            .iter()
1793            .map(|p| {
1794                format!(
1795                    "{} {}",
1796                    p.native_type.as_deref().unwrap_or("Object"),
1797                    p.name
1798                )
1799            })
1800            .collect::<Vec<_>>()
1801            .join(", ")
1802    };
1803    for f in &api.functions {
1804        let Some(e) = typed(m, f) else { continue };
1805        let ret = e.native_return.as_deref().unwrap_or("void");
1806        let args = e
1807            .params
1808            .iter()
1809            .map(|p| p.name.as_str())
1810            .collect::<Vec<_>>()
1811            .join(", ");
1812        let call_args = if args.is_empty() {
1813            "slot".to_string()
1814        } else {
1815            format!("{args}, slot")
1816        };
1817        let body = if ret == "void" {
1818            format!(
1819                "String[] slot = RustAnythingError.slot();\n            n_{}({call_args});\n            RustAnythingError.check(slot);",
1820                f.js_name
1821            )
1822        } else {
1823            format!(
1824                "String[] slot = RustAnythingError.slot();\n            {ret} out = n_{}({call_args});\n            RustAnythingError.check(slot);\n            return out;",
1825                f.js_name
1826            )
1827        };
1828        let _ = writeln!(
1829            out,
1830            "\n    public static {ret} call_{}({}) {{\n        try {{\n            {body}\n        }} catch (RustAnythingError e) {{\n            throw e.real();\n        }}\n    }}",
1831            f.js_name,
1832            sig(e)
1833        );
1834    }
1835    for (e, body, _) in java_wire_fns(m, api) {
1836        let ret = e.native_return.as_deref().unwrap_or("void");
1837        let _ = writeln!(
1838            out,
1839            "\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    }}",
1840            sig(e),
1841            name = e.name,
1842        );
1843    }
1844    out
1845}
1846
1847/// The exports with a `call_<name>` method (typed or wire).
1848fn direct_names(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<String> {
1849    let mut names = typed_names(m, api);
1850    names.extend(
1851        java_wire_fns(m, api)
1852            .into_iter()
1853            .map(|(e, ..)| e.name.clone()),
1854    );
1855    names
1856}
1857
1858#[cfg(test)]
1859mod tests {
1860    use super::*;
1861
1862    #[test]
1863    fn jni_symbols_match_javac_for_non_ascii_identifiers() {
1864        assert_eq!(mangle_jni_component("n_café"), "n_1caf_000e9");
1865        assert_eq!(mangle_jni_component("w_get$Value"), "w_1get_00024Value");
1866        assert_eq!(mangle_jni_component("n_𐐀"), "n_1_0d801_0dc00");
1867    }
1868}