Skip to content

Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.

105 KB
Raw Blame
//! Java: the JNI wrapper (the original classes' static methods over the Rust library), a small
//! JSON codec with no dependencies, and the reflection driver for record, diff and bench.

use std::collections::BTreeSet;
use std::fmt::Write as _;

use crate::bridge::Manifest;
use crate::codegen_ffi::java_native_class;
use crate::lang::java::receiver;

/// `rustanything/RustAnythingJson.java`: JSON text to Java values and back, conversion to declared
/// generic types, and the markers for floats JSON cannot carry.
pub const JSON_JAVA: &str = r#"package rustanything;

import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

/** Generated by rust-anything: a dependency-free JSON codec for the bridge. */
public final class RustAnythingJson {
    private RustAnythingJson() {}

    /** Captures a generic type: {@code new TypeRef<List<String>>() {}.type()}. */
    public abstract static class TypeRef<T> {
        public Type type() {
            return ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        }
    }

    /** A value that does not fit the declared type. */
    public static final class Mismatch extends RuntimeException {
        public Mismatch(String message) {
            super(message);
        }
    }

    // ---- parse ----

    public static Object parse(String text) {
        int[] pos = {0};
        Object value = value(text, pos);
        skip(text, pos);
        if (pos[0] != text.length()) {
            throw new IllegalArgumentException("trailing JSON at " + pos[0]);
        }
        return value;
    }

    private static void skip(String s, int[] pos) {
        while (pos[0] < s.length() && Character.isWhitespace(s.charAt(pos[0]))) {
            pos[0]++;
        }
    }

    private static Object value(String s, int[] pos) {
        skip(s, pos);
        char c = s.charAt(pos[0]);
        if (c == '{') {
            Map<String, Object> map = new LinkedHashMap<>();
            pos[0]++;
            skip(s, pos);
            if (s.charAt(pos[0]) == '}') {
                pos[0]++;
                return map;
            }
            while (true) {
                skip(s, pos);
                String key = string(s, pos);
                skip(s, pos);
                pos[0]++; // ':'
                map.put(key, value(s, pos));
                skip(s, pos);
                if (s.charAt(pos[0]++) == '}') {
                    return map;
                }
            }
        }
        if (c == '[') {
            List<Object> list = new ArrayList<>();
            pos[0]++;
            skip(s, pos);
            if (s.charAt(pos[0]) == ']') {
                pos[0]++;
                return list;
            }
            while (true) {
                list.add(value(s, pos));
                skip(s, pos);
                if (s.charAt(pos[0]++) == ']') {
                    return list;
                }
            }
        }
        if (c == '"') {
            return string(s, pos);
        }
        if (s.startsWith("true", pos[0])) {
            pos[0] += 4;
            return Boolean.TRUE;
        }
        if (s.startsWith("false", pos[0])) {
            pos[0] += 5;
            return Boolean.FALSE;
        }
        if (s.startsWith("null", pos[0])) {
            pos[0] += 4;
            return null;
        }
        int start = pos[0];
        while (pos[0] < s.length() && "+-0123456789.eE".indexOf(s.charAt(pos[0])) >= 0) {
            pos[0]++;
        }
        String number = s.substring(start, pos[0]);
        if (number.contains(".") || number.contains("e") || number.contains("E")) {
            return Double.parseDouble(number);
        }
        BigInteger big = new BigInteger(number);
        return big.bitLength() < 64 ? (Object) big.longValue() : big;
    }

    private static String string(String s, int[] pos) {
        StringBuilder out = new StringBuilder();
        pos[0]++; // opening quote
        while (true) {
            char c = s.charAt(pos[0]++);
            if (c == '"') {
                return out.toString();
            }
            if (c != '\\') {
                out.append(c);
                continue;
            }
            char e = s.charAt(pos[0]++);
            switch (e) {
                case 'n': out.append('\n'); break;
                case 't': out.append('\t'); break;
                case 'r': out.append('\r'); break;
                case 'b': out.append('\b'); break;
                case 'f': out.append('\f'); break;
                case 'u':
                    out.append((char) Integer.parseInt(s.substring(pos[0], pos[0] + 4), 16));
                    pos[0] += 4;
                    break;
                default: out.append(e);
            }
        }
    }

    // ---- write ----

    /** JSON text of a Java value; floats JSON cannot carry become {"$num": ...}. */
    public static String write(Object v) {
        StringBuilder out = new StringBuilder();
        write(out, v);
        return out.toString();
    }

    private static void write(StringBuilder out, Object v) {
        if (v == null) {
            out.append("null");
        } else if (v instanceof CharSequence || v instanceof Character) {
            String s = v.toString();
            if (hasLoneSurrogate(s)) {
                // JSON text cannot carry a lone half (a strict reader rejects "\ud83d" on its own),
                // so the string goes as its UTF-16 code units, as the other languages do.
                out.append("{\"$utf16\":[");
                for (int i = 0; i < s.length(); i++) {
                    if (i > 0) {
                        out.append(',');
                    }
                    out.append((int) s.charAt(i));
                }
                out.append("]}");
            } else {
                quote(out, s);
            }
        } else if (v instanceof Double || v instanceof Float) {
            double d = ((Number) v).doubleValue();
            if (Double.isNaN(d)) {
                out.append("{\"$num\":\"NaN\"}");
            } else if (Double.isInfinite(d)) {
                out.append(d > 0 ? "{\"$num\":\"Infinity\"}" : "{\"$num\":\"-Infinity\"}");
            } else if (d == 0 && 1 / d < 0) {
                out.append("{\"$num\":\"-0\"}");
            } else if (d == Math.rint(d) && Math.abs(d) < 1e16) {
                out.append(Long.toString((long) d)).append(".0");
            } else {
                out.append(Double.toString(d).replace("E", "e"));
            }
        } else if (v instanceof Number || v instanceof Boolean) {
            out.append(v.toString());
        } else if (v instanceof Optional) {
            write(out, ((Optional<?>) v).orElse(null));
        } else if (v instanceof Map) {
            out.append('{');
            boolean first = true;
            for (Map.Entry<?, ?> e : ((Map<?, ?>) v).entrySet()) {
                if (!first) {
                    out.append(',');
                }
                first = false;
                // A key cannot be a {"$utf16": ...} object: a lone half in it becomes U+FFFD.
                quote(out, message(String.valueOf(e.getKey())));
                out.append(':');
                write(out, e.getValue());
            }
            out.append('}');
        } else if (v instanceof Collection) {
            out.append('[');
            boolean first = true;
            for (Object x : (Collection<?>) v) {
                if (!first) {
                    out.append(',');
                }
                first = false;
                write(out, x);
            }
            out.append(']');
        } else if (v.getClass().isArray()) {
            List<Object> items = new ArrayList<>();
            for (int i = 0; i < Array.getLength(v); i++) {
                items.add(Array.get(v, i));
            }
            write(out, items);
        } else {
            out.append("{\"$object\":");
            quote(out, v.getClass().getName());
            out.append('}');
        }
    }

