rust-anything 3.0.0

Rewrite your app in Rust, one piece at a time, checked against the original's recorded behavior at every step. TypeScript/JavaScript, Python, C, Go, Ruby, Java and Kotlin
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
//! Java: the JNI wrapper (the original classes' static methods over the Rust library), a small
//! JSON codec with no dependencies, and the reflection driver for record, diff and bench.

use std::fmt::Write as _;

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

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

import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

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

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

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

    // ---- parse ----

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

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

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

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

    // ---- write ----

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

    private static void write(StringBuilder out, Object v) {
        if (v == null) {
            out.append("null");
        } else if (v instanceof String || v instanceof Character) {
            quote(out, v.toString());
        } else if (v instanceof Double || v instanceof Float) {
            double d = ((Number) v).doubleValue();
            if (Double.isNaN(d)) {
                out.append("{\"$num\":\"NaN\"}");
            } else if (Double.isInfinite(d)) {
                out.append(d > 0 ? "{\"$num\":\"Infinity\"}" : "{\"$num\":\"-Infinity\"}");
            } else if (d == 0 && 1 / d < 0) {
                out.append("{\"$num\":\"-0\"}");
            } else if (d == Math.rint(d) && Math.abs(d) < 1e16) {
                out.append(Long.toString((long) d)).append(".0");
            } else {
                out.append(Double.toString(d).replace("E", "e"));
            }
        } else if (v instanceof Number || v instanceof Boolean) {
            out.append(v.toString());
        } else if (v instanceof Optional) {
            write(out, ((Optional<?>) v).orElse(null));
        } else if (v instanceof Map) {
            out.append('{');
            boolean first = true;
            for (Map.Entry<?, ?> e : ((Map<?, ?>) v).entrySet()) {
                if (!first) {
                    out.append(',');
                }
                first = false;
                quote(out, String.valueOf(e.getKey()));
                out.append(':');
                write(out, e.getValue());
            }
            out.append('}');
        } else if (v instanceof Collection) {
            out.append('[');
            boolean first = true;
            for (Object x : (Collection<?>) v) {
                if (!first) {
                    out.append(',');
                }
                first = false;
                write(out, x);
            }
            out.append(']');
        } else if (v.getClass().isArray()) {
            List<Object> items = new ArrayList<>();
            for (int i = 0; i < Array.getLength(v); i++) {
                items.add(Array.get(v, i));
            }
            write(out, items);
        } else {
            out.append("{\"$object\":");
            quote(out, v.getClass().getName());
            out.append('}');
        }
    }

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

    // ---- convert ----

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

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

    /** Converts a parsed JSON value to {@code type}. */
    public static Object convert(Object v, Type type) {
        if (type instanceof ParameterizedType) {
            ParameterizedType p = (ParameterizedType) type;
            Class<?> raw = (Class<?>) p.getRawType();
            Type[] args = p.getActualTypeArguments();
            if (Optional.class.equals(raw)) {
                return v == null ? Optional.empty() : Optional.of(convert(v, args[0]));
            }
            if (v == null) {
                return null;
            }
            if (Map.class.isAssignableFrom(raw)) {
                if (!(v instanceof Map)) {
                    throw new Mismatch("not an object");
                }
                Map<String, Object> out = new LinkedHashMap<>();
                for (Map.Entry<?, ?> e : ((Map<?, ?>) v).entrySet()) {
                    out.put((String) e.getKey(), convert(e.getValue(), args[1]));
                }
                return out;
            }
            if (Iterable.class.isAssignableFrom(raw)) {
                if (!(v instanceof List)) {
                    throw new Mismatch("not an array");
                }
                List<Object> out = new ArrayList<>();
                for (Object x : (List<?>) v) {
                    out.add(convert(x, args[0]));
                }
                return out;
            }
            throw new Mismatch("unsupported type " + type);
        }
        if (type instanceof GenericArrayType) {
            return array(v, ((GenericArrayType) type).getGenericComponentType());
        }
        Class<?> c = (Class<?>) type;
        if (c.isArray()) {
            return array(v, c.getComponentType());
        }
        if (v == null) {
            if (c.isPrimitive()) {
                throw new Mismatch("null for " + c);
            }
            return null;
        }
        if (c == String.class || c == CharSequence.class) {
            if (!(v instanceof String)) {
                throw new Mismatch("not a string");
            }
            return v;
        }
        if (c == int.class || c == Integer.class) {
            return (int) integer(v, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }
        if (c == long.class || c == Long.class) {
            return integer(v, Long.MIN_VALUE, Long.MAX_VALUE);
        }
        if (c == short.class || c == Short.class) {
            return (short) integer(v, Short.MIN_VALUE, Short.MAX_VALUE);
        }
        if (c == byte.class || c == Byte.class) {
            return (byte) integer(v, Byte.MIN_VALUE, Byte.MAX_VALUE);
        }
        if (c == double.class || c == Double.class) {
            return number(v);
        }
        if (c == float.class || c == Float.class) {
            return (float) number(v);
        }
        if (c == boolean.class || c == Boolean.class) {
            if (!(v instanceof Boolean)) {
                throw new Mismatch("not a boolean");
            }
            return v;
        }
        if (c == Object.class) {
            return v;
        }
        throw new Mismatch("unsupported type " + c);
    }

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

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

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

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

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

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

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

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

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

    /** {{@code "IllegalArgumentException: msg"}} becomes that exception; anything else a RuntimeException. */
    private static RuntimeException exception(String message) {{
        int colon = message.indexOf(": ");
        if (colon > 0) {{
            String type = message.substring(0, colon);
            String rest = message.substring(colon + 2);
            for (String prefix : new String[] {{"", "java.lang.", "java.util.", "java.io.", "java.time."}}) {{
                try {{
                    Class<?> c = Class.forName(prefix + type);
                    if (RuntimeException.class.isAssignableFrom(c)) {{
                        return (RuntimeException) c.getConstructor(String.class).newInstance(rest);
                    }}
                }} catch (ReflectiveOperationException e) {{
                    // try the next package
                }}
            }}
        }}
        return new RuntimeException(message);
    }}
}}
"#,
        unit = m.unit,
        typed = typed_declarations(m, api),
        calls = call_methods(m, api),
    )
}

