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.util.ArrayList;
602import java.util.LinkedHashMap;
603import java.util.List;
604import java.util.Map;
605
606/** Generated by rust-anything: calls the unit's static methods by name. */
607public final class RustAnythingDriver {
608 private RustAnythingDriver() {}
609
610 private static final Map<String, Method> METHODS = new LinkedHashMap<>();
611
612 @SuppressWarnings("unchecked")
613 private static void load(String targetsPath) throws Exception {
614 Map<String, Object> targets = (Map<String, Object>) RustAnythingJson.parse(Files.readString(Path.of(targetsPath)));
615 for (Map.Entry<String, Object> e : targets.entrySet()) {
616 List<Object> t = (List<Object>) e.getValue();
617 try {
618 Class<?> c = Class.forName((String) t.get(0));
619 for (Method m : c.getMethods()) {
620 if (m.getName().equals(t.get(1)) && Modifier.isStatic(m.getModifiers())) {
621 METHODS.put(e.getKey(), m);
622 }
623 }
624 } catch (ClassNotFoundException ex) {
625 // missing: reported per case
626 }
627 }
628 }
629
630 /** {"ok": v} | {"error": msg, "error_type": name} | {"invalid": true} | {"missing": true}. */
631 @SuppressWarnings("unchecked")
632 private static Map<String, Object> call(Map<String, Object> c) {
633 Map<String, Object> out = new LinkedHashMap<>();
634 Method m = METHODS.get((String) c.get("fn"));
635 if (m == null) {
636 out.put("missing", true);
637 return out;
638 }
639 List<Object> args = (List<Object>) c.get("args");
640 Type[] types = m.getGenericParameterTypes();
641 Object[] values = new Object[types.length];
642 try {
643 for (int i = 0; i < types.length; i++) {
644 Object raw = i < args.size() ? args.get(i) : null;
645 if (raw instanceof Map && ((Map<?, ?>) raw).containsKey("$undefined")) {
646 raw = null;
647 }
648 values[i] = RustAnythingJson.convert(raw, types[i]);
649 }
650 } catch (RustAnythingJson.Mismatch e) {
651 out.put("invalid", true);
652 return out;
653 }
654 try {
655 Object result = m.invoke(null, values);
656 out.put("ok", RustAnythingJson.parse(RustAnythingJson.write(result)));
657 } catch (InvocationTargetException e) {
658 Throwable cause = e.getCause();
659 out.put("error", String.valueOf(cause.getMessage()));
660 out.put("error_type", cause.getClass().getSimpleName());
661 } catch (ReflectiveOperationException e) {
662 out.put("error", e.toString());
663 out.put("error_type", "ReflectiveOperationException");
664 } catch (StackOverflowError e) {
665 out.put("error", "stack overflow");
666 out.put("error_type", "StackOverflowError");
667 }
668 return out;
669 }
670
671 @SuppressWarnings("unchecked")
672 private static List<Map<String, Object>> lines(String path) throws Exception {
673 List<Map<String, Object>> out = new ArrayList<>();
674 for (String line : Files.readAllLines(Path.of(path), StandardCharsets.UTF_8)) {
675 if (!line.isBlank()) {
676 out.add((Map<String, Object>) RustAnythingJson.parse(line));
677 }
678 }
679 return out;
680 }
681
682 private static boolean same(Map<String, Object> expected, Map<String, Object> got) {
683 if (expected.containsKey("error")) {
684 return got.containsKey("error") && String.valueOf(expected.get("error_type")).equals(String.valueOf(got.get("error_type")));
685 }
686 return !got.containsKey("error") && RustAnythingJson.write(expected.get("ok")).equals(RustAnythingJson.write(got.get("ok")));
687 }
688
689 @SuppressWarnings("unchecked")
690 public static void main(String[] argv) throws Exception {
691 String mode = argv[0];
692 load(argv[1]);
693 String casesPath = argv[2];
694 Path outPath = Path.of(argv[3]);
695 if (mode.equals("record")) {
696 List<Object> cases = (List<Object>) RustAnythingJson.parse(Files.readString(Path.of(casesPath)));
697 try (BufferedWriter w = Files.newBufferedWriter(outPath, StandardCharsets.UTF_8)) {
698 for (Object o : cases) {
699 Map<String, Object> c = (Map<String, Object>) o;
700 Map<String, Object> result = call(c);
701 if (result.containsKey("invalid") || result.containsKey("missing")) {
702 continue;
703 }
704 Map<String, Object> line = new LinkedHashMap<>();
705 line.put("fn", c.get("fn"));
706 line.put("args", c.get("args"));
707 line.putAll(result);
708 w.write(RustAnythingJson.write(line));
709 w.write("\n");
710 }
711 }
712 } else if (mode.equals("diff")) {
713 int total = 0, passed = 0, failed = 0;
714 List<Object> missing = new ArrayList<>();
715 List<Object> mismatches = new ArrayList<>();
716 for (Map<String, Object> c : lines(casesPath)) {
717 total++;
718 Map<String, Object> got = call(c);
719 if (got.containsKey("missing")) {
720 failed++;
721 if (!missing.contains(c.get("fn"))) {
722 missing.add(c.get("fn"));
723 }
724 continue;
725 }
726 Map<String, Object> expected = new LinkedHashMap<>();
727 for (String k : new String[] {"ok", "error", "error_type"}) {
728 if (c.containsKey(k)) {
729 expected.put(k, c.get(k));
730 }
731 }
732 if (same(expected, got)) {
733 passed++;
734 } else {
735 failed++;
736 Map<String, Object> m = new LinkedHashMap<>();
737 m.put("fn", c.get("fn"));
738 m.put("args", c.get("args"));
739 m.put("expected", expected);
740 m.put("actual", got);
741 mismatches.add(m);
742 }
743 }
744 Map<String, Object> summary = new LinkedHashMap<>();
745 summary.put("total", total);
746 summary.put("passed", passed);
747 summary.put("failed", failed);
748 summary.put("missing", missing);
749 summary.put("mismatches", mismatches);
750 Files.writeString(outPath, RustAnythingJson.write(summary));
751 } else if (mode.equals("bench")) {
752 long minMs = Long.parseLong(argv[4]);
753 Map<String, List<Map<String, Object>>> groups = new LinkedHashMap<>();
754 for (Map<String, Object> c : lines(casesPath)) {
755 groups.computeIfAbsent((String) c.get("fn"), k -> new ArrayList<>()).add(c);
756 }
757 Map<String, Object> result = new LinkedHashMap<>();
758 for (Map.Entry<String, List<Map<String, Object>>> g : groups.entrySet()) {
759 List<Map<String, Object>> cases = g.getValue();
760 // Arguments are converted once: only the calls are timed.
761 Method m = METHODS.get(g.getKey());
762 if (m == null) {
763 continue;
764 }
765 Type[] types = m.getGenericParameterTypes();
766 List<Object[]> prepared = new ArrayList<>();
767 for (Map<String, Object> c : cases) {
768 List<Object> args = (List<Object>) c.get("args");
769 Object[] values = new Object[types.length];
770 try {
771 for (int i = 0; i < types.length; i++) {
772 Object raw = i < args.size() ? args.get(i) : null;
773 if (raw instanceof Map && ((Map<?, ?>) raw).containsKey("$undefined")) {
774 raw = null;
775 }
776 values[i] = RustAnythingJson.convert(raw, types[i]);
777 }
778 prepared.add(values);
779 } catch (RustAnythingJson.Mismatch e) {
780 // not a valid call
781 }
782 }
783 if (prepared.isEmpty()) {
784 continue;
785 }
786 Runnable pass = () -> {
787 for (Object[] values : prepared) {
788 try {
789 m.invoke(null, values);
790 } catch (ReflectiveOperationException | RuntimeException e) {
791 // errors count as calls
792 }
793 }
794 };
795 // Warm up the JIT before timing.
796 long warm = System.nanoTime();
797 while (System.nanoTime() - warm < minMs * 1_000_000L / 2) {
798 pass.run();
799 }
800 long passes = 0;
801 long start = System.nanoTime();
802 while (true) {
803 pass.run();
804 passes++;
805 long elapsed = System.nanoTime() - start;
806 if (elapsed / 1_000_000 >= minMs) {
807 Map<String, Object> row = new LinkedHashMap<>();
808 row.put("cases", prepared.size());
809 row.put("ns", (double) elapsed / (passes * prepared.size()));
810 result.put(g.getKey(), row);
811 break;
812 }
813 }
814 }
815 Files.writeString(outPath, RustAnythingJson.write(result));
816 }
817 }
818}
819"#;
820
821pub fn shadows(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<(String, String)> {
825 let typed = direct_names(m, api);
826 let native = java_native_class(m);
827 let mut classes: Vec<(String, Vec<String>)> = Vec::new();
828 for f in &m.exports {
829 let (class, name) = receiver(f);
830 let simple = class.rsplit('.').next().unwrap_or(&class).to_string();
831 let ret = f.native_return.as_deref().unwrap_or("void");
832 let params: Vec<String> = f
833 .params
834 .iter()
835 .map(|p| {
836 format!(
837 "{} {}",
838 p.native_type.as_deref().unwrap_or("Object"),
839 p.name
840 )
841 })
842 .collect();
843 let names: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
844 let call_args = names.join(", ");
845 let native_args = if names.is_empty() {
846 String::new()
847 } else {
848 format!(", {call_args}")
849 };
850 let type_ref = if ret == "void" {
851 "void.class".to_string()
852 } else {
853 format!(
854 "new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type()",
855 boxed(ret)
856 )
857 };
858 let port = if typed.contains(&f.name) {
859 format!("rustanything.{native}.call_{}({call_args})", f.name)
860 } else {
861 format!(
862 "rustanything.{native}.invoke(\"{}\", {type_ref}{native_args})",
863 f.name
864 )
865 };
866 let method = if ret == "void" {
867 format!(
868 " @SuppressWarnings(\"unchecked\")\n public static void {name}({params}) {{\n if (MODE.equals(\"new\")) {{\n {port};\n return;\n }}\n\
869 \x20 {simple}.{name}({call_args});\n if (!MODE.equals(\"old\")) {{\n try {{\n {port};\n compare(\"{name}\", null, null);\n\
870 \x20 }} catch (RuntimeException e) {{\n compare(\"{name}\", null, e);\n }}\n }}\n }}\n",
871 params = params.join(", "),
872 )
873 } else {
874 format!(
875 " @SuppressWarnings(\"unchecked\")\n public static {ret} {name}({params}) {{\n if (MODE.equals(\"new\")) {{\n return ({b}) {port};\n }}\n\
876 \x20 {ret} expected = {simple}.{name}({call_args});\n if (!MODE.equals(\"old\")) {{\n Object actual;\n try {{\n actual = {port};\n\
877 \x20 }} catch (RuntimeException e) {{\n actual = e;\n }}\n compare(\"{name}\", expected, actual);\n }}\n return expected;\n }}\n",
878 params = params.join(", "),
879 b = boxed(ret),
880 )
881 };
882 match classes.iter_mut().find(|(c, _)| *c == class) {
883 Some((_, methods)) => methods.push(method),
884 None => classes.push((class, vec![method])),
885 }
886 }
887 let imports = imports_of(m);
888 classes
889 .into_iter()
890 .map(|(class, methods)| {
891 let (package, simple) = class.rsplit_once('.').unwrap_or(("", class.as_str()));
892 let path = if package.is_empty() {
893 format!("shadow/{simple}Shadow.java")
894 } else {
895 format!("shadow/{}/{simple}Shadow.java", package.replace('.', "/"))
896 };
897 let mut out = String::new();
898 if !package.is_empty() {
899 let _ = writeln!(out, "package {package};\n");
900 }
901 out.push_str("import java.util.concurrent.atomic.AtomicLong;\n");
902 out.push_str(&imports.replace("\n\n", "\n"));
903 let _ = write!(
904 out,
905 "\n/** Runs `{simple}` and its Rust port side by side. Generated by rust-anything: call it in place of `{simple}`. */\n\
906 public final class {simple}Shadow {{\n private {simple}Shadow() {{}}\n\n\
907 \x20 private static final String MODE = System.getProperty(\"rust-anything.mode\", \"shadow\");\n\
908 \x20 public static final AtomicLong CALLS = new AtomicLong();\n public static final AtomicLong MISMATCHES = new AtomicLong();\n\n\
909 \x20 private static void compare(String name, Object expected, Object actual) {{\n CALLS.incrementAndGet();\n\
910 \x20 if (actual instanceof Throwable || !rustanything.RustAnythingJson.write(expected).equals(rustanything.RustAnythingJson.write(actual))) {{\n\
911 \x20 if (MISMATCHES.incrementAndGet() <= 10) {{\n System.err.println(\"[rust-anything] mismatch in \" + name + \": expected \" + expected + \", got \" + actual);\n }}\n }}\n }}\n\n{}}}\n",
912 methods.join("\n")
913 );
914 (path, out)
915 })
916 .collect()
917}
918
919struct Jni {
923 jni: &'static str,
924 port: &'static str,
925 arg: fn(&str) -> String,
926 out: &'static str,
927 default: &'static str,
928}
929
930fn jni(java: &str) -> Option<Jni> {
931 let int = |jni, out| Jni {
932 jni,
933 port: "i64",
934 arg: |n| format!("i64::from({n})"),
935 out,
936 default: "0",
937 };
938 Some(match java.trim() {
939 "int" => int("jni::sys::jint", "out as jni::sys::jint"),
940 "short" => int("jni::sys::jshort", "out as jni::sys::jshort"),
941 "byte" => int("jni::sys::jbyte", "out as jni::sys::jbyte"),
942 "long" => Jni {
943 jni: "jni::sys::jlong",
944 port: "i64",
945 arg: |n| n.to_string(),
946 out: "out",
947 default: "0",
948 },
949 "double" => Jni {
950 jni: "jni::sys::jdouble",
951 port: "f64",
952 arg: |n| n.to_string(),
953 out: "out",
954 default: "0.0",
955 },
956 "float" => Jni {
957 jni: "jni::sys::jfloat",
958 port: "f64",
959 arg: |n| format!("f64::from({n})"),
960 out: "out as jni::sys::jfloat",
961 default: "0.0",
962 },
963 "boolean" => Jni {
964 jni: "jni::sys::jboolean",
965 port: "bool",
966 arg: |n| format!("{n} != 0"),
967 out: "jni::sys::jboolean::from(out)",
968 default: "0",
969 },
970 "String" => Jni {
971 jni: "jni::objects::JString<'local>",
972 port: "String",
973 arg: |n| n.to_string(),
974 out: "java_string(&mut env, &out)",
975 default: "std::ptr::null_mut()",
976 },
977 _ => return None,
978 })
979}
980
981fn typed<'m>(
984 m: &'m Manifest,
985 f: &crate::codegen::PortFn,
986) -> Option<&'m crate::ts::exports::ExportedFn> {
987 let e = m.exports.iter().find(|e| e.name == f.js_name)?;
988 if e.params.len() != f.params.len() {
989 return None;
990 }
991 for (p, (_, port_ty)) in e.params.iter().zip(&f.params) {
992 if jni(p.native_type.as_deref()?)?.port != port_ty {
993 return None;
994 }
995 }
996 match e.native_return.as_deref()? {
997 "void" => (f.ret == "()").then_some(e),
998 r => (jni(r)?.port == f.ret).then_some(e),
999 }
1000}
1001
1002fn mangle(s: &str) -> String {
1003 s.replace('_', "_1")
1004}
1005
1006pub fn typed_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1008 let class = java_native_class(m);
1009 let mut out = String::from(
1010 r#"
1011/// `rustanything.RustAnythingError` and its `(String, String)` constructor, resolved once per process.
1012type Exception = (jni::objects::GlobalRef, jni::objects::JMethodID);
1013static RUST_ANYTHING_ERROR: std::sync::OnceLock<Option<Exception>> = std::sync::OnceLock::new();
1014
1015fn rust_anything_error(env: &mut jni::JNIEnv) -> Option<Exception> {
1016 RUST_ANYTHING_ERROR
1017 .get_or_init(|| {
1018 let class = env.find_class("rustanything/RustAnythingError").ok()?;
1019 let ctor = env
1020 .get_method_id(&class, "<init>", "(Ljava/lang/String;Ljava/lang/String;)V")
1021 .ok()?;
1022 Some((env.new_global_ref(class).ok()?, ctor))
1023 })
1024 .clone()
1025}
1026
1027/// Splits `"Type: message"`; anything else is a RuntimeException with the whole message.
1028fn split_error(message: &str) -> (&str, &str) {
1029 message
1030 .split_once(": ")
1031 .filter(|(k, _)| {
1032 k.starts_with(|c: char| c.is_ascii_alphabetic())
1033 && k.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '$'))
1034 })
1035 .unwrap_or(("RuntimeException", message))
1036}
1037
1038#[allow(dead_code)]
1039/// Hands an error back through the caller's `String[2]` slot: type and message. The Java side
1040/// throws it, which is much cheaper than an exception raised from native code.
1041fn report(env: &mut jni::JNIEnv, slot: &jni::objects::JObjectArray, message: &str) {
1042 let (kind, text) = split_error(message);
1043 if let (Ok(kind), Ok(text)) = (env.new_string(kind), env.new_string(text)) {
1044 let _ = env.set_object_array_element(slot, 0, &kind);
1045 let _ = env.set_object_array_element(slot, 1, &text);
1046 }
1047}
1048
1049#[allow(dead_code)]
1050/// Throws `"Type: message"` as a `RustAnythingError` without a stack trace, which is cheap from
1051/// native code; the generated Java turns it into a `Type` exception, built in Java.
1052fn throw(env: &mut jni::JNIEnv, message: &str) {
1053 let (kind, text) = split_error(message);
1054 let Some((class, ctor)) = rust_anything_error(env) else {
1055 let _ = env.exception_clear();
1056 let _ = env.throw_new("java/lang/RuntimeException", message);
1057 return;
1058 };
1059 let (Ok(kind), Ok(text)) = (env.new_string(kind), env.new_string(text)) else {
1060 return;
1061 };
1062 let class: &jni::objects::JClass = class.as_obj().into();
1063 let args = [
1064 jni::objects::JValue::Object(&kind).as_jni(),
1065 jni::objects::JValue::Object(&text).as_jni(),
1066 ];
1067 // SAFETY: `ctor` is the `(String, String)` constructor of `class`, looked up together, and
1068 // both arguments are Strings.
1069 if let Ok(object) = unsafe { env.new_object_unchecked(class, ctor, &args) } {
1070 let _ = env.throw(jni::objects::JThrowable::from(object));
1071 }
1072}
1073
1074/// Runs the port; a panic becomes an error instead of unwinding into the JVM.
1075#[allow(dead_code)]
1076fn run<T>(f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
1077 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|panic| {
1078 let text = panic
1079 .downcast_ref::<&str>()
1080 .map(ToString::to_string)
1081 .or_else(|| panic.downcast_ref::<String>().cloned())
1082 .unwrap_or_default();
1083 Err(format!("RuntimeException: Rust panic: {text}"))
1084 })
1085}
1086
1087/// A `String` argument; `None` (with a NullPointerException thrown) for null.
1088#[allow(dead_code)]
1089fn string_arg(env: &mut jni::JNIEnv, s: &jni::objects::JString) -> Option<String> {
1090 if s.is_null() {
1091 let _ = env.throw_new("java/lang/NullPointerException", "null String argument");
1092 return None;
1093 }
1094 let raw = env.get_raw();
1095 let mut stack = [0u16; 128];
1096 // SAFETY: `raw` is this thread's JNIEnv and `s` a live, non-null String reference; the JVM
1097 // fills every entry of the function table.
1098 let len = unsafe { ((**raw).GetStringLength?)(raw, s.as_raw()) };
1099 let n = usize::try_from(len).unwrap_or(0);
1100 let mut heap = Vec::new();
1101 let units: &mut [u16] = if n <= stack.len() {
1102 &mut stack[..n]
1103 } else {
1104 heap.resize(n, 0);
1105 &mut heap
1106 };
1107 // SAFETY: as above; `units` holds exactly `len` UTF-16 code units.
1108 unsafe { ((**raw).GetStringRegion?)(raw, s.as_raw(), 0, len, units.as_mut_ptr()) };
1109 // UTF-16 straight from the String: no modified UTF-8 in between.
1110 Some(String::from_utf16_lossy(units))
1111}
1112
1113/// A Java String from Rust text, built from UTF-16 (`NewString`), not modified UTF-8.
1114#[allow(dead_code)]
1115fn java_string(env: &mut jni::JNIEnv, text: &str) -> jni::sys::jstring {
1116 let mut stack = [0u16; 128];
1117 let mut heap = Vec::new();
1118 let units: &[u16] = if text.len() <= stack.len() {
1119 let mut n = 0;
1120 for u in text.encode_utf16() {
1121 stack[n] = u;
1122 n += 1;
1123 }
1124 &stack[..n]
1125 } else {
1126 heap.extend(text.encode_utf16());
1127 &heap
1128 };
1129 let Ok(len) = jni::sys::jsize::try_from(units.len()) else {
1130 return std::ptr::null_mut();
1131 };
1132 let raw = env.get_raw();
1133 // SAFETY: `raw` is this thread's JNIEnv, valid for the call.
1134 let Some(new_string) = (unsafe { (**raw).NewString }) else {
1135 return std::ptr::null_mut();
1136 };
1137 // SAFETY: `units` holds `len` UTF-16 code units, read during the call only.
1138 unsafe { new_string(raw, units.as_ptr(), len) }
1139}
1140"#,
1141 );
1142 for f in &api.functions {
1143 let Some(e) = typed(m, f) else { continue };
1144 let ret_java = e.native_return.as_deref().unwrap_or("void");
1145 let ret = if ret_java == "void" {
1146 None
1147 } else {
1148 jni(ret_java)
1149 };
1150 let mut params = vec![
1151 "mut env: jni::JNIEnv<'local>".to_string(),
1152 "_class: jni::objects::JClass<'local>".to_string(),
1153 ];
1154 let mut prelude = String::new();
1155 let mut args = Vec::new();
1156 let default = ret.as_ref().map_or("", |r| r.default);
1157 for (p, (name, _)) in e.params.iter().zip(&f.params) {
1158 let t = jni(p.native_type.as_deref().unwrap_or_default()).expect("typed");
1159 params.push(format!("{name}: {}", t.jni));
1160 if t.port == "String" {
1161 let _ = writeln!(
1162 prelude,
1163 " let Some({name}) = string_arg(&mut env, &{name}) else {{\n return {default};\n }};"
1164 );
1165 args.push(name.clone());
1166 } else {
1167 args.push((t.arg)(name));
1168 }
1169 }
1170 params.push("slot: jni::objects::JObjectArray<'local>".to_string());
1171 let call = format!("port::{}({})", f.rust_name, args.join(", "));
1172 let call = if f.fallible {
1173 call
1174 } else {
1175 format!("Ok({call})")
1176 };
1177 let (ret_ty, ok) = match &ret {
1178 Some(r) => (
1179 format!(
1180 " -> {}",
1181 r.jni
1182 .replace("JString<'local>", "jstring")
1183 .replace("jni::objects::jstring", "jni::sys::jstring")
1184 ),
1185 r.out.to_string(),
1186 ),
1187 None => (String::new(), "()".to_string()),
1188 };
1189 let _ = writeln!(
1190 out,
1191 "\n/// `{proto}`: typed, no JSON.\n// SAFETY: the JNI symbol of `rustanything.{class}.n_{js}`; nothing else defines it.\n\
1192 #[unsafe(no_mangle)]\npub extern \"system\" fn Java_rustanything_{mclass}_n_1{mjs}<'local>({params}){ret_ty} {{\n\
1193 {prelude} match run(|| {call}) {{\n Ok(out) => {ok},\n Err(message) => {{\n \
1194 report(&mut env, &slot, &message);\n {default}\n }}\n }}\n}}",
1195 proto = e.prototype.as_deref().unwrap_or(&e.name),
1196 js = f.js_name,
1197 mclass = mangle(&class),
1198 mjs = mangle(&f.js_name),
1199 params = params.join(", "),
1200 );
1201 }
1202 out
1203}
1204
1205fn typed_names(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<String> {
1207 api.functions
1208 .iter()
1209 .filter(|f| typed(m, f).is_some())
1210 .map(|f| f.js_name.clone())
1211 .collect()
1212}
1213
1214fn typed_declarations(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1216 let mut out = String::new();
1217 for f in &api.functions {
1218 let Some(e) = typed(m, f) else { continue };
1219 let params: Vec<String> = e
1220 .params
1221 .iter()
1222 .map(|p| {
1223 format!(
1224 "{} {}",
1225 p.native_type.as_deref().unwrap_or("Object"),
1226 p.name
1227 )
1228 })
1229 .collect();
1230 let mut params = params;
1231 params.push("String[] slot".into());
1232 let _ = writeln!(
1233 out,
1234 " public static native {} n_{}({});",
1235 e.native_return.as_deref().unwrap_or("void"),
1236 f.js_name,
1237 params.join(", ")
1238 );
1239 }
1240 out
1241}
1242
1243use crate::wire::Ty;
1246
1247fn split_generic(t: &str) -> Option<(&str, Vec<String>)> {
1248 let i = t.find('<')?;
1249 let inner = t.strip_suffix('>')?.get(i + 1..)?;
1250 let mut args = Vec::new();
1251 let mut depth = 0;
1252 let mut cur = String::new();
1253 for c in inner.chars() {
1254 match c {
1255 '<' => depth += 1,
1256 '>' => depth -= 1,
1257 ',' if depth == 0 => {
1258 args.push(cur.trim().to_string());
1259 cur.clear();
1260 continue;
1261 }
1262 _ => {}
1263 }
1264 cur.push(c);
1265 }
1266 args.push(cur.trim().to_string());
1267 Some((t[..i].trim(), args))
1268}
1269
1270fn java_ty(t: &str) -> Option<Ty> {
1272 let t = t.trim();
1273 let boxed = |inner: Ty| Ty::Opt {
1274 inner: Box::new(inner),
1275 native: t.to_string(),
1276 };
1277 Some(match t {
1278 "int" | "long" | "short" | "byte" => Ty::I64(t.into()),
1279 "double" | "float" => Ty::F64(t.into()),
1280 "boolean" => Ty::Bool,
1281 "String" | "CharSequence" => Ty::Str,
1282 "Integer" => boxed(Ty::I64("int".into())),
1283 "Long" => boxed(Ty::I64("long".into())),
1284 "Short" => boxed(Ty::I64("short".into())),
1285 "Byte" => boxed(Ty::I64("byte".into())),
1286 "Double" => boxed(Ty::F64("double".into())),
1287 "Float" => boxed(Ty::F64("float".into())),
1288 "Boolean" => boxed(Ty::Bool),
1289 _ => {
1290 if let Some(item) = t.strip_suffix("[]") {
1291 let item_ty = java_ty(item)?;
1292 if matches!(item_ty, Ty::I64(_) | Ty::F64(_) | Ty::Bool)
1294 && !matches!(item.trim(), "int" | "long" | "double" | "boolean")
1295 {
1296 return None;
1297 }
1298 return Some(Ty::List {
1299 item: Box::new(item_ty),
1300 native: t.into(),
1301 array: true,
1302 });
1303 }
1304 let (head, args) = split_generic(t)?;
1305 match head.rsplit('.').next().unwrap_or(head) {
1306 "List" | "ArrayList" | "Collection" | "Iterable" | "LinkedList" => Ty::List {
1307 item: Box::new(java_ty(args.first()?)?),
1308 native: t.into(),
1309 array: false,
1310 },
1311 "Map" | "LinkedHashMap" | "HashMap" | "TreeMap" if args.first()? == "String" => {
1312 Ty::Map {
1313 value: Box::new(java_ty(args.get(1)?)?),
1314 native: t.into(),
1315 }
1316 }
1317 "Optional" => Ty::Opt {
1318 inner: Box::new(java_ty(args.first()?)?),
1319 native: t.into(),
1320 },
1321 _ => return None,
1322 }
1323 }
1324 })
1325}
1326
1327fn java_enc(expr: &str, t: &Ty, depth: usize) -> String {
1329 let d = depth;
1330 match t {
1331 Ty::I64(_) => format!("w.i64({expr});"),
1332 Ty::F64(_) => format!("w.f64({expr});"),
1333 Ty::Bool => format!("w.bool({expr});"),
1334 Ty::Str => format!("w.str({expr});"),
1335 Ty::Opt { inner, native } if native.starts_with("Optional") => format!(
1336 "{{ var o{d} = {expr}; if (o{d} == null || o{d}.isEmpty()) {{ w.tag(0); }} else {{ w.tag(1); {} }} }}",
1337 java_enc(&format!("o{d}.get()"), inner, d + 1)
1338 ),
1339 Ty::Opt { inner, .. } => format!(
1340 "{{ var o{d} = {expr}; if (o{d} == null) {{ w.tag(0); }} else {{ w.tag(1); {} }} }}",
1341 java_enc(&format!("o{d}"), inner, d + 1)
1342 ),
1343 Ty::List { item, array, .. } => format!(
1344 "{{ 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}) {{ {} }} }} }}",
1345 if *array { "length" } else { "size()" },
1346 java_enc(&format!("v{d}"), item, d + 1)
1347 ),
1348 Ty::Map { value, .. } => format!(
1349 "{{ 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()); {} }} }} }}",
1350 java_enc(&format!("e{d}.getValue()"), value, d + 1)
1351 ),
1352 _ => String::new(),
1353 }
1354}
1355
1356fn java_dec(t: &Ty) -> Option<String> {
1358 Some(match t {
1359 Ty::I64(n) => match n.as_str() {
1360 "long" => "r.i64()".into(),
1361 other => format!("(({other}) r.i64())"),
1362 },
1363 Ty::F64(n) => match n.as_str() {
1364 "float" => "((float) r.f64())".into(),
1365 _ => "r.f64()".into(),
1366 },
1367 Ty::Bool => "r.bool()".into(),
1368 Ty::Str => "r.str()".into(),
1369 Ty::Opt { inner, native } if native.starts_with("Optional") => {
1370 let arg = split_generic(native)?.1.first()?.clone();
1371 format!(
1372 "(r.tag() == 0 ? java.util.Optional.<{arg}>empty() : java.util.Optional.of({}))",
1373 java_dec(inner)?
1374 )
1375 }
1376 Ty::Opt { inner, native } => {
1377 format!("(r.tag() == 0 ? null : ({native}) {})", java_dec(inner)?)
1378 }
1379 Ty::List {
1380 item,
1381 native,
1382 array: true,
1383 } => match native.trim_end_matches("[]") {
1384 "int" => "r.ints()".into(),
1385 "long" => "r.longs()".into(),
1386 "double" => "r.doubles()".into(),
1387 "boolean" => "r.booleans()".into(),
1388 elem => format!("r.array(() -> {}, {elem}[]::new)", java_dec(item)?),
1389 },
1390 Ty::List { item, .. } => format!("r.list(() -> {})", java_dec(item)?),
1391 Ty::Map { value, .. } => format!("r.map(() -> {})", java_dec(value)?),
1392 _ => return None,
1393 })
1394}
1395
1396pub const ERROR_JAVA: &str = r#"package rustanything;
1399
1400import java.lang.invoke.MethodHandle;
1401import java.lang.invoke.MethodHandles;
1402import java.lang.invoke.MethodType;
1403import java.util.Optional;
1404import java.util.concurrent.ConcurrentHashMap;
1405
1406/** Generated by rust-anything: a port's error, thrown from Rust without a stack trace (cheap from native code). */
1407public final class RustAnythingError extends RuntimeException {
1408 private static final long serialVersionUID = 1L;
1409 private static final ConcurrentHashMap<String, Optional<MethodHandle>> CONSTRUCTORS = new ConcurrentHashMap<>();
1410
1411 public final String type;
1412
1413 public RustAnythingError(String type, String message) {
1414 super(message, null, false, false);
1415 this.type = type;
1416 }
1417
1418 private static Optional<MethodHandle> constructor(String type) {
1419 for (String prefix : new String[] {"java.lang.", "java.util.", "java.io.", ""}) {
1420 try {
1421 Class<?> c = Class.forName(prefix + type);
1422 if (RuntimeException.class.isAssignableFrom(c)) {
1423 return Optional.of(MethodHandles.publicLookup()
1424 .findConstructor(c, MethodType.methodType(void.class, String.class))
1425 .asType(MethodType.methodType(RuntimeException.class, String.class)));
1426 }
1427 } catch (ReflectiveOperationException | IllegalArgumentException e) {
1428 // try the next package
1429 }
1430 }
1431 return Optional.empty();
1432 }
1433
1434 /** The exception the original throws: `type` with the message, else a RuntimeException. */
1435 public RuntimeException real() {
1436 return make(type, getMessage());
1437 }
1438
1439 private static final ThreadLocal<String[]> SLOTS = ThreadLocal.withInitial(() -> new String[2]);
1440
1441 /** This thread's error slot: the Rust side writes a failed call's type and message there. */
1442 public static String[] slot() {
1443 return SLOTS.get();
1444 }
1445
1446 /** Throws the error a call left in `slot`, if any. */
1447 public static void check(String[] slot) {
1448 if (slot[0] != null) {
1449 String type = slot[0];
1450 String message = slot[1];
1451 slot[0] = null;
1452 slot[1] = null;
1453 throw make(type, message);
1454 }
1455 }
1456
1457 private static RuntimeException make(String type, String message) {
1458 Optional<MethodHandle> ctor = CONSTRUCTORS.computeIfAbsent(type, RustAnythingError::constructor);
1459 if (ctor.isPresent()) {
1460 try {
1461 return (RuntimeException) ctor.get().invokeExact(message);
1462 } catch (Throwable e) {
1463 // fall through
1464 }
1465 }
1466 return new RuntimeException(type + ": " + message);
1467 }
1468}
1469"#;
1470
1471pub const WIRE_JAVA: &str = r#"package rustanything;
1473
1474import java.io.ByteArrayOutputStream;
1475import java.nio.charset.StandardCharsets;
1476import java.util.ArrayList;
1477import java.util.LinkedHashMap;
1478import java.util.List;
1479import java.util.Map;
1480import java.util.function.IntFunction;
1481import java.util.function.Supplier;
1482
1483/** Generated by rust-anything: the binary wire to the Rust port. Little endian; nullable values start with 0 for null. */
1484public final class RustAnythingWire {
1485 private RustAnythingWire() {}
1486
1487 public static final class Writer {
1488 private byte[] buf = new byte[64];
1489 private int n;
1490
1491 private void ensure(int more) {
1492 if (n + more > buf.length) {
1493 buf = java.util.Arrays.copyOf(buf, Math.max(buf.length * 2, n + more));
1494 }
1495 }
1496
1497 public void tag(int t) {
1498 ensure(1);
1499 buf[n++] = (byte) t;
1500 }
1501
1502 public void len(int v) {
1503 ensure(4);
1504 for (int i = 0; i < 4; i++) {
1505 buf[n++] = (byte) (v >>> (8 * i));
1506 }
1507 }
1508
1509 public void i64(long v) {
1510 ensure(8);
1511 for (int i = 0; i < 8; i++) {
1512 buf[n++] = (byte) (v >>> (8 * i));
1513 }
1514 }
1515
1516 public void f64(double v) {
1517 i64(Double.doubleToRawLongBits(v));
1518 }
1519
1520 public void bool(boolean v) {
1521 tag(v ? 1 : 0);
1522 }
1523
1524 public void str(String s) {
1525 if (s == null) {
1526 tag(0);
1527 return;
1528 }
1529 byte[] b = s.getBytes(StandardCharsets.UTF_8);
1530 tag(1);
1531 len(b.length);
1532 ensure(b.length);
1533 System.arraycopy(b, 0, buf, n, b.length);
1534 n += b.length;
1535 }
1536
1537 public byte[] bytes() {
1538 return java.util.Arrays.copyOf(buf, n);
1539 }
1540 }
1541
1542 public static final class Reader {
1543 private final byte[] b;
1544 private int i;
1545
1546 public Reader(byte[] b) {
1547 this.b = b;
1548 }
1549
1550 public int tag() {
1551 return b[i++] & 0xff;
1552 }
1553
1554 public int len() {
1555 int v = 0;
1556 for (int k = 0; k < 4; k++) {
1557 v |= (b[i++] & 0xff) << (8 * k);
1558 }
1559 return v;
1560 }
1561
1562 public long i64() {
1563 long v = 0;
1564 for (int k = 0; k < 8; k++) {
1565 v |= (long) (b[i++] & 0xff) << (8 * k);
1566 }
1567 return v;
1568 }
1569
1570 public double f64() {
1571 return Double.longBitsToDouble(i64());
1572 }
1573
1574 public boolean bool() {
1575 return tag() != 0;
1576 }
1577
1578 public String str() {
1579 if (tag() == 0) {
1580 return null;
1581 }
1582 int n = len();
1583 String s = new String(b, i, n, StandardCharsets.UTF_8);
1584 i += n;
1585 return s;
1586 }
1587
1588 public <T> List<T> list(Supplier<T> item) {
1589 if (tag() == 0) {
1590 return null;
1591 }
1592 int n = len();
1593 List<T> out = new ArrayList<>(n);
1594 for (int k = 0; k < n; k++) {
1595 out.add(item.get());
1596 }
1597 return out;
1598 }
1599
1600 public <T> T[] array(Supplier<T> item, IntFunction<T[]> make) {
1601 List<T> items = list(item);
1602 return items == null ? null : items.toArray(make.apply(items.size()));
1603 }
1604
1605 public <T> Map<String, T> map(Supplier<T> item) {
1606 if (tag() == 0) {
1607 return null;
1608 }
1609 int n = len();
1610 Map<String, T> out = new LinkedHashMap<>();
1611 for (int k = 0; k < n; k++) {
1612 String key = str();
1613 out.put(key, item.get());
1614 }
1615 return out;
1616 }
1617
1618 public int[] ints() {
1619 if (tag() == 0) {
1620 return null;
1621 }
1622 int[] out = new int[len()];
1623 for (int k = 0; k < out.length; k++) {
1624 out[k] = (int) i64();
1625 }
1626 return out;
1627 }
1628
1629 public long[] longs() {
1630 if (tag() == 0) {
1631 return null;
1632 }
1633 long[] out = new long[len()];
1634 for (int k = 0; k < out.length; k++) {
1635 out[k] = i64();
1636 }
1637 return out;
1638 }
1639
1640 public double[] doubles() {
1641 if (tag() == 0) {
1642 return null;
1643 }
1644 double[] out = new double[len()];
1645 for (int k = 0; k < out.length; k++) {
1646 out[k] = f64();
1647 }
1648 return out;
1649 }
1650
1651 public boolean[] booleans() {
1652 if (tag() == 0) {
1653 return null;
1654 }
1655 boolean[] out = new boolean[len()];
1656 for (int k = 0; k < out.length; k++) {
1657 out[k] = bool();
1658 }
1659 return out;
1660 }
1661 }
1662}
1663"#;
1664
1665fn java_wire_fns<'m>(
1667 m: &'m Manifest,
1668 api: &crate::codegen::PortApi,
1669) -> Vec<(&'m crate::ts::exports::ExportedFn, String, String)> {
1670 let class = java_native_class(m);
1671 let mut out = Vec::new();
1672 for f in &api.functions {
1673 if typed(m, f).is_some() {
1674 continue;
1675 }
1676 let Some(e) = m.exports.iter().find(|e| e.name == f.js_name) else {
1677 continue;
1678 };
1679 if e.params.len() != f.params.len() {
1680 continue;
1681 }
1682 let Some(params) = e
1683 .params
1684 .iter()
1685 .map(|p| Some((p.name.clone(), java_ty(p.native_type.as_deref()?)?)))
1686 .collect::<Option<Vec<_>>>()
1687 else {
1688 continue;
1689 };
1690 let ret_java = e.native_return.as_deref().unwrap_or("void");
1691 let result = if ret_java == "void" {
1692 None
1693 } else {
1694 java_ty(ret_java)
1695 };
1696 if ret_java != "void" && result.is_none() {
1697 continue;
1698 }
1699 let mut java =
1701 String::from(" RustAnythingWire.Writer w = new RustAnythingWire.Writer();\n");
1702 for (name, t) in ¶ms {
1703 let _ = writeln!(java, " {}", java_enc(name, t, 0));
1704 }
1705 let _ = writeln!(
1706 java,
1707 " String[] slot = RustAnythingError.slot();\n byte[] out = w_{}(w.bytes(), slot);\n RustAnythingError.check(slot);",
1708 f.js_name
1709 );
1710 if let Some(t) = &result {
1711 let Some(dec) = java_dec(t) else { continue };
1712 let _ = writeln!(
1713 java,
1714 " RustAnythingWire.Reader r = new RustAnythingWire.Reader(out);\n return {dec};"
1715 );
1716 }
1717 let mut statics = String::new();
1719 let prefix = format!("S_{}", f.js_name.to_uppercase());
1720 let Some(reads) = crate::wire::rust_read_args(¶ms, &f.params, &prefix, &mut statics)
1721 else {
1722 continue;
1723 };
1724 let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
1725 let call = format!("port::{}({})", f.rust_name, args.join(", "));
1726 let call = if f.fallible { format!("{call}?") } else { call };
1727 let write = match &result {
1728 None if f.ret == "()" => format!(" let () = {call};\n"),
1729 None => continue,
1730 Some(t) => {
1731 let schema = format!("{prefix}_OUT");
1732 let Some(w) = crate::wire::rust_write(t, &f.ret, "out", &schema, 0) else {
1733 continue;
1734 };
1735 if w.contains(&schema) {
1736 let _ = writeln!(
1737 statics,
1738 "static {schema}: wire::Schema = {};",
1739 crate::wire::schema_expr(t)
1740 );
1741 }
1742 format!(" let out = &{call};\n {w}\n")
1743 }
1744 };
1745 let rust = format!(
1746 "\n{statics}\n/// `{proto}`: binary wire.\n// SAFETY: the JNI symbol of `rustanything.{class}.w_{js}`; nothing else defines it.\n\
1747 #[unsafe(no_mangle)]\npub extern \"system\" fn Java_rustanything_{mclass}_w_1{mjs}<'local>(mut env: jni::JNIEnv<'local>, \
1748 _class: jni::objects::JClass<'local>, args: jni::objects::JByteArray<'local>, slot: jni::objects::JObjectArray<'local>) -> jni::sys::jbyteArray {{\n \
1749 let Ok(input) = env.convert_byte_array(&args) else {{\n return std::ptr::null_mut();\n }};\n \
1750 let result = run(|| {{\n let r = &mut wire::Reader::new(&input);\n{reads} let w = &mut wire::Writer::default();\n{write} \
1751 Ok(std::mem::take(&mut w.0))\n }});\n match result {{\n \
1752 Ok(bytes) => env.byte_array_from_slice(&bytes).map_or(std::ptr::null_mut(), jni::objects::JByteArray::into_raw),\n \
1753 Err(message) => {{\n report(&mut env, &slot, &message);\n std::ptr::null_mut()\n }}\n }}\n}}",
1754 proto = e.prototype.as_deref().unwrap_or(&e.name),
1755 js = f.js_name,
1756 mclass = mangle(&class),
1757 mjs = mangle(&f.js_name),
1758 );
1759 out.push((e, java, rust));
1760 }
1761 out
1762}
1763
1764pub fn wire_rs(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1766 java_wire_fns(m, api)
1767 .into_iter()
1768 .map(|(_, _, rust)| rust)
1769 .collect()
1770}
1771
1772fn call_methods(m: &Manifest, api: &crate::codegen::PortApi) -> String {
1774 let mut out = String::new();
1775 let sig = |e: &crate::ts::exports::ExportedFn| {
1776 e.params
1777 .iter()
1778 .map(|p| {
1779 format!(
1780 "{} {}",
1781 p.native_type.as_deref().unwrap_or("Object"),
1782 p.name
1783 )
1784 })
1785 .collect::<Vec<_>>()
1786 .join(", ")
1787 };
1788 for f in &api.functions {
1789 let Some(e) = typed(m, f) else { continue };
1790 let ret = e.native_return.as_deref().unwrap_or("void");
1791 let args = e
1792 .params
1793 .iter()
1794 .map(|p| p.name.as_str())
1795 .collect::<Vec<_>>()
1796 .join(", ");
1797 let call_args = if args.is_empty() {
1798 "slot".to_string()
1799 } else {
1800 format!("{args}, slot")
1801 };
1802 let body = if ret == "void" {
1803 format!(
1804 "String[] slot = RustAnythingError.slot();\n n_{}({call_args});\n RustAnythingError.check(slot);",
1805 f.js_name
1806 )
1807 } else {
1808 format!(
1809 "String[] slot = RustAnythingError.slot();\n {ret} out = n_{}({call_args});\n RustAnythingError.check(slot);\n return out;",
1810 f.js_name
1811 )
1812 };
1813 let _ = writeln!(
1814 out,
1815 "\n public static {ret} call_{}({}) {{\n try {{\n {body}\n }} catch (RustAnythingError e) {{\n throw e.real();\n }}\n }}",
1816 f.js_name,
1817 sig(e)
1818 );
1819 }
1820 for (e, body, _) in java_wire_fns(m, api) {
1821 let ret = e.native_return.as_deref().unwrap_or("void");
1822 let _ = writeln!(
1823 out,
1824 "\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 }}",
1825 sig(e),
1826 name = e.name,
1827 );
1828 }
1829 out
1830}
1831
1832fn direct_names(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<String> {
1834 let mut names = typed_names(m, api);
1835 names.extend(
1836 java_wire_fns(m, api)
1837 .into_iter()
1838 .map(|(e, ..)| e.name.clone()),
1839 );
1840 names
1841}