    /** An error message as JSON text can hold it: a lone surrogate becomes U+FFFD. */
    public static String message(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isHighSurrogate(c) && i + 1 < s.length() && Character.isLowSurrogate(s.charAt(i + 1))) {
                sb.append(c).append(s.charAt(++i));
            } else {
                sb.append(Character.isSurrogate(c) ? (char) 0xFFFD : c);
            }
        }
        return sb.toString();
    }

    private static boolean hasLoneSurrogate(String s) {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isHighSurrogate(c) && i + 1 < s.length() && Character.isLowSurrogate(s.charAt(i + 1))) {
                i++;
            } else if (Character.isSurrogate(c)) {
                return true;
            }
        }
        return false;
    }

    /** The string a {"$utf16": [code units]} marker stands for, or null when v is not one. */
    private static String utf16(Object v) {
        if (!(v instanceof Map) || !((Map<?, ?>) v).containsKey("$utf16")) {
            return null;
        }
        Object units = ((Map<?, ?>) v).get("$utf16");
        if (((Map<?, ?>) v).size() != 1 || !(units instanceof List)) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (Object u : (List<?>) units) {
            if (!(u instanceof Long || u instanceof Integer)) {
                return null;
            }
            long unit = ((Number) u).longValue();
            if (unit < 0 || unit > 0xffff) {
                return null;
            }
            sb.append((char) unit);
        }
        return sb.toString();
    }

    private static void quote(StringBuilder out, String s) {
        out.append('"');
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '"': out.append("\\\""); break;
                case '\\': out.append("\\\\"); break;
                case '\n': out.append("\\n"); break;
                case '\t': out.append("\\t"); break;
                case '\r': out.append("\\r"); break;
                default:
                    if (c < 0x20 || Character.isSurrogate(c)) {
                        // Escaped surrogates keep lone halves intact through any UTF-8 layer.
                        out.append(String.format("\\u%04x", (int) c));
                    } else {
                        out.append(c);
                    }
            }
        }
        out.append('"');
    }

    // ---- convert ----

    private static double number(Object v) {
        if (v instanceof Number) {
            return ((Number) v).doubleValue();
        }
        if (v instanceof Map && ((Map<?, ?>) v).containsKey("$num")) {
            switch (String.valueOf(((Map<?, ?>) v).get("$num"))) {
                case "NaN": return Double.NaN;
                case "Infinity": return Double.POSITIVE_INFINITY;
                case "-Infinity": return Double.NEGATIVE_INFINITY;
                case "-0": return -0.0;
                default: break;
            }
        }
        throw new Mismatch("not a number: " + v);
    }

    private static long integer(Object v, long min, long max) {
        if (v instanceof Long || v instanceof Integer) {
            long n = ((Number) v).longValue();
            if (n >= min && n <= max) {
                return n;
            }
        }
        throw new Mismatch("not an integer in range: " + v);
    }

    /** Converts a parsed JSON value to {@code type}. */
    @SuppressWarnings("unchecked")
    public static Object convert(Object v, Type type) {
        if (type instanceof WildcardType) {
            WildcardType w = (WildcardType) type;
            if (w.getLowerBounds().length > 0) {
                throw new Mismatch("unsupported wildcard " + type);
            }
            Type[] upper = w.getUpperBounds();
            return convert(v, upper.length > 0 ? upper[0] : Object.class);
        }
        if (type instanceof ParameterizedType) {
            ParameterizedType p = (ParameterizedType) type;
            Class<?> raw = (Class<?>) p.getRawType();
            Type[] args = p.getActualTypeArguments();
            if (Optional.class.equals(raw)) {
                return v == null ? Optional.empty() : Optional.of(convert(v, args[0]));
            }
            if (v == null) {
                return null;
            }
            if (Map.class.isAssignableFrom(raw)) {
                if (!(v instanceof Map)) {
                    throw new Mismatch("not an object");
                }
                Map<String, Object> out = new LinkedHashMap<>();
                for (Map.Entry<?, ?> e : ((Map<?, ?>) v).entrySet()) {
                    out.put((String) e.getKey(), convert(e.getValue(), args[1]));
                }
                return out;
            }
            if (Set.class.isAssignableFrom(raw)) {
                if (!(v instanceof List)) {
                    throw new Mismatch("not an array");
                }
                if (raw == SortedSet.class || raw == NavigableSet.class || raw == TreeSet.class) {
                    TreeSet<Object> out = new TreeSet<>();
                    Object prev = null;
                    for (Object x : (List<?>) v) {
                        Object item = convert(x, args[0]);
                        try {
                            out.add(item);
                            if (prev != null && ((Comparable<Object>) prev).compareTo(item) >= 0) {
                                throw new Mismatch(
                                    "sorted set elements repeat or are not in natural order (custom comparators are not supported)");
                            }
                        } catch (NullPointerException | ClassCastException e) {
                            throw new Mismatch("invalid element for " + raw.getSimpleName() + ": " + e.getMessage());
                        }
                        prev = item;
                    }
                    return out;
                }
                if (raw == LinkedHashSet.class) {
                    Set<Object> out = new LinkedHashSet<>();
                    for (Object x : (List<?>) v) {
                        out.add(convert(x, args[0]));
                    }
                    if (out.size() != ((List<?>) v).size()) {
                        throw new Mismatch("duplicate elements in a set");
                    }
                    return out;
                }
                throw new Mismatch("unsupported set type " + type);
            }
            if (Iterable.class.isAssignableFrom(raw)) {
                if (!(v instanceof List)) {
                    throw new Mismatch("not an array");
                }
                List<Object> out = new ArrayList<>();
                for (Object x : (List<?>) v) {
                    out.add(convert(x, args[0]));
                }
                return out;
            }
            throw new Mismatch("unsupported type " + type);
        }
        if (type instanceof GenericArrayType) {
            return array(v, ((GenericArrayType) type).getGenericComponentType());
        }
        Class<?> c = (Class<?>) type;
        if (c.isArray()) {
            return array(v, c.getComponentType());
        }
        if (v == null) {
            if (c.isPrimitive()) {
                throw new Mismatch("null for " + c);
            }
            return null;
        }
        if (c == String.class || c == CharSequence.class) {
            String units = utf16(v);
            if (units != null) {
                return units;
            }
            if (!(v instanceof String)) {
                throw new Mismatch("not a string");
            }
            return v;
        }
        if (c == int.class || c == Integer.class) {
            return (int) integer(v, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }
        if (c == long.class || c == Long.class) {
            return integer(v, Long.MIN_VALUE, Long.MAX_VALUE);
        }
        if (c == short.class || c == Short.class) {
            return (short) integer(v, Short.MIN_VALUE, Short.MAX_VALUE);
        }
        if (c == byte.class || c == Byte.class) {
            return (byte) integer(v, Byte.MIN_VALUE, Byte.MAX_VALUE);
        }
        if (c == double.class || c == Double.class) {
            return number(v);
        }
        if (c == float.class || c == Float.class) {
            return (float) number(v);
        }
        if (c == boolean.class || c == Boolean.class) {
            if (!(v instanceof Boolean)) {
                throw new Mismatch("not a boolean");
            }
            return v;
        }
        if (c == Object.class) {
            return v;
        }
        throw new Mismatch("unsupported type " + c);
    }

    /**
     * Writes {@code source} into the caller's own array, list, set or map, so the call's change is
     * seen by whoever passed it. What the original could not change (an immutable collection)
     * stays as it is.
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static void writeBack(Object target, Object source) {
        if (target == null || source == null) {
            return;
        }
        try {
            if (target.getClass().isArray() && source.getClass().isArray()) {
                int n = Math.min(Array.getLength(target), Array.getLength(source));
                for (int i = 0; i < n; i++) {
                    Array.set(target, i, Array.get(source, i));
                }
            } else if (target instanceof Map && source instanceof Map) {
                Map copy = new java.util.LinkedHashMap((Map) source);
                ((Map) target).clear();
                ((Map) target).putAll(copy);
            } else if (target instanceof java.util.Collection && source instanceof java.util.Collection) {
                List copy = new java.util.ArrayList((java.util.Collection) source);
                ((java.util.Collection) target).clear();
                ((java.util.Collection) target).addAll(copy);
            }
        } catch (UnsupportedOperationException e) {
            // An immutable collection: the original could not change it either.
        }
    }

    private static Class<?> rawType(Type type) {
        if (type instanceof WildcardType) {
            WildcardType w = (WildcardType) type;
            if (w.getLowerBounds().length > 0) {
                throw new Mismatch("unsupported wildcard " + type);
            }
            Type[] upper = w.getUpperBounds();
            return rawType(upper.length > 0 ? upper[0] : Object.class);
        }
        if (type instanceof Class) {
            return (Class<?>) type;
        }
        if (type instanceof ParameterizedType) {
            return (Class<?>) ((ParameterizedType) type).getRawType();
        }
        if (type instanceof GenericArrayType) {
            Class<?> elem = rawType(((GenericArrayType) type).getGenericComponentType());
            return Array.newInstance(elem, 0).getClass();
        }
        throw new Mismatch("unsupported type " + type);
    }

    private static Object array(Object v, Type component) {
        if (!(v instanceof List)) {
            throw new Mismatch("not an array");
        }
        List<?> list = (List<?>) v;
        Class<?> raw = rawType(component);
        Object out = Array.newInstance(raw, list.size());
        for (int i = 0; i < list.size(); i++) {
            Array.set(out, i, convert(list.get(i), component));
        }
        return out;
    }
}
"#;

/// Boxes a primitive type for generics: `int` to `Integer`.
fn boxed(t: &str) -> String {
    match t.trim() {
        "int" => "Integer".into(),
        "long" => "Long".into(),
        "short" => "Short".into(),
        "byte" => "Byte".into(),
        "double" => "Double".into(),
        "float" => "Float".into(),
        "boolean" => "Boolean".into(),
        "char" => "Character".into(),
        other => other.into(),
    }
}

/// The native class: loads the Rust library and calls the dispatcher.
pub fn native_class(m: &Manifest, api: &crate::codegen::PortApi) -> String {
    let class = java_native_class(m);
    let lib = m.lib_name();
    format!(
        r#"package rustanything;

import java.lang.reflect.Type;
import java.util.*;

/** Generated by rust-anything: calls the Rust port of `{unit}` through JNI. */
public final class {class} {{
    private {class}() {{}}

    static {{
        String path = System.getProperty("rust-anything.lib.{lib}");
        if (path != null) {{
            System.load(path);
        }} else {{
            System.loadLibrary("{lib}");
        }}
    }}

    private static native String call(String name, String args);

    // Typed methods: primitives and strings cross JNI directly, without JSON.
{typed}{calls}

    /**
     * Calls the port of {{@code name}}, which changes arguments or prints: answers {{@code ret}},
     * {{@code after}} (each changed argument), {{@code error}} and {{@code stdout}}.
     */
    @SuppressWarnings("unchecked")
    public static Map<String, Object> effects(String name, Object... args) {{
        String answer = call(name, RustAnythingJson.write(java.util.Arrays.asList(args)));
        Map<String, Object> parsed = (Map<String, Object>) RustAnythingJson.parse(answer);
        if (parsed.containsKey("ok")) {{
            return (Map<String, Object>) parsed.get("ok");
        }}
        throw RustAnythingError.from(parsed.containsKey("error")
            ? String.valueOf(parsed.get("error"))
            : "Rust panic: " + parsed.get("panic"));
    }}

    /** Calls the port of {{@code name}}; its answer is converted to {{@code type}}. */
    public static Object invoke(String name, Type type, Object... args) {{
        String answer = call(name, RustAnythingJson.write(java.util.Arrays.asList(args)));
        @SuppressWarnings("unchecked")
        Map<String, Object> parsed = (Map<String, Object>) RustAnythingJson.parse(answer);
        if (parsed.containsKey("ok")) {{
            return type == void.class ? null : RustAnythingJson.convert(parsed.get("ok"), type);
        }}
        String message = parsed.containsKey("error")
            ? String.valueOf(parsed.get("error"))
            : "Rust panic: " + parsed.get("panic");
        throw RustAnythingError.from(message);
    }}
}}
"#,
        unit = m.unit,
        typed = typed_declarations(m, api),
        calls = call_methods(m, api),
    )
}

