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