use std::fmt::Write as _;
use crate::bridge::Manifest;
use crate::codegen_ffi::java_native_class;
use crate::lang::java::receiver;
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.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/** 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 String || v instanceof Character) {
quote(out, v.toString());
} 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;
quote(out, 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('}');
}
}
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}. */
public static Object convert(Object v, Type type) {
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 (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) {
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);
}
private static Object array(Object v, Type component) {
if (!(v instanceof List)) {
throw new Mismatch("not an array");
}
List<?> list = (List<?>) v;
Class<?> raw = component instanceof Class ? (Class<?>) component : (Class<?>) ((ParameterizedType) component).getRawType();
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;
}
}
"#;
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(),
}
}
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}}; 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 exception(message);
}}
/** {{@code "IllegalArgumentException: msg"}} becomes that exception; anything else a RuntimeException. */
private static RuntimeException exception(String message) {{
int colon = message.indexOf(": ");
if (colon > 0) {{
String type = message.substring(0, colon);
String rest = message.substring(colon + 2);
for (String prefix : new String[] {{"", "java.lang.", "java.util.", "java.io.", "java.time."}}) {{
try {{
Class<?> c = Class.forName(prefix + type);
if (RuntimeException.class.isAssignableFrom(c)) {{
return (RuntimeException) c.getConstructor(String.class).newInstance(rest);
}}
}} catch (ReflectiveOperationException e) {{
// try the next package
}}
}}
}}
return new RuntimeException(message);
}}
}}
"#,
unit = m.unit,
typed = typed_declarations(m, api),
calls = call_methods(m, api),
)
}
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 body = 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()
}
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"] {
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
}
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(),
)
}
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<>();
@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;
}
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", String.valueOf(cause.getMessage()));
out.put("error_type", cause.getClass().getSimpleName());
} catch (ReflectiveOperationException e) {
out.put("error", e.toString());
out.put("error_type", "ReflectiveOperationException");
} catch (StackOverflowError e) {
out.put("error", "stack overflow");
out.put("error_type", "StackOverflowError");
}
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")));
}
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") || result.containsKey("missing")) {
continue;
}
Map<String, Object> line = new LinkedHashMap<>();
line.put("fn", c.get("fn"));
line.put("args", c.get("args"));
line.putAll(result);
w.write(RustAnythingJson.write(line));
w.write("\n");
w.flush();
}
}
} else if (mode.equals("diff")) {
int total = 0, passed = 0, failed = 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));
}
}
if (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);
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));
}
}
}
"#;
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)
)
};
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()
}
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,
})
}
fn typed<'m>(
m: &'m Manifest,
f: &crate::codegen::PortFn,
) -> Option<&'m crate::ts::exports::ExportedFn> {
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),
}
}
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
}
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);
if let (Ok(kind), Ok(text)) = (env.new_string(kind), env.new_string(text)) {
let _ = env.set_object_array_element(slot, 0, &kind);
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), Ok(text)) = (env.new_string(kind), 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()) };
let n = usize::try_from(len).unwrap_or(0);
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()) };
// 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 call = if f.fallible {
call
} else {
format!("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
}
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()
}
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
}
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))
}
fn java_ty(t: &str) -> Option<Ty> {
let t = t.trim();
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" | "CharSequence" => 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(item)?;
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" => Ty::List {
item: Box::new(java_ty(args.first()?)?),
native: t.into(),
array: false,
},
"Map" | "LinkedHashMap" | "HashMap" | "TreeMap" if args.first()? == "String" => {
Ty::Map {
value: Box::new(java_ty(args.get(1)?)?),
native: t.into(),
}
}
"Optional" => Ty::Opt {
inner: Box::new(java_ty(args.first()?)?),
native: t.into(),
},
_ => return None,
}
}
})
}
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(),
}
}
fn java_dec(t: &Ty) -> 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)?
)
}
Ty::Opt { inner, native } => {
format!("(r.tag() == 0 ? null : ({native}) {})", java_dec(inner)?)
}
Ty::List {
item,
native,
array: true,
} => match native.trim_end_matches("[]") {
"int" => "r.ints()".into(),
"long" => "r.longs()".into(),
"double" => "r.doubles()".into(),
"boolean" => "r.booleans()".into(),
elem => format!("r.array(() -> {}, {elem}[]::new)", java_dec(item)?),
},
Ty::List { item, .. } => format!("r.list(() -> {})", java_dec(item)?),
Ty::Map { value, .. } => format!("r.map(() -> {})", java_dec(value)?),
_ => return None,
})
}
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 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 : new String[] {"java.lang.", "java.util.", "java.io.", ""}) {
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 e) {
// try the next package
}
}
return Optional.empty();
}
/** 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);
}
}
"#;
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(String s) {
if (s == null) {
tag(0);
return;
}
byte[] b = s.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;
}
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;
}
}
}
"#;
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() {
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(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;
}
let mut java =
String::from(" RustAnythingWire.Writer w = new RustAnythingWire.Writer();\n");
for (name, t) in ¶ms {
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 Some(dec) = java_dec(t) else { continue };
let _ = writeln!(
java,
" RustAnythingWire.Reader r = new RustAnythingWire.Reader(out);\n return {dec};"
);
}
let mut statics = String::new();
let prefix = format!("S_{}", f.js_name.to_uppercase());
let Some(reads) = crate::wire::rust_read_args(¶ms, &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
}
pub fn wire_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
java_wire_fns(m, api)
.into_iter()
.map(|(_, _, rust)| rust)
.collect()
}
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
}
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");
}
}