/// The wrapper classes: `(path, source)` for each class of the unit with ported methods.
pub fn wrappers(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<(String, String)> {
    let typed = direct_names(m, api);
    let native = java_native_class(m);
    let mut classes: Vec<(String, Vec<String>)> = Vec::new();
    for f in &m.exports {
        let (class, name) = receiver(f);
        let ret = f.native_return.as_deref().unwrap_or("void");
        let params: Vec<String> = f
            .params
            .iter()
            .map(|p| {
                format!(
                    "{} {}",
                    p.native_type.as_deref().unwrap_or("Object"),
                    p.name
                )
            })
            .collect();
        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
        let args = if args.is_empty() {
            String::new()
        } else {
            format!(", {}", args.join(", "))
        };
        let direct = format!(
            "rustanything.{native}.call_{}({})",
            f.name,
            f.params
                .iter()
                .map(|p| p.name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        );
        let effects = api
            .functions
            .iter()
            .find(|p| p.js_name == f.name)
            .filter(|p| p.has_effects());
        let body = if let Some(port) = effects {
            // The dispatcher answers {ret, after, error, stdout}: each changed argument is written
            // back into the caller's own collection, the text goes to System.out, then the result
            // is returned or the error thrown.
            let call_args = if f.params.is_empty() {
                String::new()
            } else {
                format!(
                    ", {}",
                    f.params
                        .iter()
                        .map(|p| p.name.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            };
            let mut code = format!(
                "java.util.Map<String, Object> fx = rustanything.{native}.effects(\"{}\"{call_args});\n        \
                 java.util.List<Object> after = (java.util.List<Object>) fx.get(\"after\");\n",
                f.name
            );
            let mut n = 0;
            for (i, (_, _, mutable)) in port.visible().iter().enumerate() {
                if *mutable {
                    let p = &f.params[i];
                    let ty = boxed(p.native_type.as_deref().unwrap_or("Object"));
                    let _ = writeln!(
                        code,
                        "        rustanything.RustAnythingJson.writeBack({}, rustanything.RustAnythingJson.convert(after.get({n}), new rustanything.RustAnythingJson.TypeRef<{ty}>() {{}}.type()));",
                        p.name
                    );
                    n += 1;
                }
            }
            code.push_str(
                "        System.out.print((String) fx.get(\"stdout\"));\n        \
                 if (fx.get(\"error\") != null) {\n            throw rustanything.RustAnythingError.from(String.valueOf(fx.get(\"error\")));\n        }",
            );
            if ret != "void" {
                let _ = write!(
                    code,
                    "\n        return ({}) rustanything.RustAnythingJson.convert(fx.get(\"ret\"), new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type());",
                    boxed(ret),
                    boxed(ret)
                );
            }
            code
        } else if typed.contains(&f.name) {
            if ret == "void" {
                format!("{direct};")
            } else {
                format!("return {direct};")
            }
        } else if ret == "void" {
            format!(
                "rustanything.{native}.invoke(\"{}\", void.class{args});",
                f.name
            )
        } else {
            format!(
                "return ({}) rustanything.{native}.invoke(\"{}\", new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type(){args});",
                boxed(ret),
                f.name,
                boxed(ret)
            )
        };
        let method = format!(
            "    /** The Rust port of `{}` (`{}:{}`). */\n    @SuppressWarnings(\"unchecked\")\n    public static {ret} {name}({}) {{\n        {body}\n    }}\n",
            f.prototype.as_deref().unwrap_or(&f.name),
            f.file,
            f.line,
            params.join(", ")
        );
        match classes.iter_mut().find(|(c, _)| *c == class) {
            Some((_, methods)) => methods.push(method),
            None => classes.push((class, vec![method])),
        }
    }
    let imports = imports_of(m);
    classes
        .into_iter()
        .map(|(class, methods)| {
            let (package, simple) = class.rsplit_once('.').unwrap_or(("", class.as_str()));
            let path = if package.is_empty() {
                format!("java/{simple}.java")
            } else {
                format!("java/{}/{simple}.java", package.replace('.', "/"))
            };
            let mut out = String::new();
            if !package.is_empty() {
                let _ = writeln!(out, "package {package};\n");
            }
            out.push_str(&imports);
            let _ = write!(
                out,
                "/** The Rust port of `{simple}`, generated by rust-anything: the same static methods. */\n\
                 public final class {simple} {{\n    private {simple}() {{}}\n\n{}}}\n",
                methods.join("\n")
            );
            (path, out)
        })
        .collect()
}

/// The `java.util` imports the original signatures need.
fn imports_of(m: &Manifest) -> String {
    let mut names: Vec<&str> = Vec::new();
    for f in &m.exports {
        let types = f
            .params
            .iter()
            .filter_map(|p| p.native_type.as_deref())
            .chain(f.native_return.as_deref());
        for t in types {
            for name in [
                "List",
                "Map",
                "Optional",
                "Collection",
                "Set",
                "SortedSet",
                "NavigableSet",
                "TreeSet",
                "LinkedHashSet",
                "ArrayList",
                "LinkedList",
                "HashMap",
                "LinkedHashMap",
                "TreeMap",
                "OptionalInt",
                "OptionalLong",
                "OptionalDouble",
            ] {
                if t.split(|c: char| !c.is_alphanumeric()).any(|w| w == name)
                    && !names.contains(&name)
                {
                    names.push(name);
                }
            }
        }
    }
    names.sort_unstable();
    let mut out: String = names
        .iter()
        .map(|n| format!("import java.util.{n};\n"))
        .collect();
    if !out.is_empty() {
        out.push('\n');
    }
    out
}

/// `{ name: [class, method] }` for the driver.
pub fn targets(m: &Manifest) -> serde_json::Value {
    serde_json::Value::Object(
        m.exports
            .iter()
            .map(|f| {
                let (class, name) = receiver(f);
                (f.name.clone(), serde_json::json!([class, name]))
            })
            .collect(),
    )
}

/// `rustanything/RustAnythingDriver.java`: calls static methods by name for record, diff and bench.
pub const DRIVER_JAVA: &str = r#"package rustanything;

import java.io.BufferedWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/** Generated by rust-anything: calls the unit's static methods by name. */
public final class RustAnythingDriver {
    private RustAnythingDriver() {}

    // ART has java.nio.file from API 26 but not Java 11's Files.readString/writeString.
    private static String read(Path p) throws Exception {
        return new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
    }

    private static void write(Path p, String text) throws Exception {
        Files.write(p, text.getBytes(StandardCharsets.UTF_8));
    }

    private static void append(Path p, String text) throws Exception {
        Files.write(p, text.getBytes(StandardCharsets.UTF_8),
            java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.APPEND);
    }

    private static final Map<String, Method> METHODS = new LinkedHashMap<>();
    private static final boolean MESSAGES = Boolean.getBoolean("rust-anything.messages");

    @SuppressWarnings("unchecked")
    private static void load(String targetsPath) throws Exception {
        Map<String, Object> targets = (Map<String, Object>) RustAnythingJson.parse(read(Paths.get(targetsPath)));
        for (Map.Entry<String, Object> e : targets.entrySet()) {
            List<Object> t = (List<Object>) e.getValue();
            try {
                Class<?> c = Class.forName((String) t.get(0));
                for (Method m : c.getMethods()) {
                    if (m.getName().equals(t.get(1)) && Modifier.isStatic(m.getModifiers())) {
                        METHODS.put(e.getKey(), m);
                    }
                }
            } catch (ClassNotFoundException ex) {
                // missing: reported per case
            }
        }
    }

    /** {"ok": v} | {"error": msg, "error_type": name} | {"invalid": true} | {"missing": true}. */
    @SuppressWarnings("unchecked")
    private static Map<String, Object> call(Map<String, Object> c) {
        Map<String, Object> out = new LinkedHashMap<>();
        Method m = METHODS.get((String) c.get("fn"));
        if (m == null) {
            out.put("missing", true);
            return out;
        }
        List<Object> args = (List<Object>) c.get("args");
        Type[] types = m.getGenericParameterTypes();
        Object[] values = new Object[types.length];
        try {
            for (int i = 0; i < types.length; i++) {
                Object raw = i < args.size() ? args.get(i) : null;
                if (raw instanceof Map && ((Map<?, ?>) raw).containsKey("$undefined")) {
                    raw = null;
                }
                values[i] = RustAnythingJson.convert(raw, types[i]);
            }
        } catch (RustAnythingJson.Mismatch e) {
            out.put("invalid", true);
            return out;
        }
        // What the call does besides returning: the arguments after it and what it prints.
        String before = RustAnythingJson.write(java.util.Arrays.asList(values));
        java.io.PrintStream saved = System.out;
        java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream();
        try {
            System.setOut(new java.io.PrintStream(buffer, true, "UTF-8"));
        } catch (java.io.UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        try {
            Object result = m.invoke(null, values);
            out.put("ok", RustAnythingJson.parse(RustAnythingJson.write(result)));
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            out.put("error", RustAnythingJson.message(String.valueOf(cause.getMessage())));
            out.put("error_type", cause.getClass().getSimpleName());
        } catch (ReflectiveOperationException e) {
            out.put("error", RustAnythingJson.message(e.toString()));
            out.put("error_type", "ReflectiveOperationException");
        } catch (StackOverflowError e) {
            out.put("error", "stack overflow");
            out.put("error_type", "StackOverflowError");
        } finally {
            System.setOut(saved);
        }
        String after = RustAnythingJson.write(java.util.Arrays.asList(values));
        Map<String, Object> fx = new LinkedHashMap<>();
        if (!after.equals(before)) {
            fx.put("args_after", RustAnythingJson.parse(after));
        }
        String printed = new String(buffer.toByteArray(), StandardCharsets.UTF_8).replace(System.lineSeparator(), "\n");
        if (!printed.isEmpty()) {
            fx.put("stdout", printed);
        }
        out.put("fx", fx);
        out.put("now", RustAnythingJson.parse(after));
        return out;
    }

    @SuppressWarnings("unchecked")
    private static List<Map<String, Object>> lines(String path) throws Exception {
        List<Map<String, Object>> out = new ArrayList<>();
        for (String line : Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8)) {
            if (!line.isBlank()) {
                out.add((Map<String, Object>) RustAnythingJson.parse(line));
            }
        }
        return out;
    }

    private static boolean same(Map<String, Object> expected, Map<String, Object> got) {
        if (String.valueOf(got.get("error")).contains("Rust panic:")) {
            return false;
        }
        if (expected.containsKey("error")) {
            return got.containsKey("error") && String.valueOf(expected.get("error_type")).equals(String.valueOf(got.get("error_type")))
                && (!MESSAGES || String.valueOf(expected.get("error")).equals(String.valueOf(got.get("error"))));
        }
        return expected.containsKey("ok") && got.containsKey("ok")
            && RustAnythingJson.write(expected.get("ok")).equals(RustAnythingJson.write(got.get("ok")));
    }

    @SuppressWarnings("unchecked")
    public static void main(String[] argv) throws Exception {
        String mode = argv[0];
        load(argv[1]);
        String casesPath = argv[2];
        Path outPath = Paths.get(argv[3]);
        if (mode.equals("record")) {
            List<Object> cases = (List<Object>) RustAnythingJson.parse(read(Paths.get(casesPath)));
            String progress = System.getenv("RUST_ANYTHING_PROGRESS");
            try (BufferedWriter w = Files.newBufferedWriter(outPath, StandardCharsets.UTF_8)) {
                for (int index = 0; index < cases.size(); index++) {
                    if (progress != null) {
                        append(Paths.get(progress), index + "\n");
                    }
                    Map<String, Object> c = (Map<String, Object>) cases.get(index);
                    Map<String, Object> result = call(c);
                    if (result.containsKey("invalid") && progress != null) {
                        // The arguments do not fit the parameter types: tell `record`, which lists it.
                        append(Paths.get(progress), index + " invalid\n");
                    }
                    if (result.containsKey("invalid") || result.containsKey("missing")) {
                        continue;
                    }
                    Map<String, Object> line = new LinkedHashMap<>();
                    line.put("fn", c.get("fn"));
                    line.put("args", c.get("args"));
                    Map<String, Object> fx = (Map<String, Object>) result.remove("fx");
                    result.remove("now");
                    line.putAll(result);
                    // `post`: this line holds what the call changed and printed, so the port is
                    // compared on both.
                    line.put("post", true);
                    line.putAll(fx);
                    w.write(RustAnythingJson.write(line));
                    w.write("\n");
                    w.flush();
                }
            }
        } else if (mode.equals("diff")) {
            int total = 0, passed = 0, failed = 0, legacy = 0;
            List<Object> missing = new ArrayList<>();
            List<Object> mismatches = new ArrayList<>();
            for (Map<String, Object> c : lines(casesPath)) {
                total++;
                Map<String, Object> got = call(c);
                if (got.containsKey("missing")) {
                    failed++;
                    if (!missing.contains(c.get("fn"))) {
                        missing.add(c.get("fn"));
                    }
                    continue;
                }
                Map<String, Object> expected = new LinkedHashMap<>();
                for (String k : new String[] {"ok", "error", "error_type"}) {
                    if (c.containsKey(k)) {
                        expected.put(k, c.get(k));
                    }
                }
                Map<String, Object> fx = (Map<String, Object>) got.remove("fx");
                if (fx == null) {
                    fx = new LinkedHashMap<>();
                }
                Object now = got.remove("now");
                boolean effectsSame = true;
                if (c.containsKey("post")) {
                    for (String k : new String[] {"args_after", "stdout"}) {
                        if (c.containsKey(k)) {
                            expected.put(k, c.get(k));
                        }
                        if (fx.containsKey(k)) {
                            got.put(k, fx.get(k));
                        }
                        if (!RustAnythingJson.write(c.get(k)).equals(RustAnythingJson.write(fx.get(k)))) {
                            effectsSame = false;
                        }
                    }
                    // A mismatch shows the arguments after the call, changed or not.
                    if (expected.containsKey("args_after") && !got.containsKey("args_after")) {
                        got.put("args_after", now);
                    }
                    if (expected.containsKey("stdout") && !got.containsKey("stdout")) {
                        got.put("stdout", "");
                    }
                } else {
                    legacy++;
                }
                if (effectsSame && same(expected, got)) {
                    passed++;
                } else {
                    failed++;
                    Map<String, Object> m = new LinkedHashMap<>();
                    m.put("fn", c.get("fn"));
                    m.put("args", c.get("args"));
                    m.put("expected", expected);
                    m.put("actual", got);
                    mismatches.add(m);
                }
            }
            Map<String, Object> summary = new LinkedHashMap<>();
            summary.put("total", total);
            summary.put("passed", passed);
            summary.put("failed", failed);
            summary.put("missing", missing);
            summary.put("mismatches", mismatches);
            summary.put("legacy_cases", legacy);
            write(outPath, RustAnythingJson.write(summary));
        } else if (mode.equals("bench")) {
            long minMs = Long.parseLong(argv[4]);
            Map<String, List<Map<String, Object>>> groups = new LinkedHashMap<>();
            for (Map<String, Object> c : lines(casesPath)) {
                groups.computeIfAbsent((String) c.get("fn"), k -> new ArrayList<>()).add(c);
            }
            Map<String, Object> result = new LinkedHashMap<>();
            for (Map.Entry<String, List<Map<String, Object>>> g : groups.entrySet()) {
                List<Map<String, Object>> cases = g.getValue();
                // Arguments are converted once: only the calls are timed.
                Method m = METHODS.get(g.getKey());
                if (m == null) {
                    continue;
                }
                Type[] types = m.getGenericParameterTypes();
                List<Object[]> prepared = new ArrayList<>();
                for (Map<String, Object> c : cases) {
                    List<Object> args = (List<Object>) c.get("args");
                    Object[] values = new Object[types.length];
                    try {
                        for (int i = 0; i < types.length; i++) {
                            Object raw = i < args.size() ? args.get(i) : null;
                            if (raw instanceof Map && ((Map<?, ?>) raw).containsKey("$undefined")) {
                                raw = null;
                            }
                            values[i] = RustAnythingJson.convert(raw, types[i]);
                        }
                        prepared.add(values);
                    } catch (RustAnythingJson.Mismatch e) {
                        // not a valid call
                    }
                }
                if (prepared.isEmpty()) {
                    continue;
                }
                Runnable pass = () -> {
                    for (Object[] values : prepared) {
                        try {
                            m.invoke(null, values);
                        } catch (ReflectiveOperationException | RuntimeException e) {
                            // errors count as calls
                        }
                    }
                };
                // Warm up the JIT before timing.
                long warm = System.nanoTime();
                while (System.nanoTime() - warm < minMs * 1_000_000L / 2) {
                    pass.run();
                }
                long passes = 0;
                long start = System.nanoTime();
                while (true) {
                    pass.run();
                    passes++;
                    long elapsed = System.nanoTime() - start;
                    if (elapsed / 1_000_000 >= minMs) {
                        Map<String, Object> row = new LinkedHashMap<>();
                        row.put("cases", prepared.size());
                        row.put("ns", (double) elapsed / (passes * prepared.size()));
                        result.put(g.getKey(), row);
                        break;
                    }
                }
            }
            write(outPath, RustAnythingJson.write(result));
        }
    }
}
"#;

/// Shadow classes, `<Class>Shadow` beside each original class: the same static methods,
/// running the original and the Rust port, returning the original's result and counting
/// mismatches. `-Drust-anything.mode=old` runs the original only, `new` the port only.
pub fn shadows(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<(String, String)> {
    let typed = direct_names(m, api);
    let native = java_native_class(m);
    let mut classes: Vec<(String, Vec<String>)> = Vec::new();
    for f in &m.exports {
        let (class, name) = receiver(f);
        let simple = class.rsplit('.').next().unwrap_or(&class).to_string();
        let ret = f.native_return.as_deref().unwrap_or("void");
        let params: Vec<String> = f
            .params
            .iter()
            .map(|p| {
                format!(
                    "{} {}",
                    p.native_type.as_deref().unwrap_or("Object"),
                    p.name
                )
            })
            .collect();
        let names: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
        let call_args = names.join(", ");
        let native_args = if names.is_empty() {
            String::new()
        } else {
            format!(", {call_args}")
        };
        let type_ref = if ret == "void" {
            "void.class".to_string()
        } else {
            format!(
                "new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type()",
                boxed(ret)
            )
        };
        if let Some(effects) = api
            .functions
            .iter()
            .find(|p| p.js_name == f.name)
            .filter(|p| p.has_effects())
        {
            // Rust runs on copies taken before the original runs, with its output held back, and
            // both are compared on the result and the arguments after the call.
            let changed: Vec<usize> = effects
                .visible()
                .iter()
                .enumerate()
                .filter(|(_, (_, _, m))| *m)
                .map(|(i, _)| i)
                .collect();
            let copy_of = |i: usize| {
                let p = &f.params[i];
                let ty = boxed(p.native_type.as_deref().unwrap_or("Object"));
                format!(
                    "({ty}) rustanything.RustAnythingJson.convert(rustanything.RustAnythingJson.parse(rustanything.RustAnythingJson.write({})), new rustanything.RustAnythingJson.TypeRef<{ty}>() {{}}.type())",
                    p.name
                )
            };
            let mut copies = String::new();
            let mut port_args: Vec<String> = f.params.iter().map(|p| p.name.clone()).collect();
            for i in &changed {
                let _ = writeln!(
                    copies,
                    "        {} copy{i} = {};",
                    boxed(f.params[*i].native_type.as_deref().unwrap_or("Object")),
                    copy_of(*i)
                );
                port_args[*i] = format!("copy{i}");
            }
            let port_call_args = if port_args.is_empty() {
                String::new()
            } else {
                format!(", {}", port_args.join(", "))
            };
            let mut write_back = String::new();
            for (n, i) in changed.iter().enumerate() {
                let _ = writeln!(
                    write_back,
                    "                rustanything.RustAnythingJson.writeBack(copy{i}, rustanything.RustAnythingJson.convert(after.get({n}), new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type()));",
                    boxed(f.params[*i].native_type.as_deref().unwrap_or("Object"))
                );
            }
            let want: Vec<String> = std::iter::once("expected".to_string())
                .chain(changed.iter().map(|i| f.params[*i].name.clone()))
                .collect();
            let got: Vec<String> = std::iter::once("actual".to_string())
                .chain(changed.iter().map(|i| format!("copy{i}")))
                .collect();
            let ret_value = if ret == "void" {
                "null".to_string()
            } else {
                format!(
                    "rustanything.RustAnythingJson.convert(fx.get(\"ret\"), new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type())",
                    boxed(ret)
                )
            };
            let (decl, expect, give) = if ret == "void" {
                (
                    "",
                    "        Object expected = null;\n        {simple}.{name}({call_args});\n",
                    "return;",
                )
            } else {
                (
                    "",
                    "        {ret} expected = {simple}.{name}({call_args});\n",
                    "return expected;",
                )
            };
            let _ = decl;
            let expect = expect
                .replace("{simple}", &simple)
                .replace("{name}", &name)
                .replace("{call_args}", &call_args)
                .replace("{ret}", ret);
            let new_mode = {
                let mut code = format!(
                    "            java.util.Map<String, Object> fx = rustanything.{native}.effects(\"{}\"{native_args});\n            java.util.List<Object> after = (java.util.List<Object>) fx.get(\"after\");\n",
                    f.name
                );
                for (n, i) in changed.iter().enumerate() {
                    let _ = writeln!(
                        code,
                        "            rustanything.RustAnythingJson.writeBack({}, rustanything.RustAnythingJson.convert(after.get({n}), new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type()));",
                        f.params[*i].name,
                        boxed(f.params[*i].native_type.as_deref().unwrap_or("Object"))
                    );
                }
                code.push_str("            System.out.print((String) fx.get(\"stdout\"));\n            if (fx.get(\"error\") != null) {\n                throw rustanything.RustAnythingError.from(String.valueOf(fx.get(\"error\")));\n            }\n");
                if ret == "void" {
                    code.push_str("            return;\n");
                } else {
                    let _ = writeln!(code, "            return ({}) {ret_value};", boxed(ret));
                }
                code
            };
            let method = format!(
                "    @SuppressWarnings(\"unchecked\")\n    public static {ret} {name}({params}) {{\n        if (MODE.equals(\"new\")) {{\n{new_mode}        }}\n{copies}{expect}\
                 \x20       if (!MODE.equals(\"old\")) {{\n            Object actual;\n            try {{\n                java.util.Map<String, Object> fx = rustanything.{native}.effects(\"{}\"{port_call_args});\n\
                 \x20               java.util.List<Object> after = (java.util.List<Object>) fx.get(\"after\");\n{write_back}\
                 \x20               actual = fx.get(\"error\") != null ? new RuntimeException(String.valueOf(fx.get(\"error\"))) : {ret_value};\n            }} catch (RuntimeException e) {{\n                actual = e;\n            }}\n\
                 \x20           if (actual instanceof Throwable) {{\n                compare(\"{name}\", expected, actual);\n            }} else {{\n                compare(\"{name}\", java.util.Arrays.<Object>asList({}), java.util.Arrays.<Object>asList({}));\n            }}\n        }}\n        {give}\n    }}\n",
                f.name,
                want.join(", "),
                got.join(", "),
                params = params.join(", "),
            );
            match classes.iter_mut().find(|(c, _)| *c == class) {
                Some((_, methods)) => methods.push(method),
                None => classes.push((class, vec![method])),
            }
            continue;
        }
        let port = if typed.contains(&f.name) {
            format!("rustanything.{native}.call_{}({call_args})", f.name)
        } else {
            format!(
                "rustanything.{native}.invoke(\"{}\", {type_ref}{native_args})",
                f.name
            )
        };
        let method = if ret == "void" {
            format!(
                "    @SuppressWarnings(\"unchecked\")\n    public static void {name}({params}) {{\n        if (MODE.equals(\"new\")) {{\n            {port};\n            return;\n        }}\n\
                 \x20       {simple}.{name}({call_args});\n        if (!MODE.equals(\"old\")) {{\n            try {{\n                {port};\n                compare(\"{name}\", null, null);\n\
                 \x20           }} catch (RuntimeException e) {{\n                compare(\"{name}\", null, e);\n            }}\n        }}\n    }}\n",
                params = params.join(", "),
            )
        } else {
            format!(
                "    @SuppressWarnings(\"unchecked\")\n    public static {ret} {name}({params}) {{\n        if (MODE.equals(\"new\")) {{\n            return ({b}) {port};\n        }}\n\
                 \x20       {ret} expected = {simple}.{name}({call_args});\n        if (!MODE.equals(\"old\")) {{\n            Object actual;\n            try {{\n                actual = {port};\n\
                 \x20           }} catch (RuntimeException e) {{\n                actual = e;\n            }}\n            compare(\"{name}\", expected, actual);\n        }}\n        return expected;\n    }}\n",
                params = params.join(", "),
                b = boxed(ret),
            )
        };
        match classes.iter_mut().find(|(c, _)| *c == class) {
            Some((_, methods)) => methods.push(method),
            None => classes.push((class, vec![method])),
        }
    }
    let imports = imports_of(m);
    classes
        .into_iter()
        .map(|(class, methods)| {
            let (package, simple) = class.rsplit_once('.').unwrap_or(("", class.as_str()));
            let path = if package.is_empty() {
                format!("shadow/{simple}Shadow.java")
            } else {
                format!("shadow/{}/{simple}Shadow.java", package.replace('.', "/"))
            };
            let mut out = String::new();
            if !package.is_empty() {
                let _ = writeln!(out, "package {package};\n");
            }
            out.push_str("import java.util.concurrent.atomic.AtomicLong;\n");
            out.push_str(&imports.replace("\n\n", "\n"));
            let _ = write!(
                out,
                "\n/** Runs `{simple}` and its Rust port side by side. Generated by rust-anything: call it in place of `{simple}`. */\n\
                 public final class {simple}Shadow {{\n    private {simple}Shadow() {{}}\n\n\
                 \x20   private static final String MODE = System.getProperty(\"rust-anything.mode\", \"shadow\");\n\
                 \x20   public static final AtomicLong CALLS = new AtomicLong();\n    public static final AtomicLong MISMATCHES = new AtomicLong();\n\n\
                 \x20   private static void compare(String name, Object expected, Object actual) {{\n        CALLS.incrementAndGet();\n\
                 \x20       if (actual instanceof Throwable || !rustanything.RustAnythingJson.write(expected).equals(rustanything.RustAnythingJson.write(actual))) {{\n\
                 \x20           if (MISMATCHES.incrementAndGet() <= 10) {{\n                System.err.println(\"[rust-anything] mismatch in \" + name + \": expected \" + expected + \", got \" + actual);\n            }}\n        }}\n    }}\n\n{}}}\n",
                methods.join("\n")
            );
            (path, out)
        })
        .collect()
}

/// A Java type that crosses JNI without JSON: the JNI type, the port type it must match, how
/// the argument becomes the port's value, how the port's result becomes the JNI value, and the
/// value returned while an exception is pending.
struct Jni {
    jni: &'static str,
    port: &'static str,
    arg: fn(&str) -> String,
    out: &'static str,
    default: &'static str,
}

fn jni(java: &str) -> Option<Jni> {
    let int = |jni, out| Jni {
        jni,
        port: "i64",
        arg: |n| format!("i64::from({n})"),
        out,
        default: "0",
    };
    Some(match java.trim() {
        "int" => int("jni::sys::jint", "out as jni::sys::jint"),
        "short" => int("jni::sys::jshort", "out as jni::sys::jshort"),
        "byte" => int("jni::sys::jbyte", "out as jni::sys::jbyte"),
        "long" => Jni {
            jni: "jni::sys::jlong",
            port: "i64",
            arg: |n| n.to_string(),
            out: "out",
            default: "0",
        },
        "double" => Jni {
            jni: "jni::sys::jdouble",
            port: "f64",
            arg: |n| n.to_string(),
            out: "out",
            default: "0.0",
        },
        "float" => Jni {
            jni: "jni::sys::jfloat",
            port: "f64",
            arg: |n| format!("f64::from({n})"),
            out: "out as jni::sys::jfloat",
            default: "0.0",
        },
        "boolean" => Jni {
            jni: "jni::sys::jboolean",
            port: "bool",
            arg: |n| format!("{n} != 0"),
            out: "jni::sys::jboolean::from(out)",
            default: "0",
        },
        "String" => Jni {
            jni: "jni::objects::JString<'local>",
            port: "String",
            arg: |n| n.to_string(),
            out: "java_string(&mut env, &out)",
            default: "std::ptr::null_mut()",
        },
        _ => return None,
    })
}

/// Whether a function crosses as a typed JNI method: every parameter and the result are
/// primitives or `String`, and the port kept the matching Rust types.
fn typed<'m>(
    m: &'m Manifest,
    f: &crate::codegen::PortFn,
) -> Option<&'m crate::ts::exports::ExportedFn> {
    if f.has_effects() {
        return None;
    }
    let e = m.exports.iter().find(|e| e.name == f.js_name)?;
    if e.params.len() != f.params.len() {
        return None;
    }
    for (p, (_, port_ty)) in e.params.iter().zip(&f.params) {
        if jni(p.native_type.as_deref()?)?.port != port_ty {
            return None;
        }
    }
    match e.native_return.as_deref()? {
        "void" => (f.ret == "()").then_some(e),
        r => (jni(r)?.port == f.ret).then_some(e),
    }
}

/// Escape one component of a JNI symbol. Non-ASCII characters are encoded one UTF-16 unit at a time.
pub(crate) fn mangle_jni_component(s: &str) -> String {
    let mut out = String::new();
    for unit in s.encode_utf16() {
        match unit {
            0x30..=0x39 | 0x41..=0x5a | 0x61..=0x7a => out.push(char::from(unit as u8)),
            0x5f => out.push_str("_1"),
            _ => {
                let _ = write!(out, "_0{unit:04x}");
            }
        }
    }
    out
}

/// Typed JNI functions for `lib.rs`, appended after the JSON dispatcher.
pub fn typed_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
    let class = java_native_class(m);
    let mut out = String::from(
        r#"
/// `rustanything.RustAnythingError` and its `(String, String)` constructor, resolved once per process.
type Exception = (jni::objects::GlobalRef, jni::objects::JMethodID);
static RUST_ANYTHING_ERROR: std::sync::OnceLock<Option<Exception>> = std::sync::OnceLock::new();

fn rust_anything_error(env: &mut jni::JNIEnv) -> Option<Exception> {
    RUST_ANYTHING_ERROR
        .get_or_init(|| {
            let class = env.find_class("rustanything/RustAnythingError").ok()?;
            let ctor = env
                .get_method_id(&class, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V")
                .ok()?;
            Some((env.new_global_ref(class).ok()?, ctor))
        })
        .clone()
}

/// Splits `"Type: message"`; anything else is a RuntimeException with the whole message.
fn split_error(message: &str) -> (&str, &str) {
    message
        .split_once(": ")
        .filter(|(k, _)| {
            k.starts_with(|c: char| c.is_ascii_alphabetic())
                && k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '$'))
        })
        .unwrap_or(("RuntimeException", message))
}

#[allow(dead_code)]
/// Hands an error back through the caller's `String[2]` slot: type and message. The Java side
/// throws it, which is much cheaper than an exception raised from native code.
fn report(env: &mut jni::JNIEnv, slot: &jni::objects::JObjectArray, message: &str) {
    let (kind, text) = split_error(message);
    let Ok(kind) = env.new_string(kind) else {
        return;
    };
    let Ok(text) = env.new_string(text) else {
        return;
    };
    if env.set_object_array_element(slot, 0, &kind).is_err() {
        return;
    }
    let _ = env.set_object_array_element(slot, 1, &text);
}

#[allow(dead_code)]
/// Throws `"Type: message"` as a `RustAnythingError` without a stack trace, which is cheap from
/// native code; the generated Java turns it into a `Type` exception, built in Java.
fn throw(env: &mut jni::JNIEnv, message: &str) {
    let (kind, text) = split_error(message);
    let Some((class, ctor)) = rust_anything_error(env) else {
        let _ = env.exception_clear();
        let _ = env.throw_new("java/lang/RuntimeException", message);
        return;
    };
    let Ok(kind) = env.new_string(kind) else {
        return;
    };
    let Ok(text) = env.new_string(text) else {
        return;
    };
    let class: &jni::objects::JClass = class.as_obj().into();
    let args = [
        jni::objects::JValue::Object(&kind).as_jni(),
        jni::objects::JValue::Object(&text).as_jni(),
    ];
    // SAFETY: `ctor` is the `(String, String)` constructor of `class`, looked up together, and
    // both arguments are Strings.
    if let Ok(object) = unsafe { env.new_object_unchecked(class, ctor, &args) } {
        let _ = env.throw(jni::objects::JThrowable::from(object));
    }
}

/// Runs the port; a panic becomes an error instead of unwinding into the JVM.
#[allow(dead_code)]
fn run<T>(f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|panic| {
        let text = panic
            .downcast_ref::<&str>()
            .map(ToString::to_string)
            .or_else(|| panic.downcast_ref::<String>().cloned())
            .unwrap_or_default();
        Err(format!("RuntimeException: Rust panic: {text}"))
    })
}

/// A `String` argument; `None` (with a NullPointerException thrown) for null.
#[allow(dead_code)]
fn string_arg(env: &mut jni::JNIEnv, s: &jni::objects::JString) -> Option<String> {
    if s.is_null() {
        let _ = env.throw_new("java/lang/NullPointerException", "null String argument");
        return None;
    }
    let raw = env.get_raw();
    let mut stack = [0u16; 128];
    // SAFETY: `raw` is this thread's JNIEnv and `s` a live, non-null String reference; the JVM
    // fills every entry of the function table.
    let len = unsafe { ((**raw).GetStringLength?)(raw, s.as_raw()) };
    if len < 0 || env.exception_check().unwrap_or(true) {
        return None;
    }
    let n = usize::try_from(len).ok()?;
    let mut heap = Vec::new();
    let units: &mut [u16] = if n <= stack.len() {
        &mut stack[..n]
    } else {
        heap.resize(n, 0);
        &mut heap
    };
    // SAFETY: as above; `units` holds exactly `len` UTF-16 code units.
    unsafe { ((**raw).GetStringRegion?)(raw, s.as_raw(), 0, len, units.as_mut_ptr()) };
    if env.exception_check().unwrap_or(true) {
        return None;
    }
    // UTF-16 straight from the String: no modified UTF-8 in between.
    Some(String::from_utf16_lossy(units))
}

/// A Java String from Rust text, built from UTF-16 (`NewString`), not modified UTF-8.
#[allow(dead_code)]
fn java_string(env: &mut jni::JNIEnv, text: &str) -> jni::sys::jstring {
    let mut stack = [0u16; 128];
    let mut heap = Vec::new();
    let units: &[u16] = if text.len() <= stack.len() {
        let mut n = 0;
        for u in text.encode_utf16() {
            stack[n] = u;
            n += 1;
        }
        &stack[..n]
    } else {
        heap.extend(text.encode_utf16());
        &heap
    };
    let Ok(len) = jni::sys::jsize::try_from(units.len()) else {
        return std::ptr::null_mut();
    };
    let raw = env.get_raw();
    // SAFETY: `raw` is this thread's JNIEnv, valid for the call.
    let Some(new_string) = (unsafe { (**raw).NewString }) else {
        return std::ptr::null_mut();
    };
    // SAFETY: `units` holds `len` UTF-16 code units, read during the call only.
    unsafe { new_string(raw, units.as_ptr(), len) }
}
"#,
    );
    for f in &api.functions {
        let Some(e) = typed(m, f) else { continue };
        let ret_java = e.native_return.as_deref().unwrap_or("void");
        let ret = if ret_java == "void" {
            None
        } else {
            jni(ret_java)
        };
        let mut params = vec![
            "mut env: jni::JNIEnv<'local>".to_string(),
            "_class: jni::objects::JClass<'local>".to_string(),
        ];
        let mut prelude = String::new();
        let mut args = Vec::new();
        let default = ret.as_ref().map_or("", |r| r.default);
        for (p, (name, _)) in e.params.iter().zip(&f.params) {
            let t = jni(p.native_type.as_deref().unwrap_or_default()).expect("typed");
            params.push(format!("{name}: {}", t.jni));
            if t.port == "String" {
                let _ = writeln!(
                    prelude,
                    "    let Some({name}) = string_arg(&mut env, &{name}) else {{\n        return {default};\n    }};"
                );
                args.push(name.clone());
            } else {
                args.push((t.arg)(name));
            }
        }
        params.push("slot: jni::objects::JObjectArray<'local>".to_string());
        let call = format!("port::{}({})", f.rust_name, args.join(", "));
        let run_call = if args.is_empty() && f.fallible {
            format!("run(port::{})", f.rust_name)
        } else if f.fallible {
            format!("run(|| {call})")
        } else {
            format!("run(|| Ok({call}))")
        };
        let (ret_ty, ok) = match &ret {
            Some(r) => (
                format!(
                    " -> {}",
                    r.jni
                        .replace("JString<'local>", "jstring")
                        .replace("jni::objects::jstring", "jni::sys::jstring")
                ),
                r.out.to_string(),
            ),
            None => (String::new(), "()".to_string()),
        };
        let _ = writeln!(
            out,
            "\n/// `{proto}`: typed, no JSON.\n// SAFETY: the JNI symbol of `rustanything.{class}.n_{js}`; nothing else defines it.\n\
             #[unsafe(no_mangle)]\npub extern \"system\" fn Java_rustanything_{mclass}_n_1{mjs}<'local>({params}){ret_ty} {{\n\
             {prelude}    match {run_call} {{\n        Ok(out) => {ok},\n        Err(message) => {{\n            \
             report(&mut env, &slot, &message);\n            {default}\n        }}\n    }}\n}}",
            proto = e.prototype.as_deref().unwrap_or(&e.name),
            js = f.js_name,
            mclass = mangle_jni_component(&class),
            mjs = mangle_jni_component(&f.js_name),
            params = params.join(", "),
        );
    }
    out
}

