Skip to main content

rust_anything/
codegen_java.rs

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