/// The wrapper classes: `(path, source)` for each class of the unit with ported methods.
pub fn wrappers(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<(String, String)> {
    let typed = direct_names(m, api);
    let native = java_native_class(m);
    let mut classes: Vec<(String, Vec<String>)> = Vec::new();
    for f in &m.exports {
        let (class, name) = receiver(f);
        let ret = f.native_return.as_deref().unwrap_or("void");
        let params: Vec<String> = f
            .params
            .iter()
            .map(|p| {
                format!(
                    "{} {}",
                    p.native_type.as_deref().unwrap_or("Object"),
                    p.name
                )
            })
            .collect();
        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
        let args = if args.is_empty() {
            String::new()
        } else {
            format!(", {}", args.join(", "))
        };
        let direct = format!(
            "rustanything.{native}.call_{}({})",
            f.name,
            f.params
                .iter()
                .map(|p| p.name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        );
        let body = if typed.contains(&f.name) {
            if ret == "void" {
                format!("{direct};")
            } else {
                format!("return {direct};")
            }
        } else if ret == "void" {
            format!(
                "rustanything.{native}.invoke(\"{}\", void.class{args});",
                f.name
            )
        } else {
            format!(
                "return ({}) rustanything.{native}.invoke(\"{}\", new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type(){args});",
                boxed(ret),
                f.name,
                boxed(ret)
            )
        };
        let method = format!(
            "    /** The Rust port of `{}` (`{}:{}`). */\n    @SuppressWarnings(\"unchecked\")\n    public static {ret} {name}({}) {{\n        {body}\n    }}\n",
            f.prototype.as_deref().unwrap_or(&f.name),
            f.file,
            f.line,
            params.join(", ")
        );
        match classes.iter_mut().find(|(c, _)| *c == class) {
            Some((_, methods)) => methods.push(method),
            None => classes.push((class, vec![method])),
        }
    }
    let imports = imports_of(m);
    classes
        .into_iter()
        .map(|(class, methods)| {
            let (package, simple) = class.rsplit_once('.').unwrap_or(("", class.as_str()));
            let path = if package.is_empty() {
                format!("java/{simple}.java")
            } else {
                format!("java/{}/{simple}.java", package.replace('.', "/"))
            };
            let mut out = String::new();
            if !package.is_empty() {
                let _ = writeln!(out, "package {package};\n");
            }
            out.push_str(&imports);
            let _ = write!(
                out,
                "/** The Rust port of `{simple}`, generated by rust-anything: the same static methods. */\n\
                 public final class {simple} {{\n    private {simple}() {{}}\n\n{}}}\n",
                methods.join("\n")
            );
            (path, out)
        })
        .collect()
}

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

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

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

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

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

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

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

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

    private static final Map<String, Method> METHODS = new LinkedHashMap<>();

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

    /** {"ok": v} | {"error": msg, "error_type": name} | {"invalid": true} | {"missing": true}. */
    @SuppressWarnings("unchecked")
    private static Map<String, Object> call(Map<String, Object> c) {
        Map<String, Object> out = new LinkedHashMap<>();
        Method m = METHODS.get((String) c.get("fn"));
        if (m == null) {
            out.put("missing", true);
            return out;
        }
        List<Object> args = (List<Object>) c.get("args");
        Type[] types = m.getGenericParameterTypes();
        Object[] values = new Object[types.length];
        try {
            for (int i = 0; i < types.length; i++) {
                Object raw = i < args.size() ? args.get(i) : null;
                if (raw instanceof Map && ((Map<?, ?>) raw).containsKey("$undefined")) {
                    raw = null;
                }
                values[i] = RustAnythingJson.convert(raw, types[i]);
            }
        } catch (RustAnythingJson.Mismatch e) {
            out.put("invalid", true);
            return out;
        }
        try {
            Object result = m.invoke(null, values);
            out.put("ok", RustAnythingJson.parse(RustAnythingJson.write(result)));
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            out.put("error", String.valueOf(cause.getMessage()));
            out.put("error_type", cause.getClass().getSimpleName());
        } catch (ReflectiveOperationException e) {
            out.put("error", e.toString());
            out.put("error_type", "ReflectiveOperationException");
        } catch (StackOverflowError e) {
            out.put("error", "stack overflow");
            out.put("error_type", "StackOverflowError");
        }
        return out;
    }

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

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

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

/// Shadow classes, `<Class>Shadow` beside each original class: the same static methods,
/// running the original and the Rust port, returning the original's result and counting
/// mismatches. `-Drust-anything.mode=old` runs the original only, `new` the port only.
pub fn shadows(m: &Manifest, api: &crate::codegen::PortApi) -> Vec<(String, String)> {
    let typed = direct_names(m, api);
    let native = java_native_class(m);
    let mut classes: Vec<(String, Vec<String>)> = Vec::new();
    for f in &m.exports {
        let (class, name) = receiver(f);
        let simple = class.rsplit('.').next().unwrap_or(&class).to_string();
        let ret = f.native_return.as_deref().unwrap_or("void");
        let params: Vec<String> = f
            .params
            .iter()
            .map(|p| {
                format!(
                    "{} {}",
                    p.native_type.as_deref().unwrap_or("Object"),
                    p.name
                )
            })
            .collect();
        let names: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
        let call_args = names.join(", ");
        let native_args = if names.is_empty() {
            String::new()
        } else {
            format!(", {call_args}")
        };
        let type_ref = if ret == "void" {
            "void.class".to_string()
        } else {
            format!(
                "new rustanything.RustAnythingJson.TypeRef<{}>() {{}}.type()",
                boxed(ret)
            )
        };
        let port = if typed.contains(&f.name) {
            format!("rustanything.{native}.call_{}({call_args})", f.name)
        } else {
            format!(
                "rustanything.{native}.invoke(\"{}\", {type_ref}{native_args})",
                f.name
            )
        };
        let method = if ret == "void" {
            format!(
                "    @SuppressWarnings(\"unchecked\")\n    public static void {name}({params}) {{\n        if (MODE.equals(\"new\")) {{\n            {port};\n            return;\n        }}\n\
                 \x20       {simple}.{name}({call_args});\n        if (!MODE.equals(\"old\")) {{\n            try {{\n                {port};\n                compare(\"{name}\", null, null);\n\
                 \x20           }} catch (RuntimeException e) {{\n                compare(\"{name}\", null, e);\n            }}\n        }}\n    }}\n",
                params = params.join(", "),
            )
        } else {
            format!(
                "    @SuppressWarnings(\"unchecked\")\n    public static {ret} {name}({params}) {{\n        if (MODE.equals(\"new\")) {{\n            return ({b}) {port};\n        }}\n\
                 \x20       {ret} expected = {simple}.{name}({call_args});\n        if (!MODE.equals(\"old\")) {{\n            Object actual;\n            try {{\n                actual = {port};\n\
                 \x20           }} catch (RuntimeException e) {{\n                actual = e;\n            }}\n            compare(\"{name}\", expected, actual);\n        }}\n        return expected;\n    }}\n",
                params = params.join(", "),
                b = boxed(ret),
            )
        };
        match classes.iter_mut().find(|(c, _)| *c == class) {
            Some((_, methods)) => methods.push(method),
            None => classes.push((class, vec![method])),
        }
    }
    let imports = imports_of(m);
    classes
        .into_iter()
        .map(|(class, methods)| {
            let (package, simple) = class.rsplit_once('.').unwrap_or(("", class.as_str()));
            let path = if package.is_empty() {
                format!("shadow/{simple}Shadow.java")
            } else {
                format!("shadow/{}/{simple}Shadow.java", package.replace('.', "/"))
            };
            let mut out = String::new();
            if !package.is_empty() {
                let _ = writeln!(out, "package {package};\n");
            }
            out.push_str("import java.util.concurrent.atomic.AtomicLong;\n");
            out.push_str(&imports.replace("\n\n", "\n"));
            let _ = write!(
                out,
                "\n/** Runs `{simple}` and its Rust port side by side. Generated by rust-anything: call it in place of `{simple}`. */\n\
                 public final class {simple}Shadow {{\n    private {simple}Shadow() {{}}\n\n\
                 \x20   private static final String MODE = System.getProperty(\"rust-anything.mode\", \"shadow\");\n\
                 \x20   public static final AtomicLong CALLS = new AtomicLong();\n    public static final AtomicLong MISMATCHES = new AtomicLong();\n\n\
                 \x20   private static void compare(String name, Object expected, Object actual) {{\n        CALLS.incrementAndGet();\n\
                 \x20       if (actual instanceof Throwable || !rustanything.RustAnythingJson.write(expected).equals(rustanything.RustAnythingJson.write(actual))) {{\n\
                 \x20           if (MISMATCHES.incrementAndGet() <= 10) {{\n                System.err.println(\"[rust-anything] mismatch in \" + name + \": expected \" + expected + \", got \" + actual);\n            }}\n        }}\n    }}\n\n{}}}\n",
                methods.join("\n")
            );
            (path, out)
        })
        .collect()
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

use crate::wire::Ty;

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

/// The wire type of a Java type; `None` for types the wire does not carry.
fn java_ty(t: &str) -> Option<Ty> {
    let t = t.trim();
    let boxed = |inner: Ty| Ty::Opt {
        inner: Box::new(inner),
        native: t.to_string(),
    };
    Some(match t {
        "int" | "long" | "short" | "byte" => Ty::I64(t.into()),
        "double" | "float" => Ty::F64(t.into()),
        "boolean" => Ty::Bool,
        "String" | "CharSequence" => Ty::Str,
        "Integer" => boxed(Ty::I64("int".into())),
        "Long" => boxed(Ty::I64("long".into())),
        "Short" => boxed(Ty::I64("short".into())),
        "Byte" => boxed(Ty::I64("byte".into())),
        "Double" => boxed(Ty::F64("double".into())),
        "Float" => boxed(Ty::F64("float".into())),
        "Boolean" => boxed(Ty::Bool),
        _ => {
            if let Some(item) = t.strip_suffix("[]") {
                let item_ty = java_ty(item)?;
                // Primitive arrays need a helper; reference arrays use a generic one.
                if matches!(item_ty, Ty::I64(_) | Ty::F64(_) | Ty::Bool)
                    && !matches!(item.trim(), "int" | "long" | "double" | "boolean")
                {
                    return None;
                }
                return Some(Ty::List {
                    item: Box::new(item_ty),
                    native: t.into(),
                    array: true,
                });
            }
            let (head, args) = split_generic(t)?;
            match head.rsplit('.').next().unwrap_or(head) {
                "List" | "ArrayList" | "Collection" | "Iterable" | "LinkedList" => Ty::List {
                    item: Box::new(java_ty(args.first()?)?),
                    native: t.into(),
                    array: false,
                },
                "Map" | "LinkedHashMap" | "HashMap" | "TreeMap" if args.first()? == "String" => {
                    Ty::Map {
                        value: Box::new(java_ty(args.get(1)?)?),
                        native: t.into(),
                    }
                }
                "Optional" => Ty::Opt {
                    inner: Box::new(java_ty(args.first()?)?),
                    native: t.into(),
                },
                _ => return None,
            }
        }
    })
}

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

/// A Java expression reading a value of type `t` from reader `r`.
fn java_dec(t: &Ty) -> Option<String> {
    Some(match t {
        Ty::I64(n) => match n.as_str() {
            "long" => "r.i64()".into(),
            other => format!("(({other}) r.i64())"),
        },
        Ty::F64(n) => match n.as_str() {
            "float" => "((float) r.f64())".into(),
            _ => "r.f64()".into(),
        },
        Ty::Bool => "r.bool()".into(),
        Ty::Str => "r.str()".into(),
        Ty::Opt { inner, native } if native.starts_with("Optional") => {
            let arg = split_generic(native)?.1.first()?.clone();
            format!(
                "(r.tag() == 0 ? java.util.Optional.<{arg}>empty() : java.util.Optional.of({}))",
                java_dec(inner)?
            )
        }
        Ty::Opt { inner, native } => {
            format!("(r.tag() == 0 ? null : ({native}) {})", java_dec(inner)?)
        }
        Ty::List {
            item,
            native,
            array: true,
        } => match native.trim_end_matches("[]") {
            "int" => "r.ints()".into(),
            "long" => "r.longs()".into(),
            "double" => "r.doubles()".into(),
            "boolean" => "r.booleans()".into(),
            elem => format!("r.array(() -> {}, {elem}[]::new)", java_dec(item)?),
        },
        Ty::List { item, .. } => format!("r.list(() -> {})", java_dec(item)?),
        Ty::Map { value, .. } => format!("r.map(() -> {})", java_dec(value)?),
        _ => return None,
    })
}

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

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

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

    public final String type;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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