/// The exports that cross as typed JNI methods.
fn typed_names(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<String> {
    api.functions
        .iter()
        .filter(|f| typed(m, f).is_some())
        .map(|f| f.js_name.clone())
        .collect()
}

/// The `static native` declarations of the typed methods.
fn typed_declarations(m: &Manifest, api: &crate::codegen::PortApi) -> String {
    let mut out = String::new();
    for f in &api.functions {
        let Some(e) = typed(m, f) else { continue };
        let params: Vec<String> = e
            .params
            .iter()
            .map(|p| {
                format!(
                    "{} {}",
                    p.native_type.as_deref().unwrap_or("Object"),
                    p.name
                )
            })
            .collect();
        let mut params = params;
        params.push("String[] slot".into());
        let _ = writeln!(
            out,
            "    public static native {} n_{}({});",
            e.native_return.as_deref().unwrap_or("void"),
            f.js_name,
            params.join(", ")
        );
    }
    out
}

// ---- the binary wire: lists, arrays, maps, boxed and optional values, without JSON ----------

use crate::wire::Ty;

fn split_generic(t: &str) -> Option<(&str, Vec<String>)> {
    let i = t.find('<')?;
    let inner = t.strip_suffix('>')?.get(i + 1..)?;
    let mut args = Vec::new();
    let mut depth = 0;
    let mut cur = String::new();
    for c in inner.chars() {
        match c {
            '<' => depth += 1,
            '>' => depth -= 1,
            ',' if depth == 0 => {
                args.push(cur.trim().to_string());
                cur.clear();
                continue;
            }
            _ => {}
        }
        cur.push(c);
    }
    args.push(cur.trim().to_string());
    Some((t[..i].trim(), args))
}

/// The wire type of a Java type (return position); `None` for types the wire does not carry.
fn java_ty(t: &str) -> Option<Ty> {
    java_ty_inner(t, false)
}

/// The wire type of a Java parameter type: covariant `? extends T` wildcards unwrap to `T`.
fn java_ty_param(t: &str) -> Option<Ty> {
    java_ty_inner(t, true)
}

fn java_ty_inner(t: &str, in_param: bool) -> Option<Ty> {
    let t = t.trim();
    if let Some(rest) = t.strip_prefix('?') {
        if !in_param {
            return None;
        }
        let rest = rest.trim();
        let after = rest.strip_prefix("extends")?;
        if !after.starts_with(char::is_whitespace) {
            return None;
        }
        let bound = after.trim();
        if bound.is_empty() || bound.contains('&') {
            return None;
        }
        return java_ty_inner(bound, true);
    }
    let boxed = |inner: Ty| Ty::Opt {
        inner: Box::new(inner),
        native: t.to_string(),
    };
    Some(match t {
        "int" | "long" | "short" | "byte" => Ty::I64(t.into()),
        "double" | "float" => Ty::F64(t.into()),
        "boolean" => Ty::Bool,
        "String" => Ty::Str,
        // `Reader` decodes `String` (`List<String>`, `Map<String, T>`), which is not assignable
        // to invariant `List<CharSequence>` / `Map<CharSequence, T>` in return position.
        "CharSequence" if in_param => Ty::Str,
        "Integer" => boxed(Ty::I64("int".into())),
        "Long" => boxed(Ty::I64("long".into())),
        "Short" => boxed(Ty::I64("short".into())),
        "Byte" => boxed(Ty::I64("byte".into())),
        "Double" => boxed(Ty::F64("double".into())),
        "Float" => boxed(Ty::F64("float".into())),
        "Boolean" => boxed(Ty::Bool),
        _ => {
            if let Some(item) = t.strip_suffix("[]") {
                let item_ty = java_ty_inner(item, in_param)?;
                // Primitive arrays need a helper; reference arrays use a generic one.
                if matches!(item_ty, Ty::I64(_) | Ty::F64(_) | Ty::Bool)
                    && !matches!(item.trim(), "int" | "long" | "double" | "boolean")
                {
                    return None;
                }
                return Some(Ty::List {
                    item: Box::new(item_ty),
                    native: t.into(),
                    array: true,
                });
            }
            let (head, args) = split_generic(t)?;
            match head.rsplit('.').next().unwrap_or(head) {
                "List" | "ArrayList" | "Collection" | "Iterable" | "LinkedList" | "SortedSet"
                | "NavigableSet" | "TreeSet" | "LinkedHashSet" => Ty::List {
                    item: Box::new(java_ty_inner(args.first()?, in_param)?),
                    native: t.into(),
                    array: false,
                },
                "Map" | "LinkedHashMap" | "HashMap" | "TreeMap"
                    if java_ty_inner(args.first()?, in_param) == Some(Ty::Str) =>
                {
                    Ty::Map {
                        value: Box::new(java_ty_inner(args.get(1)?, in_param)?),
                        native: t.into(),
                    }
                }
                "Optional" => Ty::Opt {
                    inner: Box::new(java_ty_inner(args.first()?, in_param)?),
                    native: t.into(),
                },
                _ => return None,
            }
        }
    })
}

/// Java statements writing `expr` of type `t` to writer `w`.
fn java_enc(expr: &str, t: &Ty, depth: usize) -> String {
    let d = depth;
    match t {
        Ty::I64(_) => format!("w.i64({expr});"),
        Ty::F64(_) => format!("w.f64({expr});"),
        Ty::Bool => format!("w.bool({expr});"),
        Ty::Str => format!("w.str({expr});"),
        Ty::Opt { inner, native } if native.starts_with("Optional") => format!(
            "{{ var o{d} = {expr}; if (o{d} == null || o{d}.isEmpty()) {{ w.tag(0); }} else {{ w.tag(1); {} }} }}",
            java_enc(&format!("o{d}.get()"), inner, d + 1)
        ),
        Ty::Opt { inner, .. } => format!(
            "{{ var o{d} = {expr}; if (o{d} == null) {{ w.tag(0); }} else {{ w.tag(1); {} }} }}",
            java_enc(&format!("o{d}"), inner, d + 1)
        ),
        Ty::List { item, array, .. } => format!(
            "{{ 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}) {{ {} }} }} }}",
            if *array { "length" } else { "size()" },
            java_enc(&format!("v{d}"), item, d + 1)
        ),
        Ty::Map { value, .. } => format!(
            "{{ 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()); {} }} }} }}",
            java_enc(&format!("e{d}.getValue()"), value, d + 1)
        ),
        _ => String::new(),
    }
}

/// Picks a Java identifier not in `used` and records it in `used`.
fn fresh_java_var(prefix: &str, used: &mut BTreeSet<String>) -> String {
    let mut i = 0usize;
    loop {
        let candidate = format!("{prefix}{i}");
        if used.insert(candidate.clone()) {
            return candidate;
        }
        i += 1;
    }
}

/// A Java `IntFunction<T[]>` allocating an array of `elem`. Uses a raw-erased allocation when
/// `elem` is parameterized (`TreeSet<String>`), since Java rejects generic array creation.
fn java_array_ctor(elem: &str, used: &mut BTreeSet<String>) -> String {
    if !elem.contains('<') {
        return format!("{elem}[]::new");
    }
    let mut base = elem;
    let mut dims = String::new();
    while let Some(rest) = base.strip_suffix("[]") {
        base = rest.trim();
        dims.push_str("[]");
    }
    let raw = base.split('<').next().unwrap_or(base).trim();
    let len_var = fresh_java_var("_raLen", used);
    format!("{len_var} -> ({elem}[]) new {raw}[{len_var}]{dims}")
}

/// A Java expression reading a value of type `t` from reader `r`.
fn java_dec(t: &Ty, used: &mut BTreeSet<String>) -> Option<String> {
    Some(match t {
        Ty::I64(n) => match n.as_str() {
            "long" => "r.i64()".into(),
            other => format!("(({other}) r.i64())"),
        },
        Ty::F64(n) => match n.as_str() {
            "float" => "((float) r.f64())".into(),
            _ => "r.f64()".into(),
        },
        Ty::Bool => "r.bool()".into(),
        Ty::Str => "r.str()".into(),
        Ty::Opt { inner, native } if native.starts_with("Optional") => {
            let arg = split_generic(native)?.1.first()?.clone();
            format!(
                "(r.tag() == 0 ? java.util.Optional.<{arg}>empty() : java.util.Optional.of({}))",
                java_dec(inner, used)?
            )
        }
        Ty::Opt { inner, native } => {
            format!(
                "(r.tag() == 0 ? null : ({native}) {})",
                java_dec(inner, used)?
            )
        }
        Ty::List {
            item,
            native,
            array: true,
        } => {
            let elem = native.strip_suffix("[]").unwrap_or(native).trim();
            match elem {
                "int" => "r.ints()".into(),
                "long" => "r.longs()".into(),
                "double" => "r.doubles()".into(),
                "boolean" => "r.booleans()".into(),
                _ => {
                    let ctor = java_array_ctor(elem, used);
                    format!("r.array(() -> {}, {ctor})", java_dec(item, used)?)
                }
            }
        }
        Ty::List { item, native, .. } => {
            let head = split_generic(native)
                .map(|(h, _)| h.rsplit('.').next().unwrap_or(h))
                .unwrap_or("");
            let method = match head {
                "SortedSet" | "NavigableSet" | "TreeSet" => "treeSet",
                "LinkedHashSet" => "linkedHashSet",
                _ => "list",
            };
            format!("r.{method}(() -> {})", java_dec(item, used)?)
        }
        Ty::Map { value, .. } => format!("r.map(() -> {})", java_dec(value, used)?),
        _ => return None,
    })
}

/// `rustanything/RustAnythingError.java`: the error the Rust side throws, turned into the real
/// exception type in Java.
pub const ERROR_JAVA: &str = r#"package rustanything;

import java.lang.reflect.Constructor;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/** Generated by rust-anything: a port's error, thrown from Rust without a stack trace (cheap from native code). */
public final class RustAnythingError extends RuntimeException {
    private static final long serialVersionUID = 1L;
    private static final String[] PREFIXES = {
        "", "java.lang.", "java.util.", "java.io.", "java.time.", "java.util.concurrent."
    };
    private static final ConcurrentHashMap<String, Optional<Constructor<? extends RuntimeException>>> CONSTRUCTORS = new ConcurrentHashMap<>();

    public final String type;

    public RustAnythingError(String type, String message) {
        super(message, null, false, false);
        this.type = type;
    }

    // Plain reflection, not MethodHandle: Android only supports MethodHandle.invokeExact from
    // API 26, and these libraries run on older phones too.
    private static Optional<Constructor<? extends RuntimeException>> constructor(String type) {
        for (String prefix : PREFIXES) {
            try {
                Class<?> c = Class.forName(prefix + type);
                if (RuntimeException.class.isAssignableFrom(c)) {
                    @SuppressWarnings("unchecked")
                    Constructor<? extends RuntimeException> ctor =
                        (Constructor<? extends RuntimeException>) c.getConstructor(String.class);
                    return Optional.of(ctor);
                }
            } catch (ReflectiveOperationException | IllegalArgumentException | LinkageError e) {
                // try the next package
            }
        }
        return Optional.empty();
    }

    /** Turns {@code "Type: message"} into that RuntimeException; anything else a RuntimeException. */
    public static RuntimeException from(String message) {
        if (message != null) {
            int colon = message.indexOf(": ");
            if (colon > 0 && isTypeName(message, colon)) {
                return make(message.substring(0, colon), message.substring(colon + 2));
            }
        }
        return new RuntimeException(message);
    }

    private static boolean isTypeName(String s, int end) {
        char first = s.charAt(0);
        if (!((first >= 'A' && first <= 'Z') || (first >= 'a' && first <= 'z'))) {
            return false;
        }
        for (int i = 1; i < end; i++) {
            char c = s.charAt(i);
            boolean ok = (c >= 'A' && c <= 'Z')
                || (c >= 'a' && c <= 'z')
                || (c >= '0' && c <= '9')
                || c == '.'
                || c == '_'
                || c == '$';
            if (!ok) {
                return false;
            }
        }
        return true;
    }

    /** The exception the original throws: `type` with the message, else a RuntimeException. */
    public RuntimeException real() {
        return make(type, getMessage());
    }

    private static final ThreadLocal<String[]> SLOTS = ThreadLocal.withInitial(() -> new String[2]);

    /** This thread's error slot: the Rust side writes a failed call's type and message there. */
    public static String[] slot() {
        return SLOTS.get();
    }

    /** Throws the error a call left in `slot`, if any. */
    public static void check(String[] slot) {
        if (slot[0] != null) {
            String type = slot[0];
            String message = slot[1];
            slot[0] = null;
            slot[1] = null;
            throw make(type, message);
        }
    }

    private static RuntimeException make(String type, String message) {
        Optional<Constructor<? extends RuntimeException>> ctor = CONSTRUCTORS.computeIfAbsent(type, RustAnythingError::constructor);
        if (ctor.isPresent()) {
            try {
                return ctor.get().newInstance(message);
            } catch (ReflectiveOperationException | LinkageError | SecurityException e) {
                // fall through
            }
        }
        return new RuntimeException(type + ": " + message);
    }
}
"#;

/// `rustanything/RustAnythingWire.java`: the Java half of the binary wire.
pub const WIRE_JAVA: &str = r#"package rustanything;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.IntFunction;
import java.util.function.Supplier;

/** Generated by rust-anything: the binary wire to the Rust port. Little endian; nullable values start with 0 for null. */
public final class RustAnythingWire {
    private RustAnythingWire() {}

    public static final class Writer {
        private byte[] buf = new byte[64];
        private int n;

        private void ensure(int more) {
            if (n + more > buf.length) {
                buf = java.util.Arrays.copyOf(buf, Math.max(buf.length * 2, n + more));
            }
        }

        public void tag(int t) {
            ensure(1);
            buf[n++] = (byte) t;
        }

        public void len(int v) {
            ensure(4);
            for (int i = 0; i < 4; i++) {
                buf[n++] = (byte) (v >>> (8 * i));
            }
        }

        public void i64(long v) {
            ensure(8);
            for (int i = 0; i < 8; i++) {
                buf[n++] = (byte) (v >>> (8 * i));
            }
        }

        public void f64(double v) {
            i64(Double.doubleToRawLongBits(v));
        }

        public void bool(boolean v) {
            tag(v ? 1 : 0);
        }

        public void str(CharSequence s) {
            if (s == null) {
                tag(0);
                return;
            }
            byte[] b = s.toString().getBytes(StandardCharsets.UTF_8);
            tag(1);
            len(b.length);
            ensure(b.length);
            System.arraycopy(b, 0, buf, n, b.length);
            n += b.length;
        }

        public byte[] bytes() {
            return java.util.Arrays.copyOf(buf, n);
        }
    }

    public static final class Reader {
        private final byte[] b;
        private int i;

        public Reader(byte[] b) {
            this.b = b;
        }

        public int tag() {
            return b[i++] & 0xff;
        }

        public int len() {
            int v = 0;
            for (int k = 0; k < 4; k++) {
                v |= (b[i++] & 0xff) << (8 * k);
            }
            return v;
        }

        public long i64() {
            long v = 0;
            for (int k = 0; k < 8; k++) {
                v |= (long) (b[i++] & 0xff) << (8 * k);
            }
            return v;
        }

        public double f64() {
            return Double.longBitsToDouble(i64());
        }

        public boolean bool() {
            return tag() != 0;
        }

        public String str() {
            if (tag() == 0) {
                return null;
            }
            int n = len();
            String s = new String(b, i, n, StandardCharsets.UTF_8);
            i += n;
            return s;
        }

        public <T> List<T> list(Supplier<T> item) {
            if (tag() == 0) {
                return null;
            }
            int n = len();
            List<T> out = new ArrayList<>(n);
            for (int k = 0; k < n; k++) {
                out.add(item.get());
            }
            return out;
        }

        @SuppressWarnings("unchecked")
        public <T> java.util.TreeSet<T> treeSet(Supplier<T> item) {
            if (tag() == 0) {
                return null;
            }
            int n = len();
            java.util.TreeSet<T> out = new java.util.TreeSet<>();
            T prev = null;
            for (int k = 0; k < n; k++) {
                T elem = item.get();
                out.add(elem);
                if (prev != null && ((Comparable<Object>) prev).compareTo(elem) >= 0) {
                    throw new IllegalArgumentException(
                        "sorted set elements repeat or are not in natural order (custom comparators are not supported)");
                }
                prev = elem;
            }
            return out;
        }

        public <T> java.util.LinkedHashSet<T> linkedHashSet(Supplier<T> item) {
            if (tag() == 0) {
                return null;
            }
            int n = len();
            java.util.LinkedHashSet<T> out = new java.util.LinkedHashSet<>(n);
            for (int k = 0; k < n; k++) {
                out.add(item.get());
            }
            if (out.size() != n) {
                throw new IllegalArgumentException("duplicate elements in a set");
            }
            return out;
        }

        public <T> T[] array(Supplier<T> item, IntFunction<T[]> make) {
            List<T> items = list(item);
            return items == null ? null : items.toArray(make.apply(items.size()));
        }

        public <T> Map<String, T> map(Supplier<T> item) {
            if (tag() == 0) {
                return null;
            }
            int n = len();
            Map<String, T> out = new LinkedHashMap<>();
            for (int k = 0; k < n; k++) {
                String key = str();
                out.put(key, item.get());
            }
            return out;
        }

        public int[] ints() {
            if (tag() == 0) {
                return null;
            }
            int[] out = new int[len()];
            for (int k = 0; k < out.length; k++) {
                out[k] = (int) i64();
            }
            return out;
        }

        public long[] longs() {
            if (tag() == 0) {
                return null;
            }
            long[] out = new long[len()];
            for (int k = 0; k < out.length; k++) {
                out[k] = i64();
            }
            return out;
        }

        public double[] doubles() {
            if (tag() == 0) {
                return null;
            }
            double[] out = new double[len()];
            for (int k = 0; k < out.length; k++) {
                out[k] = f64();
            }
            return out;
        }

        public boolean[] booleans() {
            if (tag() == 0) {
                return null;
            }
            boolean[] out = new boolean[len()];
            for (int k = 0; k < out.length; k++) {
                out[k] = bool();
            }
            return out;
        }
    }
}
"#;

/// The exports that cross the binary wire, with their Java body and Rust code.
fn java_wire_fns<'m>(
    m: &'m Manifest,
    api: &crate::codegen::PortApi,
) -> Vec<(&'m crate::ts::exports::ExportedFn, String, String)> {
    let class = java_native_class(m);
    let mut out = Vec::new();
    for f in &api.functions {
        if typed(m, f).is_some() || f.has_effects() {
            continue;
        }
        let Some(e) = m.exports.iter().find(|e| e.name == f.js_name) else {
            continue;
        };
        if e.params.len() != f.params.len() {
            continue;
        }
        let Some(params) = e
            .params
            .iter()
            .map(|p| Some((p.name.clone(), java_ty_param(p.native_type.as_deref()?)?)))
            .collect::<Option<Vec<_>>>()
        else {
            continue;
        };
        let ret_java = e.native_return.as_deref().unwrap_or("void");
        let result = if ret_java == "void" {
            None
        } else {
            java_ty(ret_java)
        };
        if ret_java != "void" && result.is_none() {
            continue;
        }
        // Java body of `call_<name>`.
        let mut java =
            String::from("        RustAnythingWire.Writer w = new RustAnythingWire.Writer();\n");
        for (name, t) in &params {
            let _ = writeln!(java, "        {}", java_enc(name, t, 0));
        }
        let _ = writeln!(
            java,
            "        String[] slot = RustAnythingError.slot();\n        byte[] out = w_{}(w.bytes(), slot);\n        RustAnythingError.check(slot);",
            f.js_name
        );
        if let Some(t) = &result {
            let mut used: BTreeSet<String> = params.iter().map(|(n, _)| (*n).to_string()).collect();
            for reserved in ["w", "slot", "out", "r", "e"] {
                used.insert(reserved.to_string());
            }
            let Some(dec) = java_dec(t, &mut used) else {
                continue;
            };
            let _ = writeln!(
                java,
                "        RustAnythingWire.Reader r = new RustAnythingWire.Reader(out);\n        return {dec};"
            );
        }
        // Rust JNI function.
        let mut statics = String::new();
        let prefix = format!("S_{}", f.js_name.to_uppercase());
        let Some(reads) = crate::wire::rust_read_args(&params, &f.params, &prefix, &mut statics)
        else {
            continue;
        };
        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
        let call = format!("port::{}({})", f.rust_name, args.join(", "));
        let call = if f.fallible { format!("{call}?") } else { call };
        let write = match &result {
            None if f.ret == "()" => format!("        let () = {call};\n"),
            None => continue,
            Some(t) => {
                let schema = format!("{prefix}_OUT");
                let Some(w) = crate::wire::rust_write(t, &f.ret, "out", &schema, 0) else {
                    continue;
                };
                if w.contains(&schema) {
                    let _ = writeln!(
                        statics,
                        "static {schema}: wire::Schema = {};",
                        crate::wire::schema_expr(t)
                    );
                }
                format!("        let out = &{call};\n        {w}\n")
            }
        };
        let rust = format!(
            "\n{statics}\n/// `{proto}`: binary wire.\n// SAFETY: the JNI symbol of `rustanything.{class}.w_{js}`; nothing else defines it.\n\
             #[unsafe(no_mangle)]\npub extern \"system\" fn Java_rustanything_{mclass}_w_1{mjs}<'local>(mut env: jni::JNIEnv<'local>, \
             _class: jni::objects::JClass<'local>, args: jni::objects::JByteArray<'local>, slot: jni::objects::JObjectArray<'local>) -> jni::sys::jbyteArray {{\n    \
             let Ok(input) = env.convert_byte_array(&args) else {{\n        return std::ptr::null_mut();\n    }};\n    \
             let result = run(|| {{\n        let r = &mut wire::Reader::new(&input);\n{reads}        let w = &mut wire::Writer::default();\n{write}        \
             Ok(std::mem::take(&mut w.0))\n    }});\n    match result {{\n        \
             Ok(bytes) => env.byte_array_from_slice(&bytes).map_or(std::ptr::null_mut(), jni::objects::JByteArray::into_raw),\n        \
             Err(message) => {{\n            report(&mut env, &slot, &message);\n            std::ptr::null_mut()\n        }}\n    }}\n}}",
            proto = e.prototype.as_deref().unwrap_or(&e.name),
            js = f.js_name,
            mclass = mangle_jni_component(&class),
            mjs = mangle_jni_component(&f.js_name),
        );
        out.push((e, java, rust));
    }
    out
}

