javars 0.1.2

Java as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk, run on the shared three-tier Cranelift JIT — no bespoke VM or JVM
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
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
//! The javars host: builtin registration, Java value formatting, and the strict
//! numeric hook.
//!
//! javars keeps no object heap of its own yet (slice 1 runs on the fusevm value
//! model directly). Two places need Java semantics that fusevm's default
//! awk/shell flavour does not provide:
//!
//! 1. **Printing.** fusevm's native `PrintLn` renders values shell-style
//!    (`true`→`1`, `3.0`→`3`). `System.out.print[ln]` instead lowers to a
//!    registered builtin ([`JPRINTLN`]/[`JPRINT`]) that formats through
//!    [`java_str`] — `true`/`false`, `3.0`, `null` — matching `java`.
//! 2. **`+` overloading, and the arithmetic fusevm declines to answer.** Java's
//!    `+` is string concatenation when either operand is a `String`. fusevm runs
//!    *strict* once a numeric hook is installed, delegating to [`numeric_hook`]
//!    both any operation with a non-numeric operand — where `+` concatenates via
//!    the same [`java_str`] — and the numeric pairs it cannot answer exactly: an
//!    `i64` overflow, and a mixed `Int`/`Float` pair whose integer is past 2^53.
//!    The numeric pairs get Java's `long` wrapping and binary numeric promotion,
//!    never a concatenation; see `java_numeric`.

use fusevm::{NumOp, Value, VM};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;

/// Builtin id for `System.out.println` (one Java-formatted arg + newline).
pub const JPRINTLN: u16 = 700;
/// Builtin id for `System.out.print` (one Java-formatted arg, no newline).
pub const JPRINT: u16 = 701;
/// Builtin id for the `--dap` per-statement line marker. Emitted only by
/// [`crate::compiler::compile_debug`]; a normal run never carries it.
pub const DBG_LINE: u16 = 702;
/// Builtin id for compiling + registering an inline `rust { ... }` FFI block.
/// The desugar target `__rust_compile("<base64>", line)` lowers to a call of
/// this builtin: it pops the base64 block body and hands it to
/// `fusevm::ffi::compile_and_register`. Returns `null` (Java `Unit`).
pub const JFFI_COMPILE: u16 = 703;
/// Builtin id for calling an FFI-exported function by name. The stack holds the
/// arguments (deepest first) with the function name (a `Str`) on top; `argc` is
/// the total stack items (`args + 1`). Dispatches through `fusevm::ffi::try_call`
/// and returns the result.
pub const JFFI_CALL: u16 = 704;
/// Builtin id for an instance method call on a `String` receiver. The stack
/// holds `[recv, arg0, …, argN, methodName]` (the method name — a `Str` — on
/// top); `argc` counts every one of those items (`recv + args + name`).
/// Dispatches through `b_str_dispatch` to the `java.lang.String` method of
/// that name, returning its result.
pub const JSTR_DISPATCH: u16 = 705;
/// Builtin id for `System.err.println` (one Java-formatted arg + newline, on
/// stderr).
pub const JEPRINTLN: u16 = 706;
/// Builtin id for `System.err.print` (one Java-formatted arg, no newline, on
/// stderr).
pub const JEPRINT: u16 = 707;
/// Builtin id for a static stdlib method call (`Math.*`, `Integer.*`,
/// `String.valueOf`, …). The stack holds `[arg0, …, argN, className,
/// methodName]` (the method name — a `Str` — on top, the class name below it);
/// `argc` counts the args plus those two names. Dispatches through
/// `b_static_dispatch` to `static_method`, returning its result.
pub const JSTATIC_DISPATCH: u16 = 708;

// ── Host object heap builtins (reference arrays + class instances) ──
// `Value::Obj(u32)` is an opaque handle into [`HEAP`]; these builtins are the
// only code that dereferences it. Aliasing is by reference: passing an `Obj`
// copies the u32 handle, and a mutating builtin edits the shared heap object.

/// `new T[n]` — allocate a default-valued array. Stack `[size, default]`
/// (`default` on top); `argc == 2`. Pushes the array `Obj` handle.
pub const JARRAY_NEW: u16 = 709;
/// `{a, b, …}` array literal — pop `argc` element values (deepest first) and
/// push a fresh array `Obj`.
pub const JARRAY_LIT: u16 = 710;
/// `a[i]` element read. Stack `[array, index]` (`index` on top); `argc == 2`.
/// Pushes the element; an out-of-range index faults (`ArrayIndexOutOfBounds`).
pub const JARRAY_GET: u16 = 711;
/// `a[i] = v` element write. Stack `[array, index, value]` (`value` on top);
/// `argc == 3`. Mutates the heap array; returns `value`.
pub const JARRAY_SET: u16 = 712;
/// `new C(...)` instance allocation. Stack `[className]`; `argc == 1`. Pushes a
/// fresh instance `Obj` with an empty field map (the compiler emits field-init
/// and constructor calls after).
pub const JNEW: u16 = 713;
/// `recv.field` read — an array's `.length` or an instance field. Stack
/// `[recv, name]` (`name` on top); `argc == 2`. Pushes the value (`null`/`Undef`
/// for an absent instance field).
pub const JFIELD_GET: u16 = 714;
/// `recv.field = v` write. Stack `[recv, name, value]` (`value` on top);
/// `argc == 3`. Mutates the heap instance; returns `value`.
pub const JFIELD_SET: u16 = 715;
/// `x instanceof C` — stack `[obj, className]` (`className` on top);
/// `argc == 2`. Pushes a `Bool`: true when `obj` is a non-null instance whose
/// class is `C` or a subclass. Subclass links are resolved through `SUPERS`.
pub const JINSTANCEOF: u16 = 716;
/// Runtime class name of an instance. Stack `[obj]`; `argc == 1`. Pushes the
/// instance's class name as a `Str` (empty for a non-instance). Drives the
/// compiler's virtual method-dispatch chain.
pub const JCLASSOF: u16 = 717;
/// `new T[s0][s1]…` — allocate a rectangular multi-dimensional array. Stack
/// `[s0, s1, …, sK, leafDefault]` (`leafDefault` on top); `argc == K + 2`.
/// Builds `K+1` nested levels of default-valued arrays and pushes the outer
/// handle. Aliasing is by reference like any other array.
pub const JARRAY_NEW_MULTI: u16 = 718;

/// Builtin id for Java floating-point division. Java `/` on a floating operand
/// follows IEEE-754 — `x / 0.0` is a signed infinity and `0.0 / 0.0` is NaN,
/// never a fault — whereas fusevm's native `Op::Div` yields `Undef` for a zero
/// divisor (its shell/awk flavour has no infinities). Statically-integral
/// division keeps the native op so the JIT can still trace it; only the
/// floating path routes through here.
pub const JDIV: u16 = 719;

/// Builtin id for Java's 64-bit integral division (`long / long`).
///
/// fusevm's native `Op::Div` computes in `f64` and javars truncates the result
/// with `Op::TruncInt`. For two `int`-width operands that is exact — both fit a
/// `f64` mantissa, and the quotient's distance to the nearest integer is at
/// least `1/|b| >= 2^-31` while the rounding error is at most `|a| * 2^-53 <=
/// 2^-22 * 2^-31`, so the rounding can never cross an integer boundary — and
/// the compiler keeps the native pair there so the JIT can trace it.
///
/// A `long` operand breaks both halves of that argument. Above 2^53 the operand
/// itself no longer survives the round trip, so `9007199254740993L / 1`
/// answered 9007199254740992, and `Long.MAX_VALUE / 2` answered
/// 4611686018427387904 for a true quotient of 4611686018427387903. Separately,
/// `Long.MIN_VALUE / -1` overflows to 2^63 as a float and `TruncInt` *saturates*
/// to `i64::MAX`, where Java wraps back to `Long.MIN_VALUE`. So 64-bit integral
/// division routes here instead and divides in `i64`.
pub const JIDIV: u16 = 745;

/// `new StringBuilder(…)` / `new StringBuffer(…)` — stack `[kind, arg]`, where
/// `kind` is the class's simple name and `arg` is the constructor's single
/// argument (`Undef` for the no-arg form). Which constructor that is is read
/// from the value: an `Int` is the capacity, anything else is the initial
/// content, which is exactly the split Java's `(int)` / `(String)` /
/// `(CharSequence)` overloads make.
///
/// Every method on the builder goes through [`JSTR_DISPATCH`] like any other
/// erased receiver; only allocation needs a builtin of its own, because the
/// object is a host shape rather than a class instance.
pub const JSB_NEW: u16 = 746;

// ── Exception builtins (`throw` / `try` / `catch` / `finally`) ──
// fusevm has no unwind opcode, so javars models the in-flight exception as a
// host-side pending value plus a compiler-emitted check after every `Op::Call`.
// A `throw` parks the throwable in [`PENDING`] and the compiler jumps to the
// innermost handler in the current frame — or, when there is none, returns out
// of the frame so the caller's post-call check sees the pending value and
// repeats. That is the same "bubble the flag at every call site" contract the
// sibling frontends use; only the unwind step differs, because javars's calls
// are real fusevm call frames rather than nested VMs.

/// `throw e` — stack `[throwable]`; `argc == 1`. Parks the value as the pending
/// exception and returns `null`. The compiler emits the jump to the handler (or
/// the frame exit) immediately after.
pub const JTHROW: u16 = 720;
/// Is an exception in flight? `argc == 0`; pushes a `Bool`. Emitted after every
/// `Op::Call` in a program that uses exceptions.
pub const JEXC_PENDING: u16 = 721;
/// Take the pending exception (clearing it). `argc == 0`; pushes the throwable
/// (or `null` when none). Emitted at the top of a handler.
pub const JEXC_TAKE: u16 = 722;
/// The current value-stack depth. `argc == 0`; pushes an `Int`. Recorded on
/// entry to a `try` so the handler can discard the operands of the expression
/// the throw abandoned.
pub const JEXC_DEPTH: u16 = 723;
/// Truncate the value stack to a depth recorded by [`JEXC_DEPTH`]. Stack
/// `[depth]`; `argc == 1`.
pub const JEXC_CUT: u16 = 724;
/// Report an uncaught exception and halt. `argc == 0`. Formats Java's
/// `Exception in thread "main" <qualified class>: <message>` line and faults, so
/// the process exits non-zero the way `java` does.
pub const JEXC_ABORT: u16 = 725;
/// Raise a runtime fault the compiler detected inline (`int / 0`). Stack
/// `[className, message]`; `argc == 2`. Goes through the same `raise` path a
/// host-detected fault does, so the throwable is catchable.
pub const JFAULT: u16 = 726;

/// Builtin id for `main`'s `String[] args` — a fresh Java array of the program
/// arguments the CLI collected. Called once by the compiler's prologue, so the
/// array the program sees is its own (mutating it cannot affect a later read).
pub const JARGV: u16 = 727;

// ── Lambdas ──
// A lambda outlives the frame it was written in, but a javars local lives in a
// fusevm call-frame slot that does not. So a lambda becomes a heap closure that
// snapshots every enclosing local **by value** at the point the literal runs.
// Java only lets a lambda capture effectively-final locals, so a snapshot is
// observationally exact — and it is the only model that gives the enhanced
// `for` its per-iteration capture.

/// Build a closure. Stack `[cap0, …, capK, nameIdx, params, ncap]` (`ncap` on
/// top); `argc == ncap + 3`. `nameIdx` is the chunk name index of the lambda
/// body's subroutine and `params` its declared parameter count. Pushes the
/// closure's `Obj` handle.
pub const JMAKE_CLOSURE: u16 = 728;
/// Invoke a closure. Stack `[closure, arg0, …, argN]` (last argument on top);
/// `argc == N + 2` (the closure plus its arguments). Runs the body in its own
/// fusevm call frame through a nested `VM::run` and pushes its result.
pub const JCLOSURE_CALL: u16 = 729;

/// The runtime "class" [`JCLASSOF`] reports for a closure. `#` is not a legal
/// Java identifier character, so a user class can never collide with it; the
/// compiler's virtual-dispatch chain uses it as the arm that routes a
/// functional-interface call to the lambda body.
pub const LAMBDA_CLASS: &str = "#lambda";

// ── java.util collections ──

/// `new ArrayList<>()` / `new HashMap<>()` / … — allocate an empty collection.
/// Stack `[kindName, seedOrUndef]` (`seed` on top); `argc == 2`. `seed` is the
/// collection or array a copy constructor was given, or `null`. Pushes the
/// collection's `Obj` handle.
pub const JCOLL_NEW: u16 = 730;
/// An instance method on a collection receiver. Stack
/// `[recv, arg0, …, argN, methodName]` (`methodName` on top); `argc` counts all
/// of them. Same shape as [`JSTR_DISPATCH`], which is what routes a
/// statically-untyped receiver here.
pub const JCOLL_DISPATCH: u16 = 731;
/// The elements of an enhanced-`for` iterable, as a Java array. An array
/// receiver is returned unchanged; a collection is snapshotted into a fresh
/// array. Stack `[iterable]`; `argc == 1`. Emitted only when the compiler could
/// not prove the iterable is already an array, so array loops are unchanged.
pub const JITER_ARRAY: u16 = 732;

/// `>>>` — the logical (zero-fill) right shift. Stack `[value, count, width]`
/// (`width` on top, 32 or 64); `argc == 3`. fusevm's `Op::Shr` is always
/// arithmetic on 64 bits, so an `int` `>>>` — which must zero-fill at 32 — has
/// no native spelling; the compiler has already masked `count` to the operand's
/// width before the call.
pub const JUSHR: u16 = 733;

/// A narrowing primitive cast, `(ty) value`. Stack `[value, tyName]`
/// (`tyName` on top); `argc == 2`. Java's narrowing conversions are real value
/// changes: `(int) 3.9` truncates toward zero, `(int) 1e18` *saturates* to
/// `Integer.MAX_VALUE`, `(byte) 200` wraps to -56, and `(char) 70000` wraps to
/// its low 16 bits. Widening and identity casts never reach here — the compiler
/// emits the operand alone.
pub const JCAST: u16 = 734;

/// Java's *string conversion* of a `char` (JLS 5.1.11): the code point becomes
/// the one-character String. `argc == 1`. A `char` runs as an integer so that
/// `'a' + 1` is 98, and the compiler emits this at every point where the value
/// crosses into a String — `println(c)`, `"x" + c`, `String.valueOf(c)`, a
/// `String`-method argument — and where a `char` is boxed to a `Character` (a
/// collection element, which javars models as the one-character String). A
/// `char[]` operand converts element-wise, which is what makes
/// `Arrays.toString(s.toCharArray())` print `[a, b, c]`. Any other value passes
/// through unchanged.
pub const JCHR_STR: u16 = 735;

/// A checked *reference* cast, `(RefType) value`. Stack `[value, typeName]`
/// (`typeName` on top); `argc == 2`. The cast changes no representation — the
/// host heap already carries each object's class — so all it does is verify
/// one, raising `ClassCastException` when the runtime class is not the target
/// or a subtype of it. `null` casts to anything, and a value whose runtime
/// class javars cannot name exactly (an array, a collection, a lambda) passes
/// through unchecked rather than inventing a failure.
pub const JCHECKCAST: u16 = 736;

/// Round the top-of-stack value to 32-bit `float` precision. `argc == 1`.
///
/// fusevm has one floating representation (`f64`), so Java's `float` is modeled
/// as a `double` that is *kept* at `f32` precision: the compiler emits this
/// after every arithmetic operation whose static Java type is `float`, which is
/// what makes `1.0f / 3.0f` the `f32` 0.33333334 rather than the `f64` answer.
/// The same per-site narrowing the 32-bit `int` wrap uses, one width down.
pub const JF32: u16 = 737;

/// `Float.toString` of the top-of-stack value. `argc == 1`.
///
/// A `float` and a `double` holding the same bits print differently — Java's
/// shortest-round-trip is computed against the *type's* precision, so `0.1f`
/// prints `0.1` where the `double` with those bits prints
/// `0.10000000149011612`. The value model cannot tell them apart, so the
/// compiler emits this wherever a statically-`float` value crosses into a
/// String. A `float[]` operand converts element-wise.
pub const JF32_STR: u16 = 738;

/// One arithmetic operation performed at 32-bit `float` width. Stack
/// `[lhs, rhs, op]` (`op` on top, one of the [`f32_op`] constants); `argc == 3`.
///
/// Rounding the `f64` result afterwards is *not* the same computation: a double
/// rounding can land a ulp away from the single one Java performs.
/// `16777217.0f * 0.2f` is 3355443.2 in Java and 3355443.3 if the product is
/// formed in `f64` first. So a `float` operation is done in `f32` throughout,
/// which is why it costs a builtin rather than a native op — the only Java
/// arithmetic in javars that does.
pub const JF32_ARITH: u16 = 739;

/// `Math.round(float)` of the top-of-stack value. `argc == 1`.
///
/// `Math.round` is two methods in Java, and they do not agree: the `double` one
/// answers a `long`, the `float` one an `int`. Only the compiler knows which
/// overload a call site selected, and the difference is observable at the
/// extremes — `Math.round(1.0e20f)` is `Integer.MAX_VALUE` where the `double`
/// overload's answer is `Long.MAX_VALUE`. So a statically-`float` argument
/// routes here instead of through [`JSTATIC_DISPATCH`], the same reason
/// [`JF32_ARITH`] exists.
pub const JF32_ROUND: u16 = 743;

/// `x.getClass()` — the Java *binary* name of a value's runtime class. Stack
/// `[value, arrayDescriptor]` (the descriptor on top); `argc == 2`.
///
/// Distinct from [`JCLASSOF`], which answers the bare class name the compiler's
/// virtual-dispatch chain compares against and the empty string for everything
/// that is not a user instance. That was also what `getClass()` returned, so
/// `new ArrayList<>().getClass().getName()` printed nothing — while
/// `binary_name`, reached only from the `ClassCastException` message, already
/// knew the answer was `java.util.ArrayList`. The two now share it.
///
/// The descriptor argument carries what the *value* cannot: an array's element
/// type is erased at runtime, so `[I` versus `[Ljava.lang.String;` is knowable
/// only from the receiver's static type, which the compiler supplies. It is the
/// empty string when the receiver is not statically an array.
pub const JBINARY_CLASS: u16 = 744;

/// Box a primitive into its `java.lang` wrapper. Stack `[value, class]`
/// (`class` on top, an index into [`BOX_CLASSES`]); `argc == 2`.
///
/// Emitted wherever Java performs a *boxing conversion* — assigning an `int`
/// expression to an `Integer`, `Integer.valueOf(x)`, a cast to a wrapper type.
/// The result is a heap handle, so `==` on two of them is reference identity,
/// which is what the language says it is.
pub const JBOX: u16 = 747;

/// `new String(x)` — a `String` with an **identity of its own**. Stack
/// `[text]`; `argc == 1`.
///
/// Java's `String` is a reference type, so `new String("ab") == "ab"` is
/// `false`: the constructor is specified to produce a *fresh* object, which is
/// the only reason the expression is ever written. A `String`'s identity here
/// is its `Arc`, so this re-allocates the text — every other path that
/// *produces* a string already allocates, and this is the one path that would
/// otherwise pass an existing object through.
pub const JNEW_STRING: u16 = 749;

/// Unbox a wrapper back to its primitive; the identity function on a value that
/// is not boxed. Stack `[value]`; `argc == 1`.
///
/// Emitted wherever Java performs an *unboxing conversion* — assigning an
/// `Integer` expression to an `int`, passing one to a primitive parameter — so
/// that a later `==` between two such variables compares numbers rather than
/// the handles they were copied from.
pub const JUNBOX: u16 = 748;

/// `Comparable.compareTo` on a receiver that is not a user class instance.
/// Stack `[recv, arg, tag]` (`tag` on top); `argc == 3`.
///
/// Every boxed type spells `compareTo` differently and the answers are not
/// interchangeable: `Integer`/`Long` return the *sign* only, `Byte`/`Short`/
/// `Character` return the arithmetic difference, `Double`/`Float` go through
/// `Double.compare` (so `NaN` sorts above everything and `-0.0` below `0.0`),
/// `Boolean` is `false < true`, and `String` is the first differing `char`'s
/// difference. Routing them all through the `String` method — which is what
/// happened before this builtin existed — answered `Integer.valueOf(10)
/// .compareTo(9)` with `-8` (`'1' - '9'`) where Java answers `1`.
///
/// `tag` is the receiver's static Java type when the compiler knew it, else the
/// empty string, in which case the runtime value picks the rule.
pub const JCOMPARE_TO: u16 = 740;

/// `String.format(fmt, args…)`. Stack `[fmt, arg0, …, argN, tags]` (`tags` on
/// top); `argc == N + 2`.
///
/// `java.util.Formatter` type-checks every conversion against the *boxed class*
/// of its argument and throws `IllegalFormatConversionException` on a mismatch
/// — `%d` of a `Double`, `%f` of an `Integer`, `%c` of a `String`. fusevm's
/// value model cannot supply that class: one `Value::Int` stands for `Integer`,
/// `Long`, `Short`, `Byte` and `char` alike. So the compiler, which does know
/// each argument's static Java type, sends the boxed class names along in
/// `tags` — one per argument, `\x1f`-separated, an empty entry where the type
/// was not inferable (a lambda parameter, an erased `List.get`). The runtime
/// value picks the class for those.
pub const JFORMAT: u16 = 741;

/// Java's string conversion of one value, run with a VM in hand so a user
/// `toString()` override can be called. Stack `[value]`; `argc == 1`.
///
/// The compiler emits this only for a concatenation operand whose static type
/// does not name a user class (an `Object`, an erased `get()`) *and* only when
/// the program declares an override somewhere — see
/// [`Compiler::emit_stringified`](crate::compiler). Without it the operand
/// would reach fusevm's `Op::Add`, whose `NumericHook` takes three values and
/// no VM, so the override could not run and `"" + o` would disagree with
/// `println(o)` for the same object.
pub const JSTRINGIFY: u16 = 742;

/// The overload-width codes a `Math` static that is overloaded on width takes
/// as its extra operand, shared with the compiler.
///
/// `Math.addExact` and friends are declared at `int` *and* `long`, and
/// `Math.clamp` at four widths; the two integral ones disagree exactly where
/// the method is interesting (`Math.addExact(2000000000, 2000000000)` throws
/// for the `int` overload and answers 4000000000 for the `long` one). Java
/// resolves that from the arguments' static types, which only the compiler has,
/// so it sends the answer along.
pub mod width {
    /// `int`.
    pub const INT: i64 = 0;
    /// `long`.
    pub const LONG: i64 = 1;
    /// `float` — `Math.clamp` only.
    pub const FLOAT: i64 = 2;
    /// `double` — `Math.clamp` only.
    pub const DOUBLE: i64 = 3;
}

/// The [`JF32_ARITH`] operator codes, shared with the compiler.
pub mod f32_op {
    pub const ADD: i64 = 0;
    pub const SUB: i64 = 1;
    pub const MUL: i64 = 2;
    pub const DIV: i64 = 3;
    pub const REM: i64 = 4;
}

/// One object on the host-owned Java heap. `Value::Obj(id)` indexes [`HEAP`].
enum HostObj {
    /// A Java reference array (`int[]`, `String[]`, `Point[]`, …). Element type
    /// is erased at runtime — the compiler sets each slot's default on creation.
    Array(Vec<Value>),
    /// A class instance: its runtime class name and its instance fields.
    Instance {
        class: String,
        fields: HashMap<String, Value>,
    },
    /// A lambda: the chunk name index of its body subroutine, its declared
    /// parameter count, and the enclosing locals it snapshotted by value. The
    /// body's prologue expects the parameters first, then the captures.
    Closure {
        name_idx: u16,
        params: u8,
        captures: Vec<Value>,
    },
    /// A `java.util.List` (`ArrayList`) — elements in list order.
    List {
        items: Vec<Value>,
        fixed: Fixity,
        /// Structural-modification counter, Java's `AbstractList.modCount`.
        /// Every `add`/`remove`/`clear` and every `sort` bumps it; a `subList`
        /// view snapshots it and refuses to operate once it has moved, which is
        /// how Java reports a view whose backing list changed underneath it.
        mods: u64,
    },
    /// A `List.subList(from, to)` **view**. It owns no elements: every read and
    /// write goes to the window `[offset, offset + len)` of `parent`, which is
    /// itself either a `List` or another view. That is what makes the aliasing
    /// real in both directions — a write through the parent shows in the view
    /// and a write through the view shows in the parent — rather than the copy
    /// that would answer correctly right up until someone wrote to it.
    SubList {
        parent: u32,
        offset: usize,
        len: usize,
        /// The backing list's `mods` when this view was created. A mismatch is
        /// Java's `ConcurrentModificationException`.
        exp_mods: u64,
    },
    /// A `java.util.Map`. Entries are stored in *insertion* order whatever the
    /// implementation; [`Order`] decides what order iteration and `toString`
    /// present them in.
    Map {
        entries: Vec<(Value, Value)>,
        order: Order,
        /// The same distinction [`HostObj::List`] draws: `Map.of` is an
        /// immutable map, not a `HashMap`. Without it a `Map.of` value was
        /// indistinguishable from `new HashMap<>()`, so it answered
        /// `instanceof HashMap` `true` (Java: `false`) and accepted
        /// `put`/`remove`/`clear` silently (Java:
        /// `UnsupportedOperationException`).
        fixed: Fixity,
        /// Key -> position accelerator; see [`KeyIndex`].
        index: KeyIndex,
    },
    /// A `java.util.Set`, stored and ordered exactly like [`HostObj::Map`].
    ///
    /// `fixed` carries the same distinction [`HostObj::List`] draws: `Set.of` is
    /// an immutable set, not a `HashSet`. Without it a `Set.of` value was
    /// indistinguishable from `new HashSet<>()`, so it answered `instanceof
    /// HashSet` `true` (Java: `false`) and accepted `add`/`remove`/`clear`
    /// silently (Java: `UnsupportedOperationException`). Only `Mutable` and
    /// `Immutable` occur — there is no `Arrays.asSet` to produce a fixed-size
    /// one — but the shared vocabulary keeps the two collections' guards
    /// identical.
    Set {
        items: Vec<Value>,
        order: Order,
        fixed: Fixity,
        /// Element -> position accelerator; see [`KeyIndex`].
        index: KeyIndex,
    },
    /// A `java.lang.StringBuilder` (or `StringBuffer`) — the mutable character
    /// sequence, which `+` concatenation cannot stand in for once a program
    /// builds one in a loop.
    ///
    /// `cap` tracks `capacity()` rather than Rust's own allocation, because it
    /// is *observable*: the JDK starts at 16 (plus the initial content's
    /// length), and grows to `2 * old + 2` or the required size, whichever is
    /// larger. A `Vec`'s growth policy would answer a different number.
    Builder {
        s: String,
        /// `s.chars().count()`, maintained by every mutation.
        ///
        /// Recomputing it per call made `append` — the one method a builder
        /// exists for — walk the whole buffer every time, so building a string
        /// of n characters cost O(n²): 400k appends took 9.96s of CPU against
        /// 0.30s for 50k, where linear would be 2.4s. It also answers "is this
        /// buffer all ASCII?" in O(1) (`s.len() == len`, since UTF-8 spends one
        /// byte per character exactly then), which is what lets `charAt` and
        /// the rest index by byte instead of decoding to the i-th character.
        len: usize,
        cap: usize,
        /// `true` for a `StringBuffer`, which differs from `StringBuilder` only
        /// in its class name here: javars runs one thread, so the synchronized
        /// methods are unobservable.
        buffer: bool,
    },
    /// A boxed primitive — `java.lang.Integer` and its seven siblings.
    ///
    /// Java's wrapper types are *reference* types, and `==` on two of them is
    /// reference identity, not value equality. A bare [`Value::Int`] cannot
    /// carry an identity, so `Integer a = 128, b = 128; a == b` answered `true`
    /// where Java answers `false`. Putting the box on the heap gives it the
    /// identity the language says it has, and gives it a *class* besides:
    /// `Integer.valueOf(1).equals(Long.valueOf(1))` is `false` in Java and one
    /// `Value::Int` could not tell the two apart.
    ///
    /// `v` is the primitive it wraps — `Value::Int` for the five integral
    /// classes, `Value::Float` for `Float`/`Double`, `Value::Bool` for
    /// `Boolean`. Every numeric surface unboxes it (see [`unboxed`]), so the
    /// box is observable only where Java makes it observable: `==`, `equals`,
    /// `hashCode`, and `getClass`.
    /// A `java.util.Iterator` over a `List` or a `Set`.
    ///
    /// It reads its source *live* rather than snapshotting it, which is what
    /// makes `remove()` write through and — for a `List`, the one collection
    /// that carries a `mods` counter — makes a structural change underneath the
    /// iterator the `ConcurrentModificationException` Java raises rather than a
    /// silent walk of stale elements.
    Iterator {
        /// The collection being walked.
        source: u32,
        /// The index `next()` will return.
        pos: usize,
        /// The index `next()` last returned, which `remove()` deletes. `None`
        /// before the first `next()` and after a `remove()`, both of which make
        /// `remove()` an `IllegalStateException` in Java.
        last: Option<usize>,
        /// The source `List`'s `mods` when this iterator was created, bumped by
        /// its own `remove()`. Always 0 for a `Set`, which has no counter — see
        /// the note in `iterator_method`.
        exp_mods: u64,
    },
    /// A `java.util.Optional` — present with a value, or empty.
    ///
    /// A *value* in Java (`Optional.of("x").equals(Optional.of("x"))` is
    /// `true`) but still a reference: two `Optional.of("x")` are distinct
    /// objects, so `==` between them is `false`. Both fall out of the heap
    /// object — `equals` compares the contents, `==` the handles.
    ///
    /// `class` is `Optional` or one of the three primitive specializations
    /// (`OptionalInt`, `OptionalLong`, `OptionalDouble`), which differ in their
    /// rendering (`OptionalDouble[4.0]`) and in the name of their accessor
    /// (`getAsDouble` rather than `get`).
    Optional {
        class: &'static str,
        value: Option<Value>,
    },
    /// A `java.util.stream.Stream` — a source and the pipeline built over it.
    ///
    /// Nothing is evaluated until a terminal operation runs, which is what Java
    /// specifies and what a program can *see*: `l.stream().peek(p).limit(2)`
    /// calls `p` twice, not once per source element.
    Stream {
        source: Vec<Value>,
        stages: Vec<Stage>,
        kind: StreamKind,
    },
    /// A `java.util.stream.Collector`, as the recipe `collect` will run.
    Collector {
        kind: &'static str,
        args: Vec<Value>,
    },
    /// A marker: the payload lives in [`BOXES`], not here.
    ///
    /// Both halves — the class and the primitive — are read from surfaces that
    /// already hold a borrow of this heap: a boxed element inside a `List` is
    /// compared while the list itself is borrowed, so reading the box out of
    /// `HEAP` would be a re-entrant borrow and panic. A separate `RefCell`
    /// cannot collide with this one. The slot is still allocated here so a box
    /// owns a handle no other object can be given, which is what makes `==` on
    /// two of them mean anything.
    Boxed,
}

/// One stage of a stream pipeline, in the order the program wrote them.
///
/// `Distinct` and `Sorted` are *stateful barriers*: neither can answer for an
/// element without having seen every element before it, so the pipeline is
/// evaluated in segments split at them — which is what Java's own
/// implementation does, and why `peek` before a `sorted` runs for every element
/// while `peek` before a `limit` does not.
#[derive(Clone)]
enum Stage {
    /// `filter(p)` — keep the elements `p` accepts.
    Filter(Value),
    /// `map(f)` / `mapToInt(f)` / `mapToObj(f)` — one element in, one out.
    Map(Value),
    /// `flatMap(f)` — one element in, the elements of the stream `f` answers out.
    FlatMap(Value),
    /// `peek(f)` — run `f` for its effect and pass the element through.
    Peek(Value),
    /// `limit(n)` — pass at most `n` elements, then end the pipeline.
    Limit(i64),
    /// `skip(n)` — drop the first `n`.
    Skip(i64),
    /// `distinct()` — a barrier.
    Distinct,
    /// `sorted()` / `sorted(cmp)` — a barrier.
    Sorted(Option<Value>),
}

/// Which of the four stream shapes a pipeline is, which decides what its
/// terminals answer: `IntStream.max()` is an `OptionalInt` and
/// `DoubleStream.max()` an `OptionalDouble`, where `Stream.max(cmp)` is a plain
/// `Optional`.
#[derive(Clone, Copy, PartialEq, Eq)]
enum StreamKind {
    /// `Stream<T>`.
    Ref,
    /// `IntStream`.
    Int,
    /// `LongStream`.
    Long,
    /// `DoubleStream`.
    Double,
}

impl StreamKind {
    /// The `Optional` class this shape's `min`/`max`/`findFirst` answers.
    fn optional_class(self) -> &'static str {
        match self {
            StreamKind::Ref => "Optional",
            StreamKind::Int => "OptionalInt",
            StreamKind::Long => "OptionalLong",
            StreamKind::Double => "OptionalDouble",
        }
    }
}

/// The eight wrapper classes, indexed by the code the compiler passes [`JBOX`].
///
/// The order is fixed: `JBOX`'s first argument is an index into this table, so
/// reordering it would silently rebox every literal as a different class.
/// `Boolean` is deliberately absent. Its cache covers `true` and `false` both,
/// so every autoboxed `Boolean` pair Java can produce is already the same
/// object and `==` on them is always `true` — boxing it would buy no fidelity
/// while putting a heap handle where the VM tests truth, which is not a numeric
/// surface and so would not unbox.
pub const BOX_CLASSES: [&str; 7] = [
    "Integer",
    "Long",
    "Short",
    "Byte",
    "Character",
    "Float",
    "Double",
];

/// The index into [`BOX_CLASSES`] a wrapper class name boxes as, or `None` for
/// a name that is not a wrapper. The compiler and the host share this so a
/// spelling can never mean one class on one side and another on the other.
pub fn box_class_code(name: &str) -> Option<i64> {
    BOX_CLASSES
        .iter()
        .position(|c| *c == name)
        .map(|i| i as i64)
}

/// A hashable stand-in for the [`Value`]s a `Map` key or a `Set` element can
/// take, used only to bucket them inside [`KeyIndex`].
///
/// Two values that [`value_eq`] calls equal MUST produce the same key, or a
/// lookup would miss where the scan it replaces would hit. Equal keys need not
/// mean equal values — the candidates in a bucket are still checked with
/// `value_eq` — so a collision is free and only a *missing* one would be a bug.
/// `index_key` therefore declines (answering `None`, which makes the caller
/// scan) for exactly the values where the correspondence is not provable.
#[derive(PartialEq, Eq, Hash)]
enum IndexKey {
    Int(i64),
    Str(String),
    Bool(bool),
    Obj(u32),
    Null,
}

/// The magnitude below which an `i64` and an `f64` denote the same integers
/// one-for-one. Above it several `i64`s round to one `f64`, so
/// `value_eq(Int, Float)` can hold for a pair whose [`IndexKey`]s differ.
const EXACT_INT_FLOAT: f64 = 9_007_199_254_740_992.0; // 2^53

/// The bucket `v` belongs in, or `None` when no provably-correct one exists.
fn index_key(v: &Value) -> Option<IndexKey> {
    Some(match v {
        Value::Int(n) => IndexKey::Int(*n),
        Value::Str(s) => IndexKey::Str(s.as_str().to_string()),
        Value::Bool(b) => IndexKey::Bool(*b),
        // A box buckets with the primitive it wraps, not with its handle, so
        // `map.put(Integer.valueOf(1), x)` and `map.get(1)` meet. The bucket is
        // an accelerator — every candidate is still confirmed with `value_eq`,
        // which is where the class check lives — so sharing one is free.
        Value::Obj(id) => match unboxed(v) {
            Some(inner) => return index_key(&inner),
            None => IndexKey::Obj(*id),
        },
        Value::Undef => IndexKey::Null,
        // `value_eq` compares an integral and a floating value numerically, so
        // a `Float` has to land in the same bucket the equal `Int` does. That
        // is only sound where the two representations agree exactly: below
        // 2^53 an integral `f64` names one `i64` and vice versa. Everything
        // else — a fraction, a NaN, a magnitude past 2^53 — declines.
        Value::Float(f) => {
            let f = *f;
            if f.fract() != 0.0 || f.abs() >= EXACT_INT_FLOAT {
                return None;
            }
            IndexKey::Int(f as i64)
        }
        _ => return None,
    })
}

/// The key -> position accelerator a `Map` and a `Set` carry.
///
/// Both store their entries in a `Vec` (insertion order is what every
/// `toString` and every iteration is derived from), so finding a key was a
/// linear scan and `n` insertions cost O(n²): 20k `HashMap.put`s took 1.53s
/// against 0.10s for 5k. Java's is O(1), and a program that fills a map in a
/// loop is ordinary.
///
/// The index is an accelerator, never the authority: a hit is confirmed with
/// [`value_eq`] against the candidates in the bucket, and anything it cannot
/// represent falls back to the scan it replaces. Two conditions force that
/// fallback — a stored key with no [`IndexKey`] (`unindexed > 0`), and a
/// structural change that moved existing positions (`dirty`), which is repaired
/// by one rebuild on the next lookup rather than by tracking the shift.
struct KeyIndex {
    by_key: HashMap<IndexKey, Vec<usize>>,
    /// Stored keys with no `IndexKey`. While non-zero the index is incomplete.
    unindexed: usize,
    /// Positions have moved since the index was built.
    dirty: bool,
}

impl Default for KeyIndex {
    /// A fresh index is **stale**, not empty. A collection can be constructed
    /// already holding entries (`new HashMap<>(other)`, `Set.of(…)`, a `keySet`
    /// view), and an index that claimed to be complete would then answer
    /// "absent" for every one of them. Starting dirty makes the first lookup
    /// build it from whatever the collection actually holds, so no construction
    /// site has to remember to.
    fn default() -> Self {
        KeyIndex {
            by_key: HashMap::new(),
            unindexed: 0,
            dirty: true,
        }
    }
}

impl KeyIndex {
    /// Record the key now sitting at `at`, which must be the last position.
    fn push(&mut self, k: &Value, at: usize) {
        match index_key(k) {
            Some(key) => self.by_key.entry(key).or_default().push(at),
            None => self.unindexed += 1,
        }
    }

    /// Mark every recorded position stale. The next lookup rebuilds.
    fn invalidate(&mut self) {
        self.dirty = true;
    }

    fn rebuild<'a>(&mut self, keys: impl Iterator<Item = &'a Value>) {
        self.by_key.clear();
        self.unindexed = 0;
        self.dirty = false;
        for (i, k) in keys.enumerate() {
            self.push(k, i);
        }
    }

    /// Where `q` sits among `items`, whose key is read by `key_of`.
    ///
    /// `None` means the index cannot answer and the caller must scan;
    /// `Some(None)` is a confirmed absence.
    fn find<T>(
        &self,
        items: &[T],
        key_of: impl Fn(&T) -> &Value,
        q: &Value,
    ) -> Option<Option<usize>> {
        if self.dirty || self.unindexed > 0 {
            return None;
        }
        let key = index_key(q)?;
        Some(self.by_key.get(&key).and_then(|cands| {
            cands
                .iter()
                .copied()
                .find(|&i| items.get(i).is_some_and(|it| value_eq(key_of(it), q)))
        }))
    }
}

/// What a collection's iteration order is.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Order {
    /// `HashMap`/`HashSet` — Java's bucket order (see [`hash_order`]).
    Hash,
    /// `LinkedHashMap`/`LinkedHashSet` — insertion order.
    Insertion,
    /// `TreeMap`/`TreeSet` — ascending natural order of the keys/elements.
    Sorted,
}

/// Whether a list accepts structural modification. `Arrays.asList` is
/// fixed-size (`set` yes, `add`/`remove` no) and `List.of` is fully immutable —
/// both throw `UnsupportedOperationException` in Java, so javars throws too
/// rather than silently accepting the write.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Fixity {
    Mutable,
    /// `Arrays.asList` — elements may be replaced, the length may not change.
    FixedSize,
    /// `List.of` — nothing may change.
    Immutable,
}

thread_local! {
    /// The host-owned Java object heap. `Value::Obj(id)` is an index into this
    /// slab; the frontend owns the objects, fusevm just carries the handle. Grows
    /// per run and is cleared by [`heap_reset`] at the start of every program so
    /// handles never leak across runs.
    static HEAP: RefCell<Vec<HostObj>> = const { RefCell::new(Vec::new()) };
    /// Type → its direct supertypes (superclass + implemented/extended
    /// interfaces), populated by [`set_supertypes`] before a run. Used by
    /// `instanceof` and default `toString` to walk the supertype graph.
    static SUPERS: RefCell<HashMap<String, Vec<String>>> = RefCell::new(HashMap::new());
    /// Simple class name → Java's binary name (`Outer$Nested`), populated by
    /// [`set_binary_names`] before a run. Only nested types have an entry that
    /// differs from the key.
    static BINARY: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
    /// The exception in flight, if any. Set by [`JTHROW`], cleared by
    /// [`JEXC_TAKE`] when a handler claims it. Lives here rather than on the
    /// value stack because it has to survive the `Op::ReturnValue` that unwinds
    /// each frame between the `throw` and its handler.
    static PENDING: RefCell<Option<Value>> = const { RefCell::new(None) };
    /// True when the running program was compiled with the exception machinery
    /// (`Program::uses_exceptions`) — i.e. its call and fault sites carry the
    /// pending-exception check, so a raised throwable will actually be seen.
    /// When false there is no handler anywhere and no check to observe the
    /// pending value, so a runtime fault aborts instead (see [`raise`]).
    static EXC_ENABLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// The program arguments `main`'s `String[]` parameter is bound to — what
    /// the CLI collected after the file name. Set by [`set_argv`] before the run.
    static ARGV: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
    /// The wrapper caches the JLS mandates: `(class index, value) -> handle`.
    ///
    /// JLS 5.1.7 requires `valueOf` to return the *same* object for every
    /// `boolean`, every `char` in `0..=127`, and every `byte`, `short`, `int`
    /// and `long` in `-128..=127`. That requirement is the whole reason
    /// `Integer a = 127, b = 127; a == b` is `true` while the same pair at 128
    /// is `false`, so the cache is not an optimization here — it is the
    /// observable behaviour.
    static BOX_CACHE: RefCell<HashMap<(usize, i64), u32>> = RefCell::new(HashMap::new());
    /// Java's string pool: text -> the interned `String` for it.
    ///
    /// Seeded from the chunk's constants by [`intern_literals`], so the canonical
    /// object for a text that appears as a literal *is* that literal — which is
    /// what makes `("a" + b).intern() == "ab"` `true`. A text with no literal
    /// interns the first value offered for it.
    static INTERNED: RefCell<HashMap<String, Value>> = RefCell::new(HashMap::new());
    /// Every live box: handle -> (wrapper class, the primitive it wraps).
    ///
    /// Separate from `HEAP` on purpose — see [`HostObj::Boxed`]. Indexed by the
    /// handle rather than hashed on it, because unboxing is on the path of every
    /// arithmetic operation a wrapper takes part in and every erased read.
    static BOXES: RefCell<Vec<Option<(&'static str, Value)>>> = const { RefCell::new(Vec::new()) };
}

/// Box `v` as the wrapper class at index `code` in [`BOX_CLASSES`], returning
/// the handle.
///
/// Values in the JLS-mandated cache range share one handle; everything else
/// gets a fresh one, which is exactly the identity Java gives it.
fn box_value(code: usize, v: Value) -> Value {
    let class = BOX_CLASSES[code];
    // Only the integral classes, `Character` and `Boolean` have a cache, and
    // only over the range the JLS names. `Float`/`Double` have none at all —
    // `Double d1 = 1.0, d2 = 1.0; d1 == d2` is `false` for every value.
    let cached = match class {
        "Integer" | "Long" | "Short" | "Byte" => match &v {
            Value::Int(n) if (-128..=127).contains(n) => Some(*n),
            _ => None,
        },
        "Character" => match &v {
            Value::Int(n) if (0..=127).contains(n) => Some(*n),
            _ => None,
        },
        _ => None,
    };
    let Some(key) = cached else {
        return Value::Obj(alloc_box(class, v));
    };
    if let Some(id) = BOX_CACHE.with(|c| c.borrow().get(&(code, key)).copied()) {
        return Value::Obj(id);
    }
    let id = alloc_box(class, v);
    BOX_CACHE.with(|c| c.borrow_mut().insert((code, key), id));
    Value::Obj(id)
}

/// Give a box a heap handle of its own and record its payload in [`BOXES`].
fn alloc_box(class: &'static str, v: Value) -> u32 {
    let id = heap_alloc(HostObj::Boxed);
    BOXES.with(|b| {
        let mut b = b.borrow_mut();
        b.resize(id as usize + 1, None);
        b[id as usize] = Some((class, v));
    });
    id
}

/// The primitive inside a boxed wrapper, or `None` for anything else.
///
/// Every numeric, rendering, hashing and equality surface calls this first, so
/// a box that reaches one behaves as the primitive it wraps. That is what makes
/// the model safe to introduce incrementally: a site that has not been taught
/// about boxes answers exactly as it did before rather than answering wrongly.
fn unboxed(v: &Value) -> Option<Value> {
    let Value::Obj(id) = v else {
        return None;
    };
    BOXES.with(|b| {
        b.borrow()
            .get(*id as usize)?
            .as_ref()
            .map(|(_, v)| v.clone())
    })
}

/// The wrapper class of a boxed value, or `None` for anything else.
fn box_class(v: &Value) -> Option<&'static str> {
    let Value::Obj(id) = v else {
        return None;
    };
    BOXES.with(|b| b.borrow().get(*id as usize)?.as_ref().map(|(c, _)| *c))
}

/// `v` with any box removed — the identity function on everything else.
fn deboxed(v: &Value) -> Value {
    unboxed(v).unwrap_or_else(|| v.clone())
}

/// `to_int` / `to_float` **through any box**.
///
/// fusevm's own converters see a boxed wrapper as the heap handle it is and
/// answer 0, silently: `arr[anInteger]` indexed element 0 and
/// `String.format("%d", anInteger)` printed 0. Every host builtin that wants a
/// number out of a value therefore asks here instead. On an unboxed value the
/// answer is fusevm's exactly, so converting a call site cannot change what it
/// already answered — which is why the conversion could be mechanical.
trait JavaNumeric {
    /// The value as an `i64`, unboxing a wrapper first.
    fn jint(&self) -> i64;
    /// The value as an `f64`, unboxing a wrapper first.
    fn jfloat(&self) -> f64;
}

impl JavaNumeric for Value {
    fn jint(&self) -> i64 {
        Value::to_int(&deboxed(self))
    }

    fn jfloat(&self) -> f64 {
        Value::to_float(&deboxed(self))
    }
}

/// Seed the string pool with the chunk's `String` literals. Call after
/// [`heap_reset`] and before running.
///
/// `intern()` has to answer the *literal's* object for a text that has one, and
/// the literals live in the constant pool rather than anywhere the host can
/// reach at call time — so the pool is walked once here. Reading a text that
/// never appears as a literal is not an error: the first value offered for it
/// becomes canonical, which is what the JDK does too.
pub fn intern_literals(chunk: &fusevm::Chunk) {
    INTERNED.with(|table| {
        let mut table = table.borrow_mut();
        for c in &chunk.constants {
            if let Value::Str(text) = c {
                table
                    .entry(text.as_str().to_string())
                    .or_insert_with(|| c.clone());
            }
        }
    });
}

/// `s.intern()` — the canonical `String` for `s`'s text.
fn intern(v: &Value) -> Value {
    let text = java_str(v);
    INTERNED.with(|table| {
        table
            .borrow_mut()
            .entry(text)
            .or_insert_with(|| v.clone())
            .clone()
    })
}

/// Install the program arguments `main`'s `String[]` parameter will see. Call
/// before running the chunk.
pub fn set_argv(argv: Vec<String>) {
    ARGV.with(|a| *a.borrow_mut() = argv);
}

/// Clear the object heap (and superclass table stays until reset). Called at the
/// start of each program run so a fresh program never sees a prior run's handles.
pub fn heap_reset() {
    HEAP.with(|h| h.borrow_mut().clear());
    // The wrapper cache holds heap handles, so it has to go with the heap it
    // indexes into: a surviving entry would name a slot the next program's own
    // objects occupy, and `Integer.valueOf(1)` would answer someone else's list.
    BOX_CACHE.with(|c| c.borrow_mut().clear());
    BOXES.with(|b| b.borrow_mut().clear());
    INTERNED.with(|i| i.borrow_mut().clear());
    SUPERS.with(|s| s.borrow_mut().clear());
    BINARY.with(|b| b.borrow_mut().clear());
    PENDING.with(|p| *p.borrow_mut() = None);
    EXC_ENABLED.with(|e| e.set(false));
    ARGV.with(|a| a.borrow_mut().clear());
    // All three are keyed to the OUTGOING chunk: each gate answers whether
    // *that* chunk declared an override, and an entry ip indexes its ops.
    // Carrying any of them into the next program would render — or compare —
    // through unrelated bytecode.
    USER_TOSTRING.with(|c| c.set(None));
    USER_EQUALS.with(|c| c.set(None));
    MEMBER_ENTRY.with(|t| t.borrow_mut().clear());
}

/// Tell the host whether the compiled program carries the exception machinery.
/// Call before running the chunk; drives whether a runtime fault becomes a
/// catchable throwable or an immediate abort.
pub fn set_exceptions_enabled(on: bool) {
    EXC_ENABLED.with(|e| e.set(on));
}

/// A Java-level fault a host builtin detected: the `java.lang` throwable class
/// to raise and its `detailMessage`. An empty `class` marks a javars *internal*
/// error (an unimplemented method, a malformed format string) — those are not
/// Java exceptions and are never catchable.
struct Fault {
    class: &'static str,
    msg: String,
}

impl Fault {
    /// A catchable Java throwable of class `class` carrying `msg`.
    ///
    /// `class` is stored as the *simple* name, because that is the only spelling
    /// the rest of the machinery reads: a `catch` clause names its type simply,
    /// [`crate::prelude::qualified_throwable`] recognises only the simple name,
    /// and the uncaught report qualifies it on the way out. A call site that
    /// wrote the qualified form got a throwable whose class matched no `catch`
    /// clause and whose report was left unqualified — `Double.parseDouble("q")`
    /// aborted with `javars: Exception in thread "main"
    /// java.lang.NumberFormatException: …` where the `Float.parseFloat` arm two
    /// lines away, spelled simply, was catchable. Both spellings now arrive
    /// here as one, so the defect cannot be reintroduced at a new call site.
    fn java(class: &'static str, msg: impl Into<String>) -> Self {
        Fault {
            class: class.rsplit('.').next().unwrap_or(class),
            msg: msg.into(),
        }
    }

    /// A javars internal error — reported as `javars: <msg>`, never catchable.
    fn internal(msg: impl Into<String>) -> Self {
        Fault {
            class: "",
            msg: msg.into(),
        }
    }
}

/// Raise `f` from a builtin.
///
/// With the exception machinery compiled in, a Java fault becomes the pending
/// exception — indistinguishable from a `throw`, so `catch`/`finally` see it and
/// `getMessage()` works. Without it (a program that never mentions `try` or
/// `throw`, whose call sites carry no check) nothing would ever observe the
/// pending value, so the fault aborts the run with the same
/// `Exception in thread "main" …` line the uncaught path prints. An internal
/// error always aborts.
fn raise(vm: &mut VM, f: Fault) -> Value {
    if f.class.is_empty() {
        ffi_fault(vm, f.msg);
        return Value::Undef;
    }
    if !EXC_ENABLED.with(|e| e.get()) {
        let name =
            crate::prelude::qualified_throwable(f.class).unwrap_or_else(|| f.class.to_string());
        // Java's uncaught report names a messageless throwable with no trailing
        // `": "`, exactly as its `toString()` does.
        let detail = if f.msg.is_empty() {
            String::new()
        } else {
            format!(": {}", f.msg)
        };
        ffi_fault(vm, format!("Exception in thread \"main\" {name}{detail}"));
        return Value::Undef;
    }
    let mut fields = HashMap::new();
    // A fault raised with no message is Java's no-argument constructor, whose
    // `detailMessage` stays `null` — so `getMessage()` answers `null` and
    // `toString()` prints the class name alone. Storing an empty *String*
    // instead printed a bare trailing `": "` on every messageless throwable
    // (`java.lang.UnsupportedOperationException: `).
    let msg = if f.msg.is_empty() {
        Value::Undef
    } else {
        Value::str(f.msg)
    };
    fields.insert("detailMessage".to_string(), msg);
    let id = heap_alloc(HostObj::Instance {
        class: f.class.to_string(),
        fields,
    });
    PENDING.with(|p| *p.borrow_mut() = Some(Value::Obj(id)));
    Value::Undef
}

/// Install the type → direct-supertypes map for the current program (used by
/// `instanceof` and default `toString`). Call before running the chunk.
pub fn set_supertypes(map: HashMap<String, Vec<String>>) {
    SUPERS.with(|s| *s.borrow_mut() = map);
}

/// Record each user class's Java *binary* name (`Outer$Nested`). Call before
/// running the chunk; read by `qualified_or_binary`.
pub fn set_binary_names(map: HashMap<String, String>) {
    BINARY.with(|b| *b.borrow_mut() = map);
}

/// The name `getClass().getName()` reports for `class`: the qualified form for a
/// modeled JDK type (`java.lang.Object`), the binary form for a user one
/// (`Outer$Nested`), and the simple name for a top-level user class.
///
/// javars flattens nesting into one namespace, so the simple name is what every
/// value carries at runtime; the nesting only has to be recovered at the two
/// places Java shows it — `getName()` and the default `toString()`.
fn qualified_or_binary(class: &str) -> String {
    if let Some(q) = crate::prelude::qualified_class(class) {
        return q;
    }
    BINARY.with(|b| {
        b.borrow()
            .get(class)
            .cloned()
            .unwrap_or_else(|| class.to_string())
    })
}

/// Allocate `obj` on the heap and return its handle.
fn heap_alloc(obj: HostObj) -> u32 {
    HEAP.with(|h| {
        let mut h = h.borrow_mut();
        let id = h.len() as u32;
        h.push(obj);
        id
    })
}

/// The *direct* supertypes of the JDK types javars's value model names, spelled
/// the way the JDK declares them so each line can be checked against one
/// `extends`/`implements` clause rather than against a flattened closure.
///
/// This is the single definition of the JDK half of the supertype graph. The
/// runtime type test (`instanceof`, and the `catch` matching that shares its
/// builtin) needs it exact; the reference cast walks the same graph and then
/// adds, separately and by name, the siblings it cannot prove wrong
/// (see [`cast_allowed`]).
///
/// `java.lang.Object` is not an edge here. Every non-null reference is an
/// `Object` whether or not its class appears in this table, so that is answered
/// once at the top of [`is_instance_of`] instead of being reachable only from
/// the classes that happen to be listed.
fn jdk_supers(class: &str) -> &'static [&'static str] {
    match class {
        // java.lang
        "String" => &["CharSequence", "Comparable", "Serializable"],
        // The six `Number` wrappers. Only `Integer` and `Double` were listed
        // while those were the only two classes a bare `Value::Int`/`Float`
        // could answer as; a boxed value now names its own class, so
        // `Long.valueOf(1) instanceof Number` has a class to walk from.
        "Integer" | "Double" | "Long" | "Short" | "Byte" | "Float" => &["Number", "Comparable"],
        "Number" => &["Serializable"],
        "Boolean" | "Character" => &["Comparable", "Serializable"],
        "Enum" => &["Comparable", "Serializable"],
        // Both builders extend the package-private `AbstractStringBuilder`,
        // which is what carries `CharSequence` and `Appendable`; only
        // `Comparable` and `Serializable` are declared on the concrete classes.
        "StringBuilder" | "StringBuffer" => {
            &["AbstractStringBuilder", "Comparable", "Serializable"]
        }
        "AbstractStringBuilder" => &["CharSequence", "Appendable"],
        // The throwable chain itself comes from the prelude's declarations,
        // which reach `Throwable` and stop; `Throwable implements Serializable`
        // is the one edge above it.
        "Throwable" => &["Serializable"],
        // java.util — the collection interfaces. `List` gained
        // `SequencedCollection` in Java 21 and `Set` did not, which is why they
        // are not one arm.
        "List" => &["Collection", "SequencedCollection"],
        "Set" => &["Collection"],
        "SequencedCollection" => &["Collection"],
        "SequencedSet" => &["Set", "SequencedCollection"],
        "Collection" => &["Iterable"],
        "SortedSet" => &["SequencedSet"],
        "NavigableSet" => &["SortedSet"],
        "SequencedMap" => &["Map"],
        "SortedMap" => &["SequencedMap"],
        "NavigableMap" => &["SortedMap"],
        "AbstractCollection" => &["Collection"],
        "AbstractList" => &["AbstractCollection", "List"],
        "AbstractSet" => &["AbstractCollection", "Set"],
        "AbstractMap" => &["Map"],
        // java.util — the concrete kinds javars models. `LinkedHashMap` and
        // `LinkedHashSet` extend their hash counterparts; the tree kinds do not,
        // which is the pair a name-matching answer gets wrong.
        "ArrayList" => &["AbstractList", "RandomAccess", "Cloneable", "Serializable"],
        "HashMap" => &["AbstractMap", "Cloneable", "Serializable"],
        "LinkedHashMap" => &["HashMap", "SequencedMap"],
        "TreeMap" => &["AbstractMap", "NavigableMap", "Cloneable", "Serializable"],
        "HashSet" => &["AbstractSet", "Cloneable", "Serializable"],
        "LinkedHashSet" => &["HashSet", "SequencedSet"],
        "TreeSet" => &["AbstractSet", "NavigableSet", "Cloneable", "Serializable"],
        // The internal names [`value_class`] gives the shapes Java spells with
        // syntax, or with a class the JDK does not export, so no user type can
        // collide with one. An array is `Cloneable` and `Serializable` and
        // nothing else.
        //
        // The three list views are each a `List` that is not an `ArrayList`,
        // and they do not agree with one another either: `List.of` answers
        // `AbstractList` `false` where the other two answer `true`, and
        // `subList` alone is not `Serializable`. One shared name would have to
        // get two of the three wrong, and `Fixity` plus the `SubList` variant
        // already tell them apart.
        "[]" => &["Cloneable", "Serializable"],
        "List$immutable" => &["AbstractCollection", "List", "RandomAccess", "Serializable"],
        // `Set.of` reaches `AbstractCollection` but NOT `AbstractSet`, and is
        // not `Cloneable` — the two edges that separate it from every `new`
        // set, measured against the JDK rather than assumed from the `List.of`
        // line above (which does carry `RandomAccess`; a set does not).
        "Set$immutable" => &["AbstractCollection", "Set", "Serializable"],
        "Iterator$of" => &["Iterator"],
        "Optional" | "OptionalInt" | "OptionalLong" | "OptionalDouble" => &["Serializable"],
        "Stream$of" => &["BaseStream"],
        "Collector$of" => &["Collector"],
        // `Map.of` reaches `AbstractMap` — unlike `Set.of`, which stops at
        // `AbstractCollection` — and is not `Cloneable`. Measured against the
        // JDK rather than copied from the line above.
        "Map$immutable" => &["AbstractMap", "Map", "Serializable"],
        "List$fixed" => &["AbstractList", "RandomAccess", "Serializable"],
        "List$sub" => &["AbstractList", "RandomAccess"],
        _ => &[],
    }
}

/// True when `class` is `target`, a (transitive) subclass of it, or a type that
/// implements/extends the interface `target` — walking the supertype graph
/// (superclass + interfaces).
///
/// The graph has two halves and both are walked at every node: the program's own
/// declarations ([`SUPERS`], set before the run) and the JDK's ([`jdk_supers`]).
/// A user class that `implements Comparable` needs the second half to reach
/// `Serializable`, and a modeled `TreeMap` has no entry in the first at all.
fn is_subclass_of(class: &str, target: &str) -> bool {
    if class == target {
        return true;
    }
    SUPERS.with(|s| {
        let s = s.borrow();
        let mut stack = vec![class.to_string()];
        let mut seen = std::collections::HashSet::new();
        while let Some(cur) = stack.pop() {
            if cur == target {
                return true;
            }
            if !seen.insert(cur.clone()) {
                continue;
            }
            if let Some(sups) = s.get(&cur) {
                stack.extend(sups.iter().cloned());
            }
            stack.extend(jdk_supers(&cur).iter().map(|t| t.to_string()));
        }
        false
    })
}

thread_local! {
    /// Set by an inline-Rust FFI fault (compile error, call error, or an
    /// unresolved export). A builtin cannot return a `Result`, so it stashes the
    /// message here and halts the VM; [`crate::run_chunk`] reads it after
    /// `VM::run` returns and surfaces it as a `javars:` error.
    static FFI_ERROR: RefCell<Option<String>> = const { RefCell::new(None) };
}

/// Take and clear any pending FFI-fault message.
pub fn take_ffi_error() -> Option<String> {
    FFI_ERROR.with(|e| e.borrow_mut().take())
}

/// Record an FFI fault and halt the VM; the message surfaces after the run.
fn ffi_fault(vm: &mut VM, msg: impl Into<String>) {
    FFI_ERROR.with(|e| *e.borrow_mut() = Some(msg.into()));
    vm.request_halt();
}

/// Install javars builtins on a VM: the Java-formatting print builtins and the
/// inline-Rust FFI compile/call builtins. This is the single install choke point
/// later waves (methods, `String`/array objects) grow into.
pub fn install(vm: &mut VM) {
    vm.register_builtin(JPRINTLN, b_println);
    vm.register_builtin(JPRINT, b_print);
    vm.register_builtin(JEPRINTLN, b_eprintln);
    vm.register_builtin(JEPRINT, b_eprint);
    vm.register_builtin(JFFI_COMPILE, b_ffi_compile);
    vm.register_builtin(JFFI_CALL, b_ffi_call);
    vm.register_builtin(JSTR_DISPATCH, b_str_dispatch);
    vm.register_builtin(JSTATIC_DISPATCH, b_static_dispatch);
    vm.register_builtin(JARRAY_NEW, b_array_new);
    vm.register_builtin(JARRAY_NEW_MULTI, b_array_new_multi);
    vm.register_builtin(JARRAY_LIT, b_array_lit);
    vm.register_builtin(JARRAY_GET, b_array_get);
    vm.register_builtin(JARRAY_SET, b_array_set);
    vm.register_builtin(JNEW, b_new);
    vm.register_builtin(JFIELD_GET, b_field_get);
    vm.register_builtin(JFIELD_SET, b_field_set);
    vm.register_builtin(JINSTANCEOF, b_instanceof);
    vm.register_builtin(JCLASSOF, b_classof);
    vm.register_builtin(JDIV, b_div);
    vm.register_builtin(JIDIV, b_idiv);
    vm.register_builtin(JUSHR, b_ushr);
    vm.register_builtin(JCAST, b_cast);
    vm.register_builtin(JCHR_STR, b_chr_str);
    vm.register_builtin(JCHECKCAST, b_checkcast);
    vm.register_builtin(JF32, b_f32);
    vm.register_builtin(JF32_STR, b_f32_str);
    vm.register_builtin(JF32_ARITH, b_f32_arith);
    vm.register_builtin(JF32_ROUND, b_f32_round);
    vm.register_builtin(JBINARY_CLASS, b_binary_class);
    vm.register_builtin(JBOX, b_box);
    vm.register_builtin(JUNBOX, b_unbox);
    vm.register_builtin(JNEW_STRING, b_new_string);
    vm.register_builtin(JCOMPARE_TO, b_compare_to);
    vm.register_builtin(JFORMAT, b_format);
    vm.register_builtin(JSTRINGIFY, b_stringify);
    vm.register_builtin(JTHROW, b_throw);
    vm.register_builtin(JEXC_PENDING, b_exc_pending);
    vm.register_builtin(JEXC_TAKE, b_exc_take);
    vm.register_builtin(JEXC_DEPTH, b_exc_depth);
    vm.register_builtin(JEXC_CUT, b_exc_cut);
    vm.register_builtin(JEXC_ABORT, b_exc_abort);
    vm.register_builtin(JFAULT, b_fault);
    vm.register_builtin(JARGV, b_argv);
    vm.register_builtin(JMAKE_CLOSURE, b_make_closure);
    vm.register_builtin(JCLOSURE_CALL, b_closure_call);
    vm.register_builtin(JCOLL_NEW, b_coll_new);
    vm.register_builtin(JSB_NEW, b_sb_new);
    vm.register_builtin(JCOLL_DISPATCH, b_coll_dispatch);
    vm.register_builtin(JITER_ARRAY, b_iter_array);
}

/// `main`'s `String[] args` — a fresh array of the program arguments.
fn b_argv(vm: &mut VM, argc: u8) -> Value {
    pop_args(vm, argc);
    let elems = ARGV.with(|a| a.borrow().iter().cloned().map(Value::str).collect());
    Value::Obj(heap_alloc(HostObj::Array(elems)))
}

/// Raise a compiler-detected runtime fault (stack `[className, message]`) — the
/// integer division-by-zero check emits this.
fn b_fault(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let class = args
        .first()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    let msg = args
        .get(1)
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    // Only the modeled `java.lang` throwables are raisable this way, and the
    // compiler only ever emits one of them; look the name up so `class` can stay
    // a `&'static str` in [`Fault`].
    match crate::prelude::THROWABLES.iter().find(|(n, _)| *n == class) {
        Some((n, _)) => raise(vm, Fault::java(n, msg)),
        None => raise(
            vm,
            Fault::internal(format!("javars: unknown fault `{class}`")),
        ),
    }
}

/// `throw e` — park the throwable as the pending exception.
fn b_throw(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let exc = args.into_iter().next().unwrap_or(Value::Undef);
    PENDING.with(|p| *p.borrow_mut() = Some(exc));
    Value::Undef
}

/// True while an exception is in flight (the post-call check).
fn b_exc_pending(vm: &mut VM, argc: u8) -> Value {
    pop_args(vm, argc);
    Value::bool(PENDING.with(|p| p.borrow().is_some()))
}

/// Claim the pending exception for a handler, clearing it.
fn b_exc_take(vm: &mut VM, argc: u8) -> Value {
    pop_args(vm, argc);
    PENDING
        .with(|p| p.borrow_mut().take())
        .unwrap_or(Value::Undef)
}

/// The value-stack depth at `try` entry.
fn b_exc_depth(vm: &mut VM, argc: u8) -> Value {
    pop_args(vm, argc);
    Value::Int(vm.stack.len() as i64)
}

/// Discard everything the abandoned expression left on the value stack, back to
/// the depth [`JEXC_DEPTH`] recorded at `try` entry. Frames between the `throw`
/// and the handler clean themselves (`Op::ReturnValue` truncates to the frame
/// base), but the operands of the half-evaluated expression *inside* the
/// handler's own frame would otherwise pile up — once per throw, forever, in a
/// loop.
fn b_exc_cut(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let depth = args.first().map(|v| v.jint()).unwrap_or(0).max(0) as usize;
    if depth <= vm.stack.len() {
        vm.stack.truncate(depth);
    }
    Value::Undef
}

/// An exception that reached the top of `main`. Reports it the way `java` does
/// — `Exception in thread "main" java.lang.Foo: message` — and faults, so the
/// process exits non-zero.
fn b_exc_abort(vm: &mut VM, argc: u8) -> Value {
    pop_args(vm, argc);
    let exc = PENDING
        .with(|p| p.borrow_mut().take())
        .unwrap_or(Value::Undef);
    let msg = format!("Exception in thread \"main\" {}", throwable_str(&exc));
    ffi_fault(vm, msg);
    Value::Undef
}

/// Render a throwable the way `Throwable.toString()` does, from the heap object
/// directly. The Java-level `toString()` override is not called from here — it
/// is the same rendering boundary `java_str` keeps (BUGS.md), and this path
/// only serves the uncaught report — so it reproduces the same text: the class
/// name — qualified with
/// `java.lang.` for the modeled JDK throwables, bare for a user class — plus
/// `": " + detailMessage` when a message was supplied.
fn throwable_str(v: &Value) -> String {
    let Value::Obj(id) = v else {
        return java_str(v);
    };
    HEAP.with(|h| {
        let h = h.borrow();
        match h.get(*id as usize) {
            Some(HostObj::Instance { class, fields }) => {
                // [`qualified_or_binary`], not `qualified_throwable`: the latter
                // answers `None` for a user-defined throwable and left the
                // report printing the *simple* name, so an uncaught
                // `class MyEx extends RuntimeException` nested in `T` read
                // `Exception in thread "main" MyEx: boom` where Java prints the
                // binary name `T$MyEx: boom`. The modeled throwables are
                // unaffected — `qualified_or_binary` consults the same table
                // first.
                let name = qualified_or_binary(class);
                match fields.get("detailMessage") {
                    Some(m) if !matches!(m, Value::Undef) => format!("{name}: {}", java_str(m)),
                    _ => name,
                }
            }
            _ => java_str(v),
        }
    })
}

/// `classof(obj)` — the runtime class name of an instance (stack `[obj]`), or
/// the empty string for a non-instance value.
fn b_classof(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    match args.first() {
        Some(Value::Obj(id)) => HEAP.with(|h| {
            let h = h.borrow();
            match h.get(*id as usize) {
                Some(HostObj::Instance { class, .. }) => Value::str(class.clone()),
                // A lambda's "class" is the sentinel the dispatch chain tests,
                // so a functional-interface call routes to the closure body.
                Some(HostObj::Closure { .. }) => Value::str(LAMBDA_CLASS),
                _ => Value::str(""),
            }
        }),
        _ => Value::str(""),
    }
}

/// [`JBINARY_CLASS`] — `x.getClass()`, as the binary name `getName()` reports.
///
/// Everything the answer depends on already existed: [`value_class`] names the
/// runtime class of every shape the value model has, and [`binary_name`] maps
/// that to the JDK's own spelling — including the private classes `List.of`
/// and `Arrays.asList` return. Only `getClass()` was not asking them.
/// [`JBOX`] — box a primitive into the wrapper class named by the code on top
/// of the stack.
fn b_box(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let code = args
        .get(1)
        .map(as_i64)
        .unwrap_or(0)
        .clamp(0, BOX_CLASSES.len() as i64 - 1) as usize;
    let v = args.first().cloned().unwrap_or(Value::Undef);
    // `null` is not boxed. Java's boxing conversion applies to a *primitive*,
    // and the one place a null can reach a boxing site is an already-reference
    // expression the compiler could not type; boxing it would turn `null` into
    // an object and make `x == null` false.
    if matches!(v, Value::Undef) {
        return v;
    }
    box_value(code, v)
}

/// [`JNEW_STRING`] — a `String` with a fresh identity.
fn b_new_string(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    // `to_string` rather than a clone: a clone would share the argument's `Arc`
    // and the constructor's whole job is not to.
    Value::str(args.first().map(java_str).unwrap_or_default())
}

/// [`JUNBOX`] — the primitive inside a wrapper, or the value unchanged.
fn b_unbox(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let v = args.first().cloned().unwrap_or(Value::Undef);
    deboxed(&v)
}

/// Java `==` on two heap references: the same handle.
///
/// Reached from [`numeric_hook`], which routes a pair of handles here before it
/// considers them as numbers. That ordering is the whole model: two boxed
/// wrappers holding 128 are *numerically* equal and Java still answers `false`,
/// because `==` on two references compares the references.
fn ref_eq(a: &Value, b: &Value) -> bool {
    matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y)
}

fn b_binary_class(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let array_type = args.get(1).map(|h| h.as_str_cow().into_owned());
    let Some(v) = args.first() else {
        return Value::str("");
    };
    // An array's element type is erased, so the compiler's static spelling is
    // the only source for `[I` / `[Ljava.lang.String;`.
    if matches!(value_class(v).as_deref(), Some("[]")) {
        return Value::str(
            array_type
                .as_deref()
                .and_then(array_descriptor)
                .unwrap_or_default(),
        );
    }
    // A lambda keeps the dispatch sentinel: Java names one
    // `Class$$Lambda/0x…`, which is not reproducible (BUGS.md).
    match value_class(v) {
        Some(class) if class == LAMBDA_CLASS => Value::str(class),
        Some(class) => Value::str(binary_name(&class, v).unwrap_or(class)),
        None => Value::str(""),
    }
}

/// The JVM field descriptor `Class.getName()` reports for the array type `ty`,
/// spelled the way Java source does (`int[]`, `String[][]`).
///
/// Java names an array by its descriptor rather than by its source spelling —
/// `int[]` is `[I`, `String[][]` is `[[Ljava.lang.String;` — in the dotted form
/// `getName()` uses rather than the slashed class-file one. A reference
/// component goes through [`qualified_or_binary`], so a nested user class
/// resolves to `[LT$A;` and not `[LA;`.
fn array_descriptor(ty: &str) -> Option<String> {
    let component = ty.strip_suffix("[]")?;
    if let Some(inner) = array_descriptor(component) {
        return Some(format!("[{inner}"));
    }
    Some(format!(
        "[{}",
        match component {
            "int" => "I".to_string(),
            "long" => "J".to_string(),
            "short" => "S".to_string(),
            "byte" => "B".to_string(),
            "char" => "C".to_string(),
            "double" => "D".to_string(),
            "float" => "F".to_string(),
            "boolean" => "Z".to_string(),
            other => format!("L{};", jdk_name(other)),
        }
    ))
}

/// The simple name `Class.getSimpleName()` reports, given a binary name: the
/// text after the last `$` of a nested class, else after the last `.` of a
/// package-qualified one.
///
/// An array is the exception — Java answers with the *source* spelling of the
/// type (`int[]`, `String[]`), not with the descriptor `getName()` gave — so a
/// descriptor is decoded back rather than truncated.
fn simple_class_name(binary: &str) -> String {
    if let Some(component) = binary.strip_prefix('[') {
        // A one-character primitive descriptor is only a descriptor *inside* an
        // array type. At the top level `B` is the ordinary binary name of a
        // class the program called `B`, and answering `byte` for it renamed
        // every user class whose name is one of the eight descriptor letters.
        let elem = descriptor_primitive(component)
            .map(str::to_string)
            .unwrap_or_else(|| simple_class_name(component));
        return format!("{elem}[]");
    }
    if let Some(reference) = binary.strip_prefix('L').and_then(|r| r.strip_suffix(';')) {
        return simple_class_name(reference);
    }
    let after_package = binary.rsplit('.').next().unwrap_or(binary);
    after_package
        .rsplit('$')
        .next()
        .unwrap_or(after_package)
        .to_string()
}

/// The Java source name of a primitive field descriptor, for the array half of
/// [`simple_class_name`].
fn descriptor_primitive(d: &str) -> Option<&'static str> {
    Some(match d {
        "I" => "int",
        "J" => "long",
        "S" => "short",
        "B" => "byte",
        "C" => "char",
        "D" => "double",
        "F" => "float",
        "Z" => "boolean",
        _ => return None,
    })
}

// ── Lambdas ─────────────────────────────────────────────────────────────────

/// [`JMAKE_CLOSURE`] — snapshot the captures and register the closure.
fn b_make_closure(vm: &mut VM, _argc: u8) -> Value {
    let ncap = vm.stack.pop().unwrap_or(Value::Undef).jint() as usize;
    let params = vm.stack.pop().unwrap_or(Value::Undef).jint() as u8;
    let name_idx = vm.stack.pop().unwrap_or(Value::Undef).jint() as u16;
    let mut captures = Vec::with_capacity(ncap);
    for _ in 0..ncap {
        captures.push(vm.stack.pop().unwrap_or(Value::Undef));
    }
    captures.reverse();
    Value::Obj(heap_alloc(HostObj::Closure {
        name_idx,
        params,
        captures,
    }))
}

/// A copy of a closure handle's metadata, if `v` is one.
fn closure_meta(v: &Value) -> Option<(u16, u8, Vec<Value>)> {
    let Value::Obj(id) = v else {
        return None;
    };
    HEAP.with(|h| {
        let h = h.borrow();
        match h.get(*id as usize) {
            Some(HostObj::Closure {
                name_idx,
                params,
                captures,
            }) => Some((*name_idx, *params, captures.clone())),
            _ => None,
        }
    })
}

/// [`JCLOSURE_CALL`] — invoke a closure with the arguments already on the stack.
///
/// The body is an ordinary javars subroutine, so it runs in a real fusevm call
/// frame; the frame is entered by hand (rather than by `Op::Call`) because the
/// entry address comes from the closure value, not from a compile-time name
/// operand. A nested `VM::run` drives it, exactly as the sibling fusevm
/// frontends (kotlinrs, groovyrs, scalars) drive their closure bodies.
fn b_closure_call(vm: &mut VM, argc: u8) -> Value {
    let n = argc.saturating_sub(1) as usize;
    let mut args = Vec::with_capacity(n);
    for _ in 0..n {
        args.push(vm.stack.pop().unwrap_or(Value::Undef));
    }
    args.reverse();
    let clo = vm.stack.pop().unwrap_or(Value::Undef);
    // An exception already in flight must not start another body running: the
    // enclosing frame is unwinding and would otherwise re-run side effects.
    if PENDING.with(|p| p.borrow().is_some()) {
        return Value::Undef;
    }
    let Some((name_idx, params, captures)) = closure_meta(&clo) else {
        return raise(
            vm,
            Fault::java(
                "NullPointerException",
                "Cannot invoke a functional interface method because the target is null"
                    .to_string(),
            ),
        );
    };
    let Some(entry) = vm.chunk.find_sub(name_idx) else {
        return raise(vm, Fault::internal("javars: lambda body not found"));
    };
    // The prologue binds exactly `params` arguments then the captures, so a
    // mismatched arity is padded with `null` / truncated rather than corrupting
    // the frame.
    let stack_base = vm.stack.len();
    for i in 0..params as usize {
        vm.stack.push(args.get(i).cloned().unwrap_or(Value::Undef));
    }
    for cap in captures {
        vm.stack.push(cap);
    }
    run_sub(vm, entry, stack_base)
}

// ── java.util collections ────────────────────────────────────────────────────
//
// Every collection is a `HostObj` on the same slab arrays and instances live
// on, so `List` aliasing, `==` identity, and passing one to a method all behave
// like Java references with no extra machinery.
//
// Entries are always *stored* in insertion order; the implementation's
// [`Order`] is applied when they are iterated, printed, or handed to
// `keySet()`/`values()`. That keeps `LinkedHashMap` free and makes `HashMap`'s
// order a pure function of the keys — see [`hash_order`].

/// Java's `Object.hashCode()` for the value kinds javars models. `None` for a
/// heap object, whose Java hash is an identity hash javars cannot reproduce (and
/// whose iteration order is therefore not reproducible in Java either).
fn java_hash(v: &Value) -> Option<i32> {
    // A wrapper hashes as its primitive. The two arms below already split
    // `Integer` from `Long` by magnitude, which is exact: an `Integer` can hold
    // nothing outside `i32`, so a value that does is necessarily a `Long`.
    if let Some(inner) = unboxed(v) {
        return java_hash(&inner);
    }
    Some(match v {
        // `String.hashCode` is specified: s[0]*31^(n-1) + … + s[n-1]. Java
        // counts UTF-16 code units; javars counts scalars, the same
        // `char`-model simplification the `String` methods already make.
        Value::Str(s) => s
            .chars()
            .fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(c as i32)),
        // `Integer.hashCode` is the value; `Long.hashCode` folds the halves.
        Value::Int(n) => {
            if *n >= i32::MIN as i64 && *n <= i32::MAX as i64 {
                *n as i32
            } else {
                (*n ^ ((*n as u64) >> 32) as i64) as i32
            }
        }
        // `Double.hashCode` folds `doubleToLongBits` the way `Long` does. The
        // *canonical* bits, not the raw ones: `doubleToLongBits` collapses
        // every `NaN` encoding to one pattern, so two `NaN`s hash alike — which
        // they must, since `Double.equals` already calls them equal.
        Value::Float(f) => {
            let bits = canonical_bits(*f);
            (bits ^ ((bits as u64) >> 32) as i64) as i32
        }
        Value::Bool(b) => {
            if *b {
                1231
            } else {
                1237
            }
        }
        _ => return None,
    })
}

/// The hash one *element* of a collection contributes, which is what
/// `e.hashCode()` on that element answers.
///
/// [`java_hash`] declines a heap handle; `Object.hashCode` on one is the handle
/// itself (see [`object_method`]), and `null` contributes 0 the way Java's
/// `AbstractList.hashCode` specifies. A class that declares its own `hashCode`
/// still does not have that body run — see BUGS.md — so this is the identity
/// hash for a user instance, exactly as a direct `x.hashCode()` is.
fn element_hash(v: &Value) -> i32 {
    match java_hash(v) {
        Some(h) => h,
        None => match v {
            Value::Obj(id) => *id as i32,
            _ => 0,
        },
    }
}

/// `hasNext` / `next` / `remove` on an [`HostObj::Iterator`] receiver.
///
/// `None` for any other receiver or method, which leaves the call to the
/// dispatch that follows.
fn iterator_method(recv: &Value, method: &str, argc: usize) -> Option<Result<Value, Fault>> {
    let Value::Obj(id) = recv else {
        return None;
    };
    let state = HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::Iterator {
            source,
            pos,
            last,
            exp_mods,
        }) => Some((*source, *pos, *last, *exp_mods)),
        _ => None,
    })?;
    let (source, pos, last, exp_mods) = state;
    let items = sequence_items(&Value::Obj(source)).unwrap_or_default();
    Some(match (method, argc) {
        ("hasNext", 0) => Ok(Value::bool(pos < items.len())),
        ("next", 0) => {
            if iter_mods(source) != exp_mods {
                return Some(Err(comodification()));
            }
            match items.get(pos) {
                Some(v) => {
                    let v = v.clone();
                    HEAP.with(|h| {
                        if let Some(HostObj::Iterator { pos, last, .. }) =
                            h.borrow_mut().get_mut(*id as usize)
                        {
                            *last = Some(*pos);
                            *pos += 1;
                        }
                    });
                    Ok(v)
                }
                None => Err(Fault::java("NoSuchElementException", String::new())),
            }
        }
        // `remove()` deletes the element `next()` last returned and leaves the
        // walk where it was, so the following `next()` sees the element that
        // shifted into the gap. Calling it twice, or before any `next()`, is
        // Java's `IllegalStateException`.
        ("remove", 0) => {
            let Some(at) = last else {
                return Some(Err(Fault::java("IllegalStateException", String::new())));
            };
            if iter_mods(source) != exp_mods {
                return Some(Err(comodification()));
            }
            let removed = HEAP.with(|h| {
                let mut heap = h.borrow_mut();
                match heap.get_mut(source as usize) {
                    Some(HostObj::List { items, mods, .. }) if at < items.len() => {
                        items.remove(at);
                        *mods += 1;
                        Some(*mods)
                    }
                    Some(HostObj::Set { items, index, .. }) if at < items.len() => {
                        items.remove(at);
                        index.invalidate();
                        Some(0)
                    }
                    _ => None,
                }
            });
            match removed {
                Some(mods) => {
                    HEAP.with(|h| {
                        if let Some(HostObj::Iterator {
                            pos,
                            last,
                            exp_mods,
                            ..
                        }) = h.borrow_mut().get_mut(*id as usize)
                        {
                            *pos = at;
                            *last = None;
                            *exp_mods = mods;
                        }
                    });
                    Ok(Value::Undef)
                }
                None => Err(Fault::java("IllegalStateException", String::new())),
            }
        }
        _ => Err(Fault::internal(format!(
            "javars: unsupported Iterator method `{method}` with {argc} argument(s)"
        ))),
    })
}

/// `AbstractList.hashCode` — `31 * result + e.hashCode()`, seeded at 1.
fn list_hash(items: &[Value]) -> i64 {
    items.iter().fold(1i32, |acc, e| {
        acc.wrapping_mul(31).wrapping_add(element_hash(e))
    }) as i64
}

/// `AbstractSet.hashCode` — the *sum* of the element hashes, so it does not
/// depend on iteration order (which is the point: two equal sets in different
/// orders must hash alike).
fn set_hash(items: &[Value]) -> i64 {
    items
        .iter()
        .fold(0i32, |acc, e| acc.wrapping_add(element_hash(e))) as i64
}

/// `AbstractMap.hashCode` — the sum of the entries', each being
/// `keyHash ^ valueHash` (`Map.Entry.hashCode`).
fn map_hash(entries: &[(Value, Value)]) -> i64 {
    entries.iter().fold(0i32, |acc, (k, v)| {
        acc.wrapping_add(element_hash(k) ^ element_hash(v))
    }) as i64
}

/// The order a `HashMap`/`HashSet` iterates `keys` in, as indices into `keys`.
///
/// Java lays entries out in a power-of-two table, indexing with
/// `(capacity - 1) & (h ^ (h >>> 16))`, appending within a bucket and preserving
/// relative order across a resize. Iteration then walks bucket 0 upward. So the
/// order is exactly a *stable* sort of the insertion sequence by bucket index —
/// verified against OpenJDK 26 for `String` and `Integer` keys, including across
/// the resize at 13 entries.
///
/// Two things are not modeled, and neither is reproducible in Java either: a bin
/// that treeifies (8 collisions in one bucket with a table of 64+) and a key
/// whose `hashCode` is the JVM identity hash. A key with no modeled hash keeps
/// insertion order.
fn hash_order(keys: &[Value]) -> Vec<usize> {
    let n = keys.len();
    let mut cap = 16usize;
    while n > cap * 3 / 4 {
        cap *= 2;
    }
    let mut idx: Vec<usize> = (0..n).collect();
    idx.sort_by_key(|&i| {
        let h = java_hash(&keys[i]).unwrap_or(0) as u32;
        ((cap as u32 - 1) & (h ^ (h >> 16))) as usize
    });
    idx
}

/// The order `items` are presented in under `order`, as indices into `items`.
fn present_order(items: &[Value], order: Order) -> Vec<usize> {
    match order {
        Order::Insertion => (0..items.len()).collect(),
        Order::Hash => hash_order(items),
        Order::Sorted => {
            let mut idx: Vec<usize> = (0..items.len()).collect();
            idx.sort_by(|&a, &b| natural_cmp(&items[a], &items[b]));
            idx
        }
    }
}

/// Java's `equals` for the value kinds javars models: value equality for
/// strings, numbers, and booleans; reference identity for a heap object (the
/// same simplification javars's `==` already makes — a user `equals` override is
/// not called).
fn value_eq(a: &Value, b: &Value) -> bool {
    // `equals` between two wrappers is class-sensitive: `Integer.valueOf(1)
    // .equals(Long.valueOf(1))` is `false` in Java, and telling those two apart
    // is what the box's class tag is for. A box against a *bare* value is
    // compared numerically, because a bare `Value::Int` carries no class to
    // disagree with — it is whichever wrapper the context autoboxed it into.
    match (box_class(a), box_class(b)) {
        (Some(x), Some(y)) if x != y => return false,
        (Some(_), _) | (_, Some(_)) => return value_eq(&deboxed(a), &deboxed(b)),
        _ => {}
    }
    match (a, b) {
        (Value::Str(x), Value::Str(y)) => x == y,
        (Value::Obj(x), Value::Obj(y)) => x == y,
        (Value::Undef, Value::Undef) => true,
        (Value::Bool(x), Value::Bool(y)) => x == y,
        (Value::Int(_) | Value::Float(_), Value::Int(_) | Value::Float(_)) => {
            // `Integer.equals(Long)` is false in Java, but javars has one
            // integral kind, so numeric equality is compared by value.
            match (a, b) {
                (Value::Int(x), Value::Int(y)) => x == y,
                // `Double.equals` is *not* `==`: it compares
                // `doubleToLongBits`, so `NaN` equals itself and `-0.0` does
                // not equal `0.0` — which is what decides whether a
                // `HashSet<Double>` keeps two `NaN`s apart and whether
                // `list.contains(Double.NaN)` can ever answer true. The total
                // order [`float_compare`] already implements is the same
                // predicate, so the two cannot drift.
                (Value::Float(_), Value::Float(_)) => float_compare(a.jfloat(), b.jfloat()) == 0,
                _ => a.jfloat() == b.jfloat(),
            }
        }
        _ => false,
    }
}

/// Java's `q.equals(other)` where `q` may be a class instance whose class (or
/// an ancestor) declares one — the comparison every collection membership test
/// performs internally.
///
/// The receiver is `q`, not `other`, because that is the direction the JDK
/// calls in: `ArrayList.indexOf(o)` runs `o.equals(element)`, `HashMap.getNode`
/// runs `key.equals(storedKey)`, and `HashSet.add(e)` runs `e.equals(stored)`.
/// An asymmetric user `equals` therefore answers here exactly as it does there.
/// With no user body in play this is [`value_eq`].
fn eq_call(vm: &mut VM, q: &Value, other: &Value) -> bool {
    match user_equals(vm, q) {
        Some((id, entry)) => run_equals(vm, entry, id, other),
        None => value_eq(q, other),
    }
}

/// `java.util.Objects.equals(a, b)` — `a == b || (a != null && a.equals(b))`.
/// The null half is what separates it from [`eq_call`]: `Objects.equals(null,
/// null)` is `true` and `Objects.equals(null, x)` is `false` without calling
/// anything. It is also what a `record`'s derived `equals` uses for a reference
/// component.
fn objects_equals(vm: &mut VM, a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Undef, Value::Undef) => true,
        (Value::Undef, _) => false,
        _ => eq_call(vm, a, b),
    }
}

/// The handle and `equals(Object)` entry ip of a value that is a class instance
/// whose class resolves a user body; `None` for everything else — a scalar, a
/// collection handle, or an instance that inherits `java.lang.Object`'s
/// identity `equals`.
fn user_equals(vm: &VM, v: &Value) -> Option<(u32, usize)> {
    let Value::Obj(id) = v else {
        return None;
    };
    if !any_user_equals(vm) {
        return None;
    }
    let class = instance_class(v)?;
    Some((*id, equals_entry(vm, &class)?))
}

/// Run a user `equals(Object)` body with `id` as the receiver and return what it
/// answered.
///
/// A throwable already in flight stops the call, for the same reason
/// [`run_tostring`] stops: the enclosing frame is unwinding and a body's side
/// effects must not run twice. One raised *by* the body leaves `PENDING` set for
/// the calling builtin to surface, and the verdict is discarded with it.
/// The hash one element contributes when a *user* `hashCode()` body decides it.
///
/// Run before the heap borrow, for the same reason [`eq_plan`] resolves the
/// element comparisons there: the body reads its own fields and may allocate, so
/// it cannot run under an outstanding borrow of the slab. `None` means no body
/// is reachable and [`element_hash`] answers, which is the path every program
/// that declares no `hashCode` — and every collection of `String`s and boxed
/// primitives — takes.
fn user_element_hash(vm: &mut VM, v: &Value) -> Option<i32> {
    let Value::Obj(id) = v else {
        return None;
    };
    let class = instance_class(v)?;
    let entry = member_entry(vm, &class, HASHCODE_SUFFIX)?;
    if PENDING.with(|p| p.borrow().is_some()) {
        return None;
    }
    let stack_base = vm.stack.len();
    vm.stack.push(Value::Obj(*id));
    match run_sub(vm, entry, stack_base) {
        Value::Int(h) => Some(h as i32),
        _ => None,
    }
}

/// A collection's own `hashCode`, computed before the heap borrow so a user
/// element body can run.
///
/// `None` for a receiver that is not a collection, or a call that is not
/// `hashCode()`, which leaves the borrowed section to answer as before.
fn collection_hash(vm: &mut VM, recv: &Value, method: &str, argc: usize) -> Option<Value> {
    if method != "hashCode" || argc != 0 {
        return None;
    }
    let each = |vm: &mut VM, e: &Value| user_element_hash(vm, e).unwrap_or_else(|| element_hash(e));
    if let Some(entries) = map_entries(recv) {
        let mut h = 0i32;
        for (k, v) in &entries {
            let (kh, vh) = (each(vm, k), each(vm, v));
            h = h.wrapping_add(kh ^ vh);
        }
        return Some(Value::Int(h.into()));
    }
    let items = sequence_items(recv)?;
    // A set's hash is the order-independent sum; a list's is the `31 * h + e`
    // fold. `value_class` is what tells them apart, and it is the same question
    // `render_sequence` asks to choose between `[…]` and `{…}`.
    let is_set = value_class(recv).is_some_and(|c| c.contains("Set"));
    let mut h = if is_set { 0i32 } else { 1i32 };
    for e in &items {
        let eh = each(vm, e);
        h = if is_set {
            h.wrapping_add(eh)
        } else {
            h.wrapping_mul(31).wrapping_add(eh)
        };
    }
    Some(Value::Int(h.into()))
}

fn run_equals(vm: &mut VM, entry: usize, id: u32, other: &Value) -> bool {
    if PENDING.with(|p| p.borrow().is_some()) {
        return false;
    }
    let stack_base = vm.stack.len();
    vm.stack.push(Value::Obj(id));
    vm.stack.push(other.clone());
    matches!(run_sub(vm, entry, stack_base), Value::Bool(true))
}

/// The element comparisons one collection call needs a user `equals()` for,
/// resolved *before* the heap borrow the call itself takes.
///
/// Java compares a collection's elements with `equals`, not with identity, and
/// running a user body needs `&mut VM` with no borrow of the heap slab
/// outstanding — the body reads its own fields, and may allocate. So the
/// comparisons happen up front, in [`eq_plan`], and the borrowed section
/// consumes plain data. `None` — every program that declares no `equals` — puts
/// each site back on [`value_eq`] and the code path javars has always taken.
enum EqPlan {
    /// The position `args[0]` was found at, as an index into the receiver's
    /// *storage* order — which is what the borrowed section indexes. For a `Map`
    /// the search ran over its keys, except under `containsValue`, where it ran
    /// over its values.
    Index(Option<usize>),
    /// `List.equals(other)`: the whole pairwise verdict.
    Same(bool),
    /// `Set.addAll(c)`: the elements of `c` not already present, in order,
    /// counting the ones accepted earlier in the same call.
    Fresh(Vec<Value>),
}

/// Where `q` sits in `items`: the position a user `equals()` already found, or
/// javars's value model when no user body was in play.
///
/// The plan scanned in the direction the calling method scans and stopped at the
/// first hit, so `from_end` only selects the fallback's direction —
/// `List.lastIndexOf` is the one caller that passes `true`.
fn eq_index(eq: Option<&EqPlan>, items: &[Value], q: &Value, from_end: bool) -> Option<usize> {
    match eq {
        Some(EqPlan::Index(at)) => *at,
        _ if from_end => items.iter().rposition(|x| value_eq(x, q)),
        _ => items.iter().position(|x| value_eq(x, q)),
    }
}

/// The receiver's elements in *storage* order — the order the borrowed section
/// indexes. Distinct from [`sequence_items`], which presents a `Set` in its
/// iteration order and so would misalign the verdict vector. A `Map` answers
/// with its keys.
fn eq_elements(recv: &Value) -> Option<Vec<Value>> {
    let Value::Obj(id) = recv else {
        return None;
    };
    if let Some(window) = sublist_items(*id as usize) {
        return window.ok();
    }
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::List { items, .. }) | Some(HostObj::Set { items, .. }) => Some(items.clone()),
        Some(HostObj::Map { entries, .. }) => {
            Some(entries.iter().map(|(k, _)| k.clone()).collect())
        }
        _ => None,
    })
}

/// A `Map`'s values in storage order, for `containsValue`.
fn eq_map_values(recv: &Value) -> Option<Vec<Value>> {
    let Value::Obj(id) = recv else {
        return None;
    };
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::Map { entries, .. }) => {
            Some(entries.iter().map(|(_, v)| v.clone()).collect())
        }
        _ => None,
    })
}

/// Which collection shape a handle is, for deciding whether a method name
/// compares by value at all — `List.remove(int)` removes by index where
/// `Set.remove(Object)` removes by equality, and `List.add` appends where
/// `Set.add` de-duplicates. A `Set`/`Map` carries its iteration order too,
/// because that is what says whether it is a *hash* container.
enum EqShape {
    List,
    Set(Order),
    Map(Order),
}

fn eq_shape(recv: &Value) -> Option<EqShape> {
    let Value::Obj(id) = recv else {
        return None;
    };
    if is_sublist(*id as usize) {
        return Some(EqShape::List);
    }
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::List { .. }) => Some(EqShape::List),
        Some(HostObj::Set { order, .. }) => Some(EqShape::Set(*order)),
        Some(HostObj::Map { order, .. }) => Some(EqShape::Map(*order)),
        _ => None,
    })
}

/// Whether a *hash* container may trust `class`'s `equals`.
///
/// `HashMap`/`HashSet` find an element only when its `hashCode` puts it in the
/// bucket being searched, so a class that overrides `equals` and leaves
/// `hashCode` alone is genuinely not found by Java either — two instances get
/// distinct JVM identity hashes and never meet. javars cannot compute a JVM
/// identity hash, so the *declaration* is the signal: a class that declares
/// `hashCode`, or a `record`/`enum` whose derived one is consistent by
/// construction, is trusted; anything else keeps the identity comparison Java
/// effectively performs. `ArrayList` hashes nothing and so asks this of nobody.
fn hash_consistent(vm: &VM, class: &str) -> bool {
    member_entry(vm, class, HASHCODE_SUFFIX).is_some()
        || is_subclass_of(class, "Record")
        || is_subclass_of(class, "Enum")
}

/// Whether an iteration order belongs to a hash-bucketed container.
/// `Order::Sorted` is a `TreeMap`/`TreeSet`, which locates by `compareTo` rather
/// than by `equals` — a different question, and one javars does not answer here.
fn is_hashed(order: Order) -> bool {
    matches!(order, Order::Hash | Order::Insertion)
}

/// Resolve the comparisons a user `equals()` decides for one collection call.
///
/// Only the methods whose answer Java takes from `equals` build a plan, and only
/// when a body is actually reachable from the value being compared — so a
/// program with no `equals`, or one whose elements are `String`s and boxed
/// primitives, pays a flag read and nothing else.
fn eq_plan(
    vm: &mut VM,
    recv: &Value,
    method: &str,
    args: &[Value],
    arg_seqs: &[Option<Vec<Value>>],
) -> Option<EqPlan> {
    if !any_user_equals(vm) {
        return None;
    }
    let shape = eq_shape(recv)?;
    // `AbstractList.equals` compares position by position with *this* list's
    // element as the receiver, so the bodies it reaches are the receiver's.
    if method == "equals" && args.len() == 1 && matches!(shape, EqShape::List) {
        let mine = eq_elements(recv)?;
        let other = arg_seqs.first()?.clone()?;
        if !mine.iter().any(|v| user_equals(vm, v).is_some()) {
            return None;
        }
        if mine.len() != other.len() {
            return Some(EqPlan::Same(false));
        }
        let mut same = true;
        for (a, b) in mine.iter().zip(&other) {
            if !eq_call(vm, a, b) {
                same = false;
                break;
            }
        }
        return Some(EqPlan::Same(same));
    }
    // `Set.addAll` asks the membership question once per added element, against
    // a set that grows as the earlier ones are accepted.
    if method == "addAll" && args.len() == 1 && matches!(shape, EqShape::Set(o) if is_hashed(o)) {
        let mut items = eq_elements(recv)?;
        let add = arg_seqs.first()?.clone()?;
        if !add.iter().any(|v| trusted_equals(vm, v, true)) {
            return None;
        }
        let mut fresh = Vec::new();
        for v in add {
            let mut seen = false;
            for x in &items {
                if eq_call(vm, &v, x) {
                    seen = true;
                    break;
                }
            }
            if !seen {
                items.push(v.clone());
                fresh.push(v);
            }
        }
        return Some(EqPlan::Fresh(fresh));
    }
    // Everything else is "where does `args[0]` sit in the receiver".
    let (by_value, hashed) = match shape {
        EqShape::List => (
            matches!(
                (method, args.len()),
                ("contains", 1) | ("indexOf", 1) | ("lastIndexOf", 1) | ("removeObject", 1)
            ),
            false,
        ),
        EqShape::Set(order) => (
            matches!(
                (method, args.len()),
                ("contains", 1) | ("add", 1) | ("remove", 1)
            ) && is_hashed(order),
            true,
        ),
        EqShape::Map(order) => (
            matches!(
                (method, args.len()),
                ("get", 1)
                    | ("getOrDefault", 2)
                    | ("containsKey", 1)
                    | ("containsValue", 1)
                    | ("remove", 1)
                    | ("put", 2)
                    | ("putIfAbsent", 2)
            ) && is_hashed(order),
            true,
        ),
    };
    if !by_value {
        return None;
    }
    let q = args.first()?;
    if !trusted_equals(vm, q, hashed) {
        return None;
    }
    let against = if method == "containsValue" {
        eq_map_values(recv)?
    } else {
        eq_elements(recv)?
    };
    // The scan stops at the first hit, in the direction the calling method
    // scans, so a user body's side effects fire exactly as often as Java's do.
    let at = if method == "lastIndexOf" {
        (0..against.len())
            .rev()
            .find(|i| eq_call(vm, q, &against[*i]))
    } else {
        (0..against.len()).find(|i| eq_call(vm, q, &against[*i]))
    };
    Some(EqPlan::Index(at))
}

/// Whether `v`'s own `equals` is the one this collection would consult: a body
/// has to exist, and a hash container additionally needs a `hashCode` it can
/// trust (see [`hash_consistent`]).
fn trusted_equals(vm: &VM, v: &Value, hashed: bool) -> bool {
    if user_equals(vm, v).is_none() {
        return false;
    }
    !hashed || instance_class(v).is_some_and(|c| hash_consistent(vm, &c))
}

/// Ascending natural order (`Comparable`) for the sorted collections and
/// `Collections.sort`: numbers numerically, strings lexicographically by
/// `char`, `null` first. Mixed kinds fall back to a stable "equal".
///
/// The floating fallback is [`float_compare`], not `partial_cmp`. A `TreeSet`
/// orders its elements by `Double.compareTo`, which is a *total* order —
/// `partial_cmp` answers `None` for a `NaN` operand and `Equal` for `-0.0`
/// against `0.0`, so a `TreeSet<Double>` collapsed the two zeroes into one
/// element and put `NaN` wherever the sort happened to leave it.
/// `Collections.sort` already reached the right answer through the
/// `compareTo` lambda the compiler supplies; this is the sibling path that did
/// not.
fn natural_cmp(a: &Value, b: &Value) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    // Through any box: a `new String(…)` handle orders by its text, and a boxed
    // wrapper by its number, exactly as the values they hold do.
    let (a, b) = (&deboxed(a), &deboxed(b));
    match (a, b) {
        (Value::Str(x), Value::Str(y)) => x.cmp(y),
        (Value::Undef, Value::Undef) => Ordering::Equal,
        (Value::Undef, _) => Ordering::Less,
        (_, Value::Undef) => Ordering::Greater,
        (Value::Int(x), Value::Int(y)) => x.cmp(y),
        (Value::Bool(x), Value::Bool(y)) => x.cmp(y),
        _ => float_compare(a.jfloat(), b.jfloat()).cmp(&0),
    }
}

/// Allocate the collection `kind` names, seeded from `seed` when a copy
/// constructor supplied one.
fn new_collection(vm: &mut VM, kind: &str, seed: &Value) -> Result<Value, Fault> {
    let obj = match kind {
        "ArrayList" | "LinkedList" | "List" => HostObj::List {
            mods: 0,
            items: sequence_items(seed).unwrap_or_default(),
            fixed: Fixity::Mutable,
        },
        "HashMap" | "Map" => HostObj::Map {
            fixed: Fixity::Mutable,
            entries: map_entries(seed).unwrap_or_default(),
            order: Order::Hash,
            index: KeyIndex::default(),
        },
        "LinkedHashMap" => HostObj::Map {
            fixed: Fixity::Mutable,
            entries: map_entries(seed).unwrap_or_default(),
            order: Order::Insertion,
            index: KeyIndex::default(),
        },
        "TreeMap" => HostObj::Map {
            fixed: Fixity::Mutable,
            entries: map_entries(seed).unwrap_or_default(),
            order: Order::Sorted,
            index: KeyIndex::default(),
        },
        "HashSet" | "Set" => HostObj::Set {
            items: distinct(vm, &sequence_items(seed).unwrap_or_default()),
            order: Order::Hash,
            fixed: Fixity::Mutable,
            index: KeyIndex::default(),
        },
        "LinkedHashSet" => HostObj::Set {
            items: distinct(vm, &sequence_items(seed).unwrap_or_default()),
            order: Order::Insertion,
            fixed: Fixity::Mutable,
            index: KeyIndex::default(),
        },
        "TreeSet" => HostObj::Set {
            items: distinct(vm, &sequence_items(seed).unwrap_or_default()),
            order: Order::Sorted,
            fixed: Fixity::Mutable,
            index: KeyIndex::default(),
        },
        other => {
            return Err(Fault::internal(format!(
                "javars: `{other}` is not a collection javars models"
            )))
        }
    };
    Ok(Value::Obj(heap_alloc(obj)))
}

/// The distinct values of `vals`, keeping the first of each repeat — what
/// building a `Set` from a sequence produces.
///
/// De-duplication is the same membership question `Set.add` asks, so it goes
/// through the element's own `equals` when the element declares one; `Set.of`
/// and `new HashSet<>(list)` would otherwise keep two equal records.
fn distinct(vm: &mut VM, vals: &[Value]) -> Vec<Value> {
    let mut out: Vec<Value> = Vec::with_capacity(vals.len());
    for v in vals {
        let mut seen = false;
        for x in &out {
            let equal = if trusted_equals(vm, v, true) {
                eq_call(vm, v, x)
            } else {
                value_eq(v, x)
            };
            if equal {
                seen = true;
                break;
            }
        }
        if !seen {
            out.push(v.clone());
        }
    }
    out
}

/// The first value of `vals` that repeats an earlier one, under the same
/// comparison [`distinct`] de-duplicates with. `None` when they are all
/// distinct.
fn first_repeat(vm: &mut VM, vals: &[Value]) -> Option<Value> {
    for (i, v) in vals.iter().enumerate() {
        for x in &vals[..i] {
            let equal = if trusted_equals(vm, v, true) {
                eq_call(vm, v, x)
            } else {
                value_eq(v, x)
            };
            if equal {
                return Some(v.clone());
            }
        }
    }
    None
}

/// The elements of any sequence-shaped heap object — an array, a `List`, or a
/// `Set` (in presentation order) — cloned out from under the heap borrow.
fn sequence_items(v: &Value) -> Option<Vec<Value>> {
    let Value::Obj(id) = v else {
        return None;
    };
    // A `subList` view holds no elements of its own — its window has to be read
    // out of the backing list, and only after the view is checked against it,
    // so a stale view raises rather than reporting the wrong slice.
    if let Some(items) = sublist_items(*id as usize) {
        return items.ok();
    }
    HEAP.with(|h| {
        let h = h.borrow();
        match h.get(*id as usize) {
            Some(HostObj::Array(items)) | Some(HostObj::List { items, .. }) => Some(items.clone()),
            Some(HostObj::Set { items, order, .. }) => Some(
                present_order(items, *order)
                    .into_iter()
                    .map(|i| items[i].clone())
                    .collect(),
            ),
            _ => None,
        }
    })
}

/// The elements a `subList` view currently presents, or the comodification
/// fault if its backing list moved. `None` when the handle is not a view.
fn sublist_items(id: usize) -> Option<Result<Vec<Value>, Fault>> {
    if !is_sublist(id) {
        return None;
    }
    Some(checked_window(id).and_then(|(root, offset, len)| {
        HEAP.with(|h| match h.borrow().get(root) {
            Some(HostObj::List { items, .. }) => Ok(items[offset..offset + len].to_vec()),
            _ => Err(Fault::internal("javars: dangling subList backing")),
        })
    }))
}

/// The entries of a `Map` heap object, in insertion order.
fn map_entries(v: &Value) -> Option<Vec<(Value, Value)>> {
    let Value::Obj(id) = v else {
        return None;
    };
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::Map { entries, .. }) => Some(entries.clone()),
        _ => None,
    })
}

/// True when the handle points at a collection — the test that routes a
/// statically-untyped receiver away from the `String` methods.
fn is_collection(v: &Value) -> bool {
    let Value::Obj(id) = v else {
        return false;
    };
    HEAP.with(|h| {
        matches!(
            h.borrow().get(*id as usize),
            Some(
                HostObj::List { .. }
                    | HostObj::Map { .. }
                    | HostObj::Set { .. }
                    | HostObj::SubList { .. }
            )
        )
    })
}

// ── java.lang.StringBuilder / StringBuffer ───────────────────────────────
//
// The builder is a host shape (`HostObj::Builder`) rather than a class
// instance: its state is one growable string, and every method is a string
// operation. Allocation gets its own builtin ([`JSB_NEW`]); the methods reach
// [`builder_method`] from [`b_str_dispatch`], which is where every receiver
// whose static type is not a user class or a collection already lands.
//
// Index and length semantics use Unicode scalar positions, the same
// simplification [`string_method`] documents: Java counts UTF-16 units, so a
// builder holding an astral character reports a length one smaller here. Every
// bounds failure carries the JDK's own detail message, which is not one wording
// but three — `Index i out of bounds for length n` for a single index,
// `Range [s, e) out of bounds for length n` for a pair, and
// `String index out of range: n` for `setLength`.

/// Java's default `StringBuilder` capacity, and the slack `new
/// StringBuilder(str)` adds to its argument's length.
pub const SB_DEFAULT_CAP: usize = 16;

/// The `StringIndexOutOfBoundsException` a single out-of-range index raises.
fn sb_index_fault(i: i64, len: usize) -> Fault {
    Fault::java(
        "StringIndexOutOfBoundsException",
        format!("Index {i} out of bounds for length {len}"),
    )
}

/// The `StringIndexOutOfBoundsException` an out-of-range `[start, end)` pair
/// raises.
fn sb_range_fault(start: i64, end: i64, len: usize) -> Fault {
    Fault::java(
        "StringIndexOutOfBoundsException",
        format!("Range [{start}, {end}) out of bounds for length {len}"),
    )
}

/// Validate a scalar index against `len`, answering its byte offset in `s`.
fn sb_char_offset(s: &str, i: i64, len: usize) -> Result<usize, Fault> {
    if i < 0 || i as usize >= len {
        return Err(sb_index_fault(i, len));
    }
    Ok(sb_byte_of(s, len, i as usize))
}

/// The byte offset of the `n`-th character of a builder holding `len` of them.
///
/// A buffer whose byte length equals its character count holds nothing but
/// ASCII — UTF-8 spends one byte per character exactly then — so the character
/// index *is* the byte index and no decoding is needed. That is the common case
/// by a wide margin, and it turns `charAt` (and every other indexed operation)
/// from a walk from the start into an O(1) read.
fn sb_byte_of(s: &str, len: usize, n: usize) -> usize {
    if s.len() == len {
        return n.min(s.len());
    }
    s.char_indices().nth(n).map(|(b, _)| b).unwrap_or(s.len())
}

/// Validate a `[start, end)` pair the way `AbstractStringBuilder`'s
/// `checkRangeSIOOBE` does, answering the two byte offsets.
fn sb_range(s: &str, start: i64, end: i64, len: usize) -> Result<(usize, usize), Fault> {
    if start < 0 || start > end || end as usize > len {
        return Err(sb_range_fault(start, end, len));
    }
    Ok((
        sb_byte_of(s, len, start as usize),
        sb_byte_of(s, len, end as usize),
    ))
}

/// The next capacity `AbstractStringBuilder` grows to when `min` characters no
/// longer fit: `2 * old + 2`, or `min` when even that is too small.
fn sb_grow(cap: usize, min: usize) -> usize {
    if min <= cap {
        cap
    } else {
        (cap * 2 + 2).max(min)
    }
}

/// The text one `append`/`insert` argument contributes. javars has already
/// converted a `char` argument to its one-character String and a `float` to
/// `Float.toString` at the call site (`emit_char_string`), so this is the same
/// rendering every other Java string conversion uses.
///
/// An array argument is joined rather than rendered, because `append(char[])`
/// and `insert(int, char[])` are overloads that write the characters — the same
/// reading `String.valueOf(char[])` already takes, and for the same reason.
fn sb_arg_str(vm: &mut VM, v: &Value) -> String {
    match array_items(v) {
        Some(items) => items.iter().map(|e| java_str_vm(vm, e)).collect(),
        None => java_str_vm(vm, v),
    }
}

/// Evaluate `recv.method(args)` on a `StringBuilder`/`StringBuffer` receiver.
///
/// `None` means the name is not a builder method at all, which lets the caller
/// fall through to `java.lang.Object`'s (`equals`, `hashCode`, `getClass`) —
/// the three a builder genuinely inherits, and the reason `equals` compares
/// identity here as it does in Java rather than comparing the text.
fn builder_method(
    vm: &mut VM,
    id: u32,
    method: &str,
    args: &[Value],
) -> Option<Result<Value, Fault>> {
    // Arguments render before the heap borrow: a rendering may run a user
    // `toString()`, which re-enters the VM and can allocate.
    let rendered: Vec<String> = args.iter().map(|a| sb_arg_str(vm, a)).collect();
    Some(HEAP.with(|h| {
        let mut heap = h.borrow_mut();
        let Some(HostObj::Builder {
            s, len: count, cap, ..
        }) = heap.get_mut(id as usize)
        else {
            return Err(Fault::internal("javars: dangling StringBuilder handle"));
        };
        // The maintained character count. Every arm that changes the text
        // writes the new one back through `count`, from the delta it already
        // knows — no method walks the buffer to find out how long it is.
        let len = *count;
        let this = Value::Obj(id);
        match (method, args.len()) {
            ("toString", 0) | ("substring", 0) => Ok(Value::str(s.clone())),
            ("length", 0) => Ok(Value::Int(len as i64)),
            ("isEmpty", 0) => Ok(Value::bool(s.is_empty())),
            ("capacity", 0) => Ok(Value::Int(*cap as i64)),
            // `ensureCapacity` and `trimToSize` are allocation hints. The first
            // is observable through `capacity()`; the second is not, because
            // javars stores the text in a `String` that is already trimmed.
            ("ensureCapacity", 1) => {
                let want = args[0].jint();
                if want > 0 {
                    *cap = sb_grow(*cap, want as usize);
                }
                Ok(Value::Undef)
            }
            ("trimToSize", 0) => {
                *cap = len;
                Ok(Value::Undef)
            }
            ("append", 1) => {
                s.push_str(&rendered[0]);
                *count = len + rendered[0].chars().count();
                *cap = sb_grow(*cap, *count);
                Ok(this)
            }
            // `append(char[])` is a different method from `append(Object)`, and
            // it is the *only* one-argument `append` that rejects `null`: it
            // reads the array's length, so a null argument is an NPE where
            // `append((Object) null)` appends `"null"`. The two are one value at
            // runtime, so the compiler picks the overload from the argument's
            // static type and sends this name when it is `char[]`.
            ("appendChars", 1) => {
                if matches!(args[0], Value::Undef) {
                    return Err(Fault::java(
                        "NullPointerException",
                        "Cannot read the array length because \"str\" is null",
                    ));
                }
                s.push_str(&rendered[0]);
                *count = len + rendered[0].chars().count();
                *cap = sb_grow(*cap, *count);
                Ok(this)
            }
            // `append(char[], int, int)` — the array's characters from
            // `offset`, `len` of them. Java checks the window against the
            // array's length and reports the same `IndexOutOfBoundsException`
            // a bad `String.valueOf(char[], int, int)` does.
            ("appendChars", 3) => {
                let chars: Vec<char> = rendered[0].chars().collect();
                let (off, n) = (args[1].jint(), args[2].jint());
                if off < 0 || n < 0 || off + n > chars.len() as i64 {
                    return Err(Fault::java(
                        "IndexOutOfBoundsException",
                        format!("offset {off}, count {n}, length {}", chars.len()),
                    ));
                }
                let text: String = chars[off as usize..(off + n) as usize].iter().collect();
                s.push_str(&text);
                *count = len + n as usize;
                *cap = sb_grow(*cap, *count);
                Ok(this)
            }
            ("appendCodePoint", 1) => {
                let cp = args[0].jint();
                match u32::try_from(cp).ok().and_then(char::from_u32) {
                    Some(c) => {
                        s.push(c);
                        *count = len + 1;
                        *cap = sb_grow(*cap, *count);
                        Ok(this)
                    }
                    None => Err(Fault::java(
                        "IllegalArgumentException",
                        format!("Not a valid Unicode code point: 0x{cp:X}"),
                    )),
                }
            }
            ("repeat", 2) => {
                let n = args[1].jint().max(0) as usize;
                s.push_str(&rendered[0].repeat(n));
                *count = len + rendered[0].chars().count() * n;
                *cap = sb_grow(*cap, *count);
                Ok(this)
            }
            ("charAt", 1) => {
                let at = sb_char_offset(s, args[0].jint(), len)?;
                Ok(Value::Int(s[at..].chars().next().map_or(0, |c| c as i64)))
            }
            ("setCharAt", 2) => {
                let at = sb_char_offset(s, args[0].jint(), len)?;
                let old = s[at..].chars().next().map_or(0, char::len_utf8);
                s.replace_range(at..at + old, &rendered[1]);
                *count = len - 1 + rendered[1].chars().count();
                Ok(Value::Undef)
            }
            ("deleteCharAt", 1) => {
                let at = sb_char_offset(s, args[0].jint(), len)?;
                let old = s[at..].chars().next().map_or(0, char::len_utf8);
                s.replace_range(at..at + old, "");
                *count = len - 1;
                Ok(this)
            }
            // `delete` and `replace` clamp the end to the length before the
            // range check, which is why `delete(2, 100)` truncates rather than
            // throwing while `substring(1, 9)` throws.
            ("delete", 2) => {
                let start = args[0].jint();
                let end = args[1].jint().min(len as i64);
                let (a, b) = sb_range(s, start, end, len)?;
                s.replace_range(a..b, "");
                *count = len - (end - start) as usize;
                Ok(this)
            }
            ("replace", 3) => {
                let start = args[0].jint();
                let end = args[1].jint().min(len as i64);
                let (a, b) = sb_range(s, start, end, len)?;
                s.replace_range(a..b, &rendered[2]);
                *count = len - (end - start) as usize + rendered[2].chars().count();
                *cap = sb_grow(*cap, *count);
                Ok(this)
            }
            ("substring", 1) => {
                let (a, b) = sb_range(s, args[0].jint(), len as i64, len)?;
                Ok(Value::str(s[a..b].to_string()))
            }
            ("substring", 2) | ("subSequence", 2) => {
                let (a, b) = sb_range(s, args[0].jint(), args[1].jint(), len)?;
                Ok(Value::str(s[a..b].to_string()))
            }
            // `insert`'s bounds failure names the *builder's* length as the
            // range end, which is what `checkOffset` reports:
            // `Range [9, 3) out of bounds for length 3`.
            ("insert", 2) => {
                let at = args[0].jint();
                if at < 0 || at as usize > len {
                    return Err(sb_range_fault(at, len as i64, len));
                }
                s.insert_str(sb_byte_of(s, len, at as usize), &rendered[1]);
                *count = len + rendered[1].chars().count();
                *cap = sb_grow(*cap, *count);
                Ok(this)
            }
            // `reverse` reverses code points, not UTF-16 units, so a surrogate
            // pair survives it — which is what Java's own `reverse` guarantees.
            // The length is unchanged, so `count` is left alone.
            ("reverse", 0) => {
                *s = s.chars().rev().collect();
                Ok(this)
            }
            ("setLength", 1) => {
                let n = args[0].jint();
                if n < 0 {
                    return Err(Fault::java(
                        "StringIndexOutOfBoundsException",
                        format!("String index out of range: {n}"),
                    ));
                }
                let n = n as usize;
                if n < len {
                    s.truncate(sb_byte_of(s, len, n));
                } else {
                    // Java pads the extra positions with the NUL character,
                    // which is observable: after `setLength(4)` on "ab",
                    // `charAt(3)` is 0.
                    s.extend(std::iter::repeat('\0').take(n - len));
                }
                *count = n;
                *cap = sb_grow(*cap, n);
                Ok(Value::Undef)
            }
            ("indexOf", 1) => Ok(Value::Int(char_index_of(s, &rendered[0]))),
            ("indexOf", 2) => {
                let from = args[1].jint().clamp(0, len as i64) as usize;
                let byte = sb_byte_of(s, len, from);
                Ok(Value::Int(match char_index_of(&s[byte..], &rendered[0]) {
                    -1 => -1,
                    i => i + from as i64,
                }))
            }
            ("lastIndexOf", 1) => Ok(Value::Int(char_last_index_of(s, &rendered[0], len as i64))),
            ("lastIndexOf", 2) => Ok(Value::Int(char_last_index_of(
                s,
                &rendered[0],
                args[1].jint(),
            ))),
            // `compareTo(StringBuilder)` is `String.compareTo` on the contents
            // (Java 11+); `equals` is NOT — it stays reference identity, which
            // is why it is left to `object_method`.
            ("compareTo", 1) => Ok(Value::Int(compare_strings(s, &rendered[0], false))),
            ("chars", 0) | ("codePoints", 0) => Err(Fault::internal(format!(
                "javars: unsupported StringBuilder method `{method}` with 0 argument(s)"
            ))),
            _ => Err(Fault::internal(format!(
                "javars: unsupported StringBuilder method `{method}` with {} argument(s)",
                args.len()
            ))),
        }
    }))
}

/// True when the handle points at a `StringBuilder`/`StringBuffer` — the test
/// that routes a statically-untyped receiver away from the `String` methods.
fn is_builder(v: &Value) -> Option<u32> {
    let Value::Obj(id) = v else { return None };
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::Builder { .. }) => Some(*id),
        _ => None,
    })
}

/// [`JSB_NEW`] — allocate a `StringBuilder`/`StringBuffer`.
fn b_sb_new(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let buffer = args
        .first()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default()
        == "StringBuffer";
    let seed = args.get(1).cloned().unwrap_or(Value::Undef);
    // The three constructors, told apart by the argument's runtime shape the
    // same way Java's overload resolution tells them apart statically.
    let (s, cap) = match &seed {
        // `new StringBuilder((String) null)` dereferences its argument before
        // it sizes anything; the no-argument form reaches here as the capacity
        // 16 it is defined as, so `Undef` can only be a real `null`.
        Value::Undef => {
            return raise(
                vm,
                Fault::java(
                    "NullPointerException",
                    "Cannot invoke \"String.length()\" because \"str\" is null",
                ),
            )
        }
        Value::Int(n) => {
            if *n < 0 {
                return raise(vm, Fault::java("NegativeArraySizeException", n.to_string()));
            }
            (String::new(), *n as usize)
        }
        other => {
            let text = java_str_vm(vm, other);
            let n = text.chars().count();
            (text, n + SB_DEFAULT_CAP)
        }
    };
    let len = s.chars().count();
    Value::Obj(heap_alloc(HostObj::Builder {
        s,
        len,
        cap,
        buffer,
    }))
}

/// [`JCOLL_NEW`] — see [`new_collection`].
fn b_coll_new(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let kind = args
        .first()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    let seed = args.get(1).cloned().unwrap_or(Value::Undef);
    match new_collection(vm, &kind, &seed) {
        Ok(v) => v,
        Err(f) => raise(vm, f),
    }
}

/// [`JITER_ARRAY`] — the elements of an enhanced-`for` iterable as an array.
fn b_iter_array(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let it = args.into_iter().next().unwrap_or(Value::Undef);
    // Already an array: hand the same handle back, so an array loop keeps
    // aliasing (mutating `a[i]` inside the loop is visible).
    if let Value::Obj(id) = it {
        if HEAP.with(|h| matches!(h.borrow().get(id as usize), Some(HostObj::Array(_)))) {
            return it;
        }
    }
    match sequence_items(&it) {
        Some(items) => Value::Obj(heap_alloc(HostObj::Array(items))),
        None if matches!(it, Value::Undef) => raise(
            vm,
            Fault::java(
                "NullPointerException",
                "Cannot iterate over a null reference".to_string(),
            ),
        ),
        None => raise(
            vm,
            Fault::internal("javars: the enhanced `for` needs an array or a collection"),
        ),
    }
}

/// Run the subroutine at `entry` whose prologue values are already stacked above
/// `stack_base`, in its own call frame, and return its value.
///
/// The pushed frame's `return_ip` is past the end of the chunk, so the body's
/// `Op::ReturnValue` pops the frame and ends the nested run at exactly that
/// point. The interpreter's `ip` is saved and restored so the paused enclosing
/// dispatch loop resumes where it left off.
fn run_sub(vm: &mut VM, entry: usize, stack_base: usize) -> Value {
    let return_ip = vm.chunk.ops.len();
    vm.frames.push(fusevm::Frame {
        return_ip,
        stack_base,
        slots: Vec::new(),
        // Same identity `Op::Call` records: this frame enters the subroutine
        // at `entry`, so `Chunk::sub_slot_names` is reachable from it.
        entry_ip: Some(entry),
    });
    let saved_ip = vm.ip;
    vm.ip = entry;
    let result = vm.run();
    vm.ip = saved_ip;
    match result {
        fusevm::VMResult::Ok(v) => v,
        // A halt raised inside the body (an internal fault) leaves the halt flag
        // set, which stops the enclosing run too; hand back whatever is on top.
        fusevm::VMResult::Halted => vm.stack.pop().unwrap_or(Value::Undef),
        fusevm::VMResult::Error(e) => {
            ffi_fault(vm, format!("javars: {e}"));
            Value::Undef
        }
    }
}

/// Pop `argc` values off the VM stack, restoring source (deepest-first) order.
fn pop_args(vm: &mut VM, argc: u8) -> Vec<Value> {
    let mut v = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        v.push(vm.stack.pop().unwrap_or(Value::Undef));
    }
    v.reverse();
    v
}

/// Pop the operands of a **fixed-shape** builtin into `N` slots, deepest first
/// — the order [`pop_args`] answers in, without the `Vec` it allocates.
///
/// A field read and a field write know exactly how many operands they take, so
/// the heap allocation buys them nothing, and they sit on the hottest path an
/// object-heavy loop has: one per field access. Operands beyond the `N` the
/// builtin declares (a shape the compiler does not emit) are discarded, and
/// fewer than `N` leaves the missing slots `Undef` rather than underflowing.
fn pop_fixed<const N: usize>(vm: &mut VM, argc: u8) -> [Value; N] {
    let mut out = std::array::from_fn(|_| Value::Undef);
    for _ in N..argc as usize {
        let _ = vm.stack.pop();
    }
    for slot in out.iter_mut().take(N.min(argc as usize)).rev() {
        *slot = vm.stack.pop().unwrap_or(Value::Undef);
    }
    out
}

/// `new T[n]` — build an `n`-element array filled with the element default
/// (stack `[size, default]`).
fn b_array_new(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let size = args.first().map(|v| v.jint()).unwrap_or(0);
    let default = args.get(1).cloned().unwrap_or(Value::Undef);
    if size < 0 {
        return raise(
            vm,
            Fault::java("NegativeArraySizeException", size.to_string()),
        );
    }
    let arr = vec![default; size as usize];
    Value::Obj(heap_alloc(HostObj::Array(arr)))
}

/// `new T[s0][s1]…` — build a rectangular nested array (stack
/// `[s0, …, sK, leafDefault]`). The innermost level is filled with `leafDefault`
/// (the element type default for a fully-sized `new int[2][3]`, or `null` when
/// trailing dimensions are unsized as in `new int[2][]`).
fn b_array_new_multi(vm: &mut VM, argc: u8) -> Value {
    let mut args = pop_args(vm, argc);
    // Last arg is the leaf default; the rest are the dimension sizes.
    let default = args.pop().unwrap_or(Value::Undef);
    let sizes: Vec<i64> = args.iter().map(|v| v.jint()).collect();
    if let Some(&n) = sizes.iter().find(|&&s| s < 0) {
        return raise(vm, Fault::java("NegativeArraySizeException", n.to_string()));
    }
    match build_nested(&sizes, &default) {
        Some(v) => v,
        None => raise(
            vm,
            Fault::internal("javars: multi-dimensional array needs a size"),
        ),
    }
}

/// Recursively allocate `sizes.len()` nested array levels; the innermost holds
/// clones of `default`. `None` when `sizes` is empty (no dimension).
fn build_nested(sizes: &[i64], default: &Value) -> Option<Value> {
    let (&head, rest) = sizes.split_first()?;
    let n = head.max(0) as usize;
    let elems: Vec<Value> = if rest.is_empty() {
        vec![default.clone(); n]
    } else {
        (0..n)
            .map(|_| build_nested(rest, default).unwrap_or(Value::Undef))
            .collect()
    };
    Some(Value::Obj(heap_alloc(HostObj::Array(elems))))
}

/// `{a, b, …}` — build an array from the popped element values.
fn b_array_lit(vm: &mut VM, argc: u8) -> Value {
    let elems = pop_args(vm, argc);
    Value::Obj(heap_alloc(HostObj::Array(elems)))
}

/// `a[i]` read (stack `[array, index]`), bounds-checked.
///
/// The lookup runs inside the `HEAP` borrow and any fault is raised *after* it
/// ends — [`raise`] allocates the throwable on that same heap, so raising while
/// the borrow is live would panic.
fn b_array_get(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let arr = args.first().cloned().unwrap_or(Value::Undef);
    let idx = args.get(1).map(|v| v.jint()).unwrap_or(0);
    let id = match arr {
        Value::Obj(id) => id,
        _ => return raise(vm, Fault::java("NullPointerException", NULL_ARRAY_LOAD)),
    };
    let got = HEAP.with(|h| {
        let h = h.borrow();
        match h.get(id as usize) {
            Some(HostObj::Array(a)) => match usize::try_from(idx).ok().and_then(|i| a.get(i)) {
                Some(v) => Ok(v.clone()),
                None => Err(index_fault(idx, a.len())),
            },
            _ => Err(Fault::internal("javars: not an array")),
        }
    });
    match got {
        Ok(v) => v,
        Err(f) => raise(vm, f),
    }
}

/// Java's `ArrayIndexOutOfBoundsException` detail message.
fn index_fault(idx: i64, len: usize) -> Fault {
    Fault::java(
        "ArrayIndexOutOfBoundsException",
        format!("Index {idx} out of bounds for length {len}"),
    )
}

// Java's "helpful NullPointerException" messages name the *bytecode local slot*
// of the null reference (`because "<local3>" is null`), which javars cannot
// reproduce — it has no javac slot numbering. These keep the operation half of
// Java's wording and drop the provenance clause (see BUGS.md).
const NULL_ARRAY_LOAD: &str = "Cannot load from array because the array is null";
const NULL_ARRAY_STORE: &str = "Cannot store to array because the array is null";
const NULL_ARRAY_LENGTH: &str = "Cannot read the array length because the array is null";

/// `a[i] = v` write (stack `[array, index, value]`), bounds-checked. Returns `v`.
fn b_array_set(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let arr = args.first().cloned().unwrap_or(Value::Undef);
    let idx = args.get(1).map(|v| v.jint()).unwrap_or(0);
    let val = args.get(2).cloned().unwrap_or(Value::Undef);
    let id = match arr {
        Value::Obj(id) => id,
        _ => return raise(vm, Fault::java("NullPointerException", NULL_ARRAY_STORE)),
    };
    let stored = HEAP.with(|h| {
        let mut h = h.borrow_mut();
        match h.get_mut(id as usize) {
            Some(HostObj::Array(a)) => match usize::try_from(idx).ok().filter(|&i| i < a.len()) {
                Some(i) => {
                    a[i] = val.clone();
                    Ok(())
                }
                None => Err(index_fault(idx, a.len())),
            },
            _ => Err(Fault::internal("javars: not an array")),
        }
    });
    match stored {
        Ok(()) => val,
        Err(f) => raise(vm, f),
    }
}

/// `new C(...)` — allocate an instance with an empty field map (stack
/// `[className]`). The compiler emits field defaults/initializers and the
/// constructor call after this.
fn b_new(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let class = args
        .first()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    Value::Obj(heap_alloc(HostObj::Instance {
        class,
        fields: HashMap::new(),
    }))
}

/// `recv.field` read (stack `[recv, name]`): an array's `.length` or an instance
/// field.
fn b_field_get(vm: &mut VM, argc: u8) -> Value {
    // The compiler emits this builtin with the receiver pushed first and the
    // field name on top, so both come off the stack directly. Going through
    // `pop_args` cost a `Vec` allocation, and copying the name out of its
    // `Cow` cost a `String` allocation — two mallocs on the path a loop over an
    // object's fields takes once per read. `Value::Str`'s `as_str_cow` borrows,
    // and `HashMap<String, _>` looks up by `&str`, so neither is needed.
    let [recv, name_v] = pop_fixed::<2>(vm, argc);
    let name = name_v.as_str_cow();
    let name = name.as_ref();
    let id = match recv {
        Value::Obj(id) => id,
        _ => {
            // `null.length` is Java's array-length NPE; any other name is a
            // field read.
            let msg = if name == "length" {
                NULL_ARRAY_LENGTH.to_string()
            } else {
                format!("Cannot read field \"{name}\" because the receiver is null")
            };
            return raise(vm, Fault::java("NullPointerException", msg));
        }
    };
    let got = HEAP.with(|h| {
        let h = h.borrow();
        match h.get(id as usize) {
            Some(HostObj::Array(a)) if name == "length" => Ok(Value::Int(a.len() as i64)),
            Some(HostObj::Instance { fields, .. }) => {
                Ok(fields.get(name).cloned().unwrap_or(Value::Undef))
            }
            _ => Err(Fault::internal(format!("javars: no field `{name}`"))),
        }
    });
    match got {
        Ok(v) => v,
        Err(f) => raise(vm, f),
    }
}

/// `recv.field = v` write (stack `[recv, name, value]`). Returns `v`.
fn b_field_set(vm: &mut VM, argc: u8) -> Value {
    // Same fixed shape as [`b_field_get`], and the same two allocations saved.
    let [recv, name_v, val] = pop_fixed::<3>(vm, argc);
    let name = name_v.as_str_cow();
    let name = name.as_ref();
    let id = match recv {
        Value::Obj(id) => id,
        _ => {
            return raise(
                vm,
                Fault::java(
                    "NullPointerException",
                    format!("Cannot assign field \"{name}\" because the receiver is null"),
                ),
            )
        }
    };
    let ok = HEAP.with(|h| {
        let mut h = h.borrow_mut();
        match h.get_mut(id as usize) {
            Some(HostObj::Instance { fields, .. }) => {
                // The name is only copied when the field is *new*; an
                // assignment to an existing one — which every loop body does —
                // writes through the entry already there.
                match fields.get_mut(name) {
                    Some(slot) => *slot = val.clone(),
                    None => {
                        fields.insert(name.to_string(), val.clone());
                    }
                }
                true
            }
            _ => false,
        }
    });
    if ok {
        val
    } else {
        raise(
            vm,
            Fault::internal(format!("javars: cannot assign field `{name}`")),
        )
    }
}

/// `x instanceof C` (stack `[obj, className]`). Null is never an instance.
fn b_instanceof(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let obj = args.first().cloned().unwrap_or(Value::Undef);
    let target = args
        .get(1)
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    Value::bool(is_instance_of(&obj, &target))
}

/// The class a value answers `instanceof` as, for every shape javars's value
/// model names one.
///
/// `None` means the class is genuinely not recorded rather than absent from this
/// list: `null`, and a lambda, whose closure carries its body and its captures
/// but not the functional interface it was assigned to.
///
/// The two names that are not legal Java identifiers — `[]` and `List$view` —
/// exist so an array and a non-`ArrayList` list view can carry supertypes in
/// [`jdk_supers`] without a user type ever being able to name them.
fn value_class(v: &Value) -> Option<String> {
    Some(match v {
        Value::Str(_) => "String".to_string(),
        Value::Int(_) => "Integer".to_string(),
        Value::Float(_) => "Double".to_string(),
        Value::Bool(_) => "Boolean".to_string(),
        Value::Obj(id) => {
            return HEAP.with(|h| {
                Some(match h.borrow().get(*id as usize)? {
                    HostObj::Instance { class, .. } => class.clone(),
                    // The whole point of the box: `Integer` and `Long` are
                    // different classes for a value one `Value::Int` holds.
                    HostObj::Boxed => box_class(v)?.to_string(),
                    // Not a name a program can write, like the other internal
                    // shapes — it exists so an iterator carries supertypes.
                    HostObj::Iterator { .. } => "Iterator$of".to_string(),
                    HostObj::Optional { class, .. } => (*class).to_string(),
                    HostObj::Stream { .. } => "Stream$of".to_string(),
                    HostObj::Collector { .. } => "Collector$of".to_string(),
                    HostObj::Array(_) => "[]".to_string(),
                    // `Arrays.asList` and `List.of` are `List`s that are not
                    // `ArrayList`s, and a `subList` view is a third answer
                    // again — see the note in [`jdk_supers`].
                    HostObj::List { fixed, .. } => match fixed {
                        Fixity::Mutable => "ArrayList".to_string(),
                        Fixity::FixedSize => "List$fixed".to_string(),
                        Fixity::Immutable => "List$immutable".to_string(),
                    },
                    HostObj::SubList { .. } => "List$sub".to_string(),
                    HostObj::Map { order, fixed, .. } => match (fixed, order) {
                        (Fixity::Immutable, _) => "Map$immutable".to_string(),
                        (_, Order::Hash) => "HashMap".to_string(),
                        (_, Order::Insertion) => "LinkedHashMap".to_string(),
                        (_, Order::Sorted) => "TreeMap".to_string(),
                    },
                    // `Set.of` is not a `HashSet`, exactly as `List.of` is not
                    // an `ArrayList`; without the fixity it answered to both.
                    HostObj::Set { order, fixed, .. } => match (fixed, order) {
                        (Fixity::Mutable | Fixity::FixedSize, Order::Hash) => "HashSet".to_string(),
                        (Fixity::Mutable | Fixity::FixedSize, Order::Insertion) => {
                            "LinkedHashSet".to_string()
                        }
                        (Fixity::Mutable | Fixity::FixedSize, Order::Sorted) => {
                            "TreeSet".to_string()
                        }
                        (Fixity::Immutable, _) => "Set$immutable".to_string(),
                    },
                    HostObj::Builder { buffer, .. } => if *buffer {
                        "StringBuffer"
                    } else {
                        "StringBuilder"
                    }
                    .to_string(),
                    HostObj::Closure { .. } => return None,
                })
            });
        }
        _ => return None,
    })
}

/// Java's `x instanceof T`: true when `x` is a non-null reference whose runtime
/// class is `T`, a subclass of it, or a type implementing the interface `T`.
///
/// Two rules come before the graph walk, and both are the reason the previous
/// implementation — which answered only for a `String` and a user-class instance
/// and returned `false` for everything else — was wrong far more often than it
/// looked. `null` is an instance of nothing, including `Object`; and every
/// non-null reference *is* an `Object`, whatever javars models it as.
fn is_instance_of(v: &Value, target: &str) -> bool {
    let Some(class) = value_class(v) else {
        // `null` is an instance of nothing. A lambda is at least an `Object`;
        // its functional interface is not recorded, so that is as far as the
        // answer goes.
        return target == "Object" && matches!(v, Value::Obj(_));
    };
    target == "Object" || is_subclass_of(&class, target)
}

/// `__rust_compile("<base64>")` builtin: pop the base64-encoded `rust { ... }`
/// block body, compile it to a cdylib, and register its exports. Returns `null`.
fn b_ffi_compile(vm: &mut VM, argc: u8) -> Value {
    // The compiler emits exactly one argument (the base64 body); pop `argc`
    // defensively and keep the deepest.
    let mut body = Value::Undef;
    for _ in 0..argc {
        body = vm.stack.pop().unwrap_or(Value::Undef);
    }
    let b64 = body.as_str_cow().into_owned();
    if let Err(e) = fusevm::ffi::compile_and_register(&b64) {
        ffi_fault(vm, format!("javars: rust {{}} block: {e}"));
    }
    Value::Undef
}

/// `name(args...)` FFI dispatch builtin: pop the function name (top of stack)
/// and its `argc - 1` arguments, call the exported symbol via `fusevm::ffi`, and
/// return its result.
fn b_ffi_call(vm: &mut VM, argc: u8) -> Value {
    let name = vm
        .stack
        .pop()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    let n = argc.saturating_sub(1) as usize;
    let mut args = Vec::with_capacity(n);
    for _ in 0..n {
        args.push(vm.stack.pop().unwrap_or(Value::Undef));
    }
    args.reverse();
    match fusevm::ffi::try_call(&name, &args) {
        Some(Ok(v)) => v,
        Some(Err(e)) => {
            ffi_fault(vm, format!("javars: rust FFI call {name}: {e}"));
            Value::Undef
        }
        None => {
            ffi_fault(vm, format!("javars: unresolved reference: {name}"));
            Value::Undef
        }
    }
}

/// [`JCOLL_DISPATCH`] — an instance method on a collection receiver.
fn b_coll_dispatch(vm: &mut VM, argc: u8) -> Value {
    let method = vm
        .stack
        .pop()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    let n = argc.saturating_sub(2) as usize;
    let mut args = Vec::with_capacity(n);
    for _ in 0..n {
        args.push(vm.stack.pop().unwrap_or(Value::Undef));
    }
    args.reverse();
    let recv = vm.stack.pop().unwrap_or(Value::Undef);
    coll_method(vm, &recv, &method, &args)
}

/// Evaluate `recv.method(args)` on a collection.
///
/// Every method that mutates takes the heap borrow, edits, and drops it before
/// returning; the two that run user code (`sort` with a comparator, `forEach`)
/// snapshot first and re-enter the VM with no borrow held, because a lambda body
/// can allocate.
fn coll_method(vm: &mut VM, recv: &Value, method: &str, args: &[Value]) -> Value {
    let Value::Obj(id) = recv else {
        return raise(
            vm,
            Fault::java(
                "NullPointerException",
                format!("Cannot invoke \"{method}()\" because the receiver is null"),
            ),
        );
    };
    let id = *id as usize;
    // Every method on a view checks it against its backing list first, exactly
    // as Java's `checkForComodification` does. `sublist_method` repeats the
    // check to get the window; this one covers the paths that bypass it
    // (`toString`, `sort`, `forEach`).
    if let Some(f) = stale_view(recv) {
        return raise(vm, f);
    }
    // `subList` allocates a view over the receiver, so it needs the receiver's
    // handle — which `list_method` (working on a plain `&mut Vec`) never sees.
    if method == "subList" && args.len() == 2 {
        return match make_sublist(id, args[0].jint(), args[1].jint()) {
            Ok(v) => v,
            Err(f) => raise(vm, f),
        };
    }
    // The two VM-re-entering methods are handled before any borrow is taken.
    match (method, args.len()) {
        ("sort", 1) => {
            let Some(items) = sequence_items(recv) else {
                return raise(vm, Fault::internal("javars: `sort` needs a List receiver"));
            };
            let sorted = match sort_with(vm, items, &args[0]) {
                Ok(v) => v,
                Err(f) => return raise(vm, f),
            };
            // `ArrayList.sort` bumps `modCount` even though the length is
            // unchanged, so an outstanding view is invalidated by it — verified
            // against the reference JDK, which throws for a view read after
            // `Collections.sort(parent)`.
            if let Err(f) = write_sequence(id, sorted, true) {
                return raise(vm, f);
            }
            return Value::Undef;
        }
        ("forEach", 1) => {
            // A `Map`'s consumer takes (key, value); a List/Set's takes one.
            if let Some(entries) = map_entries(recv) {
                let order = map_order(recv);
                let keys: Vec<Value> = entries.iter().map(|(k, _)| k.clone()).collect();
                for i in present_order(&keys, order) {
                    let (k, v) = entries[i].clone();
                    invoke_closure(vm, &args[0], &[k, v]);
                }
            } else if let Some(items) = sequence_items(recv) {
                for it in items {
                    invoke_closure(vm, &args[0], &[it]);
                }
            }
            return Value::Undef;
        }
        _ => {}
    }
    // `toString` renders elements, which re-reads the heap (an element may be
    // another collection), so it runs before any borrow is taken.
    if method == "toString" && args.is_empty() {
        return Value::str(java_str_vm(vm, recv));
    }
    // `hashCode` reads each element's, which may be a user body — same
    // constraint, same treatment.
    if let Some(h) = collection_hash(vm, recv, method, args.len()) {
        return h;
    }
    // `stream()` on a collection — a *second* heap object, like the iterator
    // below, and built from the elements as they stand.
    if method == "stream" && args.is_empty() {
        if let Some(items) = sequence_items(recv) {
            return stream_of(items, StreamKind::Ref);
        }
    }
    // An iterator names a *second* heap object, so both its construction and
    // its own methods run outside the exclusive borrow below.
    if method == "iterator" && args.is_empty() {
        if let Value::Obj(id) = recv {
            return Value::Obj(heap_alloc(HostObj::Iterator {
                source: *id,
                pos: 0,
                last: None,
                exp_mods: iter_mods(*id),
            }));
        }
    }
    // Likewise `addAll`/`equals` read their argument collection: snapshot it
    // first, because the borrow below is exclusive.
    let arg_seqs: Vec<Option<Vec<Value>>> = args.iter().map(sequence_items).collect();
    // `Map.equals` reads the *other* map's entries, which `sequence_items` does
    // not carry (a map is not a sequence). Snapshot it here for the same reason:
    // the borrow below is exclusive, and reading the heap under it panics.
    let arg_entries: Vec<Option<Vec<(Value, Value)>>> = args.iter().map(map_entries).collect();
    // Java answers a membership question with the element's own `equals`, whose
    // body needs the VM and no outstanding borrow — so it runs here, ahead of
    // the borrow, and the sections below read its verdicts.
    let eq = eq_plan(vm, recv, method, args, &arg_seqs);
    // A throwable one of those bodies raised aborts the call rather than
    // answering from a half-resolved plan.
    if PENDING.with(|p| p.borrow().is_some()) {
        return Value::Undef;
    }
    let eq = eq.as_ref();
    if is_sublist(id) {
        return match sublist_method(id, method, args, &arg_seqs, eq) {
            Ok(v) => v,
            Err(f) => raise(vm, f),
        };
    }
    let result = HEAP.with(|h| {
        let mut heap = h.borrow_mut();
        let Some(obj) = heap.get_mut(id) else {
            return Err(Fault::internal("javars: dangling collection handle"));
        };
        match obj {
            HostObj::List { items, fixed, mods } => {
                let before = items.len();
                let r = list_method(items, *fixed, method, args, &arg_seqs, eq);
                // Any length change is a structural modification, which is what
                // Java's `modCount` counts (a `remove` that finds nothing does
                // not bump it there either).
                if items.len() != before {
                    *mods += 1;
                }
                r
            }
            HostObj::Map {
                entries,
                order,
                fixed,
                index,
            } => map_method(
                entries,
                MapShape {
                    order: *order,
                    fixed: *fixed,
                },
                index,
                method,
                args,
                &arg_entries,
                eq,
            ),
            HostObj::Set {
                items,
                fixed,
                index,
                ..
            } => set_method(items, *fixed, index, method, args, &arg_seqs, eq),
            _ => Err(Fault::internal(format!(
                "javars: `{method}` is not a collection method"
            ))),
        }
    });
    match result {
        Ok(NewColl::Value(v)) => v,
        // A derived view (`keySet`, `values`) is allocated after the borrow is
        // released, because allocating touches the same slab.
        Ok(NewColl::Alloc(obj)) => Value::Obj(heap_alloc(obj)),
        Err(f) => raise(vm, f),
    }
}

/// A collection method's result: a plain value, or a new heap object that must
/// be allocated once the receiver's borrow has been dropped.
enum NewColl {
    Value(Value),
    Alloc(HostObj),
}

// ── `List.subList` views ────────────────────────────────────────────────────
//
// A view owns no elements. `resolve_window` walks the (possibly nested) parent
// chain down to the backing `List`, giving an absolute window into it; every
// operation reads that window out, runs the ordinary `list_method` on it, and
// writes it back. A length change there is a structural modification of the
// backing list, so it bumps the backing `mods` and is pushed up the ancestor
// chain — matching Java's `SubList.updateSizeAndModCount`, which keeps the
// enclosing views usable while a *sibling* view correctly goes stale.

/// True when a handle is a `subList` view rather than a list of its own.
fn is_sublist(id: usize) -> bool {
    HEAP.with(|h| matches!(h.borrow().get(id), Some(HostObj::SubList { .. })))
}

/// The comodification fault a value would raise if it were rendered — `Some`
/// only for a `subList` view whose backing list has been structurally modified
/// since. Java reports it because rendering a view iterates it; javars's
/// rendering is infallible, so the raising call sites consult this first.
fn stale_view(v: &Value) -> Option<Fault> {
    let Value::Obj(id) = v else {
        return None;
    };
    sublist_items(*id as usize)?.err()
}

/// A view resolved against its backing list: the backing `List`'s handle, the
/// absolute offset of the window, and its length. `None` when `id` is not a
/// view, or when the chain does not bottom out in a `List`.
fn resolve_window(id: usize) -> Option<(usize, usize, usize)> {
    HEAP.with(|h| {
        let heap = h.borrow();
        let Some(HostObj::SubList { len, .. }) = heap.get(id) else {
            return None;
        };
        let len = *len;
        let mut offset = 0;
        let mut cur = id;
        // The chain is built parent-first and can only ever be as deep as the
        // heap is long, which bounds the walk even if a handle were corrupted.
        for _ in 0..=heap.len() {
            match heap.get(cur) {
                Some(HostObj::SubList {
                    parent, offset: o, ..
                }) => {
                    offset += o;
                    cur = *parent as usize;
                }
                Some(HostObj::List { .. }) => return Some((cur, offset, len)),
                _ => return None,
            }
        }
        None
    })
}

/// The backing list's structural-modification count, or `None` for a handle
/// that is not a `List`.
fn list_mods(id: usize) -> Option<u64> {
    HEAP.with(|h| match h.borrow().get(id) {
        Some(HostObj::List { mods, .. }) => Some(*mods),
        _ => None,
    })
}

/// Allocate a plain `java.util.Optional`.
fn optional(v: Option<Value>) -> Value {
    optional_of("Optional", v)
}

/// Allocate an `Optional` of the given class — one of `Optional`,
/// `OptionalInt`, `OptionalLong`, `OptionalDouble`.
fn optional_of(class: &'static str, value: Option<Value>) -> Value {
    Value::Obj(heap_alloc(HostObj::Optional { class, value }))
}

/// The class and contents of an `Optional` handle, or `None` when the value is
/// not an `Optional` at all.
fn as_optional_full(v: &Value) -> Option<(&'static str, Option<Value>)> {
    let Value::Obj(id) = v else {
        return None;
    };
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::Optional { class, value }) => Some((*class, value.clone())),
        _ => None,
    })
}

/// The source and pipeline of a `Stream` handle, or `None` for anything else.
fn as_stream(v: &Value) -> Option<(Vec<Value>, Vec<Stage>, StreamKind)> {
    let Value::Obj(id) = v else {
        return None;
    };
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::Stream {
            source,
            stages,
            kind,
        }) => Some((source.clone(), stages.clone(), *kind)),
        _ => None,
    })
}

/// Allocate a stream over `source`.
fn stream_of(source: Vec<Value>, kind: StreamKind) -> Value {
    Value::Obj(heap_alloc(HostObj::Stream {
        source,
        stages: Vec::new(),
        kind,
    }))
}

/// Allocate the stream `recv` becomes with `stage` appended.
///
/// A stream is single-use in Java and javars does not enforce that, so appending
/// to a *copy* rather than mutating in place is the safe reading: a program that
/// (illegally) reuses one sees the pipeline it built, not one a later stage
/// extended underneath it.
fn stream_with(recv: &Value, kind: StreamKind, stage: Option<Stage>) -> Option<Value> {
    let (source, mut stages, _) = as_stream(recv)?;
    if let Some(stage) = stage {
        stages.push(stage);
    }
    Some(Value::Obj(heap_alloc(HostObj::Stream {
        source,
        stages,
        kind,
    })))
}

/// Push one element through `stages`, calling `sink` for each element that
/// reaches the end. Answers `false` when the pipeline has been cancelled — by a
/// `limit` filling up, or by a short-circuiting terminal.
///
/// `counters` is one slot per stage, so a `limit` or a `skip` keeps its own
/// count across elements. It is split alongside `stages` so each stage reads its
/// own slot and never another's.
fn stream_push(
    vm: &mut VM,
    v: Value,
    stages: &[Stage],
    counters: &mut [i64],
    sink: &mut dyn FnMut(&mut VM, Value) -> bool,
) -> bool {
    let (Some(stage), rest) = (stages.first(), &stages[stages.len().min(1)..]) else {
        return sink(vm, v);
    };
    let (count, rest_counts) = counters.split_first_mut().expect("one counter per stage");
    match stage {
        Stage::Filter(p) => {
            if matches!(
                invoke_closure(vm, p, std::slice::from_ref(&v)),
                Value::Bool(true)
            ) {
                stream_push(vm, v, rest, rest_counts, sink)
            } else {
                true
            }
        }
        Stage::Map(f) => {
            let mapped = invoke_closure(vm, f, &[v]);
            stream_push(vm, mapped, rest, rest_counts, sink)
        }
        Stage::FlatMap(f) => {
            let inner = invoke_closure(vm, f, &[v]);
            // The mapper answers a stream (or, tolerantly, a collection): its
            // elements are pushed on in place of the one that produced them.
            let elems = match as_stream(&inner) {
                Some((src, st, _)) => {
                    let mut out = Vec::new();
                    let mut cs = vec![0i64; st.len()];
                    for e in src {
                        if !stream_push(vm, e, &st, &mut cs, &mut |_vm, x| {
                            out.push(x);
                            true
                        }) {
                            break;
                        }
                    }
                    out
                }
                None => sequence_items(&inner).unwrap_or_default(),
            };
            for e in elems {
                if !stream_push(vm, e, rest, rest_counts, sink) {
                    return false;
                }
            }
            true
        }
        Stage::Peek(f) => {
            invoke_closure(vm, f, std::slice::from_ref(&v));
            stream_push(vm, v, rest, rest_counts, sink)
        }
        Stage::Skip(n) => {
            *count += 1;
            if *count <= *n {
                true
            } else {
                stream_push(vm, v, rest, rest_counts, sink)
            }
        }
        // A full `limit` ends the pipeline rather than merely dropping the
        // element — which is what makes `peek(p).limit(2)` call `p` twice.
        Stage::Limit(n) => {
            if *count >= *n {
                return false;
            }
            *count += 1;
            let go = stream_push(vm, v, rest, rest_counts, sink);
            go && *count < *n
        }
        Stage::Distinct | Stage::Sorted(_) => {
            unreachable!("a barrier is split off before the element-wise walk")
        }
    }
}

/// Run `source` through `stages`, calling `sink` for each surviving element
/// until it answers `false` or the source is exhausted.
///
/// A stateful barrier — `distinct` or `sorted` — cannot answer for an element
/// without having seen every element before it, so the pipeline is evaluated in
/// segments split at the first one. That is Java's own shape, and it is why a
/// `peek` before a `sorted` runs for every element while a `peek` before a
/// `limit` does not.
fn stream_drive(
    vm: &mut VM,
    source: Vec<Value>,
    stages: &[Stage],
    sink: &mut dyn FnMut(&mut VM, Value) -> bool,
) {
    if let Some(i) = stages
        .iter()
        .position(|s| matches!(s, Stage::Distinct | Stage::Sorted(_)))
    {
        let mut buf = Vec::new();
        stream_drive(vm, source, &stages[..i], &mut |_vm, v| {
            buf.push(v);
            true
        });
        let buf = match &stages[i] {
            Stage::Distinct => {
                let mut seen: Vec<Value> = Vec::new();
                for v in buf {
                    if !seen.iter().any(|x| value_eq(x, &v)) {
                        seen.push(v);
                    }
                }
                seen
            }
            Stage::Sorted(cmp) => sort_values(vm, buf, cmp.as_ref()),
            _ => unreachable!("the position above found a barrier"),
        };
        return stream_drive(vm, buf, &stages[i + 1..], sink);
    }
    let mut counters = vec![0i64; stages.len()];
    for v in source {
        if !stream_push(vm, v, stages, &mut counters, sink) {
            break;
        }
    }
}

/// Sort by a comparator closure, or by the natural order when there is none.
///
/// A stable insertion sort driven by the comparator, because a user comparator
/// re-enters the VM and `slice::sort_by` cannot call back into it.
fn sort_values(vm: &mut VM, items: Vec<Value>, cmp: Option<&Value>) -> Vec<Value> {
    let mut out: Vec<Value> = Vec::with_capacity(items.len());
    for v in items {
        let mut at = out.len();
        while at > 0 {
            let ord = match cmp {
                Some(c) => invoke_closure(vm, c, &[out[at - 1].clone(), v.clone()]).jint(),
                None => natural_cmp(&out[at - 1], &v) as i64,
            };
            if ord <= 0 {
                break;
            }
            at -= 1;
        }
        out.insert(at, v);
    }
    out
}

/// Every element a pipeline yields.
fn stream_collect(vm: &mut VM, source: Vec<Value>, stages: &[Stage]) -> Vec<Value> {
    let mut out = Vec::new();
    stream_drive(vm, source, stages, &mut |_vm, v| {
        out.push(v);
        true
    });
    out
}

/// `java.util.stream.Stream`'s methods — the intermediate operations, which
/// answer a new stream, and the terminals, which run the pipeline.
///
/// `None` for any other receiver. Every terminal drives the pipeline exactly
/// once and the short-circuiting ones stop the source, which is what a `peek`
/// before a `limit` or a `findFirst` observes.
fn stream_method(
    vm: &mut VM,
    recv: &Value,
    method: &str,
    args: &[Value],
) -> Option<Result<Value, Fault>> {
    let (source, stages, kind) = as_stream(recv)?;
    let stage = |st: Stage| Ok(stream_with(recv, kind, Some(st)).expect("receiver is a stream"));
    let retyped = |k: StreamKind| Ok(stream_with(recv, k, None).expect("receiver is a stream"));
    let all = |vm: &mut VM| stream_collect(vm, source.clone(), &stages);
    Some(match (method, args.len()) {
        // ── intermediate ──
        ("filter", 1) => stage(Stage::Filter(args[0].clone())),
        ("map", 1) => stage(Stage::Map(args[0].clone())),
        ("flatMap", 1) => stage(Stage::FlatMap(args[0].clone())),
        ("peek", 1) => stage(Stage::Peek(args[0].clone())),
        ("limit", 1) => stage(Stage::Limit(args[0].jint())),
        ("skip", 1) => stage(Stage::Skip(args[0].jint())),
        ("distinct", 0) => stage(Stage::Distinct),
        ("sorted", 0) => stage(Stage::Sorted(None)),
        ("sorted", 1) => stage(Stage::Sorted(Some(args[0].clone()))),
        // The mapping operations that also change the stream's *shape*, which
        // is what decides whether `max()` answers an `OptionalInt` or an
        // `OptionalDouble`.
        ("mapToInt", 1) => {
            Ok(
                stream_with(recv, StreamKind::Int, Some(Stage::Map(args[0].clone())))
                    .expect("receiver is a stream"),
            )
        }
        ("mapToLong", 1) => {
            Ok(
                stream_with(recv, StreamKind::Long, Some(Stage::Map(args[0].clone())))
                    .expect("receiver is a stream"),
            )
        }
        ("mapToDouble", 1) => {
            Ok(
                stream_with(recv, StreamKind::Double, Some(Stage::Map(args[0].clone())))
                    .expect("receiver is a stream"),
            )
        }
        ("mapToObj", 1) => {
            Ok(
                stream_with(recv, StreamKind::Ref, Some(Stage::Map(args[0].clone())))
                    .expect("receiver is a stream"),
            )
        }
        ("boxed", 0) => retyped(StreamKind::Ref),
        ("asLongStream", 0) => retyped(StreamKind::Long),
        ("asDoubleStream", 0) => retyped(StreamKind::Double),
        // ── terminal ──
        ("toList", 0) => Ok(list_value(all(vm), Fixity::Immutable)),
        ("toArray", 0) => Ok(Value::Obj(heap_alloc(HostObj::Array(all(vm))))),
        ("count", 0) => Ok(Value::Int(all(vm).len() as i64)),
        ("forEach" | "forEachOrdered", 1) => {
            let f = args[0].clone();
            stream_drive(vm, source, &stages, &mut |vm, v| {
                invoke_closure(vm, &f, &[v]);
                true
            });
            Ok(Value::Undef)
        }
        ("sum", 0) => {
            let items = all(vm);
            Ok(if kind == StreamKind::Double {
                Value::float(items.iter().map(|v| v.jfloat()).sum())
            } else {
                Value::Int(items.iter().map(|v| v.jint()).sum())
            })
        }
        // `average` answers an `OptionalDouble` whatever the stream's width,
        // and an empty one for an empty stream rather than a NaN.
        ("average", 0) => {
            let items = all(vm);
            Ok(optional_of(
                "OptionalDouble",
                (!items.is_empty()).then(|| {
                    Value::float(items.iter().map(|v| v.jfloat()).sum::<f64>() / items.len() as f64)
                }),
            ))
        }
        ("min" | "max", 0 | 1) => {
            let items = all(vm);
            let cmp = args.first().cloned();
            let sorted = sort_values(vm, items, cmp.as_ref());
            let pick = if method == "min" {
                sorted.first()
            } else {
                sorted.last()
            };
            Ok(optional_of(kind.optional_class(), pick.cloned()))
        }
        ("findFirst" | "findAny", 0) => {
            let mut found = None;
            stream_drive(vm, source, &stages, &mut |_vm, v| {
                found = Some(v);
                false
            });
            Ok(optional_of(kind.optional_class(), found))
        }
        ("anyMatch" | "allMatch" | "noneMatch", 1) => {
            // One walk answers all three: `allMatch` looks for a counterexample
            // and the other two for an example, so each stops at the first hit.
            let want = method != "allMatch";
            let p = args[0].clone();
            let mut hit = false;
            stream_drive(vm, source, &stages, &mut |vm, v| {
                let ok = matches!(invoke_closure(vm, &p, &[v]), Value::Bool(true));
                if ok == want {
                    hit = true;
                    return false;
                }
                true
            });
            Ok(Value::bool(match method {
                "anyMatch" => hit,
                "noneMatch" => !hit,
                _ => !hit,
            }))
        }
        ("reduce", 1) => {
            let items = all(vm);
            let f = args[0].clone();
            let mut acc: Option<Value> = None;
            for v in items {
                acc = Some(match acc {
                    Some(a) => invoke_closure(vm, &f, &[a, v]),
                    None => v,
                });
            }
            Ok(optional_of(kind.optional_class(), acc))
        }
        ("reduce", 2) => {
            let items = all(vm);
            let f = args[1].clone();
            let mut acc = args[0].clone();
            for v in items {
                acc = invoke_closure(vm, &f, &[acc, v]);
            }
            Ok(acc)
        }
        ("collect", 1) => {
            let items = all(vm);
            collect_with(vm, items, &args[0])
        }
        _ => Err(Fault::internal(format!(
            "javars: unsupported Stream method `{method}` with {} argument(s)",
            args.len()
        ))),
    })
}

/// The stream shape a primitive stream class names.
fn primitive_stream_kind(class: &str) -> StreamKind {
    match class {
        "LongStream" => StreamKind::Long,
        "DoubleStream" => StreamKind::Double,
        _ => StreamKind::Int,
    }
}

/// Allocate a `Collectors.*` recipe.
fn collector(kind: &'static str, args: Vec<Value>) -> Value {
    Value::Obj(heap_alloc(HostObj::Collector { kind, args }))
}

/// Allocate a `List` holding `items`.
fn list_value(items: Vec<Value>, fixed: Fixity) -> Value {
    Value::Obj(heap_alloc(HostObj::List {
        items,
        fixed,
        mods: 0,
    }))
}

/// Run a `Collectors.*` recipe over the elements a pipeline yielded.
fn collect_with(vm: &mut VM, items: Vec<Value>, collector: &Value) -> Result<Value, Fault> {
    let Value::Obj(id) = collector else {
        return Err(Fault::internal(
            "javars: `collect` takes a `Collectors.*` collector".to_string(),
        ));
    };
    let (kind, cargs) = HEAP
        .with(|h| match h.borrow().get(*id as usize) {
            Some(HostObj::Collector { kind, args }) => Some((*kind, args.clone())),
            _ => None,
        })
        .ok_or_else(|| {
            Fault::internal("javars: `collect` takes a `Collectors.*` collector".to_string())
        })?;
    Ok(match kind {
        "toList" => list_value(items, Fixity::Mutable),
        "toSet" => {
            let mut out: Vec<Value> = Vec::new();
            for v in items {
                if !out.iter().any(|x| value_eq(x, &v)) {
                    out.push(v);
                }
            }
            Value::Obj(heap_alloc(HostObj::Set {
                items: out,
                order: Order::Hash,
                fixed: Fixity::Mutable,
                index: KeyIndex::default(),
            }))
        }
        "counting" => Value::Int(items.len() as i64),
        "joining" => {
            let sep = cargs.first().map(java_str).unwrap_or_default();
            let pre = cargs.get(1).map(java_str).unwrap_or_default();
            let suf = cargs.get(2).map(java_str).unwrap_or_default();
            let body: Vec<String> = items.iter().map(java_str).collect();
            Value::str(format!("{pre}{}{suf}", body.join(&sep)))
        }
        // `toMap(k, v)` and `groupingBy(k)` both key by a mapper's answer; they
        // differ in what they put under a repeated key — the later value, and a
        // list of every value.
        "toMap" | "groupingBy" => {
            let mut entries: Vec<(Value, Value)> = Vec::new();
            for v in items {
                let key = invoke_closure(vm, &cargs[0], std::slice::from_ref(&v));
                let val = if kind == "toMap" {
                    invoke_closure(vm, &cargs[1], std::slice::from_ref(&v))
                } else {
                    v
                };
                match entries.iter_mut().find(|(k, _)| value_eq(k, &key)) {
                    Some((_, slot)) if kind == "toMap" => *slot = val,
                    Some((_, slot)) => {
                        let mut group = sequence_items(slot).unwrap_or_default();
                        group.push(val);
                        *slot = list_value(group, Fixity::Mutable);
                    }
                    None => entries.push((
                        key,
                        if kind == "toMap" {
                            val
                        } else {
                            list_value(vec![val], Fixity::Mutable)
                        },
                    )),
                }
            }
            Value::Obj(heap_alloc(HostObj::Map {
                entries,
                order: Order::Hash,
                fixed: Fixity::Mutable,
                index: KeyIndex::default(),
            }))
        }
        other => {
            return Err(Fault::internal(format!(
                "javars: unsupported collector `Collectors.{other}`"
            )))
        }
    })
}

/// `java.util.Optional`'s instance methods.
///
/// `None` for any other receiver, which leaves the call to the dispatch that
/// follows. The contents are read out before anything runs, because `map`,
/// `filter` and `ifPresent` invoke a user closure that can allocate.
fn optional_method(
    vm: &mut VM,
    recv: &Value,
    method: &str,
    args: &[Value],
) -> Option<Result<Value, Fault>> {
    let (class, inner) = as_optional_full(recv)?;
    let empty = || Fault::java("NoSuchElementException", "No value present");
    Some(match (method, args.len()) {
        ("isPresent", 0) => Ok(Value::bool(inner.is_some())),
        ("isEmpty", 0) => Ok(Value::bool(inner.is_none())),
        // The primitive specializations spell the accessor for their own width;
        // the class already knows which, so one arm serves all four.
        ("get" | "orElseThrow" | "getAsInt" | "getAsLong" | "getAsDouble", 0) => {
            inner.ok_or_else(empty)
        }
        ("orElse", 1) => Ok(inner.unwrap_or_else(|| args[0].clone())),
        ("orElseGet", 1) => Ok(match inner {
            Some(v) => v,
            None => invoke_closure(vm, &args[0], &[]),
        }),
        ("map", 1) => Ok(match inner {
            // `map` answers an empty `Optional` when the mapper answers `null`,
            // which is what distinguishes it from a plain transformation.
            Some(v) => {
                let mapped = invoke_closure(vm, &args[0], &[v]);
                optional((!matches!(mapped, Value::Undef)).then_some(mapped))
            }
            None => optional(None),
        }),
        ("filter", 1) => Ok(match inner {
            Some(v) => {
                let keep = matches!(
                    invoke_closure(vm, &args[0], std::slice::from_ref(&v)),
                    Value::Bool(true)
                );
                optional(keep.then_some(v))
            }
            None => optional(None),
        }),
        ("ifPresent", 1) => {
            if let Some(v) = inner {
                invoke_closure(vm, &args[0], &[v]);
            }
            Ok(Value::Undef)
        }
        ("ifPresentOrElse", 2) => {
            match inner {
                Some(v) => invoke_closure(vm, &args[0], &[v]),
                None => invoke_closure(vm, &args[1], &[]),
            };
            Ok(Value::Undef)
        }
        // A value, so `equals` compares contents where `==` compares handles.
        ("equals", 1) => Ok(Value::bool(match (inner, as_optional_full(&args[0])) {
            (Some(x), Some((other, Some(y)))) => other == class && value_eq(&x, &y),
            (None, Some((other, None))) => other == class,
            _ => false,
        })),
        ("hashCode", 0) => Ok(Value::Int(match inner {
            Some(v) => element_hash(&v).into(),
            None => 0,
        })),
        ("toString", 0) => Ok(Value::str(java_str(recv))),
        _ => Err(Fault::internal(format!(
            "javars: unsupported Optional method `{method}` with {} argument(s)",
            args.len()
        ))),
    })
}

/// The `mods` counter of the `List` at `id`, or 0 for anything else — the
/// baseline an [`HostObj::Iterator`] compares against.
///
/// A `Set` has no counter, so an iterator over one cannot be fail-fast. Java's
/// is; javars's walks the set as it stands, which is noted in BUGS.md rather
/// than papered over with a counter invented here.
fn iter_mods(id: u32) -> u64 {
    list_mods(id as usize).unwrap_or(0)
}

/// Java's `ConcurrentModificationException`: the view's snapshot of the backing
/// list's `modCount` no longer matches. Carries no detail message, exactly as
/// the JDK throws it.
fn comodification() -> Fault {
    Fault::java("ConcurrentModificationException", String::new())
}

/// Check a view against its backing list and return its resolved window.
fn checked_window(id: usize) -> Result<(usize, usize, usize), Fault> {
    let (root, offset, len) =
        resolve_window(id).ok_or_else(|| Fault::internal("javars: dangling subList view"))?;
    let exp = HEAP.with(|h| match h.borrow().get(id) {
        Some(HostObj::SubList { exp_mods, .. }) => Some(*exp_mods),
        _ => None,
    });
    if exp != list_mods(root) {
        return Err(comodification());
    }
    Ok((root, offset, len))
}

/// `list.subList(from, to)` on a list **or** on another view. The result is a
/// view of the receiver, so a nested `subList` composes offsets rather than
/// copying. Bounds are Java's, including its two distinct failures: a
/// out-of-range endpoint is an `IndexOutOfBoundsException` naming the offending
/// index, and a reversed range is an `IllegalArgumentException`.
fn make_sublist(id: usize, from: i64, to: i64) -> Result<Value, Fault> {
    let (root, size) = if is_sublist(id) {
        let (root, _, len) = checked_window(id)?;
        (root, len)
    } else {
        let len = HEAP
            .with(|h| match h.borrow().get(id) {
                Some(HostObj::List { items, .. }) => Some(items.len()),
                _ => None,
            })
            .ok_or_else(|| Fault::internal("javars: `subList` needs a List receiver"))?;
        (id, len)
    };
    if from < 0 {
        return Err(Fault::java(
            "IndexOutOfBoundsException",
            format!("fromIndex = {from}"),
        ));
    }
    if to > size as i64 {
        return Err(Fault::java(
            "IndexOutOfBoundsException",
            format!("toIndex = {to}"),
        ));
    }
    if from > to {
        return Err(Fault::java(
            "IllegalArgumentException",
            format!("fromIndex({from}) > toIndex({to})"),
        ));
    }
    let exp_mods = list_mods(root).unwrap_or_default();
    Ok(Value::Obj(heap_alloc(HostObj::SubList {
        parent: id as u32,
        offset: from as usize,
        len: (to - from) as usize,
        exp_mods,
    })))
}

/// Run an ordinary `List` method against a view's window of its backing list.
///
/// The window is lifted out, the shared [`list_method`] runs on it — so a view
/// answers `get`/`set`/`add`/`remove`/`contains`/`indexOf`/`equals` exactly as
/// a list does — and the result is spliced back, which is what makes a write
/// through the view land in the backing list.
fn sublist_method(
    id: usize,
    method: &str,
    args: &[Value],
    arg_seqs: &[Option<Vec<Value>>],
    eq: Option<&EqPlan>,
) -> Result<Value, Fault> {
    let (root, offset, len) = checked_window(id)?;
    let (mut window, fixed) = HEAP
        .with(|h| match h.borrow().get(root) {
            Some(HostObj::List { items, fixed, .. }) => {
                Some((items[offset..offset + len].to_vec(), *fixed))
            }
            _ => None,
        })
        .ok_or_else(|| Fault::internal("javars: dangling subList backing"))?;
    let out = list_method(&mut window, fixed, method, args, arg_seqs, eq)?;
    let delta = window.len() as isize - len as isize;
    // The splice is unconditional: `set` rewrites an element without changing
    // the length, and that write has to reach the backing list too.
    HEAP.with(|h| {
        if let Some(HostObj::List { items, mods, .. }) = h.borrow_mut().get_mut(root) {
            items.splice(offset..offset + len, window);
            if delta != 0 {
                *mods += 1;
            }
        }
    });
    if delta != 0 {
        let new_mods = list_mods(root).unwrap_or_default();
        resize_ancestors(id, delta, new_mods);
    }
    Ok(match out {
        NewColl::Value(v) => v,
        NewColl::Alloc(obj) => Value::Obj(heap_alloc(obj)),
    })
}

/// Push a view's length change up its own ancestor chain and re-snapshot each
/// one's `modCount` — Java's `SubList.updateSizeAndModCount`. The views on the
/// path stay usable; every other outstanding view of the same list does not,
/// which is the behaviour that makes the stale one throw.
fn resize_ancestors(id: usize, delta: isize, new_mods: u64) {
    HEAP.with(|h| {
        let mut heap = h.borrow_mut();
        let mut cur = id;
        for _ in 0..=heap.len() {
            match heap.get_mut(cur) {
                Some(HostObj::SubList {
                    parent,
                    len,
                    exp_mods,
                    ..
                }) => {
                    *len = len.saturating_add_signed(delta);
                    *exp_mods = new_mods;
                    cur = *parent as usize;
                }
                _ => return,
            }
        }
    });
}

/// Replace a list's contents in place, optionally counting the write as a
/// structural modification. Through a view the elements land in its window.
fn write_sequence(id: usize, items: Vec<Value>, structural: bool) -> Result<(), Fault> {
    let (root, offset, len) = if is_sublist(id) {
        checked_window(id)?
    } else {
        (id, 0, usize::MAX)
    };
    HEAP.with(|h| {
        if let Some(HostObj::List {
            items: dst, mods, ..
        }) = h.borrow_mut().get_mut(root)
        {
            let end = len.min(dst.len().saturating_sub(offset)) + offset;
            dst.splice(offset..end, items);
            if structural {
                *mods += 1;
            }
        }
    });
    Ok(())
}

/// The presentation order of a `Map` handle.
fn map_order(v: &Value) -> Order {
    let Value::Obj(id) = v else {
        return Order::Insertion;
    };
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::Map { order, .. }) => *order,
        _ => Order::Insertion,
    })
}

/// `Collections.sort(list, cmp)` / `list.sort(cmp)` — a stable sort driven by a
/// comparator closure, matching Java's stable `List.sort`. A `null` comparator
/// is natural order, exactly as Java specifies it.
fn sort_with(vm: &mut VM, mut items: Vec<Value>, cmp: &Value) -> Result<Vec<Value>, Fault> {
    if matches!(cmp, Value::Undef) {
        items.sort_by(natural_cmp);
        return Ok(items);
    }
    if closure_meta(cmp).is_none() {
        return Err(Fault::internal("javars: `sort` needs a Comparator lambda"));
    }
    // `sort_by` needs a total order it can trust; a user comparator may not give
    // one, so a bottom-up merge sort is used instead — stable (which `List.sort`
    // is specified to be), n log n, and it can never panic on an inconsistent
    // comparator the way `sort_by` can. Every sort that names no comparator now
    // arrives here too, because the compiler supplies `(a, b) -> a.compareTo(b)`
    // for those (see `natural_order_comparator`), so this is the one sort in the
    // frontend and its cost is the one that matters.
    let n = items.len();
    let mut buf: Vec<Value> = items.clone();
    let mut width = 1;
    while width < n {
        let mut lo = 0;
        while lo < n {
            let mid = (lo + width).min(n);
            let hi = (lo + 2 * width).min(n);
            let (mut i, mut j) = (lo, mid);
            for slot in &mut buf[lo..hi] {
                // Take from the left run unless the right one compares strictly
                // smaller — the tie going left is what makes the merge stable.
                let take_left = if i >= mid {
                    false
                } else if j >= hi {
                    true
                } else {
                    invoke_closure(vm, cmp, &[items[j].clone(), items[i].clone()]).jint() >= 0
                };
                if take_left {
                    *slot = items[i].clone();
                    i += 1;
                } else {
                    *slot = items[j].clone();
                    j += 1;
                }
            }
            lo = hi;
        }
        std::mem::swap(&mut items, &mut buf);
        width *= 2;
    }
    Ok(items)
}

/// Invoke `clo` with `args` through the closure-call path, discarding the arity
/// bookkeeping the builtin ABI would otherwise do on the stack.
fn invoke_closure(vm: &mut VM, clo: &Value, args: &[Value]) -> Value {
    vm.stack.push(clo.clone());
    for a in args {
        vm.stack.push(a.clone());
    }
    b_closure_call(vm, args.len() as u8 + 1)
}

/// `java.util.List` methods.
fn list_method(
    items: &mut Vec<Value>,
    fixed: Fixity,
    method: &str,
    args: &[Value],
    arg_seqs: &[Option<Vec<Value>>],
    eq: Option<&EqPlan>,
) -> Result<NewColl, Fault> {
    // A structural change to `Arrays.asList` / `List.of` is Java's
    // `UnsupportedOperationException`, not a silent success.
    let structural = || match fixed {
        Fixity::Mutable => Ok(()),
        _ => Err(Fault::java("UnsupportedOperationException", String::new())),
    };
    let replace = || match fixed {
        Fixity::Immutable => Err(Fault::java("UnsupportedOperationException", String::new())),
        _ => Ok(()),
    };
    let bounds = |i: i64, len: usize| -> Result<usize, Fault> {
        if i < 0 || i as usize >= len {
            return Err(Fault::java(
                "IndexOutOfBoundsException",
                format!("Index {i} out of bounds for length {len}"),
            ));
        }
        Ok(i as usize)
    };
    let v = match (method, args.len()) {
        ("size", 0) => Value::Int(items.len() as i64),
        ("isEmpty", 0) => Value::bool(items.is_empty()),
        ("add", 1) => {
            structural()?;
            items.push(args[0].clone());
            Value::bool(true)
        }
        ("add", 2) => {
            structural()?;
            let at = args[0].jint();
            if at < 0 || at as usize > items.len() {
                return Err(Fault::java(
                    "IndexOutOfBoundsException",
                    format!("Index: {at}, Size: {}", items.len()),
                ));
            }
            items.insert(at as usize, args[1].clone());
            Value::Undef
        }
        ("get", 1) => {
            let i = bounds(args[0].jint(), items.len())?;
            items[i].clone()
        }
        ("set", 2) => {
            replace()?;
            let i = bounds(args[0].jint(), items.len())?;
            std::mem::replace(&mut items[i], args[1].clone())
        }
        // `List.remove(int)` removes by index — the overload Java picks for an
        // integral argument. The `remove(Object)` overload arrives under the
        // distinct name `removeObject`, chosen by the compiler from the
        // argument's static type (the same question Java answers statically),
        // because a boxed `Integer` and an `int` are one value here.
        ("remove", 1) => {
            structural()?;
            let i = bounds(args[0].jint(), items.len())?;
            items.remove(i)
        }
        // `List.remove(Object)` — removes the first element equal to the
        // argument and answers whether one was found.
        ("removeObject", 1) => {
            structural()?;
            match eq_index(eq, items, &args[0], false) {
                Some(i) => {
                    items.remove(i);
                    Value::bool(true)
                }
                None => Value::bool(false),
            }
        }
        ("clear", 0) => {
            structural()?;
            items.clear();
            Value::Undef
        }
        ("contains", 1) => Value::bool(eq_index(eq, items, &args[0], false).is_some()),
        ("indexOf", 1) => Value::Int(eq_index(eq, items, &args[0], false).map_or(-1, |i| i as i64)),
        ("lastIndexOf", 1) => {
            Value::Int(eq_index(eq, items, &args[0], true).map_or(-1, |i| i as i64))
        }
        ("addAll", 1) => {
            structural()?;
            let add = arg_seqs[0].clone().unwrap_or_default();
            let changed = !add.is_empty();
            items.extend(add);
            Value::bool(changed)
        }
        ("equals", 1) => match eq {
            Some(EqPlan::Same(same)) => Value::bool(*same),
            _ => {
                let other = arg_seqs[0].clone().unwrap_or_default();
                Value::bool(
                    other.len() == items.len()
                        && items.iter().zip(&other).all(|(a, b)| value_eq(a, b)),
                )
            }
        },
        ("hashCode", 0) => Value::Int(list_hash(items)),
        _ => {
            return Err(Fault::internal(format!(
                "javars: unsupported List method `{method}` with {} argument(s)",
                args.len()
            )))
        }
    };
    Ok(NewColl::Value(v))
}

/// `java.util.Map` methods.
/// The two properties of a `Map` that are not its contents: how it iterates and
/// whether it can be written to. Passed as one value because they always travel
/// together and always come from the same heap object.
#[derive(Clone, Copy)]
struct MapShape {
    /// What order iteration and `toString` present the entries in.
    order: Order,
    /// Whether the map accepts a mutator (`Map.of` does not).
    fixed: Fixity,
}

fn map_method(
    entries: &mut Vec<(Value, Value)>,
    shape: MapShape,
    index: &mut KeyIndex,
    method: &str,
    args: &[Value],
    arg_entries: &[Option<Vec<(Value, Value)>>],
    eq: Option<&EqPlan>,
) -> Result<NewColl, Fault> {
    // Every mutator on a `Map.of` map is Java's `UnsupportedOperationException`,
    // not a silent success. Checked once here, by name, rather than at each
    // arm: an immutable map refuses the whole set, and listing them in one
    // place is what keeps a newly added mutator from quietly escaping the rule.
    let MapShape { order, fixed } = shape;
    if fixed == Fixity::Immutable
        && matches!(
            method,
            "put"
                | "remove"
                | "clear"
                | "putAll"
                | "putIfAbsent"
                | "merge"
                | "replace"
                | "replaceAll"
                | "compute"
                | "computeIfAbsent"
                | "computeIfPresent"
        )
    {
        return Err(Fault::java("UnsupportedOperationException", String::new()));
    }
    // A stale index is repaired once, here, rather than at every arm: the
    // methods below either read it or invalidate it, and only this entry point
    // knows the keys to rebuild it from.
    if index.dirty {
        index.rebuild(entries.iter().map(|(k, _)| k));
    }
    // Only one arm below runs per call, so the single verdict vector is
    // unambiguous: it indexes the keys for every key-addressed method, and the
    // values for `containsValue`.
    //
    // A user `equals` puts the verdict in `eq` and it wins; otherwise
    // [`value_eq`] decides and the index answers in its place when it can.
    let find = |entries: &Vec<(Value, Value)>, index: &KeyIndex, k: &Value| match eq {
        Some(EqPlan::Index(at)) => *at,
        _ => match index.find(entries, |(x, _)| x, k) {
            Some(at) => at,
            None => entries.iter().position(|(x, _)| value_eq(x, k)),
        },
    };
    let out = match (method, args.len()) {
        ("size", 0) => NewColl::Value(Value::Int(entries.len() as i64)),
        ("isEmpty", 0) => NewColl::Value(Value::bool(entries.is_empty())),
        // A re-`put` keeps the entry's original insertion position, which is
        // what Java's linked/bucket layouts both do.
        // A fresh key lands at the end, which is the one shape the index can
        // record without rebuilding — and the shape a loop that fills a map
        // takes every iteration.
        ("put", 2) => NewColl::Value(match find(entries, index, &args[0]) {
            Some(i) => std::mem::replace(&mut entries[i].1, args[1].clone()),
            None => {
                index.push(&args[0], entries.len());
                entries.push((args[0].clone(), args[1].clone()));
                Value::Undef
            }
        }),
        ("putIfAbsent", 2) => NewColl::Value(match find(entries, index, &args[0]) {
            Some(i) => entries[i].1.clone(),
            None => {
                index.push(&args[0], entries.len());
                entries.push((args[0].clone(), args[1].clone()));
                Value::Undef
            }
        }),
        ("get", 1) => NewColl::Value(
            find(entries, index, &args[0]).map_or(Value::Undef, |i| entries[i].1.clone()),
        ),
        ("getOrDefault", 2) => NewColl::Value(
            find(entries, index, &args[0])
                .map_or_else(|| args[1].clone(), |i| entries[i].1.clone()),
        ),
        ("containsKey", 1) => NewColl::Value(Value::bool(find(entries, index, &args[0]).is_some())),
        ("containsValue", 1) => NewColl::Value(Value::bool(match eq {
            Some(EqPlan::Index(at)) => at.is_some(),
            _ => entries.iter().any(|(_, v)| value_eq(v, &args[0])),
        })),
        // A removal shifts every later position, so the index is marked stale
        // instead of being repaired here; the next lookup rebuilds it, which
        // costs no more than the scan the index replaced.
        ("remove", 1) => NewColl::Value(match find(entries, index, &args[0]) {
            Some(i) => {
                index.invalidate();
                entries.remove(i).1
            }
            None => Value::Undef,
        }),
        ("clear", 0) => {
            entries.clear();
            index.rebuild(std::iter::empty());
            NewColl::Value(Value::Undef)
        }
        ("keySet", 0) => {
            let keys: Vec<Value> = entries.iter().map(|(k, _)| k.clone()).collect();
            let ordered = present_order(&keys, order)
                .into_iter()
                .map(|i| keys[i].clone())
                .collect();
            // The view is a `Set` that already holds the map's order, so it
            // iterates and prints exactly as the map does.
            NewColl::Alloc(HostObj::Set {
                items: ordered,
                order: Order::Insertion,
                // A `keySet` view is writable in Java (a removal writes through
                // to the map); javars models it as a copy, so it is at least not
                // an immutable one.
                fixed: Fixity::Mutable,
                index: KeyIndex::default(),
            })
        }
        ("values", 0) => {
            let keys: Vec<Value> = entries.iter().map(|(k, _)| k.clone()).collect();
            let ordered = present_order(&keys, order)
                .into_iter()
                .map(|i| entries[i].1.clone())
                .collect();
            NewColl::Alloc(HostObj::List {
                mods: 0,
                items: ordered,
                fixed: Fixity::FixedSize,
            })
        }
        ("hashCode", 0) => NewColl::Value(Value::Int(map_hash(entries))),
        // `AbstractMap.equals` — same size, and every key maps to an equal
        // value. Order does not enter into it, which is what makes a `HashMap`
        // equal to a `LinkedHashMap` holding the same entries.
        ("equals", 1) => {
            let other = arg_entries.first().cloned().flatten();
            NewColl::Value(Value::bool(match other {
                Some(other) => {
                    other.len() == entries.len()
                        && entries.iter().all(|(k, v)| {
                            other
                                .iter()
                                .find(|(ok, _)| value_eq(ok, k))
                                .is_some_and(|(_, ov)| value_eq(ov, v))
                        })
                }
                None => false,
            }))
        }
        _ => {
            return Err(Fault::internal(format!(
                "javars: unsupported Map method `{method}` with {} argument(s)",
                args.len()
            )))
        }
    };
    Ok(out)
}

/// `java.util.Set` methods.
fn set_method(
    items: &mut Vec<Value>,
    fixed: Fixity,
    index: &mut KeyIndex,
    method: &str,
    args: &[Value],
    arg_seqs: &[Option<Vec<Value>>],
    eq: Option<&EqPlan>,
) -> Result<NewColl, Fault> {
    // See the note at the top of `map_method`: one repair point, here.
    if index.dirty {
        index.rebuild(items.iter());
    }
    // The membership question every arm below asks. `eq` (a user `equals`) wins
    // when it has a verdict; otherwise the index answers in `value_eq`'s place
    // when it can, and the scan runs when it cannot.
    let member = |items: &Vec<Value>, index: &KeyIndex, q: &Value| match eq {
        Some(EqPlan::Index(at)) => *at,
        _ => match index.find(items, |x| x, q) {
            Some(at) => at,
            None => items.iter().position(|x| value_eq(x, q)),
        },
    };
    // A structural change to a `Set.of` is Java's `UnsupportedOperationException`,
    // not a silent success — the same rule `list_method` applies to `List.of`.
    // Java throws before deciding whether the change was a no-op, so the guard
    // runs before the membership test rather than after it.
    let structural = || match fixed {
        Fixity::Mutable => Ok(()),
        _ => Err(Fault::java("UnsupportedOperationException", String::new())),
    };
    let v = match (method, args.len()) {
        ("size", 0) => Value::Int(items.len() as i64),
        ("isEmpty", 0) => Value::bool(items.is_empty()),
        ("add", 1) => {
            structural()?;
            if member(items, index, &args[0]).is_some() {
                Value::bool(false)
            } else {
                index.push(&args[0], items.len());
                items.push(args[0].clone());
                Value::bool(true)
            }
        }
        ("contains", 1) => Value::bool(member(items, index, &args[0]).is_some()),
        ("remove", 1) => {
            structural()?;
            match member(items, index, &args[0]) {
                Some(i) => {
                    index.invalidate();
                    items.remove(i);
                    Value::bool(true)
                }
                None => Value::bool(false),
            }
        }
        ("clear", 0) => {
            structural()?;
            items.clear();
            index.rebuild(std::iter::empty());
            Value::Undef
        }
        ("addAll", 1) => {
            structural()?;
            match eq {
                Some(EqPlan::Fresh(fresh)) => {
                    let changed = !fresh.is_empty();
                    for v in fresh {
                        index.push(v, items.len());
                        items.push(v.clone());
                    }
                    Value::bool(changed)
                }
                _ => {
                    let mut changed = false;
                    for v in arg_seqs[0].clone().unwrap_or_default() {
                        if member(items, index, &v).is_none() {
                            index.push(&v, items.len());
                            items.push(v);
                            changed = true;
                        }
                    }
                    Value::bool(changed)
                }
            }
        }
        ("hashCode", 0) => Value::Int(set_hash(items)),
        // `AbstractSet.equals` — same size and every element present in the
        // other, again independent of order.
        ("equals", 1) => {
            let other = arg_seqs[0].clone();
            Value::bool(match other {
                Some(other) => {
                    other.len() == items.len()
                        && items.iter().all(|e| other.iter().any(|o| value_eq(o, e)))
                }
                None => false,
            })
        }
        _ => {
            return Err(Fault::internal(format!(
                "javars: unsupported Set method `{method}` with {} argument(s)",
                args.len()
            )))
        }
    };
    Ok(NewColl::Value(v))
}

/// `[a, b, c]` — `AbstractCollection.toString`.
fn render_sequence(items: &[Value]) -> String {
    let body: Vec<String> = items.iter().map(java_str).collect();
    format!("[{}]", body.join(", "))
}

fn render_set(items: &[Value], order: Order) -> String {
    let ordered: Vec<Value> = present_order(items, order)
        .into_iter()
        .map(|i| items[i].clone())
        .collect();
    render_sequence(&ordered)
}

/// `{k=v, k=v}` — `AbstractMap.toString`.
fn render_map(entries: &[(Value, Value)], order: Order) -> String {
    let keys: Vec<Value> = entries.iter().map(|(k, _)| k.clone()).collect();
    let body: Vec<String> = present_order(&keys, order)
        .into_iter()
        .map(|i| format!("{}={}", java_str(&entries[i].0), java_str(&entries[i].1)))
        .collect();
    format!("{{{}}}", body.join(", "))
}

/// `recv.method(args...)` dispatch builtin for `String` receivers. Pops the
/// method name (top of stack), its `argc - 2` arguments, and the receiver, then
/// runs the corresponding `java.lang.String` method. A faulting method (bad
/// arity, out-of-range index, unknown method) surfaces as a `javars:` error
/// rather than silently returning a wrong value.
fn b_str_dispatch(vm: &mut VM, argc: u8) -> Value {
    let method = vm
        .stack
        .pop()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    let n = argc.saturating_sub(2) as usize; // minus receiver and method name
    let mut args = Vec::with_capacity(n);
    for _ in 0..n {
        args.push(vm.stack.pop().unwrap_or(Value::Undef));
    }
    args.reverse();
    let recv = vm.stack.pop().unwrap_or(Value::Undef);
    // A lambda whose static type the compiler could not pin down lands here —
    // the erasure of a nested generic (`Supplier<Supplier<String>>.get()` is
    // declared to return `Object`) is the common case. Any method call on a
    // closure receiver is its single abstract method, because `javac` has
    // already rejected every other name, so it is invoked directly.
    if closure_meta(&recv).is_some() {
        vm.stack.push(recv);
        for a in args {
            vm.stack.push(a);
        }
        return b_closure_call(vm, n as u8 + 1);
    }
    // A `Stream` receiver. Every stage and every terminal runs user closures, so
    // it takes the VM and sits with the other handle shapes.
    if let Some(r) = stream_method(vm, &recv, &method, &args) {
        return match r {
            Ok(v) => v,
            Err(f) => raise(vm, f),
        };
    }
    // An `Optional` receiver. Its `map`/`filter`/`ifPresent`/`orElseGet` run a
    // user closure, so it takes the VM and sits with the other handle shapes
    // rather than in the borrow-free tables below.
    if let Some(r) = optional_method(vm, &recv, &method, &args) {
        return match r {
            Ok(v) => v,
            Err(f) => raise(vm, f),
        };
    }
    // An `Iterator` receiver. It is not a collection, so without this it fell
    // through to the `String` table and `it.hasNext()` was
    // ``unsupported String method `hasNext` ``.
    if let Some(r) = iterator_method(&recv, &method, args.len()) {
        return match r {
            Ok(v) => v,
            Err(f) => raise(vm, f),
        };
    }
    // A collection receiver whose static type the compiler could not pin down
    // (an erased `Map.get` result, say) routes to the collection methods.
    if is_collection(&recv) {
        return coll_method(vm, &recv, &method, &args);
    }
    // A `StringBuilder`/`StringBuffer` receiver. This runs ahead of
    // `object_method` so `sb.toString()` answers the contents rather than
    // `java.lang.StringBuilder@<id>`, and `builder_method` declines the three
    // names a builder really does inherit from `Object` so they fall through.
    if let Some(id) = is_builder(&recv) {
        if !matches!(method.as_str(), "equals" | "hashCode" | "getClass") {
            if let Some(r) = builder_method(vm, id, &method, &args) {
                return match r {
                    Ok(v) => v,
                    Err(f) => raise(vm, f),
                };
            }
        }
    }
    // A class instance whose own class declares no such method inherits
    // `java.lang.Object`'s — including `new Object()` itself, which has no class
    // body at all.
    // `o.toString()` on an `Object`-typed receiver resolves the override the
    // same way rendering does; a class that declares none still falls to the
    // `Class@hash` form `object_method` supplies just below.
    if method == "toString"
        && args.is_empty()
        && any_user_tostring(vm)
        && instance_class(&recv).is_some()
    {
        return Value::str(java_str_vm(vm, &recv));
    }
    if let Some(v) = object_method(&recv, &method, &args) {
        return v;
    }
    // A method call on a `null` reference is Java's NPE, not an empty string.
    if matches!(recv, Value::Undef) {
        return raise(
            vm,
            Fault::java(
                "NullPointerException",
                format!("Cannot invoke \"String.{method}()\" because the receiver is null"),
            ),
        );
    }
    // A boxed number's own methods, *before* the receiver is stringified. They
    // are not `String` methods, so falling through to that table did not fail —
    // it answered from the receiver's text: `Integer.valueOf(300).hashCode()`
    // was 50547, the hash of `"300"`, where Java's is 300.
    if let Some(v) = boxed_method(&recv, &method, args.len()) {
        return v;
    }
    // The same, for a receiver that is a *wrapper handle*. The three methods
    // whose answer depends on the wrapper's class are answered here; everything
    // else re-enters with the primitive, so the tables above serve a boxed
    // receiver exactly as they serve a bare one.
    if unboxed(&recv).is_some() {
        match (method.as_str(), args.len()) {
            ("equals", 1) => return Value::bool(value_eq(&recv, &args[0])),
            ("hashCode", 0) => {
                return java_hash(&recv).map_or(Value::Undef, |h| Value::Int(h.into()))
            }
            _ => {}
        }
        let inner = deboxed(&recv);
        vm.stack.push(inner);
        for a in args {
            vm.stack.push(a);
        }
        vm.stack.push(Value::str(method));
        return b_str_dispatch(vm, argc);
    }
    // Borrowed, not copied. `into_owned` cloned the whole receiver on every
    // single `String` method call, so `s.charAt(i)` over an n-character string
    // moved n bytes per call and n² across the loop — 40k characters meant
    // 1.6GB of memcpy for a walk that reads 40k of them. `recv` is a local, so
    // the borrow is independent of the `&mut VM` the arms below take.
    // Every remaining path reads the receiver as text, and an *argument* may
    // still be a box — a `new String(…)` handle, or a wrapper in
    // `s.equals(anInteger)`. Unboxing them here is the mirror of the receiver
    // unboxing above, and is the identity on everything that is not a box.
    let args: Vec<Value> = args.iter().map(deboxed).collect();
    let s = recv.as_str_cow();
    // `"%s".formatted(x)` renders `x`, so it needs the VM `string_method` has
    // not got. Every other `String` method reads text only.
    if method == "formatted" && any_user_tostring(vm) {
        return match java_format(&s, &args, &[], Some(&mut *vm)) {
            Ok(v) => v,
            Err(f) => raise(vm, f),
        };
    }
    match string_method(&s, &method, &args) {
        // `intern()` answers the pool's object for the text, which is a
        // *different* object from the receiver whenever the receiver was built
        // at run time — the one string method whose whole purpose is to change
        // which object you hold.
        Ok(v) if method == "intern" => intern(&v),
        // Every other `String` method that would answer text equal to the
        // receiver's answers the receiver itself. That is the JDK's own
        // contract, stated method by method — `trim`, `strip`, `substring`,
        // `toLowerCase`, `replace`, `concat`, `toString` all say "this string if
        // unchanged" — and it is observable now that `==` compares identities:
        // `"ab".trim() == "ab"` is `true` in Java. One rule covers them because
        // the condition the JDK states is the same one each time.
        Ok(Value::Str(text)) if text.as_str() == s.as_ref() => recv,
        Ok(v) => v,
        Err(f) => raise(vm, f),
    }
}

/// The three `java.lang.Object` methods that have an answer without a class
/// body, for a class-instance receiver that declares no override:
///
///   * `equals(x)` is reference identity — the same heap handle.
///   * `hashCode()` is the identity hash. Java's is a JVM value that is not
///     reproducible across runs, so javars uses the heap handle: the properties
///     a program can rely on (stable within a run, equal for equal references)
///     hold, and the number itself is no more portable than Java's.
///   * `toString()` is `getClass().getName() + "@" + Integer.toHexString(hash)`.
///
/// `None` for any other method and for any non-instance handle (an array, a
/// collection, and a closure each have their own dispatch), so the caller falls
/// through to the `String` methods exactly as before.
/// The runtime class of a class-instance handle; `None` for every other value
/// (an array, a collection, a closure, a primitive).
fn instance_class(v: &Value) -> Option<String> {
    let Value::Obj(id) = v else {
        return None;
    };
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::Instance { class, .. }) => Some(class.clone()),
        _ => None,
    })
}

fn object_method(recv: &Value, method: &str, args: &[Value]) -> Option<Value> {
    let Value::Obj(id) = recv else {
        return None;
    };
    // A `StringBuilder` inherits `Object`'s `equals`/`hashCode` unchanged — it
    // overrides neither, so two builders holding the same text are unequal and
    // a builder's hash is its identity. Left out of this gate the call reached
    // the `String` table through the receiver's rendering, and both answered
    // for the *text*.
    let inherits_object = HEAP.with(|h| {
        matches!(
            h.borrow().get(*id as usize),
            Some(HostObj::Instance { .. } | HostObj::Builder { .. })
        )
    });
    if !inherits_object {
        return None;
    }
    match (method, args.len()) {
        ("equals", 1) => Some(Value::bool(
            matches!(args[0], Value::Obj(other) if other == *id),
        )),
        ("hashCode", 0) => Some(Value::Int(i64::from(*id))),
        ("toString", 0) => Some(Value::str(obj_default_str(*id))),
        _ => None,
    }
}

/// The methods a boxed primitive answers itself, for a receiver javars models
/// as a bare value rather than as a heap instance.
///
/// `Number`'s six converters plus `Boolean.booleanValue`, `Character.charValue`
/// and `Object.hashCode`. Without this the receiver was rendered to text and
/// the call went to the `String` table, which has no `intValue` (an error) but
/// *does* have `hashCode` — so a boxed number's hash was the hash of its
/// digits. `Integer.valueOf(300).hashCode()` answered 50547 against Java's 300.
///
/// The converters are the JLS narrowing conversions and need no per-box arity:
/// `intValue()` truncates to 32 bits, which is identity for an `Integer` and
/// the wrap Java performs for a `Long` (`Long.valueOf(4294967296L).intValue()`
/// is 0). A floating receiver saturates rather than wraps, which is what Java's
/// `(int) aDouble` does and what Rust's `as` already gives.
fn boxed_method(recv: &Value, method: &str, argc: usize) -> Option<Value> {
    if argc != 0 || matches!(recv, Value::Obj(_) | Value::Undef) {
        return None;
    }
    // `Number.intValue()` is `(int) value`, and the two receiver kinds narrow
    // differently: a `double` *saturates* at the `int` bounds (Java's
    // floating-to-integral conversion), while a `long` *wraps*. Going through
    // `long` first would saturate at the wrong width and then wrap —
    // `Double.valueOf(1e30).intValue()` came out -1 instead of
    // `Integer.MAX_VALUE`. `shortValue`/`byteValue` are `(short) intValue()`
    // and `(byte) intValue()`, so both derive from this one.
    let int_value = match recv {
        Value::Float(f) => *f as i32,
        other => other.jint() as i32,
    };
    let long_value = match recv {
        Value::Float(f) => *f as i64,
        other => other.jint(),
    };
    Some(match method {
        // `String.hashCode` is a different function and the `String` table
        // already answers it; a one-character `String` is javars's `char`, and
        // `Character.hashCode` is the code point, which is the same number.
        "hashCode" if !matches!(recv, Value::Str(_)) => Value::Int(java_hash(recv)?.into()),
        "intValue" => Value::Int(int_value.into()),
        "shortValue" => Value::Int((int_value as i16).into()),
        "byteValue" => Value::Int((int_value as i8).into()),
        "longValue" => Value::Int(long_value),
        "doubleValue" => Value::float(recv.jfloat()),
        "floatValue" => Value::float(recv.jfloat() as f32 as f64),
        "booleanValue" if matches!(recv, Value::Bool(_)) => recv.clone(),
        // A `char` is carried as its code point (or as the one-character
        // `String` a rendered one becomes), so unboxing it is identity — the
        // compiler types the call `char`, which is what makes it print as a
        // character rather than as a number.
        "charValue" => recv.clone(),
        _ => return None,
    })
}

/// `String.compareTo` / `compareToIgnoreCase`: the difference of the first
/// differing `char`, else the length difference. Java compares UTF-16 code
/// units; javars compares Unicode scalars, the same `char` simplification the
/// index-based methods make.
fn compare_strings(a: &str, b: &str, fold_case: bool) -> i64 {
    let norm = |s: &str| -> Vec<char> {
        if fold_case {
            s.chars().flat_map(|c| c.to_lowercase()).collect()
        } else {
            s.chars().collect()
        }
    };
    let (x, y) = (norm(a), norm(b));
    for (ca, cb) in x.iter().zip(&y) {
        if ca != cb {
            return *ca as i64 - *cb as i64;
        }
    }
    x.len() as i64 - y.len() as i64
}

/// `Double.compare`/`Float.compare`: the numeric order, except that it is a
/// *total* order — `NaN` compares greater than every other value including
/// itself, and `-0.0` compares less than `0.0`. Java gets both by falling back
/// to the raw bit pattern once `<` and `>` have both said no, which is what
/// `total_cmp` does; ordering by `f64` bits agrees with ordering by `f32` bits
/// on every value a `float` can hold, so one routine serves both.
fn double_compare(a: f64, b: f64) -> i64 {
    match a.total_cmp(&b) {
        std::cmp::Ordering::Less => -1,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    }
}

/// [`JCOMPARE_TO`] — `compareTo` on a boxed primitive or a `String`.
fn b_compare_to(vm: &mut VM, _argc: u8) -> Value {
    let tag = vm
        .stack
        .pop()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    // Through any box, for the same reason [`natural_cmp`] is: `compareTo` reads
    // the value, not the handle.
    let b = deboxed(&vm.stack.pop().unwrap_or(Value::Undef));
    let a = deboxed(&vm.stack.pop().unwrap_or(Value::Undef));
    // Java's own `Integer.compareTo(null)` is an NPE, and so is a call on a
    // `null` receiver. Both report the same way every other javars NPE does.
    if matches!(a, Value::Undef) {
        return raise(
            vm,
            Fault::java(
                "NullPointerException",
                "Cannot invoke \"java.lang.Comparable.compareTo(Object)\" because the receiver is null",
            ),
        );
    }
    // A null *argument* is an NPE too, and javars compared against the coerced
    // empty string instead: `"abc".compareTo(null)` answered 3. Every box
    // dereferences the argument to read its `value`, and names its own
    // parameter while doing so — measured on openjdk 21.0.12, one per type
    // rather than one shared wording, because the parameter names differ.
    if matches!(b, Value::Undef) {
        let param = match tag.as_str() {
            "Integer" | "int" => "anotherInteger",
            "Long" | "long" => "anotherLong",
            "Double" | "double" | "Float" | "float" => "anotherDouble",
            "Character" | "char" => "anotherCharacter",
            "Boolean" | "boolean" => "b",
            "String" | "CharSequence" => "anotherString",
            // The compiler could not name the receiver's type; the runtime value
            // decides, the same way the comparison below does.
            _ => match &a {
                Value::Str(_) => "anotherString",
                Value::Float(_) => "anotherDouble",
                Value::Bool(_) => "b",
                _ => "anotherInteger",
            },
        };
        return raise(
            vm,
            Fault::java(
                "NullPointerException",
                format!("Cannot read field \"value\" because \"{param}\" is null"),
            ),
        );
    }
    // `StringBuilder.compareTo` (Java 11+) is `String.compareTo` on the two
    // contents. It has to be answered before the arms below, all of which would
    // read two heap handles as integers and always answer 0.
    if is_builder(&a).is_some() || is_builder(&b).is_some() {
        return Value::Int(compare_strings(&java_str(&a), &java_str(&b), false));
    }
    // A class instance here means no user class declares a one-argument
    // `compareTo`, so there is no body to run — `javac` would have rejected the
    // call. Say so rather than comparing the object's default `toString`.
    if let Value::Obj(id) = a {
        let class = HEAP.with(|h| match h.borrow().get(id as usize) {
            Some(HostObj::Instance { class, .. }) => Some(class.clone()),
            _ => None,
        });
        if let Some(class) = class {
            return raise(
                vm,
                Fault::internal(format!(
                    "javars: class `{class}` does not declare `compareTo`"
                )),
            );
        }
    }
    Value::Int(match tag.as_str() {
        // Sign only: `Integer.compare` is `(x < y) ? -1 : ((x == y) ? 0 : 1)`.
        "Integer" | "int" | "Long" | "long" => as_i64(&a).cmp(&as_i64(&b)) as i64,
        // Difference: `Character.compareTo` is `this.value - other.value`, and
        // `Byte`/`Short` are the same subtraction. `as_i64` reads a boxed
        // `Character` in either of the two shapes javars stores it in — the code
        // point, and the one-character String a collection element carries.
        "Character" | "char" | "Short" | "short" | "Byte" | "byte" => as_i64(&a) - as_i64(&b),
        "Double" | "double" | "Float" | "float" => double_compare(as_f64(&a), as_f64(&b)),
        "Boolean" | "boolean" => i64::from(a.is_truthy()) - i64::from(b.is_truthy()),
        "String" | "CharSequence" => compare_strings(&a.as_str_cow(), &b.as_str_cow(), false),
        // The compiler could not name the receiver's type — an erased
        // `List.get` result is the usual reason. The runtime values decide, and
        // `Integer` is the reading a bare integer gets, being the box a literal
        // autoboxes to.
        _ => match (&a, &b) {
            (Value::Str(_), _) | (_, Value::Str(_)) => {
                compare_strings(&a.as_str_cow(), &b.as_str_cow(), false)
            }
            (Value::Float(_), _) | (_, Value::Float(_)) => double_compare(as_f64(&a), as_f64(&b)),
            (Value::Bool(_), Value::Bool(_)) => i64::from(a.is_truthy()) - i64::from(b.is_truthy()),
            _ => as_i64(&a).cmp(&as_i64(&b)) as i64,
        },
    })
}

/// `Math.nextAfter(start, direction)`: the representable `double` adjacent to
/// `start` in `direction`, or `direction` itself when the two are equal.
///
/// Consecutive `double`s of the same sign are consecutive integers when their
/// bits are read as an `i64`, which is what makes the step one increment.
/// Crossing zero is the one place that breaks — the two zeros are `0` and the
/// sign bit — so it is handled directly.
fn next_after(start: f64, direction: f64) -> f64 {
    if start.is_nan() || direction.is_nan() {
        return f64::NAN;
    }
    if start == direction {
        return direction;
    }
    let up = direction > start;
    if start == 0.0 {
        // Both zeros step to the smallest subnormal of the target's sign.
        return if up {
            f64::from_bits(1)
        } else {
            -f64::from_bits(1)
        };
    }
    let bits = start.to_bits() as i64;
    // Away from zero is "up" in magnitude for a positive value and "down" for a
    // negative one, which is exactly whether the step matches the sign.
    let step = if (start > 0.0) == up { 1 } else { -1 };
    f64::from_bits((bits + step) as u64)
}

/// `Math.ulp(d)`: the distance from `d` to the next `double` away from zero.
fn double_ulp(d: f64) -> f64 {
    if d.is_nan() {
        return f64::NAN;
    }
    if d.is_infinite() {
        return f64::INFINITY;
    }
    let d = d.abs();
    if d == f64::MAX {
        // One step further would be infinity, so the gap is measured downward.
        return d - next_after(d, f64::NEG_INFINITY);
    }
    next_after(d, f64::INFINITY) - d
}

/// The number of Unicode scalars in `s` — javars's `String.length()`.
///
/// Counting the bytes that are not UTF-8 continuation bytes is the same answer
/// `chars().count()` gives without decoding anything, and the compiler
/// vectorizes it.
fn char_count(s: &str) -> usize {
    s.as_bytes().iter().filter(|b| (*b & 0xC0) != 0x80).count()
}

/// The `i`-th character of `s`, or `None` when `i` is past the end.
///
/// `chars().nth(i)` decodes every character before the wanted one, which made
/// the ordinary `for (i = 0; i < s.length(); i++) s.charAt(i)` walk quadratic:
/// 40k characters took 13.9s where 5k took 0.25s. Java's `charAt` is a constant-
/// time array read, so the shape a program writes has to stay affordable.
///
/// The prefix test is what recovers it. If every byte before `i` is ASCII then
/// each of those characters is one byte, so the character index *is* the byte
/// index and the character at it can be read directly. `is_ascii` on a slice is
/// a vectorized byte scan rather than a decode loop, which leaves the walk with
/// a constant small enough that the quadratic shape stops mattering at the
/// sizes a program actually reaches. A string that really does hold multi-byte
/// characters falls back to decoding.
fn char_at(s: &str, i: usize) -> Option<char> {
    let bytes = s.as_bytes();
    if i < bytes.len() && bytes[..i].is_ascii() {
        return s[i..].chars().next();
    }
    s.chars().nth(i)
}

/// The byte offset of the `i`-th character of `s`, clamped to its end. The same
/// ASCII-prefix shortcut [`char_at`] takes, for the callers that want to slice
/// rather than to read one character.
fn char_byte_of(s: &str, i: usize) -> usize {
    let bytes = s.as_bytes();
    if i <= bytes.len() && bytes[..i].is_ascii() {
        return i;
    }
    s.char_indices().nth(i).map(|(b, _)| b).unwrap_or(s.len())
}

/// Evaluate a `java.lang.String` method on `s`. Index/length semantics use
/// Unicode scalar (`char`) positions — exact for the ASCII/BMP common case and
/// consistent with javars's existing "a `char` literal is a one-character
/// string" model (astral characters, which Java counts as two UTF-16 units,
/// count as one here — the same documented simplification). An out-of-range
/// index raises Java's `StringIndexOutOfBoundsException` with its exact detail
/// message; an unknown method is a javars internal error.
fn string_method(s: &str, method: &str, args: &[Value]) -> Result<Value, Fault> {
    let char_len = || char_count(s) as i64;
    null_string_argument(method, args)?;
    match (method, args.len()) {
        ("length", 0) => Ok(Value::Int(char_len())),
        ("isEmpty", 0) => Ok(Value::bool(s.is_empty())),
        // `String.compareTo` is specified as the difference of the first
        // differing character, else the length difference — not merely its sign,
        // which is why a lexicographic `Ord` cannot stand in for it.
        ("compareTo", 1) => Ok(Value::Int(compare_strings(s, &args[0].as_str_cow(), false))),
        ("compareToIgnoreCase", 1) => {
            Ok(Value::Int(compare_strings(s, &args[0].as_str_cow(), true)))
        }
        // `charAt` returns a `char`, i.e. the code point — `"abc".charAt(2) + 1`
        // is 100, not "c1". The compiler converts it back to a String wherever
        // Java's string conversion applies.
        ("charAt", 1) => {
            let i = args[0].jint();
            match usize::try_from(i).ok().and_then(|i| char_at(s, i)) {
                Some(c) => Ok(Value::Int(c as i64)),
                None => Err(Fault::java(
                    "StringIndexOutOfBoundsException",
                    format!("Index {i} out of bounds for length {}", char_len()),
                )),
            }
        }
        ("substring", 1) => substring(s, args[0].jint(), char_len()),
        ("substring", 2) => substring(s, args[0].jint(), args[1].jint()),
        ("indexOf", 1) => Ok(Value::Int(char_index_of(s, &args[0].as_str_cow()))),
        // `indexOf(t, from)` starts the search at `from`; the result is still an
        // index into the whole string.
        ("indexOf", 2) => {
            // Java clamps `fromIndex` at *both* ends before searching, so a
            // start past the end answers `-1` for a real needle and the
            // string's length for the empty one — `"abc".indexOf("", 9)` is 3,
            // not 9. Clamping only the negative end returned the unclamped
            // `from` back through the empty-needle hit.
            let from = args[1].jint().clamp(0, char_len()) as usize;
            let tail: String = s.chars().skip(from).collect();
            let hit = char_index_of(&tail, &args[0].as_str_cow());
            Ok(Value::Int(if hit < 0 { -1 } else { hit + from as i64 }))
        }
        ("lastIndexOf", 1) => Ok(Value::Int(char_last_index_of(
            s,
            &args[0].as_str_cow(),
            char_len(),
        ))),
        ("lastIndexOf", 2) => Ok(Value::Int(char_last_index_of(
            s,
            &args[0].as_str_cow(),
            args[1].jint(),
        ))),
        ("codePointAt", 1) => {
            let i = args[0].jint();
            match usize::try_from(i).ok().and_then(|i| char_at(s, i)) {
                Some(c) => Ok(Value::Int(c as i64)),
                None => Err(Fault::java(
                    "StringIndexOutOfBoundsException",
                    format!("Index {i} out of bounds for length {}", char_len()),
                )),
            }
        }
        // `strip` follows Unicode whitespace where `trim` cuts at U+0020; Rust's
        // `trim` is the Unicode one, so `trim` keeps its own ASCII-control rule
        // above and these three use the Unicode definition.
        ("strip", 0) => Ok(Value::str(s.trim_matches(java_is_whitespace).to_string())),
        ("stripLeading", 0) => Ok(Value::str(
            s.trim_start_matches(java_is_whitespace).to_string(),
        )),
        ("stripTrailing", 0) => Ok(Value::str(
            s.trim_end_matches(java_is_whitespace).to_string(),
        )),
        ("isBlank", 0) => Ok(Value::bool(s.chars().all(java_is_whitespace))),
        ("hashCode", 0) => Ok(Value::Int(
            java_hash(&Value::str(s.to_string())).unwrap_or(0).into(),
        )),
        // Both answer the receiver's text; the caller turns that into the
        // receiver itself for `toString` and into the pool's object for
        // `intern`.
        ("intern", 0) | ("toString", 0) => Ok(Value::str(s.to_string())),
        ("contentEquals", 1) => Ok(Value::bool(s == args[0].as_str_cow().as_ref())),
        // `x.getClass()` evaluates to the runtime class's *binary name*
        // ([`JBINARY_CLASS`]), so `Class`'s own two accessors land here:
        // `getName()` is that string and `getSimpleName()` drops the package
        // and enclosing-class qualifiers off it.
        ("getSimpleName", 0) => Ok(Value::str(simple_class_name(s).to_string())),
        ("getName", 0) => Ok(Value::str(s.to_string())),
        // A `char[]` of code points, matching `charAt` — so `a[i] - 'a'` is
        // arithmetic. `Arrays.toString`/`String.valueOf` of one are routed
        // through [`JCHR_STR`] by the compiler, which knows the element type.
        ("toCharArray", 0) => Ok(Value::Obj(heap_alloc(HostObj::Array(
            s.chars().map(|c| Value::Int(c as i64)).collect(),
        )))),
        // `"%s".formatted(x)` is `String.format("%s", x)` with the receiver as
        // the format string.
        ("formatted", _) => java_format(s, args, &[], None),
        // The four `java.util.regex` methods, on the engine in `crate::regex`.
        // `split(regex)` is `split(regex, 0)`: trailing empty fields are dropped
        // (interior ones are not), and a no-match returns the whole input.
        ("split", 1) | ("split", 2) => {
            let compiled = crate::regex::compile(&args[0].as_str_cow());
            let pat = compiled.as_ref().as_ref().map_err(|e| pattern_fault(e))?;
            let limit = args.get(1).map_or(0, JavaNumeric::jint);
            let parts = pat.split(s, limit).map_err(engine_fault)?;
            Ok(Value::Obj(heap_alloc(HostObj::Array(
                parts.into_iter().map(Value::str).collect(),
            ))))
        }
        ("replaceAll", 2) | ("replaceFirst", 2) => {
            let compiled = crate::regex::compile(&args[0].as_str_cow());
            let pat = compiled.as_ref().as_ref().map_err(|e| pattern_fault(e))?;
            let out = pat
                .replace(s, &args[1].as_str_cow(), method == "replaceFirst")
                .map_err(replacement_fault)?;
            Ok(Value::str(out))
        }
        // `matches` matches the whole input, not a substring of it.
        ("matches", 1) => {
            let compiled = crate::regex::compile_whole(&args[0].as_str_cow());
            let pat = compiled.as_ref().as_ref().map_err(|e| pattern_fault(e))?;
            Ok(Value::bool(pat.matches_whole(s).map_err(engine_fault)?))
        }
        ("contains", 1) => Ok(Value::bool(s.contains(args[0].as_str_cow().as_ref()))),
        ("equals", 1) => Ok(Value::bool(s == args[0].as_str_cow().as_ref())),
        ("equalsIgnoreCase", 1) => {
            let o = args[0].as_str_cow();
            Ok(Value::bool(s.to_lowercase() == o.to_lowercase()))
        }
        ("toUpperCase", 0) => Ok(Value::str(s.to_uppercase())),
        ("toLowerCase", 0) => Ok(Value::str(s.to_lowercase())),
        // Java `trim()` removes leading/trailing chars ≤ U+0020.
        ("trim", 0) => Ok(Value::str(s.trim_matches(|c: char| c <= ' ').to_string())),
        ("startsWith", 1) => Ok(Value::bool(s.starts_with(args[0].as_str_cow().as_ref()))),
        // `startsWith(prefix, offset)` tests at a character offset instead of at
        // the start. An offset outside the string is `false`, not a fault —
        // Java bounds-checks it rather than throwing.
        ("startsWith", 2) => {
            let off = args[1].jint();
            let len = char_count(s);
            Ok(Value::bool(usize::try_from(off).is_ok_and(|o| {
                o <= len && s[char_byte_of(s, o)..].starts_with(args[0].as_str_cow().as_ref())
            })))
        }
        ("endsWith", 1) => Ok(Value::bool(s.ends_with(args[0].as_str_cow().as_ref()))),
        ("concat", 1) => Ok(Value::str(format!("{s}{}", args[0].as_str_cow()))),
        ("replace", 2) => Ok(Value::str(
            s.replace(args[0].as_str_cow().as_ref(), &args[1].as_str_cow()),
        )),
        ("repeat", 1) => {
            let n = args[0].jint();
            if n < 0 {
                Err(Fault::java(
                    "IllegalArgumentException",
                    format!("count is negative: {n}"),
                ))
            } else {
                Ok(Value::str(s.repeat(n as usize)))
            }
        }
        _ => Err(Fault::internal(format!(
            "javars: unsupported String method `{method}` with {} argument(s)",
            args.len()
        ))),
    }
}

/// `String.substring(begin, end)` on `char` indices — `[begin, end)`, with
/// Java's bounds rules (`0 ≤ begin ≤ end ≤ length`) and its exact
/// `StringIndexOutOfBoundsException` message.
fn substring(s: &str, begin: i64, end: i64) -> Result<Value, Fault> {
    let len = s.chars().count() as i64;
    if begin < 0 || end > len || begin > end {
        return Err(Fault::java(
            "StringIndexOutOfBoundsException",
            format!("Range [{begin}, {end}) out of bounds for length {len}"),
        ));
    }
    let sub: String = s
        .chars()
        .skip(begin as usize)
        .take((end - begin) as usize)
        .collect();
    Ok(Value::str(sub))
}

/// `String.indexOf(sub)` returning a `char` index (not a byte offset), or `-1`.
fn char_index_of(s: &str, needle: &str) -> i64 {
    match s.find(needle) {
        Some(byte_pos) => s[..byte_pos].chars().count() as i64,
        None => -1,
    }
}

/// Static stdlib dispatch builtin (`Math.*`, `Integer.*`, `String.valueOf`, …).
/// Pops the method name (top of stack), the class name, and the `argc - 2`
/// arguments, then evaluates the corresponding static method. A faulting call
/// (bad arity, `NumberFormatException`, unknown method) surfaces as a `javars:`
/// error rather than a wrong value.
fn b_static_dispatch(vm: &mut VM, argc: u8) -> Value {
    let method = vm
        .stack
        .pop()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    let class = vm
        .stack
        .pop()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    let n = argc.saturating_sub(2) as usize; // minus class name and method name
    let mut args = Vec::with_capacity(n);
    for _ in 0..n {
        args.push(vm.stack.pop().unwrap_or(Value::Undef));
    }
    args.reverse();
    // The collection statics come first: two of them (`Collections.sort` with a
    // comparator) run user code, which `static_method` — which has no VM — could
    // not do.
    match collection_static(vm, &class, &method, &args) {
        Some(Ok(v)) => return v,
        Some(Err(f)) => return raise(vm, f),
        None => {}
    }
    // The statics that *render* an argument come next, for the same reason:
    // `static_method` has no VM, so it cannot run a user `toString()`. The gate
    // keeps a program that declares no override on the original path.
    if any_user_tostring(vm) {
        if let Some(v) = rendering_static(vm, &class, &method, &args) {
            return v;
        }
    }
    match static_method(&class, &method, &args) {
        Ok(v) => v,
        Err(f) => raise(vm, f),
    }
}

/// The stdlib statics whose whole job is to render an argument, re-implemented
/// here over [`java_str_vm`] so a user `toString()` answers for them too. Each
/// is the same rendering [`static_method`] does, with the VM-less `java_str`
/// swapped for the VM-holding one; `None` for every other static, and the
/// caller only asks when the gate is on.
fn rendering_static(vm: &mut VM, class: &str, method: &str, args: &[Value]) -> Option<Value> {
    Some(match (class, method, args.len()) {
        // `String.valueOf(char[])` concatenates the characters rather than
        // rendering the array, which is why the array case comes first.
        // `String.valueOf(Object)` is specified as `obj.toString()`, and a
        // `String`'s `toString()` is `this` — so it answers the very same
        // object, which `==` can now see.
        ("String", "valueOf", 1) if matches!(args[0], Value::Str(_)) => args[0].clone(),
        ("String", "valueOf", 1) => Value::str(match array_items(&args[0]) {
            Some(items) => items.iter().map(|v| java_str_vm(vm, v)).collect::<String>(),
            None => java_str_vm(vm, &args[0]),
        }),
        // A null delimiter falls through to [`static_method`], which raises the
        // `NullPointerException` Java does. Answering here would join on the
        // coerced empty string instead. (A null *element* is fine — Java renders
        // it "null" — so only the separator is checked.)
        ("String", "join", n) if n >= 2 && !matches!(args[0], Value::Undef) => {
            let sep = args[0].as_str_cow().into_owned();
            let parts: Vec<String> = match (sequence_items(&args[1]), n) {
                (Some(items), 2) => items.iter().map(|v| java_str_vm(vm, v)).collect(),
                _ => args[1..].iter().map(|v| java_str_vm(vm, v)).collect(),
            };
            Value::str(parts.join(&sep))
        }
        ("Arrays", "toString", 1) => match array_items(&args[0]) {
            Some(items) => {
                let inner: Vec<String> = items.iter().map(|v| java_str_vm(vm, v)).collect();
                Value::str(format!("[{}]", inner.join(", ")))
            }
            None => Value::str(java_str_vm(vm, &args[0])),
        },
        ("Arrays", "deepToString", 1) => Value::str(deep_to_string_vm(vm, &args[0])),
        _ => return None,
    })
}

/// [`arrays_deep_to_string`] with the VM in hand, so a nested array's *elements*
/// render through their overrides.
fn deep_to_string_vm(vm: &mut VM, v: &Value) -> String {
    match array_items(v) {
        Some(items) => {
            let inner: Vec<String> = items.iter().map(|e| deep_to_string_vm(vm, e)).collect();
            format!("[{}]", inner.join(", "))
        }
        None => java_str_vm(vm, v),
    }
}

/// The `java.util` statics: `Arrays.asList`, `List.of`/`Set.of`,
/// `Collections.sort`/`reverse`/`max`/`min`. `None` when `Class.method` is not
/// one of them, so the ordinary stdlib statics are reached unchanged.
fn collection_static(
    vm: &mut VM,
    class: &str,
    method: &str,
    args: &[Value],
) -> Option<Result<Value, Fault>> {
    let list = |items: Vec<Value>, fixed: Fixity| {
        Ok(Value::Obj(heap_alloc(HostObj::List {
            items,
            fixed,
            mods: 0,
        })))
    };
    Some(match (class, method) {
        // `Arrays.asList` is a fixed-size *view*: `set` works, `add` throws.
        ("Arrays", "asList") => list(varargs_items(args), Fixity::FixedSize),
        ("List", "of") => list(varargs_items(args), Fixity::Immutable),
        // `Set.of` is the one set-building factory that *rejects* a repeat
        // rather than dropping it — `Set.of(1, 1)` is an
        // `IllegalArgumentException` naming the element, not a one-element set.
        // Silently de-duplicating turned a program Java refuses to run into one
        // that ran and answered.
        ("Set", "of") => {
            let items = varargs_items(args);
            let unique = distinct(vm, &items);
            if unique.len() != items.len() {
                let dup = first_repeat(vm, &items).unwrap_or(Value::Undef);
                return Some(Err(Fault::java(
                    "IllegalArgumentException",
                    format!("duplicate element: {}", java_str_vm(vm, &dup)),
                )));
            }
            Ok(Value::Obj(heap_alloc(HostObj::Set {
                items: unique,
                order: Order::Hash,
                fixed: Fixity::Immutable,
                index: KeyIndex::default(),
            })))
        }
        // Whether `x` is a *key extractor* rather than a comparator, read off
        // the lambda's declared parameter count. `Comparator.thenComparing` is
        // overloaded on the two in Java and told apart by the target type,
        // which javars has no pass for; the arity is exact and is what the
        // prelude's `asComparator` branches on.
        ("Comparator", "isKeyExtractor") if args.len() == 1 => Ok(Value::bool(
            closure_meta(&args[0]).is_some_and(|(_, params, _)| params == 1),
        )),
        // ── java.util.stream sources ──
        ("Stream", "of") => Ok(stream_of(varargs_items(args), StreamKind::Ref)),
        // `Stream.iterate(seed, f)` and `Stream.generate(s)` are *infinite*, and
        // a stream source here is a `Vec`. Both are therefore refused unless the
        // pipeline that follows bounds them — which is what the three-argument
        // `iterate(seed, hasNext, f)` does itself, and what a `limit` does for
        // the other two. Producing some arbitrary prefix and hoping the program
        // limits it below would answer a truncated stream as though it were the
        // whole one.
        ("Stream" | "IntStream" | "LongStream" | "DoubleStream", "iterate") if args.len() == 3 => {
            let mut items = Vec::new();
            let mut cur = args[0].clone();
            while matches!(
                invoke_closure(vm, &args[1], std::slice::from_ref(&cur)),
                Value::Bool(true)
            ) {
                items.push(cur.clone());
                cur = invoke_closure(vm, &args[2], &[cur]);
            }
            Ok(stream_of(
                items,
                if class == "Stream" {
                    StreamKind::Ref
                } else {
                    primitive_stream_kind(class)
                },
            ))
        }
        ("IntStream" | "LongStream" | "DoubleStream", "of") => {
            Ok(stream_of(varargs_items(args), primitive_stream_kind(class)))
        }
        // `range` is half-open and `rangeClosed` is not, which is the whole
        // difference between them.
        ("IntStream" | "LongStream", "range" | "rangeClosed") if args.len() == 2 => {
            let (lo, hi) = (args[0].jint(), args[1].jint());
            let hi = if method == "rangeClosed" { hi + 1 } else { hi };
            Ok(stream_of(
                (lo..hi).map(Value::Int).collect(),
                primitive_stream_kind(class),
            ))
        }
        // `Arrays.stream(a)` answers an `IntStream` for an `int[]` and a
        // `Stream<T>` for a reference array. The element *type* is erased at
        // run time, so the shape is read off the elements — which is exact for
        // every array a program can build, an `int[]` holding `Value::Int` and
        // a `double[]` holding `Value::Float`.
        ("Arrays", "stream") if args.len() == 1 => {
            let items = array_items(&args[0]).unwrap_or_default();
            let kind = if items.iter().any(|v| matches!(v, Value::Float(_))) {
                StreamKind::Double
            } else if !items.is_empty() && items.iter().all(|v| matches!(v, Value::Int(_))) {
                StreamKind::Int
            } else {
                StreamKind::Ref
            };
            Ok(stream_of(items, kind))
        }
        // ── java.util.stream.Collectors ──
        ("Collectors", "toList" | "toUnmodifiableList") if args.is_empty() => {
            Ok(collector("toList", Vec::new()))
        }
        ("Collectors", "toSet" | "toUnmodifiableSet") if args.is_empty() => {
            Ok(collector("toSet", Vec::new()))
        }
        ("Collectors", "counting") if args.is_empty() => Ok(collector("counting", Vec::new())),
        ("Collectors", "joining") if args.len() <= 3 => Ok(collector("joining", args.to_vec())),
        ("Collectors", "toMap") if args.len() == 2 => Ok(collector("toMap", args.to_vec())),
        ("Collectors", "groupingBy") if args.len() == 1 => {
            Ok(collector("groupingBy", args.to_vec()))
        }
        // `java.util.Optional`'s factories. `of` rejects `null` — that is the
        // whole distinction from `ofNullable`, and accepting it would make an
        // `Optional` that claims to be present and is not.
        ("Optional", "of") if args.len() == 1 => {
            if matches!(args[0], Value::Undef) {
                return Some(Err(Fault::java("NullPointerException", String::new())));
            }
            Ok(optional(Some(args[0].clone())))
        }
        ("Optional", "ofNullable") if args.len() == 1 => Ok(optional(
            (!matches!(args[0], Value::Undef)).then(|| args[0].clone()),
        )),
        ("Optional", "empty") if args.is_empty() => Ok(optional(None)),
        // `Map.of(k1, v1, k2, v2, …)` — an immutable map, rejecting a repeated
        // key rather than letting the later pair win, and rejecting a `null`
        // key outright. Both are what `java.util.ImmutableCollections` does, and
        // both turn a program Java refuses to run into one that answers.
        ("Map", "of") if args.len() % 2 == 0 => {
            let mut entries: Vec<(Value, Value)> = Vec::with_capacity(args.len() / 2);
            for pair in args.chunks(2) {
                let (k, v) = (pair[0].clone(), pair[1].clone());
                if matches!(k, Value::Undef) || matches!(v, Value::Undef) {
                    return Some(Err(Fault::java("NullPointerException", String::new())));
                }
                if entries.iter().any(|(prev, _)| value_eq(prev, &k)) {
                    return Some(Err(Fault::java(
                        "IllegalArgumentException",
                        format!("duplicate key: {}", java_str_vm(vm, &k)),
                    )));
                }
                entries.push((k, v));
            }
            Ok(Value::Obj(heap_alloc(HostObj::Map {
                entries,
                order: Order::Hash,
                fixed: Fixity::Immutable,
                index: KeyIndex::default(),
            })))
        }
        // `Objects.equals(a, b)` — `a == b || (a != null && a.equals(b))`. It is
        // here rather than in the VM-less `static_method` because the `a.equals`
        // half runs a user body, which needs the VM.
        ("Objects", "equals") if args.len() == 2 => {
            Ok(Value::bool(objects_equals(vm, &args[0], &args[1])))
        }
        ("Collections", "sort") if !args.is_empty() => {
            let items = match sequence_items(&args[0]) {
                Some(i) => i,
                None => {
                    return Some(Err(Fault::internal(
                        "javars: `Collections.sort` needs a List",
                    )))
                }
            };
            let cmp = args.get(1).cloned().unwrap_or(Value::Undef);
            sort_with(vm, items, &cmp)
                .and_then(|sorted| write_list(&args[0], sorted))
                .map(|()| Value::Undef)
        }
        ("Collections", "reverse") if args.len() == 1 => {
            let mut items = sequence_items(&args[0]).unwrap_or_default();
            items.reverse();
            write_list(&args[0], items).map(|()| Value::Undef)
        }
        // `max`/`min` take an optional comparator, which may be a user closure
        // — so the pick goes through the same stable sort the stream terminals
        // use rather than through `Iterator::max_by`, which cannot call back
        // into the VM.
        ("Collections", "max") | ("Collections", "min") if matches!(args.len(), 1 | 2) => {
            let items = sequence_items(&args[0]).unwrap_or_default();
            if items.is_empty() {
                return Some(Err(Fault::java("NoSuchElementException", String::new())));
            }
            let sorted = sort_values(vm, items, args.get(1));
            Ok(if method == "max" {
                sorted.last().cloned().unwrap_or(Value::Undef)
            } else {
                sorted.first().cloned().unwrap_or(Value::Undef)
            })
        }
        _ => return None,
    })
}

/// The elements a varargs static receives. A lone *array* argument spreads —
/// `Arrays.asList(strArray)` is a list of the array's elements, not a
/// one-element list holding the array — which is what Java's varargs does for
/// every reference array. A lone `List`/`Set` argument does not spread, matching
/// Java exactly.
fn varargs_items(args: &[Value]) -> Vec<Value> {
    if let [Value::Obj(id)] = args {
        let spread = HEAP.with(|h| match h.borrow().get(*id as usize) {
            Some(HostObj::Array(items)) => Some(items.clone()),
            _ => None,
        });
        if let Some(items) = spread {
            return items;
        }
    }
    args.to_vec()
}

/// Overwrite a `List` handle's elements in place, so a sort or reverse is
/// visible through every reference to it — Java's semantics for these statics.
fn write_list(target: &Value, items: Vec<Value>) -> Result<(), Fault> {
    let Value::Obj(id) = target else {
        return Ok(());
    };
    // `Collections.sort`/`reverse` reorder in place; Java counts both as
    // structural modifications, so an outstanding `subList` view of the target
    // goes stale exactly as it does there.
    write_sequence(*id as usize, items, true)
}

/// Evaluate a static stdlib method `Class.method(args)`.
///
/// Numeric overloads follow Java at the value level: `Math.abs`/`max`/`min`
/// keep an `int` result for integral operands and a `double` result when any
/// operand is floating point; `Math.pow`/`sqrt`/`floor`/`ceil` always return a
/// `double`; `Math.round` returns an integer (`floor(x + 0.5)`, ties toward
/// positive infinity). `Integer.parseInt`/`Long.parseLong` reject malformed
/// input the way `javac`-compiled code would throw `NumberFormatException`.
fn static_method(class: &str, method: &str, args: &[Value]) -> Result<Value, Fault> {
    let both_int = |a: &Value, b: &Value| {
        matches!(deboxed(a), Value::Int(_)) && matches!(deboxed(b), Value::Int(_))
    };
    match (class, method, args.len()) {
        // ── java.lang.Math ──
        // `wrapping_abs`, not `abs`: Rust's `abs` panics on `i64::MIN`, so
        // `Math.abs(Long.MIN_VALUE)` aborted the process where Java answers
        // `Long.MIN_VALUE` — "if the argument is equal to the value of
        // Long.MIN_VALUE, the most negative representable long value, the result
        // is that same value, which is negative" (Math.abs javadoc). The `int`
        // overload's identical case is narrowed by the compiler's trailing
        // `emit_wrap32`; this is the 64-bit one, which had no guard at all.
        ("Math", "abs", 1) => Ok(match &args[0] {
            Value::Int(n) => Value::Int(n.wrapping_abs()),
            other => Value::float(other.jfloat().abs()),
        }),
        ("Math", "max", 2) => Ok(if both_int(&args[0], &args[1]) {
            Value::Int(args[0].jint().max(args[1].jint()))
        } else {
            Value::float(max_double(args[0].jfloat(), args[1].jfloat()))
        }),
        ("Math", "min", 2) => Ok(if both_int(&args[0], &args[1]) {
            Value::Int(args[0].jint().min(args[1].jint()))
        } else {
            Value::float(min_double(args[0].jfloat(), args[1].jfloat()))
        }),
        ("Math", "pow", 2) => Ok(Value::float(pow_double(args[0].jfloat(), args[1].jfloat()))),
        ("Math", "sqrt", 1) => Ok(Value::float(args[0].jfloat().sqrt())),
        ("Math", "floor", 1) => Ok(Value::float(args[0].jfloat().floor())),
        ("Math", "ceil", 1) => Ok(Value::float(args[0].jfloat().ceil())),
        ("Math", "round", 1) => Ok(Value::Int(round_double(args[0].jfloat()))),
        // `Math.floorDiv`/`floorMod` round toward negative infinity, unlike `/`
        // and `%` which truncate toward zero: `floorDiv(-7, 2)` is -4.
        ("Math", "floorDiv", 2) => floor_div(args[0].jint(), args[1].jint()).map(Value::Int),
        ("Math", "floorMod", 2) => {
            let (a, b) = (args[0].jint(), args[1].jint());
            // Wrapping for the same reason `floor_div` wraps: with
            // `Long.MIN_VALUE` and -1 the quotient is `Long.MIN_VALUE` and
            // `q * b` overflows, which panicked and aborted. Java answers 0.
            floor_div(a, b).map(|q| Value::Int(a.wrapping_sub(q.wrapping_mul(b))))
        }
        // ── The width-overloaded `Math` statics ──
        // Each carries one extra operand, the [`width`] code the compiler
        // resolved from the arguments' static types. That is also what makes
        // the arity here (`3` for a two-argument method) distinct from any real
        // overload's, so a program cannot reach these arms by accident.
        ("Math", "addExact", 3) => {
            exact_arith(args[0].jint(), args[1].jint(), args[2].jint(), Exact::Add)
        }
        ("Math", "subtractExact", 3) => {
            exact_arith(args[0].jint(), args[1].jint(), args[2].jint(), Exact::Sub)
        }
        ("Math", "multiplyExact", 3) => {
            exact_arith(args[0].jint(), args[1].jint(), args[2].jint(), Exact::Mul)
        }
        // `Math.toIntExact(long)` is the narrowing the `Exact` family exists
        // for: in range it is the value, out of range it is `integer overflow`.
        ("Math", "toIntExact", 2) => {
            let v = args[0].jint();
            match i32::try_from(v) {
                Ok(n) => Ok(Value::Int(n.into())),
                Err(_) => Err(Fault::java("ArithmeticException", "integer overflow")),
            }
        }
        // The unary members of the family. Each is one of the binary ones with a
        // constant operand — Java specifies them that way and their overflow
        // messages agree — except `absExact`, whose message names the constant
        // it cannot represent.
        ("Math", "incrementExact", 2) => exact_arith(args[0].jint(), 1, args[1].jint(), Exact::Add),
        ("Math", "decrementExact", 2) => exact_arith(args[0].jint(), 1, args[1].jint(), Exact::Sub),
        ("Math", "negateExact", 2) => exact_arith(0, args[0].jint(), args[1].jint(), Exact::Sub),
        ("Math", "absExact", 2) => {
            let (v, width) = (args[0].jint(), args[1].jint());
            let min = if width == width::LONG {
                i64::MIN
            } else {
                i64::from(i32::MIN)
            };
            if v == min {
                let name = if width == width::LONG {
                    "Long.MIN_VALUE"
                } else {
                    "Integer.MIN_VALUE"
                };
                return Err(Fault::java(
                    "ArithmeticException",
                    format!("Overflow to represent absolute value of {name}"),
                ));
            }
            Ok(Value::Int(v.abs()))
        }
        // The three exact divisions. Each rounds differently and all three
        // overflow in exactly one place — `MIN_VALUE / -1`, whose quotient is
        // one past the width — while a zero divisor is `/ by zero` first.
        ("Math", "divideExact", 3) => exact_divide(
            args[0].jint(),
            args[1].jint(),
            args[2].jint(),
            Rounding::Truncate,
        ),
        ("Math", "floorDivExact", 3) => exact_divide(
            args[0].jint(),
            args[1].jint(),
            args[2].jint(),
            Rounding::Floor,
        ),
        ("Math", "ceilDivExact", 3) => exact_divide(
            args[0].jint(),
            args[1].jint(),
            args[2].jint(),
            Rounding::Ceil,
        ),
        ("Math", "clamp", 4) => math_clamp(&args[0], &args[1], &args[2], args[3].jint()),
        ("Math", "signum", 1) => Ok(Value::float(match args[0].jfloat() {
            f if f > 0.0 => 1.0,
            f if f < 0.0 => -1.0,
            f => f,
        })),
        // The transcendentals (`sin`/`cos`/`tan`/`atan`/`atan2`/`exp`/`log`/
        // `log10`/`cbrt`/`hypot`) are deliberately absent. The JDK permits them
        // a 1-ulp error and answers from its own fdlibm-derived implementation,
        // which Rust's libm does not reproduce bit-for-bit: a 180-value
        // differential sweep against OpenJDK 26 diverged in the last digit for
        // every one of them (`sin` 14/180, `cbrt` 25/180, `tan` 5/10). An
        // unregistered method is a clear error; a silently different last digit
        // is not, so they stay out until a StrictMath port can answer exactly.
        ("Math", "toRadians", 1) => Ok(Value::float(args[0].jfloat().to_radians())),
        ("Math", "toDegrees", 1) => Ok(Value::float(args[0].jfloat().to_degrees())),
        // The exactly-specified `double` statics, as opposed to the
        // transcendentals just above. Each is an IEEE operation or a walk over
        // the bit pattern, so there is one right answer and Rust gives it:
        // `rint` is roundToIntegralTiesToEven (2.5 is 2.0, 3.5 is 4.0, unlike
        // `round`'s half-up), `fma` is fusedMultiplyAdd with a single rounding,
        // and `ulp`/`nextUp`/`nextDown`/`nextAfter` step the representable
        // neighbours. They were unregistered — an error at the call site — for
        // want of a reason rather than for one.
        ("Math", "rint", 1) => Ok(Value::float(args[0].jfloat().round_ties_even())),
        ("Math", "copySign", 2) => Ok(Value::float(args[0].jfloat().copysign(args[1].jfloat()))),
        ("Math", "fma", 3) => Ok(Value::float(
            args[0].jfloat().mul_add(args[1].jfloat(), args[2].jfloat()),
        )),
        ("Math", "ulp", 1) => Ok(Value::float(double_ulp(args[0].jfloat()))),
        ("Math", "nextUp", 1) => Ok(Value::float(next_after(args[0].jfloat(), f64::INFINITY))),
        ("Math", "nextDown", 1) => Ok(Value::float(next_after(
            args[0].jfloat(),
            f64::NEG_INFINITY,
        ))),
        ("Math", "nextAfter", 2) => {
            Ok(Value::float(next_after(args[0].jfloat(), args[1].jfloat())))
        }

        // ── java.lang.Integer / Long ──
        // A null argument is rejected before the text is looked at; without the
        // guard it coerced to `""` and reported `For input string: ""`, which is
        // the message a genuinely empty string gets. See [`null_number_fault`].
        ("Integer", "parseInt", 1) if matches!(args[0], Value::Undef) => Err(null_number_fault()),
        ("Integer", "parseInt", 2) if matches!(args[0], Value::Undef) => Err(null_number_fault()),
        ("Long", "parseLong", 1) if matches!(args[0], Value::Undef) => Err(null_number_fault()),
        ("Integer", "parseInt", 1) => parse_int_radix(&args[0].as_str_cow(), 10, true),
        ("Integer", "parseInt", 2) => {
            let radix = args[1].jint();
            parse_int_radix(&args[0].as_str_cow(), radix, true)
        }
        ("Long", "parseLong", 1) => parse_int_radix(&args[0].as_str_cow(), 10, false),
        // `Integer.valueOf(String)` parses; `Integer.valueOf(int)` is identity.
        // `null` is neither: it is the `String` overload, and it faults. Left to
        // the `other` arm it read as the `int` overload and answered 0.
        ("Integer", "valueOf", 1) => match &args[0] {
            Value::Str(s) => parse_int_radix(s, 10, true),
            Value::Undef => Err(null_number_fault()),
            other => Ok(Value::Int(other.jint())),
        },
        // `Integer.toString(int)` / `Integer.toString(int, radix)`.
        ("Integer", "toString", 1) => Ok(Value::str(args[0].jint().to_string())),
        ("Integer", "toString", 2) => Ok(Value::str(int_to_radix_string(
            args[0].jint(),
            args[1].jint(),
        ))),
        // The unsigned radix renderings read the value as a *bit pattern* at its
        // declared width — `Integer.toHexString(-1)` is "ffffffff" and
        // `Long.toHexString(-1L)` is sixteen f's.
        ("Integer", "toBinaryString", 1) => {
            Ok(Value::str(format!("{:b}", args[0].jint() as i32 as u32)))
        }
        ("Integer", "toHexString", 1) => {
            Ok(Value::str(format!("{:x}", args[0].jint() as i32 as u32)))
        }
        ("Integer", "toOctalString", 1) => {
            Ok(Value::str(format!("{:o}", args[0].jint() as i32 as u32)))
        }
        ("Long", "toBinaryString", 1) => Ok(Value::str(format!("{:b}", args[0].jint() as u64))),
        ("Long", "toHexString", 1) => Ok(Value::str(format!("{:x}", args[0].jint() as u64))),
        ("Long", "toOctalString", 1) => Ok(Value::str(format!("{:o}", args[0].jint() as u64))),
        ("Integer" | "Long", "compare", 2) => {
            Ok(Value::Int(cmp_to_int(args[0].jint().cmp(&args[1].jint()))))
        }
        ("Integer" | "Long", "max", 2) => Ok(Value::Int(args[0].jint().max(args[1].jint()))),
        ("Integer" | "Long", "min", 2) => Ok(Value::Int(args[0].jint().min(args[1].jint()))),
        ("Integer" | "Long", "sum", 2) => {
            Ok(Value::Int(args[0].jint().wrapping_add(args[1].jint())))
        }
        ("Integer" | "Long", "signum", 1) => Ok(Value::Int(args[0].jint().signum())),
        // `Xxx.hashCode(x)` is the static spelling of the boxed instance
        // method, and each box folds a different width: `Integer` is the value,
        // `Long` folds its halves, `Double` folds `doubleToLongBits`, and
        // `Float` is `floatToIntBits` *unfolded* — so `Float.hashCode(1.5f)` is
        // 1069547520 where `Double.hashCode(1.5)` is 1073217536.
        ("Integer" | "Long" | "Double" | "Boolean" | "Character", "hashCode", 1) => {
            let v = match class {
                "Double" => Value::float(args[0].jfloat()),
                "Boolean" => Value::bool(matches!(args[0], Value::Bool(true))),
                "Character" => Value::Int(i64::from(char_arg(&args[0]) as u32)),
                _ => Value::Int(args[0].jint()),
            };
            Ok(Value::Int(java_hash(&v).unwrap_or(0).into()))
        }
        ("Float", "hashCode", 1) => Ok(Value::Int(
            ((args[0].jfloat() as f32).to_bits() as i32).into(),
        )),
        ("Long", "toString", 1) => Ok(Value::str(args[0].jint().to_string())),
        ("Long", "valueOf", 1) => match &args[0] {
            Value::Str(s) => parse_int_radix(s, 10, false),
            Value::Undef => Err(null_number_fault()),
            other => Ok(Value::Int(other.jint())),
        },

        // ── java.lang.Double ──
        // The floating parsers answer a null with a `NullPointerException`, not
        // with the integral parsers' `NumberFormatException` — see
        // [`null_float_parse_fault`]. javars reported `NumberFormatException:
        // empty String` for both, which is the wrong *class*, so a
        // `catch (NumberFormatException e)` caught what Java does not.
        ("Double" | "Float", "parseDouble" | "parseFloat" | "valueOf", 1)
            if matches!(args[0], Value::Undef) =>
        {
            Err(null_float_parse_fault())
        }
        ("Double", "parseDouble", 1) | ("Double", "valueOf", 1) => {
            let s = args[0].as_str_cow();
            parse_java_double(&s)
                .map(Value::float)
                .ok_or_else(|| Fault::java("NumberFormatException", float_format_message(&s)))
        }
        ("Double", "toString", 1) => Ok(Value::str(format_double(args[0].jfloat()))),

        // ── java.lang.Float ──
        // Every one of these answers at 32-bit precision, which is the whole
        // reason they are not aliases of the `Double` arm above.
        ("Float", "toString", 1) => Ok(Value::str(format_float(args[0].jfloat() as f32))),
        ("Float", "parseFloat", 1) | ("Float", "valueOf", 1) => {
            let s = args[0].as_str_cow();
            parse_java_double(&s)
                .map(|f| Value::float(f as f32 as f64))
                .ok_or_else(|| Fault::java("NumberFormatException", float_format_message(&s)))
        }
        ("Float", "compare", 2) => Ok(Value::Int(float_compare(
            f64::from(args[0].jfloat() as f32),
            f64::from(args[1].jfloat() as f32),
        ))),
        ("Float", "isNaN", 1) => Ok(Value::bool(args[0].jfloat().is_nan())),
        ("Float", "isInfinite", 1) => Ok(Value::bool(args[0].jfloat().is_infinite())),
        ("Double", "compare", 2) => Ok(Value::Int(float_compare(
            args[0].jfloat(),
            args[1].jfloat(),
        ))),
        ("Double", "isNaN", 1) => Ok(Value::bool(args[0].jfloat().is_nan())),
        ("Double", "isInfinite", 1) => Ok(Value::bool(args[0].jfloat().is_infinite())),

        // ── java.lang.Character ──
        // The argument is a `char` code point (`char_arg` also accepts the
        // one-character String a boxed `Character` is). `toUpperCase`/
        // `toLowerCase` return a `char`, so they return a code point too.
        ("Character", "isDigit", 1) => Ok(Value::bool(char_arg(&args[0]).is_ascii_digit())),
        ("Character", "isLetter", 1) => Ok(Value::bool(char_arg(&args[0]).is_alphabetic())),
        ("Character", "isLetterOrDigit", 1) => {
            Ok(Value::bool(char_arg(&args[0]).is_alphanumeric()))
        }
        ("Character", "isWhitespace", 1) => Ok(Value::bool(java_is_whitespace(char_arg(&args[0])))),
        ("Character", "isUpperCase", 1) => Ok(Value::bool(char_arg(&args[0]).is_uppercase())),
        ("Character", "isLowerCase", 1) => Ok(Value::bool(char_arg(&args[0]).is_lowercase())),
        // Java's `Character.toUpperCase(char)` is a *one-to-one* code-point map:
        // a character whose full uppercasing is multi-character (`ß`) is left
        // alone, unlike `String.toUpperCase`.
        ("Character", "toUpperCase", 1) => Ok(Value::Int(one_to_one_case(
            char_arg(&args[0]),
            char::to_uppercase,
        ))),
        ("Character", "toLowerCase", 1) => Ok(Value::Int(one_to_one_case(
            char_arg(&args[0]),
            char::to_lowercase,
        ))),
        ("Character", "toString", 1) => Ok(Value::str(char_arg(&args[0]).to_string())),
        ("Character", "getNumericValue", 1) => Ok(Value::Int(
            char_arg(&args[0]).to_digit(36).map_or(-1, i64::from),
        )),

        // ── java.lang.Boolean ──
        ("Boolean", "parseBoolean", 1) => Ok(Value::bool(
            args[0].as_str_cow().eq_ignore_ascii_case("true"),
        )),

        // ── java.lang.String ──
        // `String.valueOf(x)` renders any value with Java's `println` rules —
        // except a `char[]`, whose overload concatenates the characters rather
        // than printing the array.
        // `copyValueOf(char[])` is `valueOf(char[])` — the JDK's own
        // implementation is one call to the other — so it takes the same arm
        // rather than a second reading of the array.
        // See the `valueOf` note in `static_method_vm`. `copyValueOf` is
        // *not* here: it is documented to copy, and its argument is a `char[]`
        // rather than a `String` in every legal call.
        ("String", "valueOf", 1) if matches!(args[0], Value::Str(_)) => Ok(args[0].clone()),
        ("String", "valueOf" | "copyValueOf", 1) => Ok(Value::str(match array_items(&args[0]) {
            Some(items) => items.iter().map(java_str).collect::<String>(),
            None => java_str(&args[0]),
        })),
        // `String.format(fmt, args…)` — printf-style formatting (subset).
        ("String", "format", _) if !args.is_empty() => {
            let fmt = args[0].as_str_cow().into_owned();
            java_format(&fmt, &args[1..], &[], None)
        }

        // `String.join(sep, a, b, …)`, `String.join(sep, array)`, and
        // `String.join(sep, iterable)` — Java's second overload takes an
        // `Iterable<CharSequence>`, so a `List`/`Set` argument joins its
        // *elements*. Matching only arrays here rendered the collection's own
        // `toString` as one part (`String.join("-", List.of("a","b"))` gave
        // `[a, b]` instead of `a-b`).
        // `String.join` dereferences the delimiter before it looks at anything
        // else, so a null one is an NPE rather than a join on "".
        ("String", "join", n) if n >= 2 && matches!(args[0], Value::Undef) => Err(Fault::java(
            "NullPointerException",
            "Cannot invoke \"java.lang.CharSequence.toString()\" because \"delimiter\" is null",
        )),
        ("String", "join", n) if n >= 2 => {
            let sep = args[0].as_str_cow().into_owned();
            let parts: Vec<String> = match (sequence_items(&args[1]), n) {
                (Some(items), 2) => items.iter().map(java_str).collect(),
                _ => args[1..].iter().map(java_str).collect(),
            };
            Ok(Value::str(parts.join(&sep)))
        }

        // ── java.lang.Boolean ──
        ("Boolean", "toString", 1) => Ok(Value::str(java_str(&args[0]))),
        ("Boolean", "compare", 2) => Ok(Value::Int(cmp_to_int(
            args[0].is_truthy().cmp(&args[1].is_truthy()),
        ))),

        // ── java.util.Arrays ──
        // `Arrays.toString(a)` — shallow `[e0, e1, …]` (null → "null").
        ("Arrays", "toString", 1) => Ok(Value::str(arrays_to_string(&args[0]))),
        // `Arrays.deepToString(a)` recurses into nested arrays, which is what a
        // rectangular `int[][]` needs.
        ("Arrays", "deepToString", 1) => Ok(Value::str(arrays_deep_to_string(&args[0]))),
        // `Arrays.sort(a)` sorts in place, so it mutates the heap array and
        // returns nothing.
        ("Arrays", "sort", 1) => {
            array_mutate(&args[0], |a| a.sort_by(natural_cmp))?;
            Ok(Value::Undef)
        }
        ("Arrays", "fill", 2) => {
            let v = args[1].clone();
            array_mutate(&args[0], |a| a.fill(v))?;
            Ok(Value::Undef)
        }
        ("Arrays", "equals", 2) => match (array_items(&args[0]), array_items(&args[1])) {
            (Some(x), Some(y)) => Ok(Value::bool(
                x.len() == y.len()
                    && x.iter()
                        .zip(y.iter())
                        .all(|(p, q)| natural_cmp(p, q) == std::cmp::Ordering::Equal),
            )),
            _ => Ok(Value::bool(false)),
        },
        // `Arrays.copyOf` pads with the element type's default when it grows.
        // javars erases the element type at runtime, so the pad is inferred from
        // element 0's kind — the only evidence available — and is `null` for an
        // empty source.
        // Both copies clamp their arguments, and Java does not: a bad length or
        // a reversed range threw where javars silently answered an array.
        // `Arrays.copyOf` allocates before it copies, so a negative length is
        // the allocation's own `NegativeArraySizeException`.
        ("Arrays", "copyOf", 2) => {
            let items = array_items(&args[0]).unwrap_or_default();
            let len = args[1].jint();
            if len < 0 {
                return Err(Fault::java("NegativeArraySizeException", len.to_string()));
            }
            let pad = element_default(&items);
            let mut out = items;
            out.resize(len as usize, pad);
            Ok(Value::Obj(heap_alloc(HostObj::Array(out))))
        }
        ("Arrays", "copyOfRange", 3) => {
            let items = array_items(&args[0]).unwrap_or_default();
            let (from, to) = (args[1].jint(), args[2].jint());
            // `Arrays.copyOfRange` checks the range itself and reports it with
            // the two endpoints alone; a `from` outside the source is left to
            // the `System.arraycopy` underneath, whose message names the
            // element type javars has erased, so that one keeps the class and
            // omits the text (BUGS.md).
            if from > to {
                return Err(Fault::java(
                    "IllegalArgumentException",
                    format!("{from} > {to}"),
                ));
            }
            if from < 0 || from > items.len() as i64 {
                return Err(Fault::java("ArrayIndexOutOfBoundsException", String::new()));
            }
            let (from, to) = (from as usize, to as usize);
            let pad = element_default(&items);
            let mut out: Vec<Value> = items
                .get(from..to.min(items.len()))
                .unwrap_or_default()
                .to_vec();
            out.resize(to - from, pad);
            Ok(Value::Obj(heap_alloc(HostObj::Array(out))))
        }
        // `Arrays.binarySearch` returns `-(insertion point) - 1` when absent,
        // exactly as the JDK does.
        ("Arrays", "binarySearch", 2) => {
            let items = array_items(&args[0]).unwrap_or_default();
            Ok(Value::Int(
                match items.binary_search_by(|p| natural_cmp(p, &args[1])) {
                    Ok(i) => i as i64,
                    Err(i) => -(i as i64) - 1,
                },
            ))
        }
        // `Arrays.hashCode(a)` — the JDK's documented `31 * result + e` fold,
        // seeded at 1, wrapping at 32 bits.
        ("Arrays", "hashCode", 1) => {
            let items = array_items(&args[0]).unwrap_or_default();
            let h = items.iter().fold(1i32, |acc, e| {
                acc.wrapping_mul(31).wrapping_add(java_hash(e).unwrap_or(0))
            });
            Ok(Value::Int(h as i64))
        }

        _ => Err(Fault::internal(format!(
            "javars: unsupported static method `{class}.{method}` with {} argument(s)",
            args.len()
        ))),
    }
}

/// The last index (in characters) at which `needle` starts at or before
/// `from`, or -1.
///
/// The clamping order is the JDK's (`StringLatin1.lastIndexOf`) and it matters:
/// `fromIndex` is first pulled *down* to the last position a needle of this
/// length could start at, and only then rejected for being negative. Testing
/// the empty needle before that ordering — which is what a `clamp(0, len)`
/// does — answered `"abc".lastIndexOf("", -1)` with 0 where Java answers -1.
fn char_last_index_of(hay: &str, needle: &str, from: i64) -> i64 {
    let chars: Vec<char> = hay.chars().collect();
    let pat: Vec<char> = needle.chars().collect();
    let start = from.min(chars.len() as i64 - pat.len() as i64);
    if start < 0 {
        return -1;
    }
    if pat.is_empty() {
        return start;
    }
    (0..=start)
        .rev()
        .find(|&i| chars[i as usize..].starts_with(&pat))
        .unwrap_or(-1)
}

/// The literal text a `String` regex argument matches, for the pattern subset
/// javars supports.
///
/// javars links no regex engine, so `split`/`replaceAll`/`replaceFirst`/
/// `matches` accept only patterns with no metacharacter — which is what the
/// overwhelmingly common single-separator call is, and which the JDK itself
/// fast-paths. A pattern that would need real matching is reported rather than
/// silently treated as a literal and answered wrong.
fn pattern_fault(msg: &str) -> Fault {
    Fault::java("PatternSyntaxException", msg)
}

/// A replacement string Java rejects: a dangling `\`, a bare `$`, or a
/// reference to a group the pattern does not have. Java raises
/// `IllegalArgumentException` for the malformed forms and
/// `IndexOutOfBoundsException` for the missing group, and the message text
/// distinguishes them.
fn replacement_fault(msg: String) -> Fault {
    // The split is by *which* group reference failed, not by the shared "No
    // group" prefix. `Matcher.appendExpandedReplacement` throws
    // `IndexOutOfBoundsException` for a numbered group that does not exist
    // (`$9`) and `IllegalArgumentException` for a named one (`${nope}`), so
    // keying on the prefix alone gave the named case the numbered case's
    // class. Measured on `openjdk 21.0.12`.
    if msg.starts_with("No group") && !msg.starts_with("No group with name") {
        Fault::java("IndexOutOfBoundsException", msg)
    } else {
        Fault::java("IllegalArgumentException", msg)
    }
}

/// The matching engine giving up (its backtrack limit), which is not a Java
/// outcome at all — Java would either answer or overflow its own stack. javars
/// reports rather than guessing.
fn engine_fault(msg: String) -> Fault {
    Fault::internal(format!("javars: regular expression failed: {msg}"))
}

/// Which of the three exact binary operations [`exact_arith`] performs.
enum Exact {
    /// `Math.addExact`.
    Add,
    /// `Math.subtractExact`.
    Sub,
    /// `Math.multiplyExact`.
    Mul,
}

/// `Math.addExact` / `subtractExact` / `multiplyExact` at the width the
/// compiler resolved.
///
/// The `int` overloads compute in `i64` and then check the `i32` range, which is
/// exact: no sum, difference or product of two `i32`s can leave `i64`. The
/// `long` ones use the checked operations, because there is nothing wider to
/// compute in. Java's messages are `integer overflow` and `long overflow`, and
/// which one a program sees is the whole reason the width travels with the call.
fn exact_arith(a: i64, b: i64, width: i64, op: Exact) -> Result<Value, Fault> {
    if width == width::LONG {
        let r = match op {
            Exact::Add => a.checked_add(b),
            Exact::Sub => a.checked_sub(b),
            Exact::Mul => a.checked_mul(b),
        };
        return match r {
            Some(v) => Ok(Value::Int(v)),
            None => Err(Fault::java("ArithmeticException", "long overflow")),
        };
    }
    let r = match op {
        Exact::Add => a + b,
        Exact::Sub => a - b,
        Exact::Mul => a * b,
    };
    match i32::try_from(r) {
        Ok(n) => Ok(Value::Int(n.into())),
        Err(_) => Err(Fault::java("ArithmeticException", "integer overflow")),
    }
}

/// Which way [`exact_divide`] rounds an inexact quotient.
enum Rounding {
    /// Toward zero — `Math.divideExact`, the `/` operator's own rounding.
    Truncate,
    /// Toward negative infinity — `Math.floorDivExact`.
    Floor,
    /// Toward positive infinity — `Math.ceilDivExact`.
    Ceil,
}

/// `Math.divideExact` / `floorDivExact` / `ceilDivExact` at the width the
/// compiler resolved.
///
/// All three overflow in exactly one place, `MIN_VALUE / -1`, whose quotient is
/// one past the width in every rounding — and a zero divisor is `/ by zero`
/// before that, which is the order openjdk 26.0.2 reports them in.
fn exact_divide(a: i64, b: i64, width: i64, round: Rounding) -> Result<Value, Fault> {
    if b == 0 {
        return Err(Fault::java("ArithmeticException", "/ by zero"));
    }
    let overflow = || {
        Fault::java(
            "ArithmeticException",
            if width == width::LONG {
                "long overflow"
            } else {
                "integer overflow"
            },
        )
    };
    let q = match round {
        Rounding::Truncate => a.checked_div(b),
        Rounding::Floor => Some(floor_div(a, b)?),
        // Ceiling is the floor plus one whenever the division was inexact,
        // whatever the signs: `ceilDiv(7, 2)` is 4 (floor 3) and
        // `ceilDiv(-7, 2)` is -3 (floor -4). Reusing `floor_div` keeps the one
        // correction step in a single place.
        Rounding::Ceil => floor_div(a, b)
            .map(|f| {
                if a.wrapping_rem(b) != 0 {
                    f.wrapping_add(1)
                } else {
                    f
                }
            })
            .map(Some)?,
    };
    let q = q.ok_or_else(overflow)?;
    if width == width::LONG {
        // `checked_div` already refused `i64::MIN / -1`; the two rounding arms
        // reach it through `wrapping` arithmetic, so they are checked here.
        if a == i64::MIN && b == -1 {
            return Err(overflow());
        }
        return Ok(Value::Int(q));
    }
    match i32::try_from(q) {
        Ok(n) => Ok(Value::Int(n.into())),
        Err(_) => Err(overflow()),
    }
}

/// `Math.clamp(value, min, max)` at the width the compiler resolved.
///
/// The bounds decide the overload, so `clamp(aLong, 1, 10)` answers an `int` and
/// `clamp(aLong, 1L, 10L)` a `long`. Verified against openjdk 26.0.2 for the
/// cases that are not `min(max(v, lo), hi)`: `min` or `max` being NaN is
/// `IllegalArgumentException: min is NaN` / `max is NaN`, `min > max` is
/// `IllegalArgumentException: "<min> > <max>"` rendered at the overload's width,
/// a NaN *value* passes through as NaN, and the signed zeros order
/// (`clamp(-1.0, -0.0, 0.0)` is `-0.0`).
fn math_clamp(value: &Value, min: &Value, max: &Value, width: i64) -> Result<Value, Fault> {
    if width == width::INT || width == width::LONG {
        let (v, lo, hi) = (value.jint(), min.jint(), max.jint());
        if lo > hi {
            return Err(Fault::java(
                "IllegalArgumentException",
                format!("{lo} > {hi}"),
            ));
        }
        return Ok(Value::Int(v.max(lo).min(hi)));
    }
    let (v, lo, hi) = (value.jfloat(), min.jfloat(), max.jfloat());
    let render = |x: f64| {
        if width == width::FLOAT {
            format_float(x as f32)
        } else {
            format_double(x)
        }
    };
    if lo.is_nan() {
        return Err(Fault::java("IllegalArgumentException", "min is NaN"));
    }
    if hi.is_nan() {
        return Err(Fault::java("IllegalArgumentException", "max is NaN"));
    }
    if float_compare(lo, hi) > 0 {
        return Err(Fault::java(
            "IllegalArgumentException",
            format!("{} > {}", render(lo), render(hi)),
        ));
    }
    Ok(Value::float(java_min(java_max(v, lo), hi)))
}

/// Java's `Math.max(double, double)`: NaN wins, and `-0.0` is below `0.0`.
///
/// Rust's `f64::max` disagrees on both — it *drops* a NaN operand and treats the
/// two zeros as interchangeable — so the ordering comes from
/// [`float_compare`], which is `Double.compare`'s total order.
fn java_max(a: f64, b: f64) -> f64 {
    if a.is_nan() || b.is_nan() {
        return f64::NAN;
    }
    if float_compare(a, b) >= 0 {
        a
    } else {
        b
    }
}

/// Java's `Math.min(double, double)`; [`java_max`]'s counterpart.
fn java_min(a: f64, b: f64) -> f64 {
    if a.is_nan() || b.is_nan() {
        return f64::NAN;
    }
    if float_compare(a, b) <= 0 {
        a
    } else {
        b
    }
}

/// Java's `Math.floorDiv`: integer division rounded toward negative infinity
/// rather than toward zero, so `floorDiv(-7, 2)` is -4 where `-7 / 2` is -3.
fn floor_div(a: i64, b: i64) -> Result<i64, Fault> {
    if b == 0 {
        return Err(Fault::java("ArithmeticException", "/ by zero"));
    }
    let q = a.wrapping_div(b);
    // One correction step when the signs differ and the division was inexact.
    //
    // Every arithmetic step here wraps, because `Long.MIN_VALUE / -1` reaches
    // all three. The divide already used `wrapping_div`; plain `%` panicked
    // ("attempt to calculate the remainder with overflow") and aborted the
    // process, and `q - 1` would have been the next panic. Java's answer is
    // `Long.MIN_VALUE`: the remainder is 0, so no correction applies.
    Ok(if a.wrapping_rem(b) != 0 && (a ^ b) < 0 {
        q.wrapping_sub(1)
    } else {
        q
    })
}

/// Java's `Character.isWhitespace(int)`.
///
/// Rust's `char::is_whitespace` is the Unicode `White_Space` property, and the
/// two sets are different in *both* directions — which is why neither
/// `String.strip` nor `String.isBlank` can be spelled with it. Java's
/// definition (its own Javadoc) is a Unicode space separator that is not one of
/// the three non-breaking spaces, plus the five ASCII controls `\t\n\f\r`
/// and the four information separators ``–``. So `White_Space`
/// includes `U+00A0`, `U+2007`, `U+202F` and `U+0085` that Java excludes, and
/// excludes `U+001C`–`U+001F` that Java includes.
///
/// Enumerated rather than derived: Rust exposes no general-category table, and
/// the space separators have not changed since Unicode 4, so the list is stable
/// for as long as the property is.
fn java_is_whitespace(c: char) -> bool {
    matches!(c,
        // The ASCII controls Java names one by one, then SPACE.
        '\u{09}'..='\u{0D}' | '\u{1C}'..='\u{1F}' | '\u{20}'
        // Zs (SPACE_SEPARATOR) less the non-breaking U+00A0, U+2007, U+202F.
        | '\u{1680}' | '\u{2000}'..='\u{2006}' | '\u{2008}'..='\u{200A}'
        | '\u{205F}' | '\u{3000}'
        // Zl (LINE_SEPARATOR) and Zp (PARAGRAPH_SEPARATOR).
        | '\u{2028}' | '\u{2029}')
}

/// `Double.parseDouble` / `Float.parseFloat` — Java's accepted grammar, which is
/// not Rust's.
///
/// `f64::from_str` and `Double.valueOf` disagree at both ends. Rust accepts
/// `inf`, `infinity` and `nan` in any case, where Java accepts only the exact
/// spellings `Infinity` and `NaN` and throws on the rest; Rust rejects the
/// `d`/`D`/`f`/`F` type suffix that Java's `FloatingPointLiteral` allows, so
/// `Double.parseDouble("1d")` is 1.0 in Java and an error under `from_str`.
/// Both were live: `parseDouble("inf")` answered `Infinity` here and
/// `NumberFormatException` on `openjdk 21.0.12`.
///
/// The grammar is validated explicitly rather than delegated, so an input Rust
/// happens to accept cannot slip through a future toolchain. `None` is the
/// caller's `NumberFormatException`.
fn parse_java_double(text: &str) -> Option<f64> {
    // `FloatingDecimal.readJavaFormatString` trims first, with `String.trim()`
    // — chars <= U+0020, not the Unicode set.
    let s = text.trim_matches(|c: char| c <= ' ');
    let (negative, body) = match s.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, s.strip_prefix('+').unwrap_or(s)),
    };
    if body.is_empty() {
        return None;
    }
    let signed = |v: f64| if negative { -v } else { v };
    // Case-sensitive, and the sign is already off: `Double.parseDouble("nan")`
    // is an error in Java however Rust spells it.
    if body == "NaN" {
        return Some(f64::NAN);
    }
    if body == "Infinity" {
        return Some(signed(f64::INFINITY));
    }
    // The optional `FloatTypeSuffix`. A hex significand needs a `p` exponent to
    // be legal at all, so stripping a trailing `D`/`F` off one cannot turn an
    // invalid literal into a valid one.
    let digits = match body.as_bytes().last() {
        Some(b'f' | b'F' | b'd' | b'D') => &body[..body.len() - 1],
        _ => body,
    };
    if !is_java_decimal_literal(digits) {
        return None;
    }
    // The grammar is now known to be a subset of Rust's, so the conversion
    // itself — correctly rounded in both — can be delegated.
    digits.parse::<f64>().ok().map(signed)
}

/// The `NumberFormatException` message `Double.parseDouble`/`Float.parseFloat`
/// carries for input they reject.
///
/// The floating parsers do *not* share the integral ones' single message.
/// `FloatingDecimal.readJavaFormatString` trims, and answers `empty String` for
/// what is left of nothing — so `Double.parseDouble("")` and
/// `Double.parseDouble("   ")` both report that, where `Integer.parseInt("")`
/// reports `For input string: ""`. Measured on `openjdk 21.0.12`.
/// The failure `Integer.parseInt(null)` / `Long.parseLong(null)` /
/// `Integer.valueOf((String) null)` raises.
///
/// `Integer.parseInt` checks its argument for null *before* it looks at any
/// character, so the message is not the `For input string: ""` an empty string
/// gets — a null and an empty string are distinguishable outcomes. Measured on
/// `openjdk 21.0.12`.
fn null_number_fault() -> Fault {
    Fault::java("NumberFormatException", "Cannot parse null string")
}

/// The failure `Double.parseDouble(null)` / `Float.parseFloat(null)` raises —
/// which is a *different class* from the integral parsers' answer above.
///
/// `FloatingDecimal.readJavaFormatString` has no null check at all: it calls
/// `in.trim()` on its argument and the dereference is what fails, so a null
/// reaches the caller as a `NullPointerException`, not as the
/// `NumberFormatException` every other parse failure raises. A program that
/// writes `catch (NumberFormatException e)` around `Double.parseDouble` does not
/// catch this one, so answering with the integral parsers' class would let code
/// through a handler Java sends it past. The quoted name `in` is
/// `readJavaFormatString`'s own parameter, not a bytecode slot javars would have
/// to invent. Measured on `openjdk 21.0.12`.
fn null_float_parse_fault() -> Fault {
    Fault::java(
        "NullPointerException",
        "Cannot invoke \"String.trim()\" because \"in\" is null",
    )
}

fn float_format_message(text: &str) -> String {
    if text.trim_matches(|c: char| c <= ' ').is_empty() {
        "empty String".to_string()
    } else {
        format!("For input string: \"{text}\"")
    }
}

/// Whether `s` is a Java `FloatingPointLiteral` body: sign and type suffix
/// already removed, and no `Infinity`/`NaN`/hex form.
///
/// Java requires at least one digit somewhere in the significand (so `.` alone
/// and `e5` are errors) and at least one digit in an exponent that is present
/// at all. It permits no underscores, no leading/interior whitespace, and no
/// trailing text.
fn is_java_decimal_literal(s: &str) -> bool {
    let b = s.as_bytes();
    let mut i = 0;
    let mut significand_digits = 0;
    while i < b.len() && b[i].is_ascii_digit() {
        i += 1;
        significand_digits += 1;
    }
    if i < b.len() && b[i] == b'.' {
        i += 1;
        while i < b.len() && b[i].is_ascii_digit() {
            i += 1;
            significand_digits += 1;
        }
    }
    if significand_digits == 0 {
        return false;
    }
    if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
        i += 1;
        if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
            i += 1;
        }
        let exponent_start = i;
        while i < b.len() && b[i].is_ascii_digit() {
            i += 1;
        }
        if i == exponent_start {
            return false;
        }
    }
    i == b.len()
}

/// Java's `Math.max(double, double)`, ported from `java.lang.Math`.
///
/// Rust's `f64::max` is `fmax`, which *ignores* a NaN operand and answers the
/// other one; Java propagates it. The two also part over signed zero, where
/// `fmax` is permitted to return either. Both departures are load-bearing —
/// `Math.max(Double.NaN, 1.0)` is `NaN` in Java and `1.0` under `f64::max`.
fn max_double(a: f64, b: f64) -> f64 {
    if a.is_nan() {
        return a;
    }
    // Raw bits are safe here: NaN is already out, and only `-0.0` carries the
    // sign bit over a zero.
    if a == 0.0 && b == 0.0 && a.is_sign_negative() {
        return b;
    }
    if a >= b {
        a
    } else {
        b
    }
}

/// Java's `Math.min(double, double)`, ported from `java.lang.Math` — the mirror
/// of [`max_double`], including the NaN propagation `f64::min` does not do.
fn min_double(a: f64, b: f64) -> f64 {
    if a.is_nan() {
        return a;
    }
    if a == 0.0 && b == 0.0 && b.is_sign_negative() {
        return b;
    }
    if a <= b {
        a
    } else {
        b
    }
}

/// Java's `Math.pow`, which is IEEE 754 `pow` with two documented exceptions.
///
/// `java.lang.Math.pow`'s contract says "if the second argument is NaN, then
/// the result is NaN" with no carve-out for a base of 1, and "if the absolute
/// value of the first argument equals 1 and the second argument is infinite,
/// then the result is NaN". IEEE 754 — and so Rust's `powf` — instead makes
/// `pow(1, y)` equal 1 for *every* `y`, NaN and infinity included. The
/// zero-exponent rule comes first in Java's own list, so `pow(NaN, 0.0)` stays
/// 1.0; everything outside these cases is left to `powf`.
fn pow_double(a: f64, b: f64) -> f64 {
    if b == 0.0 {
        return 1.0;
    }
    if b.is_nan() || (a.abs() == 1.0 && b.is_infinite()) {
        return f64::NAN;
    }
    a.powf(b)
}

/// Java's `Math.round(double)`, ported from `java.lang.Math`.
///
/// The obvious spelling — `(long) Math.floor(a + 0.5)` — is the *pre-Java-7*
/// implementation, and it is wrong wherever `a + 0.5` is not exactly
/// representable: `0.49999999999999994 + 0.5` rounds up to exactly `1.0`, so
/// the naive form answers 1 where every JDK since 7 answers 0 (JDK-6430675).
/// Rust's `f64::round` is not it either — that is half-away-from-zero, so it
/// answers -3 for `-2.5` where Java's half-*up* answers -2.
///
/// The JDK avoids the addition entirely: it reads the significand as an
/// integer, shifts it down to leave one fractional bit, and rounds that bit
/// with `(x + 1) >> 1`. No intermediate rounding can occur, so the tie case is
/// decided by the bits actually present. `shift` outside `0..64` means the
/// value is either already a mathematical integer, smaller in magnitude than
/// 1/2, or non-finite — all four of which `(long) a` answers directly, and
/// Rust's saturating `as i64` matches Java's narrowing (0 for NaN, the
/// `Long` extremes for the infinities).
fn round_double(a: f64) -> i64 {
    // `DoubleConsts`: SIGNIFICAND_WIDTH 53, EXP_BIAS 1023.
    const EXP_BIT_MASK: i64 = 0x7FF0_0000_0000_0000u64 as i64;
    const SIGNIF_BIT_MASK: i64 = 0x000F_FFFF_FFFF_FFFF;
    let long_bits = a.to_bits() as i64;
    let biased_exp = (long_bits & EXP_BIT_MASK) >> (53 - 1);
    let shift = (53 - 2 + 1023) - biased_exp;
    if (shift & -64) == 0 {
        let mut r = (long_bits & SIGNIF_BIT_MASK) | (SIGNIF_BIT_MASK + 1);
        if long_bits < 0 {
            r = -r;
        }
        ((r >> shift) + 1) >> 1
    } else {
        a as i64
    }
}

/// Java's `Math.round(float)`, ported from `java.lang.Math`.
///
/// The same algorithm one width down, and it is a *separate* method rather than
/// a narrowing of [`round_double`] because its result is an `int`: Java
/// saturates `Math.round(1.0e20f)` at `Integer.MAX_VALUE`, where truncating the
/// `long` answer to 32 bits would give -1.
fn round_float(a: f32) -> i32 {
    // `FloatConsts`: SIGNIFICAND_WIDTH 24, EXP_BIAS 127.
    const EXP_BIT_MASK: i32 = 0x7F80_0000;
    const SIGNIF_BIT_MASK: i32 = 0x007F_FFFF;
    let int_bits = a.to_bits() as i32;
    let biased_exp = (int_bits & EXP_BIT_MASK) >> (24 - 1);
    let shift = (24 - 2 + 127) - biased_exp;
    if (shift & -32) == 0 {
        let mut r = (int_bits & SIGNIF_BIT_MASK) | (SIGNIF_BIT_MASK + 1);
        if int_bits < 0 {
            r = -r;
        }
        ((r >> shift) + 1) >> 1
    } else {
        a as i32
    }
}

/// The `-1`/`0`/`1` an `Integer.compare`-style method returns.
/// `Double.compare` / `Float.compare` — a *total* order over the doubles, which
/// `<`/`>`/`==` are not.
///
/// Java specifies three departures from the operators, all of which a
/// `record`'s derived `equals` and a `TreeSet<Double>` depend on: `-0.0` sorts
/// strictly below `0.0`, `NaN` compares equal to itself, and `NaN` sorts above
/// every other value including `+Infinity`. `partial_cmp` answers `None` for a
/// `NaN` operand and `Equal` for `0.0` against `-0.0`, so it cannot express any
/// of the three; the JDK's own implementation compares the raw bit patterns
/// once the numeric case is out of the way, and so does this.
fn float_compare(a: f64, b: f64) -> i64 {
    if a < b {
        return -1;
    }
    if a > b {
        return 1;
    }
    // Neither `<` nor `>` leaves exactly two cases: `0.0` against `-0.0`, and
    // any pair involving `NaN`. Both are settled the way the JDK settles them,
    // by comparing `doubleToLongBits` as a signed long — `-0.0` is
    // `Long.MIN_VALUE` and so below `0.0`'s zero, and a canonical `NaN` is
    // above every finite pattern and equal to itself. The sign bit needs no
    // folding here because the ordinary negatives never reach this point.
    let (ab, bb) = (canonical_bits(a), canonical_bits(b));
    cmp_to_int(ab.cmp(&bb))
}

/// `Double.doubleToLongBits` as a signed long: every `NaN` collapses to the one
/// canonical pattern the JDK reports, so two different `NaN` encodings compare
/// equal.
fn canonical_bits(v: f64) -> i64 {
    if v.is_nan() {
        0x7ff8_0000_0000_0000u64 as i64
    } else {
        v.to_bits() as i64
    }
}

fn cmp_to_int(o: std::cmp::Ordering) -> i64 {
    match o {
        std::cmp::Ordering::Less => -1,
        std::cmp::Ordering::Equal => 0,
        std::cmp::Ordering::Greater => 1,
    }
}

/// The `char` a `Character.*` argument names. javars models a `char` as a
/// one-character string, and a numeric argument is a code point.
/// The code point of `c` after a one-to-one case mapping, or `c` itself when the
/// mapping expands to more than one character. Java's `Character.toUpperCase`
/// works on a single `char` and so has no way to express `ß` → `SS`; it returns
/// the argument unchanged there, where `String.toUpperCase` expands.
fn one_to_one_case<I: Iterator<Item = char>>(c: char, map: fn(char) -> I) -> i64 {
    let mut mapped = map(c);
    match (mapped.next(), mapped.next()) {
        (Some(m), None) => m as i64,
        _ => c as i64,
    }
}

fn char_arg(v: &Value) -> char {
    // Through a `Character` box too: `Character.isLetter(aCharacter)` reads the
    // wrapper as its code point, and the handle would otherwise render as text
    // whose first character is a digit of the id.
    match &deboxed(v) {
        Value::Int(n) => char::from_u32(*n as u32).unwrap_or('\u{0}'),
        other => other.as_str_cow().chars().next().unwrap_or('\u{0}'),
    }
}

/// A copy of the elements of `v` when it is a heap array, else `None`.
fn array_items(v: &Value) -> Option<Vec<Value>> {
    let Value::Obj(id) = v else {
        return None;
    };
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::Array(a)) => Some(a.clone()),
        _ => None,
    })
}

/// Run `f` over `v`'s elements *in place* — what the mutating `Arrays` statics
/// (`sort`, `fill`) need, since they return `void` and are observed through the
/// caller's own handle.
fn array_mutate(v: &Value, f: impl FnOnce(&mut Vec<Value>)) -> Result<(), Fault> {
    let Value::Obj(id) = v else {
        return Err(Fault::java(
            "NullPointerException",
            "null array".to_string(),
        ));
    };
    HEAP.with(|h| match h.borrow_mut().get_mut(*id as usize) {
        Some(HostObj::Array(a)) => {
            f(a);
            Ok(())
        }
        _ => Err(Fault::java(
            "NullPointerException",
            "null array".to_string(),
        )),
    })
}

/// The value `Arrays.copyOf` pads a grown copy with. The element type is erased
/// at runtime, so it is read off element 0: a numeric array pads with its zero,
/// a boolean array with `false`, and anything else (including an empty source)
/// with `null`.
fn element_default(items: &[Value]) -> Value {
    match items.first() {
        Some(Value::Int(_)) => Value::Int(0),
        Some(Value::Float(_)) => Value::float(0.0),
        Some(Value::Bool(_)) => Value::bool(false),
        _ => Value::Undef,
    }
}

/// `Arrays.deepToString(a)` — like [`arrays_to_string`] but recursing into
/// nested arrays, which is what a rectangular `int[][]` needs.
fn arrays_deep_to_string(v: &Value) -> String {
    match array_items(v) {
        Some(items) => {
            let inner: Vec<String> = items.iter().map(arrays_deep_to_string).collect();
            format!("[{}]", inner.join(", "))
        }
        None => java_str(v),
    }
}

/// `Arrays.toString(a)` — a shallow `[e0, e1, …]` rendering (Java's
/// `java.util.Arrays.toString`), each element via [`java_str`]. A `null`
/// reference renders as `null`.
fn arrays_to_string(v: &Value) -> String {
    match v {
        Value::Obj(id) => HEAP.with(|h| {
            let h = h.borrow();
            match h.get(*id as usize) {
                Some(HostObj::Array(a)) => {
                    let inner: Vec<String> = a.iter().map(java_str).collect();
                    format!("[{}]", inner.join(", "))
                }
                _ => java_str(v),
            }
        }),
        Value::Undef => "null".to_string(),
        _ => java_str(v),
    }
}

/// `String.format(fmt, args…)` — a faithful subset of `java.util.Formatter`:
/// conversions `d s S f b B x X o c %` and `%n`, with `-` (left-justify), `0`
/// (zero-pad), `+` (leading sign) flags, an optional width, and an optional
/// `.precision` (decimals for `f`, max length for `s`). Unsupported conversions
/// surface an error rather than a wrong string.
fn java_format(
    fmt: &str,
    args: &[Value],
    tags: &[&str],
    mut vm: Option<&mut VM>,
) -> Result<Value, Fault> {
    let mut out = String::new();
    let mut chars = fmt.chars().peekable();
    let mut argi = 0usize;
    while let Some(c) = chars.next() {
        if c != '%' {
            out.push(c);
            continue;
        }
        // The specifier's own source text, accumulated as it is consumed.
        // `MissingFormatArgumentException`'s message is the specifier verbatim
        // — `Format specifier '%,10.2f'` — so it cannot be rebuilt from the
        // parsed flags without re-deriving the original spelling and ordering.
        let mut spec = String::from("%");
        // An explicit argument index, `%2$s`. It is digits followed by `$`, so
        // it can only be told from a width by scanning past the digits first.
        let mut lead = String::new();
        while let Some(&d) = chars.peek() {
            if d.is_ascii_digit() {
                lead.push(d);
                spec.push(d);
                chars.next();
            } else {
                break;
            }
        }
        let mut explicit_index: Option<usize> = None;
        if chars.peek() == Some(&'$') {
            chars.next();
            spec.push('$');
            // Java indexes arguments from 1.
            explicit_index = lead.parse::<usize>().ok().map(|n| n.saturating_sub(1));
            lead.clear();
        }
        // flags
        let mut left = false;
        let mut zero = false;
        let mut plus = false;
        let mut group = false;
        let mut parens = false;
        // `%​ d` shows a leading space where `%+d` would show a `+`, and `%#x`
        // writes the radix prefix Java calls the "alternate form". Both were
        // parsed and discarded, so ``String.format("% d", 42)`` answered `42`
        // (Java: ` 42`) and `%#x` of 255 answered `ff` (Java: `0xff`).
        let mut space = false;
        let mut alt = false;
        // A leading `0` already consumed as part of `lead` is the zero-pad flag,
        // not a width digit — Java has no zero-width conversion.
        if lead.starts_with('0') {
            zero = true;
            lead.remove(0);
        }
        while let Some(&f) = chars.peek() {
            match f {
                '-' => left = true,
                '0' => zero = true,
                '+' => plus = true,
                ',' => group = true,
                '(' => parens = true,
                ' ' => space = true,
                '#' => alt = true,
                _ => break,
            }
            spec.push(f);
            chars.next();
        }
        // width
        let mut width = lead;
        while let Some(&d) = chars.peek() {
            if d.is_ascii_digit() {
                width.push(d);
                spec.push(d);
                chars.next();
            } else {
                break;
            }
        }
        // .precision
        let mut prec: Option<usize> = None;
        if chars.peek() == Some(&'.') {
            chars.next();
            spec.push('.');
            let mut p = String::new();
            while let Some(&d) = chars.peek() {
                if d.is_ascii_digit() {
                    p.push(d);
                    spec.push(d);
                    chars.next();
                } else {
                    break;
                }
            }
            // Java's width and precision are `int`. A digit string that does not
            // fit one is rejected outright, and the detail message is the
            // overflowed value — literally `-2147483648` for every such input,
            // measured on openjdk 21.0.12. javars parsed into `usize` instead:
            // `%.99999999999f` reached `format!("{:.*}", prec + 30, x)` and
            // *panicked* ("Formatting argument out of range"), and
            // `%99999999999d` reached `pad` and hung building the padding. Both
            // are catchable `IllegalFormatException`s in Java.
            prec = Some(int_format_field(&p, "IllegalFormatPrecisionException")?);
        }
        let conv = chars.next().ok_or_else(|| {
            // Java's own class for a `%` with nothing after it.
            Fault::java("UnknownFormatConversionException", "Conversion = '%'")
        })?;
        spec.push(conv);
        let width_n: Option<usize> = if width.is_empty() {
            None
        } else {
            Some(int_format_field(&width, "IllegalFormatWidthException")?)
        };
        let flags = FmtFlags {
            left,
            alt,
            plus,
            space,
            zero,
            group,
            parens,
        };
        check_format_flags(conv, &flags, width_n, prec, &spec)?;
        match conv {
            // Width applies to the literal conversions too: `%5%` is four
            // spaces and a `%`.
            '%' => out.push_str(&pad("", "%", "", width_n, left, false)),
            'n' => out.push('\n'),
            _ => {
                // An explicit `%n$` index does not advance the implicit cursor,
                // which is what lets `%2$s %1$s` repeat and reorder arguments.
                let idx = explicit_index.unwrap_or(argi);
                // Java's `MissingFormatArgumentException`, naming the specifier
                // that had no argument — not an internal javars error, which
                // aborted the run where Java lets the program catch it.
                let arg = args.get(idx).ok_or_else(|| {
                    Fault::java(
                        "MissingFormatArgumentException",
                        format!("Format specifier '{spec}'"),
                    )
                })?;
                if explicit_index.is_none() {
                    argi += 1;
                }
                let tag = tags.get(idx).copied().unwrap_or("");
                check_conversion(conv, arg, tag)?;
                let Rendered {
                    mut prefix,
                    mut body,
                    numeric,
                } = format_conversion(conv, arg, prec, &flags, tag, vm.as_deref_mut())?;
                if group && numeric {
                    body = group_digits(&body);
                }
                // The `(` flag wraps a negative number in parentheses instead of
                // showing its minus sign. The parentheses count toward the
                // width and the zero padding goes *inside* them, which is why
                // the sign travels as its own piece rather than glued to the
                // digits: `%(08d` of -1 is `(000001)`.
                let mut suffix = "";
                if parens && numeric && prefix == "-" {
                    prefix = "(".to_string();
                    suffix = ")";
                }
                out.push_str(&pad(&prefix, &body, suffix, width_n, left, zero && numeric));
            }
        }
    }
    Ok(Value::str(out))
}

/// The boxed class `java.util.Formatter` sees for one argument: the static Java
/// type the compiler recorded when it had one, else the class the runtime value
/// implies. `None` for `null`, which every conversion accepts and prints as
/// `null`.
fn boxed_class(tag: &str, v: &Value) -> Option<&'static str> {
    if matches!(v, Value::Undef) {
        return None;
    }
    Some(match tag {
        "int" | "Integer" => "java.lang.Integer",
        "long" | "Long" => "java.lang.Long",
        "short" | "Short" => "java.lang.Short",
        "byte" | "Byte" => "java.lang.Byte",
        "char" | "Character" => "java.lang.Character",
        "double" | "Double" => "java.lang.Double",
        "float" | "Float" => "java.lang.Float",
        "boolean" | "Boolean" => "java.lang.Boolean",
        "String" => "java.lang.String",
        // No static type. The value model collapses `Integer`/`Long`/`Short`/
        // `Byte` onto one variant and `Double`/`Float` onto another, so the
        // widest of each group is the reading — `Integer` for an integer,
        // because that is what a literal autoboxes to.
        _ => match v {
            Value::Int(_) => "java.lang.Integer",
            Value::Float(_) => "java.lang.Double",
            Value::Bool(_) => "java.lang.Boolean",
            Value::Str(_) => "java.lang.String",
            // A heap object's class is not one the conversion table rejects.
            _ => return None,
        },
    })
}

/// Reject a conversion whose argument is the wrong boxed type, the way
/// `java.util.Formatter` does — `%d` takes the integral boxes only, `%f` the
/// floating ones only, `%c` a `Character` or an integral code point. `%s`,
/// `%b`, and `%h` take anything, and a `null` argument prints as `null` under
/// every conversion rather than throwing.
///
/// Without this, `String.format("%.2f", 3)` answered `3.00` where Java throws:
/// a silently-formatted wrong-typed argument instead of the program's real
/// behaviour.
fn check_conversion(conv: char, arg: &Value, tag: &str) -> Result<(), Fault> {
    let integral = [
        "java.lang.Integer",
        "java.lang.Long",
        "java.lang.Short",
        "java.lang.Byte",
    ];
    let ok = |cls: &str| -> bool {
        match conv {
            'd' | 'x' | 'X' | 'o' => integral.contains(&cls),
            'f' | 'e' | 'E' | 'g' | 'G' | 'a' | 'A' => {
                matches!(cls, "java.lang.Double" | "java.lang.Float")
            }
            'c' | 'C' => {
                cls == "java.lang.Character"
                    // javars models a `char` value as a one-character String
                    // wherever it has crossed into text (a collection element,
                    // a `%s` slot), so a String whose type the compiler could
                    // not name is a `char` as often as it is a `String`. Only a
                    // *declared* `String` is rejected here; see `check_char`.
                    || integral.contains(&cls)
            }
            _ => true,
        }
    };
    let Some(cls) = boxed_class(tag, arg) else {
        return Ok(());
    };
    if ok(cls) {
        return Ok(());
    }
    // The unknown-tag `%c` case: a bare String could be javars's `char`
    // spelling, so it is only rejected when the compiler named the type.
    if matches!(conv, 'c' | 'C') && tag.is_empty() {
        return Ok(());
    }
    Err(Fault::java(
        "IllegalFormatConversionException",
        format!("{conv} != {cls}"),
    ))
}

/// [`JFORMAT`] — `String.format` with the compiler's per-argument type tags.
fn b_format(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let tag_blob = args
        .last()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    let tags: Vec<&str> = if tag_blob.is_empty() {
        Vec::new()
    } else {
        tag_blob.split('\x1f').collect()
    };
    let fmt = args
        .first()
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    let body = &args[1..args.len().saturating_sub(1)];
    match java_format(&fmt, body, &tags, Some(&mut *vm)) {
        Ok(v) => v,
        Err(f) => raise(vm, f),
    }
}

/// The flag characters of one `String.format` conversion.
struct FmtFlags {
    left: bool,
    alt: bool,
    plus: bool,
    space: bool,
    zero: bool,
    group: bool,
    parens: bool,
}

impl FmtFlags {
    /// The flags this set holds that are also in `want`, spelled in
    /// `java.util.Formatter$Flags`' declaration order (`-`, `#`, `+`, ` `, `0`,
    /// `,`, `(`) — the order its `toString` uses, and therefore the order every
    /// flag-related exception message spells them in.
    fn spell(&self, want: &[char]) -> String {
        [
            ('-', self.left),
            ('#', self.alt),
            ('+', self.plus),
            (' ', self.space),
            ('0', self.zero),
            (',', self.group),
            ('(', self.parens),
        ]
        .iter()
        .filter(|(c, set)| *set && want.contains(c))
        .map(|(c, _)| *c)
        .collect()
    }
}

/// Reject the flag/conversion combinations `java.util.Formatter` rejects, with
/// its own exception class and detail message.
///
/// Every one of these used to be accepted and silently ignored, so
/// `String.format("%,x", 1)` answered `1` where Java throws — the format string
/// said something the program could not have meant, and nothing said so. The
/// checks run in the JDK's order, which is observable: `%,(x` reports `,` (the
/// per-conversion group check) rather than `(` (the later sign-flag check).
fn check_format_flags(
    conv: char,
    f: &FmtFlags,
    width: Option<usize>,
    prec: Option<usize>,
    spec: &str,
) -> Result<(), Fault> {
    let mismatch = |want: &[char]| -> Result<(), Fault> {
        let bad = f.spell(want);
        if bad.is_empty() {
            return Ok(());
        }
        Err(Fault::java(
            "FormatFlagsConversionMismatchException",
            format!("Conversion = {conv}, Flags = {bad}"),
        ))
    };
    let bad_flags = |want: &[char]| -> Fault {
        Fault::java(
            "IllegalFormatFlagsException",
            format!("Flags = '{}'", f.spell(want)),
        )
    };
    let missing_width = || Fault::java("MissingFormatWidthException", spec.to_string());
    let bad_precision = || {
        Fault::java(
            "IllegalFormatPrecisionException",
            prec.unwrap_or(0).to_string(),
        )
    };
    const ALL: &[char] = &['-', '#', '+', ' ', '0', ',', '('];
    // `%n` is a line separator, not a conversion: it takes no flag, no width,
    // and no precision.
    if conv == 'n' {
        if !f.spell(ALL).is_empty() {
            return Err(bad_flags(ALL));
        }
        if let Some(w) = width {
            return Err(Fault::java("IllegalFormatWidthException", w.to_string()));
        }
        if let Some(p) = prec {
            return Err(Fault::java(
                "IllegalFormatPrecisionException",
                p.to_string(),
            ));
        }
        return Ok(());
    }
    if conv == '%' {
        if f.left && width.is_none() {
            return Err(missing_width());
        }
        return Ok(());
    }
    match conv {
        // The general conversions take neither a sign nor a numeric layout.
        // `#` is checked *after* the width, which is why `%,#s` reports `,`.
        's' | 'S' | 'b' | 'B' | 'h' | 'H' => {
            let mut bad: Vec<char> = vec!['+', ' ', '0', ',', '('];
            if !matches!(conv, 's' | 'S') {
                bad.push('#');
            }
            mismatch(&bad)?;
            if f.left && width.is_none() {
                return Err(missing_width());
            }
            if matches!(conv, 's' | 'S') {
                mismatch(&['#'])?;
            }
        }
        'c' | 'C' => {
            if prec.is_some() {
                return Err(bad_precision());
            }
            mismatch(&['#', '+', ' ', '0', ',', '('])?;
            if f.left && width.is_none() {
                return Err(missing_width());
            }
        }
        // The numeric conversions share `checkNumeric`: `-`/`0` need a width,
        // and `+`/` ` and `-`/`0` are mutually exclusive.
        _ => {
            if width.is_none() && (f.left || f.zero) {
                return Err(missing_width());
            }
            if f.plus && f.space {
                return Err(bad_flags(&['+', ' ']));
            }
            if f.left && f.zero {
                return Err(bad_flags(&['-', '0']));
            }
            match conv {
                'd' => {
                    mismatch(&['#'])?;
                    if prec.is_some() {
                        return Err(bad_precision());
                    }
                }
                // The radix conversions render a two's-complement bit pattern,
                // which has no sign to decorate and no groups to separate.
                'o' | 'x' | 'X' => {
                    mismatch(&[','])?;
                    mismatch(&['+', ' ', '('])?;
                    if prec.is_some() {
                        return Err(bad_precision());
                    }
                }
                'e' | 'E' => mismatch(&[','])?,
                'g' | 'G' => mismatch(&['#'])?,
                _ => {}
            }
        }
    }
    Ok(())
}

/// One rendered conversion, split so the padding can be inserted in the right
/// place. `prefix` is the sign or radix marker (`-`, `+`, a leading space,
/// `0x`), `body` the digits or text; zero padding goes *between* them, which is
/// what makes `% 08d` of 1 ` 0000001` and `%#010x` of 255 `0x000000ff`.
struct Rendered {
    prefix: String,
    body: String,
    numeric: bool,
}

impl Rendered {
    fn text(body: String) -> Self {
        Rendered {
            prefix: String::new(),
            body,
            numeric: false,
        }
    }
}

/// Render one `String.format` conversion.
fn format_conversion(
    conv: char,
    arg: &Value,
    prec: Option<usize>,
    flags: &FmtFlags,
    tag: &str,
    vm: Option<&mut VM>,
) -> Result<Rendered, Fault> {
    // The sign piece a non-negative number carries: `+` for the `+` flag, a
    // space for the ` ` flag, nothing otherwise. A negative one carries its own
    // `-`, which the callers below put in `prefix`.
    let pos_sign = || {
        if flags.plus {
            "+"
        } else if flags.space {
            " "
        } else {
            ""
        }
    };
    let float_sign = |x: f64| {
        if x.is_sign_negative() {
            "-".to_string()
        } else {
            pos_sign().to_string()
        }
    };
    // Every `Formatter.print*` starts with `if (arg == null) print("null")`, so
    // a `null` renders as the four characters under every conversion — width and
    // precision still apply, and it is not numeric, so `%08d` of `null` pads
    // with spaces. `%b`/`%B` are the exception: they answer `false`.
    if matches!(arg, Value::Undef) && !matches!(conv, 'b' | 'B') {
        let mut s: String = "null".chars().take(prec.unwrap_or(4)).collect();
        if conv.is_ascii_uppercase() {
            s = s.to_uppercase();
        }
        return Ok(Rendered::text(s));
    }
    let num = |prefix: String, body: String| Rendered {
        prefix,
        body,
        numeric: true,
    };
    match conv {
        'd' => {
            let n = arg.jint();
            Ok(num(
                if n < 0 {
                    "-".to_string()
                } else {
                    pos_sign().to_string()
                },
                n.unsigned_abs().to_string(),
            ))
        }
        'f' => {
            let x = arg.jfloat();
            // `#` on a fixed conversion forces the decimal point to appear even
            // at precision 0: `%#.0f` of 1.0 is `1.`.
            let mut body = fixed_half_up(x, prec.unwrap_or(6));
            if flags.alt && !body.contains('.') {
                body.push('.');
            }
            Ok(num(float_sign(x), body))
        }
        // `%s`/`%S` are `Formatter`'s call to the argument's own `toString()`, so
        // they are the two conversions a user override answers for. The rest
        // read the value numerically and never render an object.
        's' | 'S' => {
            let mut s = match vm {
                Some(vm) => java_str_vm(vm, arg),
                None => java_str(arg),
            };
            if conv == 'S' {
                s = s.to_uppercase();
            }
            if let Some(p) = prec {
                s = s.chars().take(p).collect();
            }
            Ok(Rendered::text(s))
        }
        // The general conversions all truncate to the precision, not just `%s`
        // — `%.2b` of `true` is `tr`.
        'b' | 'B' => {
            let mut s = java_bool(arg).to_string();
            if conv == 'B' {
                s = s.to_uppercase();
            }
            if let Some(p) = prec {
                s = s.chars().take(p).collect();
            }
            Ok(Rendered::text(s))
        }
        // The radix conversions read the argument as an *unsigned* bit pattern
        // at the width its declared type has — `%x` of the `int` -1 is
        // `ffffffff` and of the `long` -1 eight more `f`s. javars stores both in
        // one 64-bit `Value::Int`, so the width comes from the compiler's type
        // tag; without it every negative `int` rendered sixteen digits.
        'x' | 'X' | 'o' => {
            let bits = radix_bits(arg, tag);
            let body = match conv {
                'x' => format!("{bits:x}"),
                'X' => format!("{bits:X}"),
                _ => format!("{bits:o}"),
            };
            // `#` writes Java's alternate form: `0x`/`0X` for hex, a leading
            // `0` for octal. It sits ahead of any zero padding.
            let prefix = if flags.alt {
                match conv {
                    'x' => "0x",
                    'X' => "0X",
                    _ => "0",
                }
            } else {
                ""
            };
            Ok(num(prefix.to_string(), body))
        }
        'c' => Ok(Rendered::text(match arg {
            // `%c` on an integer renders its code point as a character.
            Value::Int(n) => char::from_u32(*n as u32).unwrap_or('\u{fffd}').to_string(),
            other => java_str(other),
        })),
        // Java's `%e` always writes a two-digit exponent with an explicit sign
        // (`1.234568e+03`), where Rust's `{:e}` writes `1.234568e3`.
        'e' | 'E' => {
            let x = arg.jfloat();
            // `sci_notation` carries a negative sign; the split rendering wants
            // the magnitude, so it is stripped and re-supplied as the prefix.
            let s = sci_notation(x, prec.unwrap_or(6));
            let body = s.strip_prefix('-').unwrap_or(&s).to_string();
            let body = if conv == 'E' {
                body.to_uppercase()
            } else {
                body
            };
            Ok(num(float_sign(x), body))
        }
        // `%g` picks fixed or scientific by the value's magnitude; Java's
        // precision counts *significant* digits and defaults to 6.
        'g' | 'G' => {
            let x = arg.jfloat();
            let p = prec.unwrap_or(6).max(1);
            let s = if x != 0.0 && (x.abs() < 1e-4 || x.abs() >= 10f64.powi(p as i32)) {
                sci_notation(x, p - 1)
            } else {
                let exp = if x == 0.0 {
                    0
                } else {
                    x.abs().log10().floor() as i32
                };
                fixed_half_up(x, (p as i32 - 1 - exp).max(0) as usize)
            };
            let body = s.strip_prefix('-').unwrap_or(&s).to_string();
            let body = if conv == 'G' {
                body.to_uppercase()
            } else {
                body
            };
            Ok(num(float_sign(x), body))
        }
        // `%h` is the argument's `hashCode()` in hex, or "null".
        'h' | 'H' => {
            let s = match arg {
                Value::Undef => "null".to_string(),
                other => format!("{:x}", java_hash(other).unwrap_or(0) as u32),
            };
            let mut s = if conv == 'H' { s.to_uppercase() } else { s };
            if let Some(p) = prec {
                s = s.chars().take(p).collect();
            }
            Ok(Rendered::text(s))
        }
        // Java's own class and wording for a conversion character it does not
        // define. javars reported an internal error, which the program could not
        // catch even though `catch (IllegalArgumentException e)` catches it in
        // Java (`UnknownFormatConversionException` is an `IllegalFormatException`
        // is an `IllegalArgumentException` — read off `getSuperclass()` on
        // openjdk 21.0.12).
        other => Err(Fault::java(
            "UnknownFormatConversionException",
            format!("Conversion = '{other}'"),
        )),
    }
}

/// The `NullPointerException` a `String` method raises when its first argument
/// is `null`, or `Ok(())` when this method tolerates one.
///
/// Every one of these dereferences its argument, so Java fails before it can
/// compute anything. javars coerced `null` to `""` instead and answered:
/// `"abc".compareTo(null)` was 3, `"abc".startsWith(null)` was `true`,
/// `"abc".split(null)` returned the whole string. A wrong answer where Java
/// throws is worse than either, because nothing marks it.
///
/// `equals` and `equalsIgnoreCase` are deliberately absent: they are specified
/// to answer `false` for a null argument rather than throw, and both already do.
///
/// The messages name the JDK's own parameter (`anotherString`, `prefix`,
/// `regex`) and the member it dereferenced, which is fixed text per method
/// rather than the bytecode-slot provenance javars cannot reproduce. Each is
/// quoted from a run on openjdk 21.0.12.
fn null_string_argument(method: &str, args: &[Value]) -> Result<(), Fault> {
    if !matches!(args.first(), Some(Value::Undef)) {
        return Ok(());
    }
    let detail = match method {
        "compareTo" => "Cannot read field \"value\" because \"anotherString\" is null",
        "compareToIgnoreCase" => "Cannot read field \"value\" because \"s2\" is null",
        "contains" => "Cannot invoke \"java.lang.CharSequence.toString()\" because \"s\" is null",
        "replace" => {
            "Cannot invoke \"java.lang.CharSequence.toString()\" because \"target\" is null"
        }
        "indexOf" | "lastIndexOf" => "Cannot invoke \"String.coder()\" because \"str\" is null",
        "startsWith" => "Cannot invoke \"String.length()\" because \"prefix\" is null",
        "endsWith" => "Cannot invoke \"String.length()\" because \"suffix\" is null",
        "concat" => "Cannot invoke \"String.isEmpty()\" because \"str\" is null",
        "split" | "matches" | "replaceAll" | "replaceFirst" => {
            "Cannot invoke \"String.length()\" because \"regex\" is null"
        }
        _ => return Ok(()),
    };
    Err(Fault::java("NullPointerException", detail))
}

/// Parse a format specifier's width or precision the way Java does: as an `int`.
///
/// A digit string too long for an `int` is not a large width, it is an error —
/// and Java's detail message for it is the overflowed value, which is
/// `-2147483648` for every such input (measured on openjdk 21.0.12). `class` is
/// which of the two exceptions to raise, since the digits are parsed the same
/// way for both.
fn int_format_field(digits: &str, class: &'static str) -> Result<usize, Fault> {
    match digits.parse::<i32>() {
        Ok(n) if n >= 0 => Ok(n as usize),
        _ => Err(Fault::java(class, i32::MIN.to_string())),
    }
}

/// Java's `%f` rendering: fixed-point with `prec` decimals, rounded HALF_UP on
/// the double's *exact* decimal value.
///
/// Rust's `{:.p}` rounds half-to-even, so `%.0f` of 2.5 is 2 there and 3 in
/// Java. The exact value is materialised well past `prec` (a double's decision
/// digit is nowhere near that far out), the digit after the cut decides, and the
/// carry is propagated through the decimal string.
fn fixed_half_up(x: f64, prec: usize) -> String {
    if !x.is_finite() {
        return java_str(&Value::float(x));
    }
    // Java rounds the value's *shortest round-trip decimal*, not its exact
    // binary expansion. `%.2f` of 1.005 is `1.01` because the digits it rounds
    // are `1.005`, where the exact value is 1.00499999999999989…, and `%.20f` of
    // 0.1 is `0.10000000000000000000` rather than …0555. Rust's `{}` for `f64`
    // is that same shortest representation and never uses exponent notation, so
    // it is the digit string to cut — padded with zeros when the requested
    // precision runs past the digits the value actually has.
    let mut exact = format!("{}", x.abs());
    if !exact.contains('.') {
        exact.push('.');
    }
    let point = exact.find('.').unwrap_or(exact.len());
    let cut = point + if prec == 0 { 0 } else { prec + 1 };
    while exact.len() <= point + prec + 1 {
        exact.push('0');
    }
    let round_up = exact[cut..]
        .chars()
        .find(char::is_ascii_digit)
        .is_some_and(|c| c >= '5');
    let mut digits: Vec<u8> = exact[..cut].bytes().collect();
    if round_up {
        let mut i = digits.len();
        loop {
            if i == 0 {
                digits.insert(0, b'1');
                break;
            }
            i -= 1;
            match digits[i] {
                b'.' => continue,
                b'9' => digits[i] = b'0',
                d => {
                    digits[i] = d + 1;
                    break;
                }
            }
        }
    }
    String::from_utf8(digits).unwrap_or_default()
}

/// Java's `%e` rendering: `<mantissa>e<sign><at least two exponent digits>`,
/// carrying the value's own sign.
fn sci_notation(x: f64, prec: usize) -> String {
    let neg = if x.is_sign_negative() { "-" } else { "" };
    if x == 0.0 {
        return format!("{neg}{:.*}e+00", prec, 0.0);
    }
    // The mantissa is rounded HALF_UP like `%f`'s digits, not half-to-even:
    // Java's `Formatter` rounds through `BigDecimal.ROUND_HALF_UP`, so
    // `%e` of 5592405.5 is `5.592406e+06` where Rust's `{:.6e}` gives
    // `5.592405e+06`. Rounding the mantissa *after* dividing by a power of ten
    // would not see the exact tie at all, so the digits are taken from the
    // value's own decimal expansion.
    let (digits, exp) = sci_digits_half_up(x.abs(), prec);
    let mantissa = if prec == 0 {
        digits
    } else {
        format!("{}.{}", &digits[..1], &digits[1..])
    };
    format!(
        "{neg}{mantissa}e{}{:02}",
        if exp < 0 { '-' } else { '+' },
        exp.abs()
    )
}

/// The first `prec + 1` significant digits of `x` (positive, finite, non-zero),
/// rounded HALF_UP, with the decimal exponent they belong to.
///
/// Taken from the value's decimal expansion rather than from a scaled mantissa,
/// because scaling by a power of ten is itself inexact and would round the tie
/// away before it could be seen.
fn sci_digits_half_up(x: f64, prec: usize) -> (String, i32) {
    // The shortest round-trip digits, the same source `fixed_half_up` rounds:
    // `%.2e` of 1.005 is `1.01e+00`, and `%.20e` of 0.1 is
    // `1.00000000000000000000e-01` rather than the exact expansion's …05551.
    // Rust's `{:e}` with no precision is exactly those digits in scientific
    // form; a precision short of them is what the HALF_UP cut below decides.
    let expanded = format!("{:e}", x);
    let (mantissa, exp) = expanded.split_once('e').unwrap_or((expanded.as_str(), "0"));
    let mut exp: i32 = exp.parse().unwrap_or(0);
    let all: Vec<u8> = mantissa
        .bytes()
        .filter(u8::is_ascii_digit)
        .map(|b| b - b'0')
        .collect();
    let keep = prec + 1;
    let mut digits: Vec<u8> = all.iter().copied().take(keep).collect();
    digits.resize(keep, 0);
    if all.get(keep).is_some_and(|d| *d >= 5) {
        let mut i = digits.len();
        loop {
            if i == 0 {
                // 999… carried out: the digits become 100… one exponent up.
                digits.insert(0, 1);
                digits.pop();
                exp += 1;
                break;
            }
            i -= 1;
            if digits[i] == 9 {
                digits[i] = 0;
            } else {
                digits[i] += 1;
                break;
            }
        }
    }
    (digits.iter().map(|d| (d + b'0') as char).collect(), exp)
}

/// Insert Java's `,` grouping separators into the integer part of a rendered
/// number, leaving any sign and fractional part alone.
fn group_digits(s: &str) -> String {
    let (sign, rest) = match s.strip_prefix(['-', '+']) {
        Some(r) => (&s[..1], r),
        None => ("", s),
    };
    let (int_part, frac) = match rest.find('.') {
        Some(i) => (&rest[..i], &rest[i..]),
        None => (rest, ""),
    };
    let digits: Vec<char> = int_part.chars().collect();
    let mut grouped = String::new();
    for (i, c) in digits.iter().enumerate() {
        if i > 0 && (digits.len() - i) % 3 == 0 {
            grouped.push(',');
        }
        grouped.push(*c);
    }
    format!("{sign}{grouped}{frac}")
}

/// Java `%b`: `true` for a `true` Boolean, `false` for `false`/`null`, `true`
/// for any other non-null value.
fn java_bool(v: &Value) -> bool {
    match v {
        Value::Bool(b) => *b,
        Value::Undef => false,
        _ => true,
    }
}

/// The unsigned bit pattern `%x`/`%X`/`%o` renders, read at the width of the
/// argument's *declared* type. javars keeps every integral value in one 64-bit
/// `Value::Int`, so the width has to come from the compiler's type tag; an
/// argument it could not type falls back to the narrowest width that still
/// holds the value, which is `int` for everything an `int` can hold — the same
/// default [`boxed_class`] applies.
fn radix_bits(arg: &Value, tag: &str) -> u64 {
    let n = arg.jint();
    match tag {
        "byte" | "Byte" => n as u8 as u64,
        "short" | "Short" => n as u16 as u64,
        "long" | "Long" => n as u64,
        "int" | "Integer" => n as i32 as u32 as u64,
        _ if i32::try_from(n).is_ok() => n as i32 as u32 as u64,
        _ => n as u64,
    }
}

/// Lay one conversion out in `width` columns (char count).
///
/// `prefix` is the sign or radix marker and `suffix` the `(` flag's closing
/// parenthesis; both count toward the width, and zero padding goes *between*
/// the prefix and the body — which is what makes `% 08d` of 1 ` 0000001` and
/// `%(08d` of -1 `(000001)`. Left-justify with `-`, otherwise right-justify.
fn pad(
    prefix: &str,
    body: &str,
    suffix: &str,
    width: Option<usize>,
    left: bool,
    zero: bool,
) -> String {
    let joined = || format!("{prefix}{body}{suffix}");
    let w = match width {
        Some(w) => w,
        None => return joined(),
    };
    let len = prefix.chars().count() + body.chars().count() + suffix.chars().count();
    if len >= w {
        return joined();
    }
    let fill = w - len;
    if left {
        format!("{prefix}{body}{suffix}{}", " ".repeat(fill))
    } else if zero {
        format!("{prefix}{}{body}{suffix}", "0".repeat(fill))
    } else {
        format!("{}{prefix}{body}{suffix}", " ".repeat(fill))
    }
}

/// Parse a signed integer in the given radix with `java.lang.Integer`'s exact
/// rules: no surrounding whitespace is tolerated, the radix must be in
/// `[Character.MIN_RADIX, Character.MAX_RADIX]`, and the value must fit the
/// target type (`int` for `parseInt`, `long` for `parseLong`) — every failure
/// carries Java's own `NumberFormatException` detail message.
fn parse_int_radix(s: &str, radix: i64, int_width: bool) -> Result<Value, Fault> {
    let nfe = |m: String| Fault::java("NumberFormatException", m);
    if radix < 2 {
        return Err(nfe(format!("radix {radix} less than Character.MIN_RADIX")));
    }
    if radix > 36 {
        return Err(nfe(format!(
            "radix {radix} greater than Character.MAX_RADIX"
        )));
    }
    // Java quotes the raw input and, for a non-decimal radix, names it.
    let bad = || {
        if radix == 10 {
            nfe(format!("For input string: \"{s}\""))
        } else {
            nfe(format!("For input string: \"{s}\" under radix {radix}"))
        }
    };
    let n = i64::from_str_radix(s, radix as u32).map_err(|_| bad())?;
    if int_width && i32::try_from(n).is_err() {
        return Err(bad());
    }
    Ok(Value::Int(n))
}

/// Render `n` in the given radix (2..=36), matching `Integer.toString(i, radix)`.
fn int_to_radix_string(n: i64, radix: i64) -> String {
    if !(2..=36).contains(&radix) {
        // Java falls back to radix 10 for an out-of-range radix.
        return n.to_string();
    }
    let radix = radix as u64;
    if n == 0 {
        return "0".to_string();
    }
    let neg = n < 0;
    let mut v = (n as i128).unsigned_abs();
    let mut digits = Vec::new();
    while v > 0 {
        let d = (v % radix as u128) as u32;
        digits.push(std::char::from_digit(d, radix as u32).unwrap());
        v /= radix as u128;
    }
    if neg {
        digits.push('-');
    }
    digits.iter().rev().collect()
}

/// Install the debug line-marker builtin used by `java --dap`. The marker fires
/// synchronously at each statement; it delegates to the DAP server, which pauses
/// in place when the line is a breakpoint or step target.
pub fn install_debug(vm: &mut VM) {
    install(vm);
    vm.register_builtin(DBG_LINE, b_dbg_line);
}

/// The `DBG_LINE` marker builtin: hand control to the DAP server for this line,
/// then return `null` (popped by the trailing `Op::Pop` the compiler emits).
fn b_dbg_line(vm: &mut VM, _argc: u8) -> Value {
    crate::dap::on_debug_line(vm);
    Value::Undef
}

/// `System.out.println` builtin: pop `argc` values (0 or 1 in slice 1), print
/// them Java-formatted followed by a newline, and return `null`.
fn b_println(vm: &mut VM, argc: u8) -> Value {
    print_args(vm, argc, true, false)
}

/// `System.out.print` builtin: as [`b_println`] but with no trailing newline.
fn b_print(vm: &mut VM, argc: u8) -> Value {
    print_args(vm, argc, false, false)
}

/// `System.err.println` builtin: as [`b_println`] but on stderr.
fn b_eprintln(vm: &mut VM, argc: u8) -> Value {
    print_args(vm, argc, true, true)
}

/// `System.err.print` builtin: as [`b_print`] but on stderr.
fn b_eprint(vm: &mut VM, argc: u8) -> Value {
    print_args(vm, argc, false, true)
}

/// [`JSTRINGIFY`] — Java's string conversion of one value, with the VM in hand.
fn b_stringify(vm: &mut VM, _argc: u8) -> Value {
    let v = vm.stack.pop().unwrap_or(Value::Undef);
    Value::str(java_str_vm(vm, &v))
}

fn print_args(vm: &mut VM, argc: u8, newline: bool, err: bool) -> Value {
    use std::io::Write;
    // Pop the args (pushed left-to-right, so the last is on top) and restore
    // source order.
    let mut vals = Vec::with_capacity(argc as usize);
    for _ in 0..argc {
        vals.push(vm.stack.pop().unwrap_or(Value::Undef));
    }
    vals.reverse();
    // Rendering a `subList` view iterates it, which is where Java reports a
    // backing list that moved — so the check happens before anything is
    // written, not after a wrong (empty) list has already reached the stream.
    if let Some(f) = vals.iter().find_map(stale_view) {
        return raise(vm, f);
    }
    // Format once, then write to the selected stream. Boxing the lock keeps the
    // two branches on one write path. Rendering runs user `toString()` bodies,
    // which may themselves print — so it happens before the lock is taken, and a
    // throwable one of them raised aborts the write rather than emitting the
    // half-built text.
    let text: String = if any_user_tostring(vm) {
        let text: String = vals.iter().map(|v| java_str_vm(vm, v)).collect();
        if PENDING.with(|p| p.borrow().is_some()) {
            return Value::Undef;
        }
        text
    } else {
        vals.iter().map(java_str).collect()
    };
    let stdout = std::io::stdout();
    let stderr = std::io::stderr();
    let mut lock: Box<dyn Write> = if err {
        Box::new(stderr.lock())
    } else {
        Box::new(stdout.lock())
    };
    let _ = write!(lock, "{text}");
    if newline {
        let _ = writeln!(lock);
    }
    // `println`/`print` are `void`; the CallBuiltin result is discarded by a
    // trailing Pop in statement position.
    Value::Undef
}

/// Render a value with Java's `String.valueOf`/`println` rules (as opposed to
/// fusevm's shell-flavoured `as_str_cow`): booleans as `true`/`false`, whole
/// floats with a trailing `.0`, `Undef` as `null`.
pub fn java_str(v: &Value) -> String {
    match v {
        Value::Bool(b) => if *b { "true" } else { "false" }.to_string(),
        Value::Float(f) => format_double(*f),
        Value::Undef => "null".to_string(),
        // A heap handle renders like Java's default `Object.toString`
        // (`ClassName@hex`). Reaching a user `toString()` override needs a VM to
        // run the body in, which this signature has not got — every rendering
        // surface that holds one calls [`java_str_vm`] instead.
        Value::Obj(id) => obj_default_str(*id),
        other => other.as_str_cow().into_owned(),
    }
}

/// [`java_str`] with a VM in hand, so a class instance whose class (or an
/// ancestor) declares `toString()` renders through that body, at every depth of
/// a nested collection.
///
/// Every rendering surface that holds a `&mut VM` routes here, which is what
/// keeps them agreeing: `println(o)`, `"" + o` (via [`JSTRINGIFY`]),
/// `String.valueOf(o)`, `Arrays.toString`, `list.toString()`, `String.join`,
/// and `%s`. When the program declares no override at all the gate
/// (`any_user_tostring`) is off and this is [`java_str`] exactly.
pub fn java_str_vm(vm: &mut VM, v: &Value) -> String {
    match v {
        Value::Obj(id) if any_user_tostring(vm) => obj_str_vm(vm, *id),
        other => java_str(other),
    }
}

/// The mangled suffix `toString()`'s subroutine is registered under.
const TOSTRING_SUFFIX: &str = "#toString#";

/// The mangled suffix an *overriding* `equals` is registered under. Java's
/// collections call `equals(Object)` and nothing else, so a class that declares
/// `equals(C)` has written an overload rather than an override and does not
/// appear here — which is the answer Java gives too.
const EQUALS_SUFFIX: &str = "#equals#Object";

/// The mangled suffix a user `hashCode()` is registered under. Its *presence* is
/// what [`hash_consistent`] reads; javars does not call the body.
const HASHCODE_SUFFIX: &str = "#hashCode#";

thread_local! {
    /// Whether the running chunk registers any `Class#toString#` subroutine,
    /// computed once per run. `None` until the first rendering asks.
    static USER_TOSTRING: Cell<Option<bool>> = const { Cell::new(None) };
    /// The same question for `Class#equals#Object`. `None` until the first
    /// element comparison asks.
    static USER_EQUALS: Cell<Option<bool>> = const { Cell::new(None) };
    /// (mangled suffix, class name) → the entry ip that class resolves the
    /// member to, walking supertypes; `None` for a class that inherits
    /// `java.lang.Object`'s. Memoised because rendering — or searching — a list
    /// asks once per element.
    static MEMBER_ENTRY: RefCell<HashMap<(&'static str, String), Option<usize>>> =
        RefCell::new(HashMap::new());
}

/// Whether the chunk declares a user `toString()` anywhere. False means every
/// rendering surface keeps the bytecode and the code path it always had.
fn any_user_tostring(vm: &VM) -> bool {
    cached_flag(&USER_TOSTRING, vm, TOSTRING_SUFFIX)
}

/// Whether the chunk declares an `equals(Object)` anywhere — a class of its own,
/// or the one a `record` or `enum` has synthesized. False means every collection
/// comparison keeps [`value_eq`] and the code path javars has always taken.
fn any_user_equals(vm: &VM) -> bool {
    cached_flag(&USER_EQUALS, vm, EQUALS_SUFFIX)
}

/// Whether any subroutine name carries `suffix`, answered once per run.
fn cached_flag(
    cell: &'static std::thread::LocalKey<Cell<Option<bool>>>,
    vm: &VM,
    suffix: &str,
) -> bool {
    cell.with(|c| match c.get() {
        Some(b) => b,
        None => {
            let b = vm.chunk.names.iter().any(|n| n.contains(suffix));
            c.set(Some(b));
            b
        }
    })
}

/// The entry ip of the `toString()` a runtime class resolves.
fn tostring_entry(vm: &VM, class: &str) -> Option<usize> {
    member_entry(vm, class, TOSTRING_SUFFIX)
}

/// The entry ip of the `equals(Object)` a runtime class resolves.
fn equals_entry(vm: &VM, class: &str) -> Option<usize> {
    member_entry(vm, class, EQUALS_SUFFIX)
}

/// The entry ip of the member body a runtime class resolves, following the
/// supertype chain the way the compiler's own dispatch does — a subclass that
/// declares none inherits its parent's body, and only a class that reaches
/// `java.lang.Object` without finding one has no body at all.
///
/// `suffix` is the mangled tail the member's subroutine is registered under
/// (`Class` + [`TOSTRING_SUFFIX`] / [`EQUALS_SUFFIX`]); the walk is shared
/// because `toString` and `equals` resolve by exactly the same rule.
fn member_entry(vm: &VM, class: &str, suffix: &'static str) -> Option<usize> {
    let cache_key = (suffix, class.to_string());
    if let Some(hit) = MEMBER_ENTRY.with(|t| t.borrow().get(&cache_key).copied()) {
        return hit;
    }
    let mut stack = vec![class.to_string()];
    let mut seen = std::collections::HashSet::new();
    let mut found = None;
    while let Some(cur) = stack.pop() {
        if !seen.insert(cur.clone()) {
            continue;
        }
        let key = format!("{cur}{suffix}");
        if let Some(i) = vm.chunk.names.iter().position(|n| *n == key) {
            if let Some(entry) = vm.chunk.find_sub(i as u16) {
                found = Some(entry);
                break;
            }
        }
        SUPERS.with(|s| {
            if let Some(sups) = s.borrow().get(&cur) {
                stack.extend(sups.iter().cloned());
            }
        });
    }
    MEMBER_ENTRY.with(|t| t.borrow_mut().insert(cache_key, found));
    found
}

/// What a heap object needs in order to render, read out of the heap in one
/// borrow so the borrow is dropped before any user body runs — a `toString()`
/// reads its own fields, and a nested one allocates.
enum RenderShape {
    /// A class instance: its runtime class, and the enum constant name when the
    /// synthesized field carries one.
    Instance(String, Option<String>),
    /// A `List`/`SubList`/`Set`, already in presentation order.
    Sequence(Vec<Value>),
    /// A `Map`, already in presentation order.
    Entries(Vec<(Value, Value)>),
    /// An array, a lambda, or a dangling handle — nothing to recurse into, so
    /// the pure renderer answers.
    Opaque,
}

/// [`java_str_vm`]'s heap case: snapshot the shape, drop the borrow, then either
/// run the override or recurse into the elements.
fn obj_str_vm(vm: &mut VM, id: u32) -> String {
    let shape = HEAP.with(|h| {
        let h = h.borrow();
        match h.get(id as usize) {
            Some(HostObj::Instance { class, fields }) => RenderShape::Instance(
                class.clone(),
                fields
                    .get(crate::ast::ENUM_NAME)
                    .filter(|n| !matches!(n, Value::Undef))
                    .map(|n| n.as_str_cow().into_owned()),
            ),
            Some(HostObj::List { items, .. }) => RenderShape::Sequence(items.clone()),
            Some(HostObj::Set { items, order, .. }) => RenderShape::Sequence(
                present_order(items, *order)
                    .into_iter()
                    .map(|i| items[i].clone())
                    .collect(),
            ),
            Some(HostObj::Map { entries, order, .. }) => {
                let keys: Vec<Value> = entries.iter().map(|(k, _)| k.clone()).collect();
                RenderShape::Entries(
                    present_order(&keys, *order)
                        .into_iter()
                        .map(|i| entries[i].clone())
                        .collect(),
                )
            }
            _ => RenderShape::Opaque,
        }
    });
    match shape {
        // A `SubList` owns no elements, so its window is read through the
        // parent — outside the borrow above, which `sublist_items` takes itself.
        RenderShape::Opaque if is_sublist(id as usize) => {
            let items = sublist_items(id as usize)
                .and_then(Result::ok)
                .unwrap_or_default();
            render_sequence_vm(vm, &items)
        }
        RenderShape::Opaque => obj_default_str(id),
        // `Enum.toString()` returns the constant's name unless the enum declares
        // its own override, and the override wins — the same precedence Java's
        // virtual dispatch gives it.
        RenderShape::Instance(class, enum_name) => match tostring_entry(vm, &class) {
            Some(entry) => run_tostring(vm, entry, id),
            None => enum_name.unwrap_or_else(|| obj_default_str(id)),
        },
        RenderShape::Sequence(items) => render_sequence_vm(vm, &items),
        RenderShape::Entries(entries) => {
            let body: Vec<String> = entries
                .iter()
                .map(|(k, v)| format!("{}={}", java_str_vm(vm, k), java_str_vm(vm, v)))
                .collect();
            format!("{{{}}}", body.join(", "))
        }
    }
}

/// `[a, b, c]` with each element rendered through its own `toString()`.
fn render_sequence_vm(vm: &mut VM, items: &[Value]) -> String {
    let body: Vec<String> = items.iter().map(|e| java_str_vm(vm, e)).collect();
    format!("[{}]", body.join(", "))
}

/// Run a user `toString()` body on `id` and return what it answered.
///
/// A throwable already in flight stops the call: the enclosing frame is
/// unwinding, and rendering must not start a body whose side effects would run
/// a second time. One raised *by* the body leaves `PENDING` set for the calling
/// builtin to surface, and the half-built text is discarded with it.
fn run_tostring(vm: &mut VM, entry: usize, id: u32) -> String {
    if PENDING.with(|p| p.borrow().is_some()) {
        return String::new();
    }
    let stack_base = vm.stack.len();
    vm.stack.push(Value::Obj(id));
    let out = run_sub(vm, entry, stack_base);
    // Java's string conversion of a `toString()` that answered `null` is the
    // four characters "null", not an empty string.
    java_str(&out)
}

/// Java's default `toString` for a heap object: `ClassName@<identity-hash>` for
/// an instance, `[@<hash>` for an array. The class name is the qualified one
/// `getClass().getName()` reports (`java.lang.Object`, not `Object`), and the
/// hash is the handle (deterministic within a run) rather than a JVM identity
/// hash.
fn obj_default_str(id: u32) -> String {
    // A wrapper renders as the primitive it holds, and two of the eight need
    // their class to do it: a `char` rides `Value::Int`, so `Character` has to
    // turn the code point back into the character, and `Float.toString` is the
    // 32-bit rendering (`0.1f` prints `0.1`, not the `double` widening's
    // `0.10000000149011612`). Computed before the heap borrow below so the
    // formatting helpers are free to touch the heap themselves.
    let handle = Value::Obj(id);
    if let (Some(class), Some(v)) = (box_class(&handle), unboxed(&handle)) {
        return match class {
            "Character" => char::from_u32(as_i64(&v) as u32)
                .map(String::from)
                .unwrap_or_default(),
            "Float" => java_str(&float_to_string(&v)),
            _ => java_str(&v),
        };
    }
    HEAP.with(|h| {
        let h = h.borrow();
        match h.get(id as usize) {
            // An enum constant carries its name in a synthesized field, and
            // `Enum.toString()` returns exactly that. Reading it here is what
            // makes `String.valueOf(color)` and `Arrays.toString(values())`
            // print `RED` rather than `Color@1` without calling the Java-level
            // `toString()`. Rendering does not call an override at all — not
            // because it could not (this runs under a builtin, which holds
            // `&mut VM`), but because `"" + obj` renders from the numeric hook,
            // which does not, and the two must not disagree. See BUGS.md.
            Some(HostObj::Instance { class, fields }) => match fields.get(crate::ast::ENUM_NAME) {
                Some(n) if !matches!(n, Value::Undef) => n.as_str_cow().into_owned(),
                _ => format!("{}@{id:x}", qualified_or_binary(class)),
            },
            Some(HostObj::Array(_)) => format!("[@{id:x}"),
            // `StringBuilder.toString()` IS its contents, so every rendering
            // surface — `println(sb)`, `"" + sb`, `%s`, a list element — shows
            // the text rather than a handle.
            Some(HostObj::Builder { s, .. }) => s.clone(),
            Some(HostObj::List { items, .. }) => render_sequence(items),
            // A view renders its window of the backing list. Rendering cannot
            // raise, so a view whose backing list moved prints as though it
            // were empty rather than reporting the comodification the next
            // real method call does report.
            Some(HostObj::SubList { .. }) => render_sequence(
                &sublist_items(id as usize)
                    .and_then(Result::ok)
                    .unwrap_or_default(),
            ),
            Some(HostObj::Set { items, order, .. }) => render_set(items, *order),
            Some(HostObj::Map { entries, order, .. }) => render_map(entries, *order),
            // Java renders a lambda as `Class$$Lambda/0x…@<identity hash>`,
            // which is not reproducible (and not stable across JVM runs), so
            // javars prints a fixed marker instead. See `BUGS.md`.
            Some(HostObj::Closure { .. }) => format!("<lambda>@{id:x}"),
            Some(HostObj::Boxed) => unreachable!("a box is answered above"),
            Some(HostObj::Iterator { .. }) => format!("<iterator>@{id:x}"),
            // `Optional[x]` / `Optional.empty` — the JDK's own rendering, and
            // the same shape for the three primitive specializations.
            Some(HostObj::Optional { class, value }) => match value {
                Some(v) => format!("{class}[{}]", java_str(v)),
                None => format!("{class}.empty"),
            },
            Some(HostObj::Stream { .. }) => format!("<stream>@{id:x}"),
            Some(HostObj::Collector { .. }) => format!("<collector>@{id:x}"),
            None => format!("(obj:{id})"),
        }
    })
}

/// Java's `Double.toString` prints whole values with a trailing `.0`
/// (`3.0`, not `3`) and keeps a decimal point; non-finite values print as
/// `Infinity`/`-Infinity`/`NaN`.
fn format_double(f: f64) -> String {
    // Rust's `{}`/`{:e}` are the shortest round-tripping decimal, which is what
    // Java selects too — except when that decimal has a single digit, where
    // Java widens the candidate set (see [`widen_exact`]).
    let sci = format!("{f:e}");
    if f.is_finite() && f != 0.0 && shortest_is_one_digit(&sci) {
        if let Some((digits, exp)) = widen_exact(f) {
            let sign = if f < 0.0 { "-" } else { "" };
            return format_ieee(
                f,
                format!("{sign}{}", plain_form(&digits, exp)),
                format!("{sign}{}", sci_form(&digits, exp)),
            );
        }
    }
    format_ieee(f, format!("{f}"), sci)
}

/// True when a Rust `{:e}` rendering has a single-digit mantissa (`1e-45`, not
/// `1.4e-45`) — the gate on Java's **two-digit widening**, the one rule its
/// `toString` specification applies that "shortest decimal that round-trips"
/// does not.
///
/// `Double.toString`/`Float.toString` take `R` to be every decimal that rounds
/// to the value and `p` to be the minimal length in `R`. For `p >= 2` the
/// candidates `T` are the decimals of length exactly `p` — shortest-round-trip.
/// **For `p < 2`, `T` is the decimals of length 1 _or 2_**, and the answer is
/// the member of `T` nearest the value (ties to even). So a one-digit shortest
/// form is not automatically the answer: a two-digit decimal that is closer
/// beats it.
///
/// For every normal value the two rules agree, because a normal's binary ulp is
/// some sixteen decimal orders below the value: the nearest two-digit decimal is
/// always the one-digit answer with a `0` appended, which canonicalizes straight
/// back (a decimal's length counts a mantissa not divisible by 10). Down at the
/// subnormal floor the binary ulp is the same size as the value, and they part:
/// `Double.MIN_VALUE` is 4.9406…E-324, which `5.0E-324` does round-trip to, but
/// `4.9E-324` is nearer — so Java prints `4.9E-324`. The same holds for
/// `Float.MIN_VALUE` (`1.4E-45`, not `1.0E-45`) and for every subnormal whose
/// shortest form is one digit. [`widen_exact`] does the widening.
fn shortest_is_one_digit(sci: &str) -> bool {
    sci.split_once('e')
        .is_some_and(|(mantissa, _)| mantissa.bytes().filter(u8::is_ascii_digit).count() == 1)
}

/// The two-digit widening itself (see [`shortest_is_one_digit`] for the rule).
///
/// Applied by rounding `|v|`'s **exact** decimal expansion to two significant
/// digits, half to even — which is precisely "the nearest decimal of length 1 or
/// 2, ties to even". The exact expansion is the only way to compare decimals
/// down there: `10^exp` is not itself a representable `double` at the subnormal
/// floor, so the arithmetic `v / 10^(exp-1)` underflows to zero. Nineteen
/// significant digits (`{:.18e}`, which Rust renders exactly) decide any
/// two-digit rounding.
///
/// Returns the widened `(digits, exp10)`, or `None` when the result canonicalizes
/// back to one digit (a trailing `0`) — the no-change case. Callers gate this on
/// [`shortest_is_one_digit`], because it is only the `p < 2` branch of the rule.
fn widen_exact(v: f64) -> Option<(String, i32)> {
    let exact = format!("{:.*e}", 18, v.abs());
    let (mantissa, exp) = exact.split_once('e')?;
    let exp: i32 = exp.parse().ok()?;
    let d: Vec<u8> = mantissa
        .bytes()
        .filter(u8::is_ascii_digit)
        .map(|b| b - b'0')
        .collect();
    let mut two = u32::from(d[0]) * 10 + u32::from(d[1]);
    let beyond_half = d[2] > 5 || (d[2] == 5 && d[3..].iter().any(|&x| x != 0));
    if beyond_half || (d[2] == 5 && two % 2 == 1) {
        two += 1;
    }
    // A carry out of `99` is `100`, i.e. one digit more and one decade up.
    let (two, exp) = if two == 100 {
        (10, exp + 1)
    } else {
        (two, exp)
    };
    if two % 10 == 0 {
        return None;
    }
    Some((two.to_string(), exp))
}

/// `Float.toString` — the same layout rules, but the shortest decimal is
/// computed against **32-bit** precision. That is the whole difference between
/// the two: the `f64` nearest `0.1f` prints as `0.10000000149011612` as a
/// `double` and as `0.1` as a `float`, because only 32 bits have to round-trip.
fn format_float(f: f32) -> String {
    if !f.is_finite() || f == 0.0 {
        return format_ieee(f as f64, String::new(), String::new());
    }
    // The digit selection works on magnitude; the sign is put back on both
    // renderings so `format_ieee` only has to choose between them.
    let (digits, exp10) = java_shortest_f32(f);
    // `Float.toString` carries the same two-digit widening as `Double`'s, over
    // the `float`'s own rounding interval — which is what makes
    // `Float.MIN_VALUE` print as `1.4E-45` rather than `1.0E-45`.
    let (digits, exp10) = if digits.len() == 1 {
        widen_exact(f64::from(f)).unwrap_or((digits, exp10))
    } else {
        (digits, exp10)
    };
    let sign = if f < 0.0 { "-" } else { "" };
    format_ieee(
        f as f64,
        format!("{sign}{}", plain_form(&digits, exp10)),
        format!("{sign}{}", sci_form(&digits, exp10)),
    )
}

/// The digits and decimal exponent `Float.toString` selects for `v`, as
/// (significant digits, exponent) where the value is `d.ddd × 10^exp`.
///
/// Java and Rust agree on the *length* — both emit the shortest decimal that
/// round-trips — but not always on which one. Java's rule (`Double.toString`'s
/// specification, which `Float`'s mirrors) picks the candidate closest to the
/// value and, when two are equidistant, the one whose last digit is **even**.
/// Rust's formatter breaks that final tie the other way, so `16777217.0f * 0.2f`
/// (exactly 3355443.25) prints `3355443.3` there and `3355443.2` in Java.
fn java_shortest_f32(v: f32) -> (String, i32) {
    let sci = format!("{v:e}");
    let (mantissa, exp) = sci.split_once('e').unwrap_or((sci.as_str(), "0"));
    let exp: i32 = exp.parse().unwrap_or(0);
    let neg = mantissa.starts_with('-');
    let digits: String = mantissa.chars().filter(|c| c.is_ascii_digit()).collect();

    // The only other candidate of the same length is one decimal ulp away, on
    // whichever side of the value Rust's answer is not.
    let here = rebuild(&digits, exp, neg);
    let delta = here - f64::from(v);
    if delta == 0.0 {
        return (digits, exp);
    }
    let toward = if (delta > 0.0) != neg { -1 } else { 1 };
    let Some((other_digits, other_exp)) = step_last_digit(&digits, exp, toward) else {
        return (digits, exp);
    };
    // A candidate that does not round-trip is not a candidate.
    let other = rebuild(&other_digits, other_exp, neg);
    if other as f32 != v {
        return (digits, exp);
    }
    let (d_here, d_other) = (delta.abs(), (other - f64::from(v)).abs());
    // Both distances sum to one decimal ulp, so "equidistant" is a comparison at
    // that scale; f64 carries eight more digits than the nine at stake here.
    let tie = (d_here - d_other).abs() <= (d_here + d_other) * 1e-9;
    if tie {
        let even = |d: &str| d.as_bytes().last().is_some_and(|b| (b - b'0') % 2 == 0);
        return if even(&digits) {
            (digits, exp)
        } else {
            (other_digits, other_exp)
        };
    }
    if d_other < d_here {
        (other_digits, other_exp)
    } else {
        (digits, exp)
    }
}

/// The value of `d.ddd × 10^exp`, signed.
fn rebuild(digits: &str, exp: i32, neg: bool) -> f64 {
    let mut s = String::new();
    if neg {
        s.push('-');
    }
    s.push_str(&digits[..1]);
    if digits.len() > 1 {
        s.push('.');
        s.push_str(&digits[1..]);
    }
    s.push('e');
    s.push_str(&exp.to_string());
    s.parse().unwrap_or(f64::NAN)
}

/// Add `step` (±1) to the last significant digit, carrying through. A carry out
/// of the leading digit shortens the digit string and bumps the exponent, which
/// keeps the candidate the same *length* as the one it came from.
fn step_last_digit(digits: &str, exp: i32, step: i8) -> Option<(String, i32)> {
    let mut d: Vec<u8> = digits.bytes().map(|b| b - b'0').collect();
    let mut i = d.len();
    if step > 0 {
        loop {
            if i == 0 {
                // 999… + 1 → 100… one decimal place up.
                let mut out = vec![1u8];
                out.resize(d.len(), 0);
                return Some((to_digits(&out), exp + 1));
            }
            i -= 1;
            if d[i] < 9 {
                d[i] += 1;
                break;
            }
            d[i] = 0;
        }
    } else {
        loop {
            if i == 0 {
                // 100… - 1 → 999… one decimal place down.
                return Some((("9").repeat(d.len()), exp - 1));
            }
            i -= 1;
            if d[i] > 0 {
                d[i] -= 1;
                break;
            }
            d[i] = 9;
        }
    }
    Some((to_digits(&d), exp))
}

fn to_digits(d: &[u8]) -> String {
    d.iter().map(|b| (b + b'0') as char).collect()
}

/// `d.ddd × 10^exp` written out in full, the form Java uses inside
/// [1e-3, 1e7). Always carries at least one fractional digit.
fn plain_form(digits: &str, exp: i32) -> String {
    if exp < 0 {
        return format!("0.{}{digits}", "0".repeat((-exp - 1) as usize));
    }
    let int_len = exp as usize + 1;
    if digits.len() <= int_len {
        format!("{digits}{}.0", "0".repeat(int_len - digits.len()))
    } else {
        format!("{}.{}", &digits[..int_len], &digits[int_len..])
    }
}

/// `d.ddd × 10^exp` in the `1.5e3` shape [`format_ieee`] uppercases.
fn sci_form(digits: &str, exp: i32) -> String {
    if digits.len() > 1 {
        format!("{}.{}e{exp}", &digits[..1], &digits[1..])
    } else {
        format!("{digits}e{exp}")
    }
}

/// The shared layout of `Double.toString` / `Float.toString`, given the value
/// and its shortest plain and scientific renderings at the right precision.
fn format_ieee(f: f64, plain: String, sci: String) -> String {
    if f.is_nan() {
        return "NaN".to_string();
    }
    if f.is_infinite() {
        return if f < 0.0 { "-Infinity" } else { "Infinity" }.to_string();
    }
    if f == 0.0 {
        // Java distinguishes the signed zeroes: `-0.0` prints with its sign.
        return if f.is_sign_negative() { "-0.0" } else { "0.0" }.to_string();
    }

    // Java uses plain decimal only inside [1e-3, 1e7); outside that range it
    // switches to "computerized scientific notation". Rust's `{}` never
    // switches, so the range test has to be explicit or large/small magnitudes
    // print as long digit strings (`25000000.0` where Java says `2.5E7`).
    let mag = f.abs();
    if (1e-3..1e7).contains(&mag) {
        // Java always keeps a fractional digit: `1.0`, never `1`.
        return if plain.contains('.') {
            plain
        } else {
            format!("{plain}.0")
        };
    }

    // Scientific form. Rust renders `2.5e7` / `1e7`; Java wants `2.5E7` / `1.0E7`
    // — an uppercase exponent, no `+`, and a mantissa that always carries a
    // fractional digit.
    let (mantissa, exp) = match sci.split_once('e') {
        Some((m, e)) => (m, e),
        None => return sci,
    };
    let mantissa = if mantissa.contains('.') {
        mantissa.to_string()
    } else {
        format!("{mantissa}.0")
    };
    format!("{mantissa}E{exp}")
}

/// Whether `v` is one of Java's primitive numeric shapes on the fusevm value
/// model: `byte`/`short`/`char`/`int`/`long` ride [`Value::Int`], `float` and
/// `double` ride [`Value::Float`]. A `boolean`, a `String`, and every reference
/// type answer `false`.
///
/// [`numeric_hook`] gates its arithmetic on this predicate rather than on an
/// arm being written above the `String` ones. Java's `+` is overloaded, so a
/// catch-all concatenating arm will answer an *arithmetic* pair the moment a
/// numeric case is missing from the arms before it — and it answers with a
/// number-shaped `String` rather than an error, which is why the failure is
/// silent. Requiring both operands to be numbers up front makes the two paths
/// disjoint by construction instead of by ordering.
fn is_java_number(v: &Value) -> bool {
    // A boxed wrapper is a number too: every arithmetic and relational operator
    // Java allows on one unboxes it first (JLS 5.1.8), so the hook must reach
    // `java_numeric` for it rather than falling into the `String` arms and
    // concatenating.
    matches!(v, Value::Int(_) | Value::Float(_))
        || unboxed(v).is_some_and(|inner| matches!(inner, Value::Int(_) | Value::Float(_)))
}

/// One binary operation on two Java primitive numbers — the pairs fusevm hands
/// back rather than answering natively.
///
/// **Two `Value::Int`s are Java `long`s:** two's-complement and silently
/// wrapping, never a promotion to a wider representation. fusevm delegates such
/// a pair when the native operation overflows `i64` (`Long.MAX_VALUE + 1` is
/// `Long.MIN_VALUE`) or when `checked_rem` overflows, which is the single pair
/// `Long.MIN_VALUE % -1L` — Java answers `0`.
///
/// **A mixed `Int`/`Float` pair is Java's binary numeric promotion** (JLS
/// 5.6.2: if either operand is of type `double`, the other is converted to
/// `double`). fusevm delegates such a pair once the integer is past 2^53,
/// because converting it *rounds* and only the host knows whether the rounding
/// is a defect. **For Java it is not a defect: the language mandates the
/// conversion, so the rounded `double` is the correct answer and is returned
/// here deliberately.** Measured against `java` 26.0.2 with
/// `L = 3^34 = 16677181699666569L` and `R = 1.6677181699666568E16` (its
/// `double` image, a neighbouring value): `L == R` is `true` and `L + 2.0` is
/// `1.667718169966657E16`. The same pair in Ruby answers `false` — that
/// divergence is precisely why the decision belongs to the frontend and not to
/// the VM.
///
/// A zero divisor is Java's `ArithmeticException`; fusevm answers integral
/// `%` by zero natively so it does not currently arrive here, but the hook is
/// public and must not depend on that.
fn java_numeric(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
    if let (Value::Int(x), Value::Int(y)) = (a, b) {
        let (x, y) = (*x, *y);
        return match op {
            NumOp::Add => Ok(Value::Int(x.wrapping_add(y))),
            NumOp::Sub => Ok(Value::Int(x.wrapping_sub(y))),
            NumOp::Mul => Ok(Value::Int(x.wrapping_mul(y))),
            NumOp::Div | NumOp::Mod if y == 0 => {
                Err("java.lang.ArithmeticException: / by zero".to_string())
            }
            // Both truncate toward zero, and both wrap on the one overflowing
            // pair: `Long.MIN_VALUE / -1L` is `Long.MIN_VALUE`, `% -1L` is `0`.
            NumOp::Div => Ok(Value::Int(x.wrapping_div(y))),
            NumOp::Mod => Ok(Value::Int(x.wrapping_rem(y))),
            NumOp::Eq => Ok(Value::bool(x == y)),
            NumOp::Ne => Ok(Value::bool(x != y)),
            NumOp::Lt => Ok(Value::bool(x < y)),
            NumOp::Gt => Ok(Value::bool(x > y)),
            NumOp::Le => Ok(Value::bool(x <= y)),
            NumOp::Ge => Ok(Value::bool(x >= y)),
            NumOp::Neg => Ok(Value::Int(x.wrapping_neg())),
            NumOp::Pow => Err(NO_POW.to_string()),
        };
    }
    // Promoted to `double`. Rust's `f64` operators are IEEE-754 with the same
    // NaN and infinity rules Java specifies, and its `%` is the truncated
    // remainder that takes the dividend's sign, like Java's — `7L % -2.5` is
    // `2.0` in both.
    let (x, y) = (as_f64(a), as_f64(b));
    match op {
        NumOp::Add => Ok(Value::float(x + y)),
        NumOp::Sub => Ok(Value::float(x - y)),
        NumOp::Mul => Ok(Value::float(x * y)),
        NumOp::Div => Ok(Value::float(x / y)),
        NumOp::Mod => Ok(Value::float(x % y)),
        NumOp::Eq => Ok(Value::bool(x == y)),
        NumOp::Ne => Ok(Value::bool(x != y)),
        NumOp::Lt => Ok(Value::bool(x < y)),
        NumOp::Gt => Ok(Value::bool(x > y)),
        NumOp::Le => Ok(Value::bool(x <= y)),
        NumOp::Ge => Ok(Value::bool(x >= y)),
        NumOp::Neg => Ok(Value::float(-x)),
        NumOp::Pow => Err(NO_POW.to_string()),
    }
}

/// Java has no exponentiation operator, so [`NumOp::Pow`] is never emitted;
/// `Math.pow` is a builtin call instead.
const NO_POW: &str = "javars: Java has no `**` operator";

/// Strict numeric hook: fusevm delegates here whenever it cannot answer an
/// operation itself under the strict policy. Three cases arrive:
///
/// 1. **A non-numeric operand** — Java's `String` `+` overload, and value
///    comparisons against a string. This is the case slice 1 was written for.
/// 2. **An all-integer operation fusevm could not complete in `i64`** — an
///    overflowing `Add`/`Sub`/`Mul`/`Neg`, or `Long.MIN_VALUE % -1L`.
/// 3. **A mixed `Int`/`Float` pair whose integer is past 2^53** — converting it
///    to `f64` would round, so fusevm hands over the operands instead of an
///    answer computed on a neighbouring value.
///
/// Case 3 is newer than this hook. The comment that stood here asserted that
/// "all-numeric arithmetic never reaches here (it stays on the native fast path
/// and the JIT)"; that was true when written and fusevm's strict-exactness fix
/// falsified it. Under the old text every mixed pair fell through to the
/// `String` arms below — `Add` returned a concatenation, the comparisons
/// answered by lexicographic string order, and the rest returned a type error.
/// `java_numeric` now answers all three cases and is reached on operand
/// shape, so no numeric pair can fall into a `String` arm again.
pub fn numeric_hook(op: NumOp, a: &Value, b: &Value) -> Result<Value, String> {
    // `Neg` is unary — fusevm passes `Undef` as the second operand, so it can
    // never satisfy the two-number gate below and is answered first.
    if op == NumOp::Neg && is_java_number(a) {
        return java_numeric(op, &deboxed(a), &Value::Int(0));
    }
    // `==`/`!=` involving a heap reference is reference identity — before the
    // numeric gate below, because a boxed wrapper is a number as well as a
    // reference and Java compares two of them as references.
    //
    // The one exception is a *mixed* box/primitive pair of numbers, which Java
    // unboxes (JLS 15.21.1): `anInteger == anInt` compares the numbers. Two
    // boxes are NOT that case however numeric they are — that is the whole
    // point of the wrapper model — so the exception needs exactly one handle.
    // Everything else a handle can be compared against stays identity,
    // including a `new String(…)` box against a `String` literal, which is
    // `false` because the constructor produced a fresh object.
    let both_handles = matches!((a, b), (Value::Obj(_), Value::Obj(_)));
    let one_handle = matches!(a, Value::Obj(_)) || matches!(b, Value::Obj(_));
    let unboxing_pair = one_handle && !both_handles && is_java_number(a) && is_java_number(b);
    if one_handle && !unboxing_pair {
        match op {
            NumOp::Eq => return Ok(Value::bool(ref_eq(a, b))),
            NumOp::Ne => return Ok(Value::bool(!ref_eq(a, b))),
            _ => {}
        }
    }
    // Two `String`s compare as *references*, which is what Java's `==` does on
    // them. The reference is the `Arc`: a literal is one pool entry per distinct
    // text (see `Compiler::string_literal`), so two occurrences share a pointer
    // and `"ab" == "ab"` is `true`, while every string built at run time —
    // a concatenation, a `substring`, a `String.valueOf` — allocates its own and
    // is `==` to nothing else. No heap box and no extra allocation: the
    // identity was already there in the representation, unread.
    if let (Value::Str(x), Value::Str(y)) = (a, b) {
        match op {
            NumOp::Eq => return Ok(Value::bool(std::sync::Arc::ptr_eq(x, y))),
            NumOp::Ne => return Ok(Value::bool(!std::sync::Arc::ptr_eq(x, y))),
            _ => {}
        }
    }
    if is_java_number(a) && is_java_number(b) {
        return java_numeric(op, &deboxed(a), &deboxed(b));
    }
    match op {
        // Java `+`: if either side is non-numeric (a String), concatenate using
        // Java's value-to-string rules.
        NumOp::Add => Ok(Value::str(format!("{}{}", java_str(a), java_str(b)))),
        // Value equality/ordering against a string operand (Java `.equals`/
        // `.compareTo`-style; `==` reference identity is not modeled in slice 1).
        NumOp::Eq => Ok(Value::bool(java_str(a) == java_str(b))),
        NumOp::Ne => Ok(Value::bool(java_str(a) != java_str(b))),
        NumOp::Lt => Ok(Value::bool(java_str(a) < java_str(b))),
        NumOp::Gt => Ok(Value::bool(java_str(a) > java_str(b))),
        NumOp::Le => Ok(Value::bool(java_str(a) <= java_str(b))),
        NumOp::Ge => Ok(Value::bool(java_str(a) >= java_str(b))),
        // Arithmetic other than `+` on a non-numeric operand is a type error in
        // Java (`"a" - 1` does not compile). Report it rather than coercing.
        NumOp::Sub | NumOp::Mul | NumOp::Div | NumOp::Mod | NumOp::Pow => Err(format!(
            "javars: operator `{op:?}` is not defined for operands `{}` and `{}`",
            java_str(a),
            java_str(b)
        )),
        NumOp::Neg => Err(format!(
            "javars: unary `-` is not defined for `{}`",
            java_str(a)
        )),
    }
}

/// Java floating-point `/`: IEEE-754 semantics, including the infinities and
/// NaN that a zero divisor produces. Both operands are coerced to `f64`, which
/// is correct because the compiler only routes a division here when at least one
/// side is not statically integral.
fn b_div(vm: &mut VM, _argc: u8) -> Value {
    let b = vm.stack.pop().unwrap_or(Value::Undef);
    let a = vm.stack.pop().unwrap_or(Value::Undef);
    Value::float(as_f64(&a) / as_f64(&b))
}

/// Java's 64-bit integral `/`, divided in `i64` rather than in `f64`. See
/// [`JIDIV`] for why the native float pair cannot serve a `long`.
///
/// `wrapping_div`, not `/`: Rust's `/` panics on `i64::MIN / -1`, and that
/// overflow check runs in release too. Java defines the case — JLS 15.17.2, "if
/// the dividend is the negative integer of largest possible magnitude for its
/// type, and the divisor is -1, then integer overflow occurs and the result is
/// equal to the dividend" — so the answer is `i64::MIN`, which is exactly what
/// `wrapping_div` gives. A zero divisor cannot reach here: the compiler emits
/// [`Compiler::emit_zero_divisor_check`] ahead of the call, which raises
/// `ArithmeticException` first. Guarding it anyway keeps a panic out of the
/// builtin regardless of how it is reached.
fn b_idiv(vm: &mut VM, _argc: u8) -> Value {
    let b = as_i64(&vm.stack.pop().unwrap_or(Value::Undef));
    let a = as_i64(&vm.stack.pop().unwrap_or(Value::Undef));
    Value::Int(if b == 0 { 0 } else { a.wrapping_div(b) })
}

/// `>>>` — zero-fill right shift at `width` bits (32 for `int`, 64 for `long`).
/// See [`JUSHR`].
fn b_ushr(vm: &mut VM, _argc: u8) -> Value {
    let width = as_i64(&vm.stack.pop().unwrap_or(Value::Undef));
    let count = as_i64(&vm.stack.pop().unwrap_or(Value::Undef)) as u32;
    let value = as_i64(&vm.stack.pop().unwrap_or(Value::Undef));
    if width == 32 {
        Value::Int(((value as u32) >> count) as i32 as i64)
    } else {
        Value::Int(((value as u64) >> count) as i64)
    }
}

/// A narrowing primitive cast. See [`JCAST`].
///
/// Rust's `as` between a float and an integer saturates and maps NaN to 0,
/// which is exactly Java's narrowing rule for `double`/`float` → `int`/`long`;
/// the integral narrowings are plain two's-complement truncations.
fn b_cast(vm: &mut VM, _argc: u8) -> Value {
    let ty = vm.stack.pop().unwrap_or(Value::Undef);
    let ty = ty.as_str_cow().into_owned();
    let v = vm.stack.pop().unwrap_or(Value::Undef);
    match ty.as_str() {
        "int" => Value::Int(match &v {
            Value::Float(f) => *f as i32 as i64,
            other => as_i64(other) as i32 as i64,
        }),
        "long" => Value::Int(match &v {
            Value::Float(f) => *f as i64,
            other => as_i64(other),
        }),
        "short" => Value::Int(cast_to_i64(&v) as i16 as i64),
        "byte" => Value::Int(cast_to_i64(&v) as i8 as i64),
        // A `char` is a 16-bit *unsigned* integral value, so `(char) -1` is
        // 65535 — the one narrowing cast that does not sign-extend.
        "char" => Value::Int(i64::from(cast_to_i64(&v) as u16)),
        // `(double)` only has to make an integral operand floating; `(float)`
        // additionally rounds to 32-bit precision, which is a real value change
        // (`(float) 0.1` is not `0.1`).
        "double" => Value::float(as_f64(&v)),
        "float" => Value::float(as_f64(&v) as f32 as f64),
        // `boolean` and every reference type keep their representation.
        _ => v,
    }
}

/// [`JCHR_STR`] — Java's string conversion of a `char` code point. An integer
/// becomes the one-character String; a `char[]` converts element-wise (a fresh
/// array, so the operand is not mutated); anything else passes through, which
/// keeps the builtin safe to emit on a statically-`char` expression whose value
/// turned out to be `null`.
fn b_chr_str(vm: &mut VM, _argc: u8) -> Value {
    let v = vm.stack.pop().unwrap_or(Value::Undef);
    match &v {
        Value::Obj(_) => match array_items(&v) {
            Some(items) => Value::Obj(heap_alloc(HostObj::Array(
                items.iter().map(char_to_string).collect(),
            ))),
            None => v,
        },
        _ => char_to_string(&v),
    }
}

/// One `char` code point as its one-character String. A non-integer passes
/// through, so a `null` (or an already-boxed `Character`) is left alone.
fn char_to_string(v: &Value) -> Value {
    match v {
        Value::Int(n) => Value::str(char::from_u32(*n as u32).unwrap_or('\u{fffd}').to_string()),
        other => other.clone(),
    }
}

/// [`JF32`] — round to 32-bit `float` precision.
fn b_f32(vm: &mut VM, _argc: u8) -> Value {
    let v = vm.stack.pop().unwrap_or(Value::Undef);
    match &v {
        Value::Float(f) => Value::float(*f as f32 as f64),
        Value::Int(n) => Value::float(*n as f32 as f64),
        _ => v,
    }
}

/// [`JF32_ARITH`] — one arithmetic operation at 32-bit width.
fn b_f32_arith(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let a = args.first().map(JavaNumeric::jfloat).unwrap_or(0.0) as f32;
    let b = args.get(1).map(JavaNumeric::jfloat).unwrap_or(0.0) as f32;
    let r = match args.get(2).map(JavaNumeric::jint).unwrap_or(f32_op::ADD) {
        f32_op::SUB => a - b,
        f32_op::MUL => a * b,
        f32_op::DIV => a / b,
        f32_op::REM => a % b,
        _ => a + b,
    };
    Value::float(r as f64)
}

/// [`JF32_ROUND`] — `Math.round(float)`, answering an `int`.
fn b_f32_round(vm: &mut VM, _argc: u8) -> Value {
    let v = vm.stack.pop().unwrap_or(Value::Undef);
    Value::Int(round_float(v.jfloat() as f32).into())
}

/// [`JF32_STR`] — `Float.toString`, or element-wise over a `float[]`.
fn b_f32_str(vm: &mut VM, _argc: u8) -> Value {
    let v = vm.stack.pop().unwrap_or(Value::Undef);
    // A boxed `Float` is rendered from the primitive it wraps; without this the
    // `Value::Obj` arm below would see a handle that is not an array and hand
    // the box straight back, which renders through `Double`'s rules instead.
    let v = unboxed(&v).unwrap_or(v);
    match &v {
        Value::Obj(_) => match array_items(&v) {
            Some(items) => Value::Obj(heap_alloc(HostObj::Array(
                items.iter().map(float_to_string).collect(),
            ))),
            None => v,
        },
        _ => float_to_string(&v),
    }
}

/// One `float` rendered the way `Float.toString` does. A non-floating value
/// passes through, so the builtin is safe on a statically-`float` expression
/// whose value turned out to be `null`.
fn float_to_string(v: &Value) -> Value {
    match v {
        Value::Float(f) => Value::str(format_float(*f as f32)),
        other => other.clone(),
    }
}

/// [`JCHECKCAST`] — the reference cast's runtime check.
///
/// The value's class comes from [`value_class`] — the same answer `instanceof`
/// reads. This path used to keep its own, narrower copy of that question, which
/// named only a `String`, a boxed primitive and a user instance and returned
/// `None` for every collection and array. The two then disagreed: `aList
/// instanceof String` was `false` while `(String) aList` passed, though a
/// program can only observe one runtime class per value.
fn b_checkcast(vm: &mut VM, argc: u8) -> Value {
    let args = pop_args(vm, argc);
    let value = args.first().cloned().unwrap_or(Value::Undef);
    let target = args
        .get(1)
        .map(|v| v.as_str_cow().into_owned())
        .unwrap_or_default();
    // `(Anything) null` succeeds in Java, and a lambda carries no interface to
    // check against — the two shapes [`value_class`] does not name.
    let Some(runtime) = value_class(&value) else {
        return value;
    };
    if cast_allowed(&runtime, &target, &value) {
        return value;
    }
    // The cast does not fit — but javars reports only a failure it can *name*.
    // An array's element type is erased, so `[I` and `[Ljava.lang.String;` are
    // both unavailable, and a `ClassCastException` whose message had to invent
    // the class it names would be worse than the miss.
    let Some(from) = binary_name(&runtime, &value) else {
        return value;
    };
    raise(
        vm,
        Fault::java("ClassCastException", cast_message(&from, &target)),
    );
    Value::Undef
}

/// The binary name `getClass().getName()` reports for a value whose class is
/// `class`, or `None` when javars cannot produce the JDK's exactly.
///
/// Most shapes are a straight qualification. The four that are not are the
/// collections the JDK implements with a private class whose identity depends
/// on the value rather than on its kind, each measured against the reference
/// JDK rather than inferred:
///
///   * `List.of` is `ImmutableCollections$List12` at one or two elements and
///     `$ListN` otherwise — including at zero, which is a `ListN`.
///   * `Set.of` splits the same way between `$Set12` and `$SetN`.
///   * `Arrays.asList` is `Arrays$ArrayList`, whatever its length.
///   * a `subList` is named for the *root* list it is a window onto, not for
///     itself: `ArrayList$SubList` over a mutable list,
///     `AbstractList$RandomAccessSubList` over `Arrays.asList`, and
///     `ImmutableCollections$SubList` over `List.of`. A view of a view keeps
///     the root's answer.
///
/// An array is the one shape with no answer at all: its element type is gone,
/// and `[I` and `[Ljava.lang.String;` differ only by it.
fn binary_name(class: &str, v: &Value) -> Option<String> {
    let len = || sequence_len(v).unwrap_or(0);
    Some(match class {
        "[]" => return None,
        "List$fixed" => "java.util.Arrays$ArrayList".to_string(),
        "List$immutable" => match len() {
            1 | 2 => "java.util.ImmutableCollections$List12".to_string(),
            _ => "java.util.ImmutableCollections$ListN".to_string(),
        },
        "Set$immutable" => match len() {
            1 | 2 => "java.util.ImmutableCollections$Set12".to_string(),
            _ => "java.util.ImmutableCollections$SetN".to_string(),
        },
        // The JDK's map factory has a one-entry specialization and nothing
        // between it and the general one, so `Map.of()` — with no entries at
        // all — is a `MapN` too.
        "Map$immutable" => match len() {
            1 => "java.util.ImmutableCollections$Map1".to_string(),
            _ => "java.util.ImmutableCollections$MapN".to_string(),
        },
        "List$sub" => match sublist_root_fixity(v) {
            Some(Fixity::Mutable) => "java.util.ArrayList$SubList".to_string(),
            Some(Fixity::FixedSize) => "java.util.AbstractList$RandomAccessSubList".to_string(),
            Some(Fixity::Immutable) => "java.util.ImmutableCollections$SubList".to_string(),
            None => return None,
        },
        other => crate::prelude::qualified_throwable(other).unwrap_or_else(|| jdk_name(other)),
    })
}

/// The element count of a list or set value, for the factories whose JDK class
/// depends on it.
fn sequence_len(v: &Value) -> Option<usize> {
    let Value::Obj(id) = v else { return None };
    HEAP.with(|h| match h.borrow().get(*id as usize) {
        Some(HostObj::List { items, .. }) | Some(HostObj::Set { items, .. }) => Some(items.len()),
        // A map's size is its entry count. It is here because the JDK names its
        // immutable map classes by size the way it names the list and set ones,
        // and `binary_name` asks all three the same question.
        Some(HostObj::Map { entries, .. }) => Some(entries.len()),
        _ => None,
    })
}

/// The [`Fixity`] of the list at the root of a `subList` chain — a view of a
/// view is named for the list that actually owns the elements.
fn sublist_root_fixity(v: &Value) -> Option<Fixity> {
    let Value::Obj(id) = v else { return None };
    HEAP.with(|h| {
        let h = h.borrow();
        let mut cur = *id as usize;
        // The chain is finite (a view is created from an existing list), but
        // bound the walk anyway rather than trusting the heap not to cycle.
        for _ in 0..64 {
            match h.get(cur) {
                Some(HostObj::SubList { parent, .. }) => cur = *parent as usize,
                Some(HostObj::List { fixed, .. }) => return Some(*fixed),
                _ => return None,
            }
        }
        None
    })
}

/// Whether a value of runtime class `runtime` may be cast to `target`.
///
/// A user class walks the same supertype graph `instanceof` does. The
/// `java.lang` types are decided from the value model, which is why the
/// *integral* wrappers all answer yes to each other: `int`, `long`, `short`,
/// `byte` are one `Value::Int` here, so javars cannot prove a cast between them
/// wrong and does not pretend to. It can prove `(String) anInteger` wrong, and
/// that is the cast programs actually write.
fn cast_allowed(runtime: &str, target: &str, value: &Value) -> bool {
    if target == "Object" || runtime == target {
        return true;
    }
    // The exact supertype graph — the same one `instanceof` walks, so the two
    // cannot drift into disagreeing about what a type extends.
    if is_subclass_of(runtime, target) {
        return true;
    }
    // On top of it, and only here, the sibling types the value model cannot
    // tell apart: `int`/`long`/`short`/`byte` are one `Value::Int`, a `double`
    // and a `float` one `Value::Float`, and a boxed `Character` is the
    // one-character String javars models it as. A cast between any of these
    // cannot be proven wrong, so it is allowed rather than invented as a
    // failure. `instanceof` deliberately does NOT share this leniency: it has
    // to answer a boolean, and Java's answer for `42 instanceof Long` is
    // `false`.
    match runtime {
        "Integer" => matches!(target, "Long" | "Short" | "Byte" | "Character"),
        "Double" => target == "Float",
        "String" => target == "Character" && value.as_str_cow().chars().count() == 1,
        // `new LinkedList<>()` is modeled as the mutable list an `ArrayList` is,
        // so a `LinkedList` value arrives here calling itself an `ArrayList`.
        // Refusing `(LinkedList) aLinkedList` would be inventing a failure out
        // of javars's own modelling choice, which is exactly what the wrapper
        // arms above avoid.
        "ArrayList" => target == "LinkedList",
        _ => false,
    }
}

/// Java's `ClassCastException` detail message.
///
/// The leading `class X cannot be cast to class Y` is exact. Java appends a
/// parenthetical naming each class's module and class loader, which is
/// reproducible only when both are JDK types — for a user class the launcher's
/// loader is identified by an identity hash javars has no counterpart for — so
/// that clause is emitted for the JDK pair and dropped otherwise, the same
/// bounded omission `NullPointerException`'s provenance clause already makes.
fn cast_message(from: &str, target: &str) -> String {
    let qual = |n: &str| crate::prelude::qualified_throwable(n).unwrap_or_else(|| jdk_name(n));
    // `from` arrives already resolved by [`binary_name`], which is the only
    // side that can depend on the *value* rather than on the class name.
    let (r, t) = (from.to_string(), qual(target));
    let head = format!("class {r} cannot be cast to class {t}");
    if r.starts_with("java.") && t.starts_with("java.") {
        format!("{head} ({r} and {t} are in module java.base of loader 'bootstrap')")
    } else {
        head
    }
}

/// Whether a reference cast to `ty` is one javars can decide.
///
/// This is the *target* half of the same question `value_class` answers for a
/// value, and it lives here so the two halves read one list. The compiler asks
/// it before emitting a [`JCHECKCAST`] at all: a name that is neither a
/// declared class nor one of these is a type javars does not model — a type
/// *variable* after erasure, an array type, a JDK class it has never heard of —
/// and a check it cannot decide must not invent a failure.
///
/// `Object` is deliberately absent: every value satisfies it, so a check would
/// only cost ops. Every other name here appears in `jdk_supers`, is produced
/// by `value_class`, or is one of the wrapper siblings `cast_allowed`
/// answers for — which `castable_targets_are_closed_over_the_supertype_graph`
/// asserts, so this list cannot fall behind the graph.
pub fn is_checkable_cast_target(ty: &str) -> bool {
    CHECKABLE_CAST_TARGETS.contains(&ty)
}

/// The list [`is_checkable_cast_target`] answers from. A slice rather than a
/// `matches!` so the closure test can walk it.
const CHECKABLE_CAST_TARGETS: &[&str] = &[
    // java.lang, and the wrapper siblings `cast_allowed` decides by leniency.
    "String",
    "Integer",
    "Long",
    "Short",
    "Byte",
    "Double",
    "Float",
    "Boolean",
    "Character",
    "Number",
    "CharSequence",
    "Comparable",
    "Cloneable",
    "Iterable",
    "Enum",
    "Record",
    // java.io
    "Serializable",
    // java.util — the concrete kinds, then the interfaces above them.
    "List",
    "ArrayList",
    "LinkedList",
    "Collection",
    "SequencedCollection",
    "AbstractCollection",
    "AbstractList",
    "RandomAccess",
    "Set",
    "HashSet",
    "LinkedHashSet",
    "TreeSet",
    "SortedSet",
    "NavigableSet",
    "SequencedSet",
    "AbstractSet",
    "Map",
    "HashMap",
    "LinkedHashMap",
    "TreeMap",
    "SortedMap",
    "NavigableMap",
    "SequencedMap",
    "AbstractMap",
];

/// The qualified name of a modeled JDK type, or the bare name of a user class.
///
/// The package is part of the `ClassCastException` message and of the
/// module-and-loader clause that follows it, so a `java.util` type named as
/// though it were unpackaged would produce a message that is wrong in two
/// places at once.
fn jdk_name(n: &str) -> String {
    match n {
        "String"
        | "Integer"
        | "Long"
        | "Short"
        | "Byte"
        | "Double"
        | "Float"
        | "Boolean"
        | "Character"
        | "Number"
        | "CharSequence"
        | "Comparable"
        | "Cloneable"
        | "Iterable"
        | "Enum"
        | "Record"
        | "Object"
        | "StringBuilder"
        | "StringBuffer"
        | "AbstractStringBuilder"
        | "Appendable" => {
            format!("java.lang.{n}")
        }
        "Serializable" => "java.io.Serializable".to_string(),
        "List"
        | "ArrayList"
        | "LinkedList"
        | "Set"
        | "HashSet"
        | "LinkedHashSet"
        | "TreeSet"
        | "SortedSet"
        | "NavigableSet"
        | "SequencedSet"
        | "SequencedCollection"
        | "Collection"
        | "Map"
        | "HashMap"
        | "LinkedHashMap"
        | "TreeMap"
        | "SortedMap"
        | "NavigableMap"
        | "SequencedMap"
        | "AbstractCollection"
        | "AbstractList"
        | "AbstractSet"
        | "AbstractMap"
        | "RandomAccess" => format!("java.util.{n}"),
        // Not a modeled JDK type, so it is a user class: Java names a nested one
        // `Outer$Nested`, which is what [`qualified_or_binary`] recovers.
        other => qualified_or_binary(other),
    }
}

/// The 64-bit value a narrowing integral cast starts from: a floating operand
/// truncates toward zero first, and a `char` (a one-character string) yields its
/// code point.
fn cast_to_i64(v: &Value) -> i64 {
    match unboxed(v).as_ref().unwrap_or(v) {
        Value::Float(f) => *f as i64,
        other => as_i64(other),
    }
}

/// Coerce a value to `i64`. A one-character string is a `char`, and its code
/// point is its numeric value — `(int) 'a'` is 97.
fn as_i64(v: &Value) -> i64 {
    // A wrapper is its primitive everywhere a number is wanted; the box exists
    // for `==`, `equals`, `hashCode` and `getClass` and nothing else.
    if let Some(inner) = unboxed(v) {
        return as_i64(&inner);
    }
    match v {
        Value::Int(i) => *i,
        Value::Float(f) => *f as i64,
        Value::Bool(b) => i64::from(*b),
        other => {
            let s = other.as_str_cow();
            let mut chars = s.chars();
            match (chars.next(), chars.next()) {
                (Some(c), None) => c as i64,
                _ => s.parse::<i64>().unwrap_or(0),
            }
        }
    }
}

/// Coerce a value to `f64` for the floating division path.
fn as_f64(v: &Value) -> f64 {
    if let Some(inner) = unboxed(v) {
        return as_f64(&inner);
    }
    match v {
        Value::Int(i) => *i as f64,
        Value::Float(f) => *f,
        Value::Bool(b) => {
            if *b {
                1.0
            } else {
                0.0
            }
        }
        other => other.as_str_cow().parse::<f64>().unwrap_or(f64::NAN),
    }
}

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

    /// Every supertype reachable from a checkable target is itself checkable.
    ///
    /// The cast walks [`is_subclass_of`], which climbs [`jdk_supers`] one edge
    /// at a time. If a name on that graph were missing from
    /// [`CHECKABLE_CAST_TARGETS`], the compiler would decline to emit the check
    /// at all for that target and the cast would silently pass — the exact
    /// shape of the gap this list replaced. Walking the closure means the list
    /// cannot fall behind the graph as `jdk_supers` grows.
    #[test]
    fn castable_targets_are_closed_over_the_supertype_graph() {
        let mut missing = Vec::new();
        for t in CHECKABLE_CAST_TARGETS {
            for sup in jdk_supers(t) {
                if !is_checkable_cast_target(sup) {
                    missing.push(format!("{t} -> {sup}"));
                }
            }
        }
        assert!(
            missing.is_empty(),
            "supertypes reachable from a checkable target but not checkable \
             themselves (the cast would decline to check them):\n  {}",
            missing.join("\n  ")
        );
    }

    /// The internal names exist so a shape can carry supertypes without a user
    /// type being able to name one. A program cannot write them, so they must
    /// NOT be castable targets — but they must still carry a supertype line,
    /// or the value wearing one would reach nothing.
    #[test]
    fn the_internal_shape_names_are_unwritable_but_still_carry_supertypes() {
        for internal in [
            "[]",
            "List$immutable",
            "List$fixed",
            "List$sub",
            "Set$immutable",
            "Map$immutable",
            "Iterator$of",
            "Stream$of",
            "Collector$of",
        ] {
            assert!(
                !is_checkable_cast_target(internal),
                "`{internal}` is not a legal Java type name and must not be a cast target"
            );
            assert!(
                !jdk_supers(internal).is_empty(),
                "`{internal}` carries no supertypes, so a value wearing it reaches nothing"
            );
        }
    }

    /// `Object` is deliberately absent: every value satisfies it, so emitting a
    /// check would only cost ops.
    #[test]
    fn object_is_not_a_checkable_target() {
        assert!(!is_checkable_cast_target("Object"));
    }
}