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