/// Rust code of every wire export, for `lib.rs`.
pub fn wire_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
    java_wire_fns(m, api)
        .into_iter()
        .map(|(_, _, rust)| rust)
        .collect()
}

/// `call_<name>` methods of the native class: the one entry point wrappers and shadows use.
fn call_methods(m: &Manifest, api: &crate::codegen::PortApi) -> String {
    let mut out = String::new();
    let sig = |e: &crate::ts::exports::ExportedFn| {
        e.params
            .iter()
            .map(|p| {
                format!(
                    "{} {}",
                    p.native_type.as_deref().unwrap_or("Object"),
                    p.name
                )
            })
            .collect::<Vec<_>>()
            .join(", ")
    };
    for f in &api.functions {
        let Some(e) = typed(m, f) else { continue };
        let ret = e.native_return.as_deref().unwrap_or("void");
        let args = e
            .params
            .iter()
            .map(|p| p.name.as_str())
            .collect::<Vec<_>>()
            .join(", ");
        let call_args = if args.is_empty() {
            "slot".to_string()
        } else {
            format!("{args}, slot")
        };
        let body = if ret == "void" {
            format!(
                "String[] slot = RustAnythingError.slot();\n            n_{}({call_args});\n            RustAnythingError.check(slot);",
                f.js_name
            )
        } else {
            format!(
                "String[] slot = RustAnythingError.slot();\n            {ret} out = n_{}({call_args});\n            RustAnythingError.check(slot);\n            return out;",
                f.js_name
            )
        };
        let _ = writeln!(
            out,
            "\n    public static {ret} call_{}({}) {{\n        try {{\n            {body}\n        }} catch (RustAnythingError e) {{\n            throw e.real();\n        }}\n    }}",
            f.js_name,
            sig(e)
        );
    }
    for (e, body, _) in java_wire_fns(m, api) {
        let ret = e.native_return.as_deref().unwrap_or("void");
        let _ = writeln!(
            out,
            "\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    }}",
            sig(e),
            name = e.name,
        );
    }
    out
}

/// The exports with a `call_<name>` method (typed or wire).
fn direct_names(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<String> {
    let mut names = typed_names(m, api);
    names.extend(
        java_wire_fns(m, api)
            .into_iter()
            .map(|(e, ..)| e.name.clone()),
    );
    names
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn jni_symbols_match_javac_for_non_ascii_identifiers() {
        assert_eq!(mangle_jni_component("n_café"), "n_1caf_000e9");
        assert_eq!(mangle_jni_component("w_get$Value"), "w_1get_00024Value");
        assert_eq!(mangle_jni_component("n_𐐀"), "n_1_0d801_0dc00");
    }

    #[test]
    fn wildcard_params_cross_wire_and_json_converter() {
        assert!(java_ty("List<? extends CharSequence>").is_none());
        assert!(java_ty("Map<CharSequence, Integer>").is_none());
        assert!(java_ty("List<CharSequence>").is_none());
        assert!(java_ty_param("List<? extends CharSequence>").is_some());
        assert!(java_ty_param("Map<CharSequence, Integer>").is_some());
        assert!(java_ty_param("Map<String, ? extends Integer>").is_some());
        assert!(java_ty_param("Map<? extends CharSequence, ? extends Integer>").is_some());
        assert!(java_ty_param("Optional<? extends CharSequence>").is_some());
        assert!(java_ty_param("List<? super String>").is_none());
        assert!(java_ty_param("List<?>").is_none());

        assert!(JSON_JAVA.contains("import java.lang.reflect.WildcardType;"));
        assert!(JSON_JAVA.contains("type instanceof WildcardType"));
        assert!(JSON_JAVA.contains("type instanceof GenericArrayType"));
        assert!(JSON_JAVA.contains("v instanceof CharSequence"));
        assert!(WIRE_JAVA.contains("public void str(CharSequence s)"));

        let src = r#"package acme;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class Wildcards {
    public static int count(List<? extends CharSequence> xs) { return xs.size(); }
    public static int sumMap(Map<String, ? extends Integer> m) { return m.size(); }
    public static int optLen(Optional<? extends CharSequence> s) { return s.map(CharSequence::length).orElse(0); }
}
"#;
        let exports = crate::lang::java::exports("acme/Wildcards.java", src);
        let manifest = Manifest {
            schema: String::new(),
            root: std::path::PathBuf::new(),
            root_written: None,
            unit: "acme/Wildcards.java".into(),
            language: crate::lang::Lang::Java,
            kind: crate::bridge::Kind::Ffi,
            crate_name: "wildcards-rs".into(),
            exports,
            classes: vec![],
            js_only: vec![],
            batches: vec![],
            allocator: Default::default(),
            float_tolerance: None,
            ignore_key_order: false,
            messages: false,
            end_state: None,
        };
        let mut api = crate::codegen::parse_port(&crate::codegen::port_rs(&manifest));
        crate::bridge::match_export_names(&manifest, &mut api);
        let native = native_class(&manifest, &api);
        assert!(
            native.contains("public static int call_count(List<? extends CharSequence> xs)"),
            "{native}"
        );
        assert!(native.contains("w.str(v0);"), "{native}");
        assert!(
            native.contains("public static int call_optLen(Optional<? extends CharSequence> s)"),
            "{native}"
        );
    }

    #[test]
    fn native_class_shares_error_lookup_with_rust_anything_error() {
        let m = Manifest {
            schema: String::new(),
            root: std::path::PathBuf::new(),
            root_written: None,
            unit: "Dates.java".into(),
            language: crate::lang::Lang::Java,
            kind: crate::bridge::Kind::Ffi,
            crate_name: "time-rs".into(),
            exports: Vec::new(),
            classes: Vec::new(),
            js_only: Vec::new(),
            batches: Vec::new(),
            allocator: Default::default(),
            float_tolerance: None,
            ignore_key_order: false,
            messages: false,
            end_state: None,
        };
        let native = native_class(&m, &crate::codegen::PortApi::default());
        assert!(native.contains("throw RustAnythingError.from(message);"));
        assert!(!native.contains("private static RuntimeException exception("));
        assert!(ERROR_JAVA.contains("\"java.time.\""));
        assert!(ERROR_JAVA.contains("\"java.util.concurrent.\""));
    }

    #[test]
    fn ordered_sets_generate_matching_imports_wire_and_decoders() {
        let src = r#"package acme;
import java.util.*;
public class Sets {
    public static int distinctSorted(SortedSet<String> words) { return words.size(); }
    public static TreeSet<String> sortWords(LinkedHashSet<String> words) { return new TreeSet<>(words); }
    public static LinkedHashSet<Integer> keepOrder(NavigableSet<Integer> nums) { return new LinkedHashSet<>(nums); }
    @SuppressWarnings("unchecked")
    public static TreeSet<String>[] splitSets(int n) { return new TreeSet[n]; }
    public static String[] toArray(LinkedHashSet<String> words) { return words.toArray(new String[0]); }
}
"#;
        let exports = crate::lang::java::exports("acme/Sets.java", src);
        assert!(exports.iter().all(|f| f.blocker.is_none()), "{exports:?}");
        let manifest = Manifest {
            schema: String::new(),
            root: std::path::PathBuf::new(),
            root_written: None,
            unit: "acme/Sets.java".into(),
            language: crate::lang::Lang::Java,
            kind: crate::bridge::Kind::Ffi,
            crate_name: "sets-rs".into(),
            exports,
            classes: vec![],
            js_only: vec![],
            batches: vec![],
            allocator: Default::default(),
            float_tolerance: None,
            ignore_key_order: false,
            messages: false,
            end_state: None,
        };
        let mut api = crate::codegen::parse_port(&crate::codegen::port_rs(&manifest));
        crate::bridge::match_export_names(&manifest, &mut api);

        let native = native_class(&manifest, &api);
        assert!(
            native.contains("public static int call_distinctSorted(SortedSet<String> words)"),
            "{native}"
        );
        assert!(
            native.contains("return r.treeSet(() -> r.str());"),
            "{native}"
        );
        assert!(native.contains("return r.linkedHashSet(() ->"), "{native}");
        assert!(
            native.contains(
                "return r.array(() -> r.treeSet(() -> r.str()), _raLen0 -> (TreeSet<String>[]) new TreeSet[_raLen0]);"
            ),
            "{native}"
        );
        assert!(
            native.contains("return r.array(() -> r.str(), String[]::new);"),
            "{native}"
        );

        let wrappers = wrappers(&manifest, &api);
        let wrapper_src = &wrappers[0].1;
        for imp in [
            "import java.util.LinkedHashSet;",
            "import java.util.NavigableSet;",
            "import java.util.SortedSet;",
            "import java.util.TreeSet;",
        ] {
            assert!(
                wrapper_src.contains(imp),
                "missing {imp} in:\n{wrapper_src}"
            );
        }
    }

    #[test]
    fn concrete_collections_and_primitive_optionals_are_imported_in_the_wrapper() {
        let src = "package demo;\nimport java.util.*;\npublic class Stats {\n    public static int total(ArrayList<Integer> xs) { int s = 0; for (int x : xs) s += x; return s; }\n    public static int width(TreeMap<String, Integer> m) { return m.size(); }\n    public static OptionalInt first(List<Integer> xs) { return xs.isEmpty() ? OptionalInt.empty() : OptionalInt.of(xs.get(0)); }\n}\n";
        let exports = crate::lang::java::exports("demo/Stats.java", src);
        assert!(exports.iter().all(|f| f.blocker.is_none()), "{exports:?}");
        let manifest = Manifest {
            schema: String::new(),
            root: std::path::PathBuf::new(),
            root_written: None,
            unit: "demo/Stats.java".into(),
            language: crate::lang::Lang::Java,
            kind: crate::bridge::Kind::Ffi,
            crate_name: "stats-rs".into(),
            exports,
            classes: vec![],
            js_only: vec![],
            batches: vec![],
            allocator: Default::default(),
            float_tolerance: None,
            ignore_key_order: false,
            messages: false,
            end_state: None,
        };
        let imports = imports_of(&manifest);
        assert_eq!(
            imports,
            "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.OptionalInt;\nimport java.util.TreeMap;\n\n"
        );
        let mut api = crate::codegen::parse_port(&crate::codegen::port_rs(&manifest));
        crate::bridge::match_export_names(&manifest, &mut api);
        let wrappers = wrappers(&manifest, &api);
        for imp in [
            "import java.util.ArrayList;",
            "import java.util.TreeMap;",
            "import java.util.OptionalInt;",
        ] {
            assert!(
                wrappers[0].1.contains(imp),
                "missing {imp} in:\n{}",
                wrappers[0].1
            );
        }

        // `List` alone imports `List` only.
        let mut only_list = manifest.clone();
        only_list.exports.retain(|f| f.name == "first");
        for f in &mut only_list.exports {
            f.native_return = Some("int".into());
        }
        assert_eq!(imports_of(&only_list), "import java.util.List;\n\n");
    }

    #[test]
    fn typed_rs_avoids_redundant_closure_for_zero_arg_fallible_functions() {
        let src = r#"package acme;
public class Ping {
    public static String pong() { return "pong"; }
    public static String purePong() { return "pong"; }
    public static String echo(String s) { return s; }
}
"#;
        let exports = crate::lang::java::exports("acme/Ping.java", src);
        let manifest = Manifest {
            schema: String::new(),
            root: std::path::PathBuf::new(),
            root_written: None,
            unit: "acme/Ping.java".into(),
            language: crate::lang::Lang::Java,
            kind: crate::bridge::Kind::Ffi,
            crate_name: "ping-rs".into(),
            exports,
            classes: vec![],
            js_only: vec![],
            batches: vec![],
            allocator: Default::default(),
            float_tolerance: None,
            ignore_key_order: false,
            messages: false,
            end_state: None,
        };
        let mut api = crate::codegen::parse_port(
            "pub fn pong() -> Result<String, String> { Ok(\"pong\".into()) }\n\
             pub fn pure_pong() -> String { \"pong\".into() }\n\
             pub fn echo(s: String) -> Result<String, String> { Ok(s) }\n",
        );
        crate::bridge::match_export_names(&manifest, &mut api);
        let rs = typed_rs(&manifest, &api);
        assert!(rs.contains("match run(port::pong)"), "{rs}");
        assert!(!rs.contains("run(|| port::pong())"), "{rs}");
        assert!(rs.contains("match run(|| Ok(port::pure_pong()))"), "{rs}");
        assert!(rs.contains("match run(|| port::echo(s))"), "{rs}");
    }
}