javars 0.1.14

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
//! Differential parity fuzzer: reference `java <file>` vs our `java <file>`.
//!
//! Generates grammar-driven, deterministic-output Java programs, runs each
//! through a real JDK and through this frontend, and reports every case whose
//! stdout OR success/failure diverges. Each program is produced from a per-index
//! seed so any divergence replays exactly: `parity-fuzz --seed <N> --once`.
//!
//! The reference JDK pays a multi-second compile+JVM cost per invocation (it
//! compiles the single file in memory before running it), so every program packs
//! many independent probe statements (`--probes`, default 40) into one `main`; a
//! single invocation therefore exercises dozens of probes. On divergence,
//! [`minimize`] bisects the probe list down to the single offending probe before
//! reporting.
//!
//! The generator is biased toward the historically weak areas of a from-scratch
//! Java frontend: `int`-vs-`double` division dispatch (`7/2==3`, `7/2.0==3.5`),
//! `+` string-concatenation coercion, `Double.toString` notation (the
//! decimal/scientific threshold), `String.format`, the `String` instance methods,
//! `Math` overload result typing, the runtime faults javars raises itself
//! (`fault`), the cleanup blocks a jump has to run (`finally`),
//! try-with-resources close ordering (`resource`), `enum` identity, ordering,
//! per-constant state and constant bodies (`enum`), class-level `static` field
//! storage and initialization order (`static`), the members a `record` derives
//! from its components (`record`), and the two-sided `char` boundary where an
//! integral code point has to do arithmetic *and* render as a character
//! (`char`), the declaration statement that declares several variables at once
//! and the C-style array suffix that binds to one of them (`decl`), and the
//! identity `java.lang.Object` supplies to a lock, a sentinel, and a map key
//! (`object`). Pure random bytes only produce
//! mutual parse errors that agree on both sides and teach nothing.
//!
//! Five modes exist specifically because a *shape* the rest of the generator
//! could not emit hid a wrong answer behind an otherwise clean sweep:
//!   * `super` — the qualified `super.method(args)` / `super.field`. Not one
//!     probe in the generator wrote `super.` before this mode existed, so the
//!     whole form was unreachable: it reached the runtime as a call on a null
//!     receiver and every sweep was clean anyway. Its support chain declares the
//!     same method at three levels, so a `super` that dispatched virtually would
//!     recurse rather than answer.
//!   * `staticref` — a **qualified** `C.m(…)` where a second, unrelated class
//!     also declares `m`. With one static name per program, a resolver that
//!     ignores the receiver is indistinguishable from a correct one; with two,
//!     it runs the wrong body.
//!   * `loopkind` — `continue`/`break` in a `while` and a `do`/`while`, labelled
//!     and unlabelled, nested, through a `switch`, and through a `finally`.
//!     `continue` lowers differently in each of Java's three loops; the older
//!     probes emitted only the `for` one.
//!   * `narrow` — `byte` and `short`, the two integral widths no probe declared,
//!     and the implicit narrowing cast Java inserts into their compound
//!     assignments.
//!   * `listop` — the methods whose *meaning* depends on an argument's static
//!     type, above all `List.remove`, which is an index for an `int` and a value
//!     for an `Integer`. A mode that only *builds* collections cannot see it.
//!
//! The generators added in the second round (class initialization order,
//! conditional promotion, `String.format` flag products, hash iteration order,
//! fail-fast iteration, and the rest) live in the `round2` module next to this
//! file; `--help` lists every mode.
//!
//! Scope + determinism invariants (mirroring the scalars/node-js harnesses):
//!   * Only constructs javars actually implements are emitted — an unsupported
//!     construct would be a known gap, not a parity signal.
//!   * No nondeterministic output (no `Random`, no `currentTimeMillis`, no
//!     unordered collections). Every probe's output is a pure function of its
//!     source. An identity hash is never *printed* — Java's differs between runs
//!     of the same program — only the properties that do hold across runs
//!     (`o.hashCode() == o.hashCode()`, the `java.lang.Object@` prefix).
//!   * Documented `BUGS.md` simplifications are NOT generated, because they would
//!     only reproduce known entries rather than find anything:
//!       - `NullPointerException` detail messages (Java's helpful NPE names the
//!         javac local slot, which javars cannot reproduce — the `fault` mode
//!         raises every *other* runtime fault and prints its message),
//!       - widening *value* conversion (`double d = 7;` printing `7` not `7.0`),
//!       - `==` where javars compares by value and Java by reference: two
//!         `String`s, and two boxed `Character`s (which javars models as
//!         one-character `String`s). Reference `==` between *instances* is not
//!         a simplification — it is exact, and the `object` mode asserts it,
//!       - `int` arithmetic whose operand types are not statically known (the
//!         `overflow` mode uses only statically `int`-typed operands, which is
//!         exactly the subset javars wraps).
//!
//! Subprocess-only: this binary never links the javars library — it compares two
//! `java` processes, exactly as a user would observe them.
//!
//! Build:  cargo build --bin parity-fuzz
//! Run:    ./target/debug/parity-fuzz --iters 200
//!         ./target/debug/parity-fuzz --seed 12345 --once
//!         ./target/debug/parity-fuzz --mode concat --iters 50

// Every probe generator is a table of `match` arms, each one program source.
// Most arms interpolate the case's seeded operands; the handful that happen to
// need none are still written `format!` so the table reads as one shape and an
// arm can gain an operand without being respelled.
#![allow(clippy::useless_format)]

#[path = "parity_fuzz/round2.rs"]
mod round2;

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Mutex;
use std::time::Duration;

/// xorshift64*, seeded per program index so any case replays from its seed.
struct Rng(u64);

impl Rng {
    fn new(seed: u64) -> Self {
        Rng(if seed == 0 { 0x9E3779B97F4A7C15 } else { seed })
    }
    fn next(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        self.0 = x;
        x.wrapping_mul(0x2545F4914F6CDD1D)
    }
    fn below(&mut self, n: usize) -> usize {
        (self.next() % n as u64) as usize
    }
}

fn pick<'a, T>(rng: &mut Rng, xs: &'a [T]) -> &'a T {
    &xs[rng.below(xs.len())]
}

// Operand pools. These integers stay well inside `int` range so the general
// modes test arithmetic rather than wrapping; 32-bit overflow has its own
// `overflow` mode with its own operand pool.
const INTS: &[&str] = &[
    "0", "1", "2", "3", "7", "10", "42", "100", "-1", "-7", "-42",
];
const DIVS: &[&str] = &["1", "2", "3", "4", "5", "7", "-2", "-3"];
const DBLS: &[&str] = &[
    "0.0",
    "1.0",
    "0.5",
    "2.5",
    "3.14",
    "-1.5",
    "100.0",
    "1e3",
    "1e-3",
    "0.1",
    "1234567.0",
    "1.0e7",
    "1.0e-7",
    "123456789.0",
];
/// `char` literals for the `char` mode: letters at both cases, a digit, a
/// space, and `~` so the code points span the printable ASCII range.
const CHARS: &[&str] = &["a", "b", "z", "A", "Z", "0", "9", " ", "~"];
const STRS: &[&str] = &[
    "\"\"",
    "\"a\"",
    "\"abc\"",
    "\"Hello\"",
    "\" x \"",
    "\"AbC\"",
    "\"aXbXc\"",
];
const BOOLS: &[&str] = &["true", "false"];
const AOPS: &[&str] = &["+", "-", "*"];
const CMPOPS: &[&str] = &["==", "!=", "<", ">", "<=", ">="];
const LOGOPS: &[&str] = &["&&", "||"];

fn p(body: String) -> String {
    format!("System.out.println({body});")
}

/// Integer arithmetic on native ops.
fn g_arith(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, INTS);
    let c = pick(r, INTS);
    let o1 = pick(r, AOPS);
    let o2 = pick(r, AOPS);
    p(format!("({a} {o1} {b}) {o2} {c}"))
}

/// `int` division and modulo truncate toward zero; divisors are never 0.
fn g_intdiv(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, DIVS);
    let op = if r.below(2) == 0 { "/" } else { "%" };
    p(format!("{a} {op} {b}"))
}

/// `double` arithmetic — the other side of the `/` dispatch.
fn g_doublearith(r: &mut Rng) -> String {
    let a = pick(r, DBLS);
    let b = pick(r, DBLS);
    let op = pick(r, &["+", "-", "*", "/"]);
    p(format!("{a} {op} {b}"))
}

/// Mixed int/double: the operand that forces promotion.
fn g_mixeddiv(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, DBLS);
    if r.below(2) == 0 {
        p(format!("{a} / {b}"))
    } else {
        p(format!("{b} / {a}"))
    }
}

/// `Double.toString` notation — the decimal/scientific threshold.
fn g_doublefmt(r: &mut Rng) -> String {
    // Subnormals get their own share of the pool: the bottom of the exponent
    // range is where "shortest decimal that round-trips" and Java's actual
    // specification part company (its `p < 2` two-digit widening), and
    // `Double.MIN_VALUE * k` is the only way to spell one — a literal that small
    // is a `javac` error ("floating-point number too small").
    match r.below(8) {
        0 => p(format!("Double.MIN_VALUE * {}L", r.below(64) + 1)),
        1 => p("Double.MIN_VALUE".to_string()),
        2 => p("Double.MIN_NORMAL".to_string()),
        _ => p((*pick(r, DBLS)).to_string()),
    }
}

/// `+` string concatenation and its coercion rules.
fn g_concat(r: &mut Rng) -> String {
    let s = pick(r, STRS);
    match r.below(4) {
        0 => p(format!("{s} + {}", pick(r, INTS))),
        1 => p(format!("{s} + {}", pick(r, DBLS))),
        2 => p(format!("{s} + {}", pick(r, BOOLS))),
        _ => p(format!("{s} + {} + {}", pick(r, INTS), pick(r, STRS))),
    }
}

fn g_compare(r: &mut Rng) -> String {
    let op = pick(r, CMPOPS);
    if r.below(2) == 0 {
        p(format!("{} {op} {}", pick(r, INTS), pick(r, INTS)))
    } else {
        p(format!("{} {op} {}", pick(r, DBLS), pick(r, DBLS)))
    }
}

fn g_bool(r: &mut Rng) -> String {
    let op = pick(r, LOGOPS);
    p(format!(
        "({} < {}) {op} ({} > {})",
        pick(r, INTS),
        pick(r, INTS),
        pick(r, INTS),
        pick(r, INTS)
    ))
}

/// Ternary, with both branches the same static kind.
fn g_ternary(r: &mut Rng) -> String {
    p(format!(
        "({} < {}) ? {} : {}",
        pick(r, INTS),
        pick(r, INTS),
        pick(r, INTS),
        pick(r, INTS)
    ))
}

/// `String` instance methods on ASCII receivers (astral chars are a known gap).
fn g_strmethod(r: &mut Rng) -> String {
    let s = pick(r, STRS);
    match r.below(9) {
        0 => p(format!("{s}.length()")),
        1 => p(format!("{s}.isEmpty()")),
        2 => p(format!("{s}.toUpperCase()")),
        3 => p(format!("{s}.toLowerCase()")),
        4 => p(format!("{s}.trim()")),
        5 => p(format!("{s}.indexOf(\"b\")")),
        6 => p(format!("{s}.contains(\"b\")")),
        7 => p(format!("{s}.replace(\"X\", \"-\")")),
        _ => p(format!("{s}.concat(\"z\")")),
    }
}

/// `Math` statics — Java's int-vs-double overload result typing.
fn g_math(r: &mut Rng) -> String {
    match r.below(6) {
        0 => p(format!("Math.abs({})", pick(r, INTS))),
        1 => p(format!("Math.max({}, {})", pick(r, INTS), pick(r, INTS))),
        2 => p(format!("Math.min({}, {})", pick(r, DBLS), pick(r, DBLS))),
        3 => p(format!("Math.floor({})", pick(r, DBLS))),
        4 => p(format!("Math.ceil({})", pick(r, DBLS))),
        _ => p(format!(
            "Math.sqrt({})",
            pick(r, &["0.0", "1.0", "2.0", "9.0", "16.0"])
        )),
    }
}

/// `String.format` — the `Formatter` subset javars implements.
fn g_format(r: &mut Rng) -> String {
    let f = pick(r, FLTS);
    match r.below(11) {
        0 => p(format!("String.format(\"%d\", {})", pick(r, INTS))),
        1 => p(format!("String.format(\"%s\", {})", pick(r, STRS))),
        2 => p(format!("String.format(\"%5d|\", {})", pick(r, INTS))),
        3 => p(format!("String.format(\"%-5d|\", {})", pick(r, INTS))),
        4 => p(format!(
            "String.format(\"%x\", Math.abs({}))",
            pick(r, INTS)
        )),
        // A `float` argument splits by conversion: `%s` wants `Float.toString`,
        // every numeric conversion wants the widened `double`. Both spellings
        // have to be generated or the split is only half tested.
        5 => p(format!("String.format(\"%s\", {f} / 3.0f)")),
        6 => p(format!("String.format(\"%f\", {f} / 3.0f)")),
        7 => p(format!("String.format(\"%.9f\", {f} / 3.0f)")),
        8 => p(format!("String.format(\"%e|%s\", {f} / 3.0f, {f} / 3.0f)")),
        9 => p(format!("String.format(\"%2$s|%1$.4f\", {f}, {f} / 7.0f)")),
        _ => p(format!("String.format(\"%b %s %d%%\", true, {f}, 3)")),
    }
}

/// `Integer` statics.
fn g_integer(r: &mut Rng) -> String {
    match r.below(3) {
        0 => p(format!(
            "Integer.parseInt(\"{}\")",
            pick(r, &["0", "7", "-42", "100"])
        )),
        1 => p(format!("Integer.toString({})", pick(r, INTS))),
        _ => p(format!("Integer.valueOf({})", pick(r, INTS))),
    }
}

/// A counted loop with an accumulator — exercises the loop lowering and the
/// backpatched `break`/`continue` edges.
fn g_loop(r: &mut Rng) -> String {
    let n = 2 + r.below(5);
    let step = pick(r, &["1", "2", "3"]);
    format!(
        "{{ int acc = 0; for (int i = 0; i < {n}; i++) {{ if (i == 1) {{ continue; }} acc += i * {step}; }} System.out.println(acc); }}"
    )
}

/// `switch` with fall-through and a default.
fn g_switch(r: &mut Rng) -> String {
    let v = r.below(4);
    format!(
        "{{ int s = {v}; switch (s) {{ case 0: System.out.println(\"zero\"); break; case 1: case 2: System.out.println(\"small\"); break; default: System.out.println(\"other\"); }} }}"
    )
}

/// A one-dimensional array: literal, index, mutate, `.length`.
fn g_array(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, INTS);
    format!(
        "{{ int[] arr = {{{a}, {b}, 5}}; arr[1] += 2; System.out.println(arr[0] + \",\" + arr[1] + \",\" + arr.length); }}"
    )
}

/// 32-bit `int` overflow. Every operand is statically `int`-typed (a literal, an
/// `int` local, an `int` parameter, an `int[]` element, an `int` field) — the
/// shape javars models — so a divergence here is a real wrap bug and not the
/// documented "operand type not statically known" gap.
fn g_overflow(r: &mut Rng) -> String {
    let big = pick(
        r,
        &[
            "2147483647",
            "-2147483648",
            "2000000000",
            "1103515245",
            "65536",
            "100000",
            "46341",
        ],
    );
    let k = pick(r, &["2", "3", "31", "-1", "1103515245", "100000"]);
    match r.below(7) {
        0 => p(format!("{big} * {k}")),
        1 => p(format!("{big} + {big}")),
        2 => format!("{{ int ov = {big}; ov *= {k}; System.out.println(ov); }}"),
        3 => format!("{{ int ov = {big}; ov++; System.out.println(ov); }}"),
        4 => format!(
            "{{ int ov = 12345; for (int i = 0; i < 8; i++) {{ ov = ov * {k} + 7; }} System.out.println(ov); }}"
        ),
        5 => format!("{{ int[] ova = {{{big}}}; ova[0] *= {k}; System.out.println(ova[0]); }}"),
        // A `long` operand must NOT wrap — the other half of the rule.
        _ => format!("{{ long ovl = {big}; System.out.println(ovl * {k}); }}"),
    }
}

/// The enhanced `for` over an array — element rebinding, `.length` bound, and
/// the `break`/`continue` edges.
fn g_foreach(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, INTS);
    match r.below(3) {
        0 => format!(
            "{{ int[] fe = {{{a}, {b}, 5}}; int t = 0; for (int v : fe) {{ t += v; }} System.out.println(t); }}"
        ),
        1 => "{ String[] fs = {\"a\", \"bb\", \"ccc\"}; for (String v : fs) { System.out.print(v.length()); } System.out.println(); }"
            .to_string(),
        _ => format!(
            "{{ int[] fe = {{{a}, {b}, 5, 9}}; int t = 0; for (int v : fe) {{ if (v == 5) {{ continue; }} if (v == 9) {{ break; }} t += v; }} System.out.println(t); }}"
        ),
    }
}

/// `throw`/`catch`/`finally` — handler selection by class, propagation out of a
/// call, and the `finally` ordering.
fn g_exception(r: &mut Rng) -> String {
    let msg = pick(r, &["boom", "x", "bad input"]);
    match r.below(4) {
        0 => format!(
            "{{ try {{ throw new IllegalStateException(\"{msg}\"); }} catch (RuntimeException e) {{ System.out.println(e.getMessage()); }} }}"
        ),
        1 => format!(
            "{{ try {{ throw new NumberFormatException(\"{msg}\"); }} catch (IllegalStateException e) {{ System.out.println(\"wrong\"); }} catch (IllegalArgumentException e) {{ System.out.println(e); }} finally {{ System.out.println(\"fin\"); }} }}"
        ),
        2 => format!(
            "{{ int t = 0; for (int i = 0; i < 4; i++) {{ try {{ if (i % 2 == 0) {{ throw new RuntimeException(\"{msg}\"); }} t += i; }} catch (RuntimeException e) {{ t += 10; }} }} System.out.println(t); }}"
        ),
        _ => format!(
            "{{ try {{ try {{ throw new IllegalArgumentException(\"{msg}\"); }} finally {{ System.out.println(\"inner\"); }} }} catch (Exception e) {{ System.out.println(\"outer \" + e.getMessage()); }} }}"
        ),
    }
}

/// Catchable *runtime* faults — the ones javars raises itself rather than a
/// `throw`: an out-of-range array index, `Integer.parseInt` on junk, integral
/// `/ 0` and `% 0`, a negative array size, and the `String` index/argument
/// faults. Each probe both catches the fault and prints its `getMessage()`/
/// `toString()`, so a wrong exception *type* and a wrong detail message are
/// both divergences.
///
/// Divisors and indices come from computed values (`arr.length - 3`), never
/// literals, so the compile-time constant-divisor path cannot mask the check.
/// `NullPointerException` messages are deliberately not printed: Java's helpful
/// NPE names the javac local slot (`because "<local3>" is null`), which javars
/// cannot reproduce (see BUGS.md).
fn g_fault(r: &mut Rng) -> String {
    let catch_as = pick(
        r,
        &[
            "RuntimeException",
            "Exception",
            "Throwable",
            "IndexOutOfBoundsException",
        ],
    );
    match r.below(9) {
        0 => format!(
            "{{ int[] fa = {{1, 2, 3}}; int fi = fa.length + {}; try {{ System.out.println(fa[fi]); }} catch (ArrayIndexOutOfBoundsException e) {{ System.out.println(e.getMessage()); }} }}",
            pick(r, &["0", "2", "-7", "-4"])
        ),
        1 => format!(
            "{{ int[] fa = new int[2]; int fi = {}; try {{ fa[fi] = 1; }} catch (ArrayIndexOutOfBoundsException e) {{ System.out.println(e); }} System.out.println(fa[0]); }}",
            pick(r, &["2", "-1", "9"])
        ),
        2 => format!(
            "{{ try {{ System.out.println(Integer.parseInt(\"{}\")); }} catch (NumberFormatException e) {{ System.out.println(e.getMessage()); }} }}",
            pick(r, &["abc", "", " 7 ", "1x", "99999999999", "-", "+"])
        ),
        3 => format!(
            "{{ int fz = {} - {}; try {{ System.out.println(7 {} fz); }} catch (ArithmeticException e) {{ System.out.println(e); }} }}",
            pick(r, &["1", "3", "5"]),
            pick(r, &["1", "3", "5"]),
            if r.below(2) == 0 { "/" } else { "%" }
        ),
        4 => format!(
            "{{ int fn = {}; try {{ int[] fq = new int[fn]; System.out.println(fq.length); }} catch (NegativeArraySizeException e) {{ System.out.println(e.getMessage()); }} }}",
            pick(r, &["-1", "-9", "2"])
        ),
        5 => format!(
            "{{ String fs = \"abcd\"; int fi = {}; try {{ System.out.println(fs.charAt(fi)); }} catch (StringIndexOutOfBoundsException e) {{ System.out.println(e.getMessage()); }} }}",
            pick(r, &["1", "4", "-1", "9"])
        ),
        6 => format!(
            "{{ String fs = \"abcd\"; int fi = {}; try {{ System.out.println(fs.substring(fi, 3)); }} catch (StringIndexOutOfBoundsException e) {{ System.out.println(e.getMessage()); }} }}",
            pick(r, &["0", "5", "-2"])
        ),
        7 => format!(
            "{{ int fc = {}; try {{ System.out.println(\"ab\".repeat(fc)); }} catch (IllegalArgumentException e) {{ System.out.println(e.getMessage()); }} }}",
            pick(r, &["-1", "-3", "2"])
        ),
        // The fault must propagate out of a call frame and be catchable by any
        // supertype of its class.
        _ => format!(
            "{{ int[] fa = {{4, 5}}; try {{ System.out.println(fa[fa.length + 1] + Integer.parseInt(\"z\")); }} catch ({catch_as} e) {{ System.out.println(\"c:\" + e); }} }}"
        ),
    }
}

/// `finally` interaction with the jumps that leave it — `return`, `break`,
/// `continue`, labeled forms, nesting, and an exception raised inside a `catch`
/// arm (which must still run the cleanup on its way out).
fn g_finally(r: &mut Rng) -> String {
    match r.below(6) {
        0 => format!(
            "{{ int fv = {}; System.out.println(fv); }}",
            pick(
                r,
                &[
                    "fin1()",
                    "fin2()",
                    "fin3()"
                ]
            )
        ),
        1 => "{ int t = 0; for (int i = 0; i < 4; i++) { try { if (i == 2) { break; } t += i; } finally { System.out.println(\"b\" + i); } } System.out.println(t); }"
            .to_string(),
        2 => "{ int t = 0; for (int i = 0; i < 4; i++) { try { if (i % 2 == 0) { continue; } t += i; } finally { System.out.println(\"c\" + i); } } System.out.println(t); }"
            .to_string(),
        3 => "{ int t = 0; outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { try { if (j == 1) { continue outer; } if (i == 2) { break outer; } t++; } finally { System.out.println(\"l\" + i + j); } } } System.out.println(t); }"
            .to_string(),
        4 => format!(
            "{{ try {{ try {{ throw new IllegalStateException(\"a\"); }} catch (IllegalStateException e) {{ throw new RuntimeException(\"{}\"); }} finally {{ System.out.println(\"fin\"); }} }} catch (RuntimeException e) {{ System.out.println(\"out \" + e.getMessage()); }} }}",
            pick(r, &["b", "c"])
        ),
        _ => "{ try { try { int[] z = new int[1]; System.out.println(z[3]); } catch (NumberFormatException e) { System.out.println(\"no\"); } finally { System.out.println(\"fin2\"); } } catch (RuntimeException e) { System.out.println(\"out2 \" + e.getMessage()); } }"
            .to_string(),
    }
}

/// Try-with-resources: close order (reverse of declaration), closing before the
/// outer `catch`/`finally` runs, the exceptional path, a `return` out of the
/// block, and the Java 9 bare-name form.
fn g_resource(r: &mut Rng) -> String {
    match r.below(5) {
        0 => "{ try (Res a = new Res(\"a\")) { System.out.println(\"body\"); } }".to_string(),
        1 => "{ try (Res a = new Res(\"a\"); Res b = new Res(\"b\")) { System.out.println(\"body\"); } }"
            .to_string(),
        2 => format!(
            "{{ try (Res a = new Res(\"a\"); Res b = new Res(\"b\")) {{ throw new IllegalStateException(\"{}\"); }} catch (IllegalStateException e) {{ System.out.println(\"c \" + e.getMessage()); }} finally {{ System.out.println(\"fin\"); }} }}",
            pick(r, &["x", "y"])
        ),
        3 => "{ try (Res a = new Res(\"a\")) { int[] q = {1}; System.out.println(q[4]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); } }"
            .to_string(),
        _ => "{ Res h = new Res(\"h\"); try (h) { System.out.println(\"body\"); } System.out.println(resret()); }"
            .to_string(),
    }
}

/// `enum` types: constant identity, `name()`/`ordinal()`/`toString()`,
/// `values()` order, `valueOf` (including its `IllegalArgumentException`),
/// `switch` on an unqualified constant, an enum-typed parameter/return, and an
/// enum with a body of its own.
fn g_enum(r: &mut Rng) -> String {
    let c = pick(r, &["RED", "GREEN", "BLUE"]);
    match r.below(10) {
        0 => format!(
            "{{ Color e = Color.{c}; System.out.println(e + \",\" + e.name() + \",\" + e.ordinal()); }}"
        ),
        1 => format!(
            "{{ Color e = Color.{c}; System.out.println((e == Color.{}) + \",\" + e.equals(Color.{})); }}",
            pick(r, &["RED", "BLUE"]),
            pick(r, &["GREEN", "RED"])
        ),
        2 => "{ for (Color e : Color.values()) { System.out.print(e + \":\" + e.ordinal() + \" \"); } System.out.println(Color.values().length); }"
            .to_string(),
        3 => format!(
            "{{ try {{ System.out.println(Color.valueOf(\"{}\")); }} catch (IllegalArgumentException x) {{ System.out.println(x.getMessage()); }} }}",
            pick(r, &["RED", "BLUE", "PINK", "red", ""])
        ),
        4 => format!(
            "{{ Color e = Color.{c}; switch (e) {{ case RED: System.out.println(\"r\"); break; case GREEN: System.out.println(\"g\"); break; default: System.out.println(\"d\"); }} }}"
        ),
        5 => format!("{{ System.out.println(shout(Color.{c}) + \" \" + next(Color.{c})); }}"),
        6 => format!(
            "{{ Op o = Op.{}; System.out.println(o.apply({}, {}) + \" \" + o.isMul() + \" \" + o); }}",
            pick(r, &["ADD", "SUB", "MUL"]),
            pick(r, INTS),
            pick(r, DIVS)
        ),
        // A constant carrying constructor arguments — per-constant state.
        7 => format!(
            "{{ Planet pl = Planet.{}; System.out.println(pl + \",\" + pl.mass() + \",\" + pl.heavy() + \",\" + pl.ordinal()); }}",
            pick(r, &["MERCURY", "EARTH", "JUPITER"])
        ),
        8 => "{ for (Planet pl : Planet.values()) { System.out.print(pl.mass() + \" \"); } System.out.println(); }"
            .to_string(),
        // A constant with a *body* — an anonymous subclass whose override the
        // enum's own abstract method dispatches to.
        _ => format!(
            "{{ Ops o = Ops.{}; System.out.println(o.apply({}, {}) + \",\" + o.label() + \",\" + o); }}",
            pick(r, &["PLUS", "MINUS", "TIMES"]),
            pick(r, INTS),
            pick(r, DIVS)
        ),
    }
}

/// `static` fields: class-level storage that outlives every instance, reached
/// both qualified (`St.n`) and through an inheriting class (`Sub2.n`), plus the
/// `static { … }` block and static-field initializers that seed it before
/// `main` runs. Every probe assigns before it reads, so a probe's output does
/// not depend on which other probes ran first.
fn g_static(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    match r.below(6) {
        0 => format!("{{ St.n = {a}; System.out.println(St.n + \",\" + St.get()); }}"),
        1 => format!("{{ St.n = {a}; St.bump(); St.n += 3; System.out.println(St.n); }}"),
        2 => "{ System.out.println(St.LABEL + St.SIZE + \",\" + St.INIT); }".to_string(),
        3 => format!("{{ St.n = {a}; System.out.println(St.n / 2 + \",\" + St.n % 3); }}"),
        4 => format!(
            "{{ St.arr[1] = {a}; System.out.println(St.arr[0] + \",\" + St.arr[1] + \",\" + St.arr.length); }}"
        ),
        _ => format!("{{ St.n = {a}; St.n++; System.out.println(St.n + \",\" + Sub2.n); }}"),
    }
}

/// `record` types: the derived accessors, `toString`, component-wise `equals`,
/// a compact constructor's validation, and a user-declared extra method.
fn g_record(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, INTS);
    match r.below(6) {
        0 => format!("{{ System.out.println(new Pt({a}, {b})); }}"),
        1 => format!(
            "{{ Pt p = new Pt({a}, {b}); System.out.println(p.x() + \",\" + p.y() + \",\" + p.sum()); }}"
        ),
        2 => format!(
            "{{ System.out.println(new Pt({a}, {b}).equals(new Pt({a}, {b})) + \",\" + new Pt({a}, {b}).equals(new Pt({b}, {a}))); }}"
        ),
        3 => format!(
            "{{ Tag t = new Tag({}, {}); System.out.println(t + \" \" + t.tag().length()); }}",
            pick(r, STRS),
            pick(r, DBLS)
        ),
        4 => format!(
            "{{ Pt[] ps = {{ new Pt({a}, {b}), new Pt(0, 0) }}; for (Pt q : ps) {{ System.out.print(q + \";\"); }} System.out.println(); }}"
        ),
        _ => format!(
            "{{ try {{ System.out.println(new Ord({a}, {b})); }} catch (IllegalArgumentException e) {{ System.out.println(\"bad \" + e.getMessage()); }} }}"
        ),
    }
}

/// Lambdas and functional interfaces: an expression and a block body, a
/// captured effectively-final local, a lambda passed as an argument, one
/// returned from a method (so it outlives the frame that built it), the target
/// interface's declared `int` parameters driving `/` truncation and the 32-bit
/// wrap inside the body, and the three method-reference shapes. A lambda's own
/// `toString` is a JVM identity hash, so no probe ever prints one.
fn g_lambda(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, INTS);
    let d = pick(r, DIVS);
    let s = pick(r, STRS);
    let op = pick(r, AOPS);
    match r.below(11) {
        0 => format!("{{ Calc c = (x, y) -> x {op} y; System.out.println(c.of({a}, {b})); }}"),
        1 => format!("{{ Calc c = (x, y) -> {{ return x {op} y; }}; System.out.println(c.of({a}, {b})); }}"),
        2 => format!("{{ Calc c = (x, y) -> x / y; System.out.println(c.of({a}, {d})); }}"),
        3 => format!("{{ System.out.println(useCalc((x, y) -> x {op} y, {a}, {b})); }}"),
        4 => format!(
            "{{ int cap = {a}; Calc c = (x, y) -> x + y + cap; System.out.println(c.of({b}, {d})); }}"
        ),
        5 => format!("{{ System.out.println(mkAdder({a}).of({b}, {d})); }}"),
        6 => format!(
            "{{ Str1 f = t -> t.toUpperCase() + t.length(); System.out.println(f.of({s})); }}"
        ),
        7 => format!(
            "{{ Pred1 pr = x -> x > {a}; System.out.println(pr.of({b}) + \",\" + pr.of({d})); }}"
        ),
        8 => format!("{{ Sup0 g = () -> {a} * {b}; System.out.println(g.of()); }}"),
        9 => format!("{{ Str1 f = String::toUpperCase; System.out.println(f.of({s})); }}"),
        _ => format!(
            "{{ Calc c = (x, y) -> {{ if (y == 0) {{ return -1; }} return x % y; }}; System.out.println(c.of({a}, {d})); }}"
        ),
    }
}

/// `java.util` collections: `List`/`ArrayList`, the three `Map`s and three
/// `Set`s, `Arrays.asList`, `Collections.sort`/`reverse`, the enhanced `for`
/// over a collection, and the views (`keySet`, `values`). The point of the mode
/// is **iteration order**: a `HashMap`/`HashSet` prints in Java's bucket order,
/// which is a pure function of the keys and the size, so it is a parity signal
/// rather than nondeterminism. Elements stay `String`/`int`/`double`/`boolean`,
/// because a user object inside a collection renders through its `toString()`
/// in Java and through the default form in javars (a documented gap).
fn g_collection(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, INTS);
    let c = pick(r, INTS);
    let s1 = pick(r, STRS);
    let s2 = pick(r, STRS);
    match r.below(14) {
        0 => format!(
            "{{ List<Integer> l = new ArrayList<>(); l.add({a}); l.add({b}); l.add({c}); System.out.println(l + \" \" + l.size() + \" \" + l.get(1)); }}"
        ),
        1 => format!(
            "{{ List<String> l = new ArrayList<>(); l.add({s1}); l.add({s2}); System.out.println(l.contains({s1}) + \",\" + l.indexOf({s2}) + \",\" + l.isEmpty()); }}"
        ),
        2 => format!(
            "{{ List<Integer> l = new ArrayList<>(Arrays.asList({a}, {b}, {c})); Collections.sort(l); System.out.println(l); }}"
        ),
        3 => format!(
            "{{ List<Integer> l = new ArrayList<>(Arrays.asList({a}, {b}, {c})); Collections.reverse(l); System.out.println(l); }}"
        ),
        4 => format!(
            "{{ List<Integer> l = new ArrayList<>(Arrays.asList({a}, {b}, {c})); l.sort((p, q) -> p - q); System.out.println(l); }}"
        ),
        5 => format!(
            "{{ Map<String, Integer> m = new HashMap<>(); m.put({s1}, {a}); m.put({s2}, {b}); m.put(\"zz\", {c}); System.out.println(m); }}"
        ),
        6 => format!(
            "{{ Map<String, Integer> m = new LinkedHashMap<>(); m.put({s1}, {a}); m.put({s2}, {b}); System.out.println(m + \" \" + m.keySet() + \" \" + m.values()); }}"
        ),
        7 => format!(
            "{{ Map<String, Integer> m = new TreeMap<>(); m.put({s1}, {a}); m.put({s2}, {b}); m.put(\"m\", {c}); System.out.println(m); }}"
        ),
        8 => format!(
            "{{ Set<Integer> t = new HashSet<>(); t.add({a}); t.add({b}); t.add({c}); System.out.println(t + \" \" + t.size() + \" \" + t.contains({a})); }}"
        ),
        9 => format!(
            "{{ Set<String> t = new LinkedHashSet<>(Arrays.asList({s1}, {s2}, {s1})); System.out.println(t); }}"
        ),
        10 => format!(
            "{{ Set<Integer> t = new TreeSet<>(Arrays.asList({a}, {b}, {c})); System.out.println(t); }}"
        ),
        11 => format!(
            "{{ int tot = 0; for (int v : Arrays.asList({a}, {b}, {c})) {{ tot += v; }} System.out.println(tot); }}"
        ),
        12 => format!(
            "{{ Map<String, Integer> m = new HashMap<>(); for (int i = 0; i < 15; i++) {{ m.put(\"k\" + i, i * {a}); }} System.out.println(m); }}"
        ),
        _ => format!(
            "{{ Map<String, Integer> m = new LinkedHashMap<>(); m.put({s1}, {a}); System.out.println(m.get({s1}) + \",\" + m.getOrDefault(\"absent\", -1) + \",\" + m.containsKey({s2})); }}"
        ),
    }
}

/// Arrow `switch` expressions and statements: multi-label arms, a `default`
/// (including one written before a matching arm, which must not shadow it),
/// block arms with `yield`, an `enum` discriminant with unqualified labels, a
/// `String` discriminant, a `throw` arm, and the result feeding `/` typing —
/// which only truncates if the expression's static type survives the switch.
fn g_switchexpr(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, INTS);
    let s = pick(r, STRS);
    match r.below(10) {
        0 => format!(
            "{{ int v = {a}; System.out.println(switch (v) {{ case 0 -> \"zero\"; case 1, 2 -> \"low\"; default -> \"other\"; }}); }}"
        ),
        1 => format!(
            "{{ int v = {a}; System.out.println(switch (v) {{ case 0 -> 100; default -> {{ int t = v * 2; yield t + 1; }} }}); }}"
        ),
        2 => format!(
            "{{ int v = {a}; switch (v) {{ case 0 -> System.out.println(\"z\"); case 1 -> System.out.println(\"o\"); default -> System.out.println(\"d\"); }} }}"
        ),
        3 => format!(
            "{{ Color c = {}; System.out.println(switch (c) {{ case RED -> \"r\"; case GREEN -> \"g\"; default -> \"b\"; }}); }}",
            pick(r, &["Color.RED", "Color.GREEN", "Color.BLUE", "next(Color.BLUE)"])
        ),
        4 => format!(
            "{{ String t = {s}; System.out.println(switch (t) {{ case \"\" -> \"empty\"; case \"a\", \"abc\" -> \"hit\"; default -> \"miss\"; }}); }}"
        ),
        5 => format!(
            "{{ int v = {a}; System.out.println(switch (v) {{ default -> \"d\"; case 0 -> \"zero\"; }}); }}"
        ),
        6 => format!(
            "{{ int v = {a}; System.out.println(switch (v) {{ case 0 -> 8; default -> 7; }} / 2); }}"
        ),
        7 => format!(
            "{{ int v = {a}; System.out.println({b} + switch (v) {{ case 0 -> 20; default -> 3; }} + 300); }}"
        ),
        8 => format!(
            "{{ int v = {a}; try {{ System.out.println(switch (v) {{ case 0 -> throw new IllegalStateException(\"z\"); default -> \"ok\"; }}); }} catch (IllegalStateException e) {{ System.out.println(\"c \" + e.getMessage()); }} }}"
        ),
        _ => format!(
            "{{ Op o = {}; System.out.println(switch (o) {{ case ADD -> o.apply({a}, {b}); case SUB -> o.apply({b}, {a}); default -> 0; }}); }}",
            pick(r, &["Op.ADD", "Op.SUB", "Op.MUL"])
        ),
    }
}

/// `var` inference and `long` literals. A `var` local has to carry the *type*
/// of its initializer, not just its value, or `/` stops truncating and `int`
/// arithmetic stops wrapping — so every probe reads the binding back through an
/// operation that only a correct static type gets right. The `long` half is the
/// other side of the same coin: an `L`-suffixed literal must NOT wrap at 32
/// bits, which is only visible past `Integer.MAX_VALUE`.
fn g_varinfer(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let d = pick(r, DIVS);
    let f = pick(r, DBLS);
    let s = pick(r, STRS);
    let big = pick(
        r,
        &["3000000000L", "2147483648L", "1000000000L", "5000000000L"],
    );
    match r.below(11) {
        0 => format!("{{ var v = {a}; System.out.println(v / {d} + \",\" + v % {d}); }}"),
        1 => format!("{{ var v = {f}; System.out.println(v / {d}); }}"),
        2 => format!("{{ var v = {s}; System.out.println(v.length() + v.toUpperCase()); }}"),
        3 => format!(
            "{{ var arr = new int[]{{{a}, {d}, 8}}; for (var e : arr) {{ System.out.print(e / 2 + \",\"); }} System.out.println(); }}"
        ),
        4 => format!(
            "{{ var g = new int[][]{{{{{a}, 2}}, {{3, {d}}}}}; for (var row : g) {{ for (var c : row) {{ System.out.print(c / 2); }} }} System.out.println(); }}"
        ),
        5 => format!(
            "{{ var t = 0; for (var i = 0; i < 5; i++) {{ t += i * {a}; }} System.out.println(t / 2); }}"
        ),
        6 => format!("{{ var v = {big}; System.out.println(v + v); }}"),
        7 => format!("{{ System.out.println({big} + {big}); }}"),
        8 => format!("{{ var v = {big}; System.out.println(v * 3 + \",\" + v / 7); }}"),
        9 => format!(
            "{{ var ps = new String[]{{{s}, \"zz\"}}; for (var p : ps) {{ System.out.print(p.length()); }} System.out.println(); }}"
        ),
        _ => format!(
            "{{ var p = new Pt({a}, {d}); System.out.println(p + \",\" + p.x() / 2 + \",\" + p.sum()); }}"
        ),
    }
}

/// `&`, `|`, `^`, `~` — bitwise on integral operands, non-short-circuiting
/// logical on booleans (where the result must print `true`/`false`, not 0/1).
fn g_bitwise(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, INTS);
    let op = pick(r, &["&", "|", "^"]);
    match r.below(5) {
        0 => p(format!("{a} {op} {b}")),
        1 => p(format!("~{a}")),
        2 => p(format!("{} {op} {}", pick(r, BOOLS), pick(r, BOOLS))),
        3 => p(format!("({a} {op} {b}) + 1")),
        _ => format!("{{ long v = {a}L; v {op}= {b}; System.out.println(v); }}"),
    }
}

/// `<<`, `>>`, `>>>` — the distance is masked to the *left* operand's width
/// (5 bits for `int`, 6 for `long`), and only `int` narrows afterwards.
fn g_shift(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    // Distances deliberately past the width, so the mask is exercised.
    let n = pick(r, &["0", "1", "3", "16", "31", "32", "33", "63", "64"]);
    let op = pick(r, &["<<", ">>", ">>>"]);
    match r.below(4) {
        0 => p(format!("{a} {op} {n}")),
        1 => p(format!("{a}L {op} {n}")),
        2 => format!("{{ int v = {a}; v {op}= {n}; System.out.println(v); }}"),
        _ => format!("{{ long v = {a}L; v {op}= {n}; System.out.println(v); }}"),
    }
}

/// Narrowing and widening primitive casts — the saturating float→integral rule
/// and the two's-complement integral narrowings.
fn g_cast(r: &mut Rng) -> String {
    let d = pick(r, DBLS);
    let i = pick(r, INTS);
    // The boxed values a *reference* cast is applied to, and the target types
    // it is applied with. Every failing pair here is between `java.lang` types,
    // whose `ClassCastException` message javars reproduces exactly; the
    // user-class pairs print the exception's class instead, because Java's
    // message names its class loader by identity hash.
    // A boxed `char` is deliberately absent: javars models a `Character` as the
    // one-character String it prints as, so a cast that fails on one names
    // `java.lang.String` in its message. That is a documented simplification,
    // not a finding.
    const BOXED: &[&str] = &["\"hi\"", "42", "3.5", "true"];
    const TARGETS: &[&str] = &[
        "String",
        "Integer",
        "Double",
        "Boolean",
        "Number",
        "CharSequence",
        "Object",
    ];
    match r.below(12) {
        0 => p(format!("(int) {d}")),
        1 => p(format!("(long) {d}")),
        // Parenthesised because `DBLS` holds negative literals: `-{d}` spliced
        // onto `-1.5` is `--1.5`, which Java lexes as the decrement operator and
        // rejects with "unexpected type / required: variable".
        2 => p(format!("(int) -({d})")),
        3 => p(format!("(byte) ({i} * 37)")),
        4 => p(format!("(short) ({i} * 5000)")),
        5 => p(format!("(double) {i} / 2")),
        6 => p(format!("(char) (65 + {})", r.below(20))),
        7 => p(format!("(int) 1e18 + {i}")),
        // A reference cast between JDK types: succeeds, or throws with the
        // message Java prints.
        8 | 9 => {
            let val = pick(r, BOXED);
            let target = pick(r, TARGETS);
            format!(
                "{{ Object o = {val}; try {{ System.out.println(({target}) o); }} catch (ClassCastException e) {{ System.out.println(e.getMessage()); }} }}"
            )
        }
        // A downcast in a user hierarchy: the exception's *class*, since its
        // message names the launcher's class loader.
        10 => {
            let src = pick(r, &["new Left()", "new Right()", "new Base()"]);
            let target = pick(r, &["Left", "Right", "Base", "Marker", "Object"]);
            format!(
                "{{ Base b = {src}; try {{ System.out.println(({target}) b); }} catch (ClassCastException e) {{ System.out.println(\"CCE \" + e.getClass().getSimpleName()); }} }}"
            )
        }
        // A `null` casts to anything, and a cast does not erase what the
        // operand is — `println((Object) left)` still finds `Left.toString`.
        _ => {
            let src = pick(r, &["new Left()", "new Right()"]);
            format!(
                "{{ Base n = null; System.out.println((Base) n); System.out.println((Object) {src}); }}"
            )
        }
    }
}

/// `i++` / `++i` / `i--` / `--i` in *value* position, where the pre- and
/// post-forms differ in what the expression evaluates to.
fn g_incdec(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    match r.below(5) {
        0 => format!("{{ int v = {a}; System.out.println(v++ + \",\" + v); }}"),
        1 => format!("{{ int v = {a}; System.out.println(++v + \",\" + v); }}"),
        2 => format!("{{ int v = {a}; System.out.println(v-- + \",\" + v); }}"),
        3 => format!("{{ int v = {a}; System.out.println(--v + \",\" + v); }}"),
        _ => "{ int t = 0; for (int x = 0, y = 5; x < y; x++, y--) { t += x + y; } System.out.println(t); }"
            .to_string(),
    }
}

/// Hex, binary, octal, and `_`-separated integer literals — including the
/// bit-pattern reading that makes `0xFFFFFFFF` the `int` -1.
fn g_literal(r: &mut Rng) -> String {
    p(pick(
        r,
        &[
            "0x1F",
            "0xFF",
            "0xFFFFFFFF",
            "0xFFFFFFFFFFFFFFFFL",
            "0X7fffffff",
            "0b1010",
            "0b1111_0000",
            "0B1",
            "017",
            "0777",
            "1_000_000",
            "1_2_3",
            "0x7FL",
        ],
    )
    .to_string())
}

/// `System.out.printf` / `String.format` beyond the plain conversions: the
/// grouping and parenthesis flags, argument indexes, and `%e`/`%g`/`%h`.
fn g_printf(r: &mut Rng) -> String {
    let i = pick(r, INTS);
    let d = pick(r, DBLS);
    match r.below(9) {
        0 => format!("System.out.printf(\"%d|%s%n\", {i}, {});", pick(r, STRS)),
        1 => p(format!("String.format(\"%,d\", {i} * 100000)")),
        2 => p(format!("String.format(\"%(d\", {i})")),
        3 => p("String.format(\"%2$s-%1$s\", \"a\", \"b\")".to_string()),
        4 => p(format!("String.format(\"%e\", {d})")),
        5 => p(format!("String.format(\"%E\", {d})")),
        6 => p(format!("String.format(\"%.3f\", {d})")),
        7 => p(format!("String.format(\"%08.2f\", {d})")),
        _ => p(format!("String.format(\"%,.2f\", {d} * 1000)")),
    }
}

/// Labeled `break`/`continue` out of nested loops, including from inside a
/// `try` whose `finally` must still run on the way out.
fn g_labelflow(r: &mut Rng) -> String {
    match r.below(4) {
        0 => "{ outer: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (j == 1) continue outer; System.out.print(i + \":\" + j + \" \"); } } System.out.println(); }".to_string(),
        1 => "{ up: for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i * j > 2) break up; System.out.print(i * j); } } System.out.println(); }".to_string(),
        2 => "{ lp: for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { try { if (j == 1) continue lp; System.out.print(\"b\" + i + j); } finally { System.out.print(\"f\" + i + j); } } } System.out.println(); }".to_string(),
        _ => "{ int k = 0; ex: while (true) { k++; try { if (k > 2) break ex; } finally { System.out.print(\"w\" + k); } } System.out.println(k); }".to_string(),
    }
}

/// `char` — the boundary between Java's *integral* `char` and its string
/// conversion. Arithmetic on a `char` promotes to `int` (`'a' + 1` is 98), while
/// a `char` reaching a String, a `println`, or a collection element renders as
/// the character. Both sides have to be right at once, which is what makes this
/// worth generating: an implementation that models a `char` as a one-character
/// string passes every rendering probe and fails every arithmetic one.
fn g_char(r: &mut Rng) -> String {
    let c = pick(r, CHARS);
    let d = pick(r, CHARS);
    // A third char guaranteed distinct from `c`: `switch` rejects duplicate
    // case labels at compile time, so the two arms must not collide.
    let e = CHARS[(CHARS.iter().position(|x| x == c).unwrap_or(0) + 1) % CHARS.len()];
    let s = pick(r, STRS);
    let n = pick(r, &["0", "1", "2", "7", "32", "-1"]);
    match r.below(20) {
        // Arithmetic and promotion.
        0 => p(format!("'{c}' + {n}")),
        1 => p(format!("'{c}' - '{d}'")),
        2 => p(format!("'{c}' * 2 + '{d}'")),
        3 => p(format!("(char) ('{c}' + {n})")),
        4 => p(format!("'{c}' & 0x0F | '{d}' ^ 3")),
        // String conversion.
        5 => p(format!("\"[\" + '{c}' + \"]\" + {n}")),
        6 => p(format!("'{c}' + \"\" + '{d}'")),
        7 => p(format!("String.valueOf('{c}') + String.format(\"%c%s\", '{d}', '{c}')")),
        // Casts both ways.
        8 => p(format!("(int) '{c}' + (int) '{d}'")),
        9 => p(format!(
            "(char) ({} + {n})",
            c.chars().next().unwrap_or('a') as u32
        )),
        10 => p(format!("(long) '{c}' + (double) '{d}'")),
        // `charAt` and the code-point idioms built on it.
        11 => format!(
            "{{ String s = {s}; int t = 0; for (int i = 0; i < s.length(); i++) t += s.charAt(i) - 'a'; System.out.println(t); }}"
        ),
        12 => format!("{{ String s = {s}; System.out.println(s.isEmpty() ? '?' : s.charAt(0)); }}"),
        13 => format!(
            "{{ String s = {s}; String o = \"\"; for (char x : s.toCharArray()) o += (char) (x + {n}); System.out.println(o); }}"
        ),
        14 => format!("System.out.println(Arrays.toString({s}.toCharArray()));"),
        // Mutation: `++`, compound assign, and the 16-bit `char` width.
        15 => format!(
            "{{ char v = '{c}'; v++; v += {n}; System.out.println(v + \"|\" + (int) v); }}"
        ),
        // Comparison and `switch`.
        16 => p(format!("('{c}' < '{d}') + \",\" + ('{c}' == '{d}')")),
        17 => format!(
            "{{ char v = '{d}'; switch (v) {{ case '{e}': System.out.println(\"e\"); break; case '{c}': System.out.println(\"c\"); break; default: System.out.println(\"?\"); }} }}"
        ),
        // `Character` statics, whose results are `char` again.
        18 => p(format!(
            "Character.toUpperCase('{c}') + \"/\" + Character.isDigit('{c}') + \"/\" + Character.toLowerCase('{d}')"
        )),
        // A boxed `Character` in a collection.
        _ => format!(
            "{{ List<Character> l = new ArrayList<>(); l.add('{c}'); l.add('{d}'); System.out.println(l + \"|\" + l.get(0) + \"|\" + l.contains('{c}')); }}"
        ),
    }
}

/// `float` operands, chosen so most are *not* exactly representable in 32 bits
/// — that is where a `double` standing in for a `float` gives itself away.
const FLTS: &[&str] = &[
    "0.1f",
    "0.2f",
    "1.0f",
    "3.0f",
    "2.5f",
    "-1.5f",
    "1.1f",
    "100.0f",
    "1e3f",
    "0.0f",
    "7.0f",
    "1e-4f",
    "1e8f",
    "16777217.0f",
];

/// `float` — a 32-bit type javars models as a `double` kept at 32-bit
/// precision. Both halves have to hold: every operation rounds to `f32` (Java
/// rounds per operation, so `a * b + c` rounds twice), and the value prints with
/// `Float.toString`'s shortest-round-trip *at 32 bits* (`1.0f / 3.0f` is
/// `0.33333334`, where the `double` answer is `0.3333333333333333`).
fn g_float(r: &mut Rng) -> String {
    let a = pick(r, FLTS);
    let b = pick(r, FLTS);
    let c = pick(r, FLTS);
    let d = pick(r, DBLS);
    let i = pick(r, INTS);
    match r.below(17) {
        // The `float` subnormal floor, where Java's two-digit widening decides
        // the last digit (`Float.MIN_VALUE` is `1.4E-45`, not `1.0E-45`).
        14 => p(format!("Float.MIN_VALUE * {}", r.below(64) + 1)),
        15 => p("Float.MIN_VALUE".to_string()),
        16 => p("Float.MIN_NORMAL".to_string()),
        0 => p(format!("{a} / {b}")),
        1 => p(format!("{a} + {b}")),
        2 => p(format!("{a} * {b}")),
        3 => p(format!("{a} - {b}")),
        4 => p(format!("{a} % {b}")),
        // Rounding happens per operation, so the grouping changes the answer.
        5 => p(format!("{a} * {b} + {c}")),
        6 => p(format!("{a} * ({b} + {c})")),
        // A `double` operand promotes the whole operation; an `int` does not.
        7 => p(format!("{a} / {d}")),
        8 => p(format!("{a} / {i}")),
        9 => p(format!("(float) {d} + {a}")),
        10 => p(format!("(double) {a}")),
        // Accumulation, where 32-bit rounding compounds.
        11 => format!(
            "{{ float v = {a}; for (int k = 0; k < 8; k++) v += {b}; System.out.println(v); }}"
        ),
        12 => format!("{{ float v = {a}; v *= {b}; v /= {c}; System.out.println(v + \"|\" + (v < {a})); }}"),
        // Rendering paths: concatenation, `String.valueOf`, an array.
        _ => format!(
            "{{ float[] fa = {{{a}, {b}}}; System.out.println(java.util.Arrays.toString(fa) + \"|\" + String.valueOf(fa[0] + fa[1]) + \"|\" + ({a} / {c})); }}"
        ),
    }
}

/// The `java.util.regex` patterns the `regex` mode draws from. Every one is a
/// construct javars translates rather than refuses, and the pool deliberately
/// mixes the places where Java's *defaults* differ from the engine's — ASCII
/// `\d`/`\w`/`\s`/`\b`, ASCII `(?i)` folding, `.` against a `\r`, and a `$` that
/// sits before a final line terminator.
const PATTERNS: &[&str] = &[
    ",",
    "\\\\.",
    "\\\\d",
    "\\\\d+",
    "\\\\D",
    "\\\\w",
    "\\\\W+",
    "\\\\s",
    "\\\\s+",
    "\\\\S",
    "[abc]",
    "[^abc]",
    "[a-z]",
    "[0-9]+",
    "[-.]",
    "[\\\\w.]",
    "a|b",
    "ab?",
    "a*",
    "a+?",
    "(a)(b)",
    "(?:ab)+",
    "(?<g>a)b",
    "a.c",
    ".",
    "^a",
    "a$",
    "$",
    "\\\\ba",
    "a\\\\b",
    "\\\\B",
    "(?i)a",
    "(?i)[a-c]",
    "(?i:AB)",
    "(?s)a.b",
    "\\\\Qa.c\\\\E",
    "\\\\p{Upper}",
    "\\\\p{Digit}+",
    "\\\\h",
    "\\\\R",
    "a{2}",
    "a{1,2}",
    "(a)\\\\1",
    "a(?=b)",
    "(?<=a)b",
    "x(?!y)",
    "",
    "\\\\u0061",
    // Group-bearing patterns. The pool above is almost entirely group-free,
    // which left the `$n` replacements with nothing legal to pair with; these
    // give the numbered and named back-references a subject, and cover nesting
    // (where the group *number* is the order of the opening paren), an optional
    // group (which can go unmatched, so `$2` expands to nothing rather than
    // throwing), and a named group that a `${name}` replacement can reach.
    "(a)",
    "([a-z])",
    "(\\\\d)",
    "(a|b)",
    "(a)(b)?",
    "(a(b))",
    "(\\\\w)(\\\\w)",
    "(\\\\w)(\\\\w)(\\\\w)",
    "(?<g>a)",
    "(?<g>[a-z])(\\\\d)",
];

/// The subjects the `regex` mode matches against — ASCII, non-ASCII (where the
/// ASCII-only defaults show), embedded line terminators (where `$` and `.` do),
/// and the empty string.
const SUBJECTS: &[&str] = &[
    "\"\"",
    "\"a\"",
    "\"abc\"",
    "\"aabbcc\"",
    "\"a,b,,c\"",
    "\"a1b22c\"",
    "\"a b\\tc\"",
    "\"Hello World\"",
    "\"AbC\"",
    "\"a.b.c\"",
    "\"2024-01-31\"",
    "\"naïve café\"",
    "\"abc\\n\"",
    "\"a\\nb\"",
    "\"a\\rb\"",
    "\"x-y_z\"",
    "\"aaa\"",
];

/// The replacement strings, covering Java's `$n` / `${name}` grammar and its
/// backslash escaping (which is not the `regex` crate's).
///
/// Entries carry their own enclosing quotes, because a replacement is passed to
/// `replaceAll` as an expression rather than interpolated into one.
///
/// A replacement here may reference groups; it is [`pairable`] that keeps it
/// from being handed a pattern that does not have them.
const REPLACEMENTS: &[&str] = &[
    "\"-\"",
    "\"\"",
    "\"[$0]\"",
    "\"<$1>\"",
    "\"$1$1\"",
    "\"\\\\$\"",
    "\"x\"",
    "\"\\\\\\\\\"",
    "\"$2$1\"",
    "\"$0|$1\"",
    "\"${g}\"",
    "\"[${g}]$0\"",
];

/// One Java string *literal body* with the compiler's escapes resolved — the
/// value the running program actually receives. Both pools are written as
/// literal bodies, so a regex `\d` appears here as `\\d` and has to be collapsed
/// before the regex or replacement grammar can be read off it.
///
/// A `backslash-u` escape resolves too, because javac processes those in the
/// lexer rather than passing them through: the pool's hex escape for U+0061
/// reaches `Pattern.compile` as the single character `a`, not as an escape the
/// regex engine ever sees.
fn java_unescape(body: &str) -> String {
    let cs: Vec<char> = body.chars().collect();
    let mut out = String::with_capacity(body.len());
    let mut i = 0;
    while i < cs.len() {
        if cs[i] != '\\' {
            out.push(cs[i]);
            i += 1;
            continue;
        }
        match cs.get(i + 1) {
            Some('u') => {
                let hex: String = cs.iter().skip(i + 2).take(4).collect();
                match u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
                    Some(c) => {
                        out.push(c);
                        i += 6;
                    }
                    None => {
                        out.push('\\');
                        i += 1;
                    }
                }
            }
            Some('n') => {
                out.push('\n');
                i += 2;
            }
            Some('r') => {
                out.push('\r');
                i += 2;
            }
            Some('t') => {
                out.push('\t');
                i += 2;
            }
            Some(&c) => {
                out.push(c);
                i += 2;
            }
            None => {
                out.push('\\');
                i += 1;
            }
        }
    }
    out
}

/// The number of capturing groups a pattern has, and the names of its named
/// groups — the two facts that decide which replacements are legal against it.
///
/// A `(` opens a capturing group unless it is followed by `?`, with `(?<name>`
/// the exception: that one IS capturing, while the lookbehinds `(?<=` and `(?<!`
/// are not — the distinguishing character is whether an identifier follows the
/// `<`. A `(` inside a character class, or escaped, is literal.
fn pattern_groups(pat: &str) -> (usize, Vec<String>) {
    let cs: Vec<char> = java_unescape(pat).chars().collect();
    let (mut count, mut names) = (0usize, Vec::new());
    let (mut i, mut in_class) = (0usize, false);
    while i < cs.len() {
        match cs[i] {
            '\\' => {
                i += 2;
                continue;
            }
            '[' if !in_class => in_class = true,
            ']' if in_class => in_class = false,
            '(' if !in_class => {
                if cs.get(i + 1) != Some(&'?') {
                    count += 1;
                } else if cs.get(i + 2) == Some(&'<')
                    && cs.get(i + 3).is_some_and(|c| c.is_ascii_alphabetic())
                {
                    count += 1;
                    names.push(cs[i + 3..].iter().take_while(|c| **c != '>').collect());
                }
            }
            _ => {}
        }
        i += 1;
    }
    (count, names)
}

/// The highest numbered back-reference, and every `${name}` reference, a
/// replacement uses. A backslash-escaped `$` is a literal dollar and references
/// nothing. The entry carries enclosing quotes (see [`REPLACEMENTS`]), which are
/// stripped before the grammar is read.
///
/// Java resolves `$nn` greedily but only as far as a group that exists, so
/// `$12` against a one-group pattern is group 1 followed by a literal `2`.
/// Taking every digit instead is deliberately *conservative*: it can only refuse
/// a pairing Java would have allowed, never allow one Java would abort on. For
/// this pool, whose references are all single-digit, the two agree exactly.
fn replacement_refs(rep: &str) -> (usize, Vec<String>) {
    let body = rep
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .unwrap_or(rep);
    let cs: Vec<char> = java_unescape(body).chars().collect();
    let (mut max_num, mut names) = (0usize, Vec::new());
    let mut i = 0;
    while i < cs.len() {
        match cs[i] {
            '\\' => {
                i += 2;
                continue;
            }
            '$' if cs.get(i + 1) == Some(&'{') => {
                let name: String = cs[i + 2..].iter().take_while(|c| **c != '}').collect();
                i += name.len() + 2;
                names.push(name);
            }
            '$' => {
                let digits: String = cs[i + 1..]
                    .iter()
                    .take_while(|c| c.is_ascii_digit())
                    .collect();
                if let Ok(n) = digits.parse::<usize>() {
                    max_num = max_num.max(n);
                }
                i += digits.len();
            }
            _ => {}
        }
        i += 1;
    }
    (max_num, names)
}

/// Whether `rep` references only groups `pat` actually has — the invariant that
/// keeps the generator from emitting a program the reference JDK aborts on.
fn pairable(pat: &str, rep: &str) -> bool {
    let (count, names) = pattern_groups(pat);
    let (max_num, refs) = replacement_refs(rep);
    max_num <= count && refs.iter().all(|n| names.contains(n))
}

/// A replacement drawn uniformly from those legal against `pat`.
///
/// This bounds the pairing without narrowing the replacement grammar under
/// test: every entry in [`REPLACEMENTS`] stays reachable, because the
/// group-bearing patterns admit all of them. Constraining the *pairing* rather
/// than shrinking the pool is what keeps the fix from trading skips for lost
/// coverage.
fn pick_replacement(r: &mut Rng, pat: &str) -> &'static str {
    let legal: Vec<&'static str> = REPLACEMENTS
        .iter()
        .copied()
        .filter(|rep| pairable(pat, rep))
        .collect();
    assert!(
        !legal.is_empty(),
        "no replacement is legal against pattern `{pat}`: REPLACEMENTS must keep \
         at least one entry that references no group"
    );
    legal[r.below(legal.len())]
}

/// `java.util.regex` through `String.split`/`replaceAll`/`replaceFirst`/
/// `matches` — the pattern *translation* as much as the engine, since Java's
/// defaults and fancy-regex's disagree on `\d`, `\b`, `(?i)`, `.`, and `$`.
fn g_regex(r: &mut Rng) -> String {
    let pat = *pick(r, PATTERNS);
    let s = pick(r, SUBJECTS);
    // The replacement is drawn from the subset legal for *this* pattern, not
    // from the pool at large. Pairing them independently emitted programs like
    // `"aabbcc".replaceAll("[a-z]", "$1$1")`, which the reference JDK aborts
    // with `IndexOutOfBoundsException: No group 1` — so the whole packed program
    // produced no comparable output and was counted a skip. A skip is
    // indistinguishable from coverage in the summary, so the corpus reported
    // agreement it had never actually tested.
    let rep = pick_replacement(r, pat);
    match r.below(7) {
        0 => format!("System.out.println(Arrays.toString({s}.split(\"{pat}\")) + \"/\" + {s}.split(\"{pat}\").length);"),
        1 => format!(
            "System.out.println(Arrays.toString({s}.split(\"{pat}\", {})));",
            r.below(4) as i64 - 1
        ),
        2 => p(format!("{s}.replaceAll(\"{pat}\", {rep})")),
        3 => p(format!("{s}.replaceFirst(\"{pat}\", {rep})")),
        4 => p(format!("{s}.matches(\"{pat}\")")),
        5 => p(format!("{s}.matches(\"{pat}\") + \"|\" + {s}.replaceAll(\"{pat}\", \"#\")")),
        _ => format!(
            "try {{ System.out.println({s}.replaceAll(\"{pat}\", {rep})); }} catch (RuntimeException e) {{ System.out.println(e.getClass().getSimpleName()); }}"
        ),
    }
}

/// Declaration statements with more than one declarator, and the C-style array
/// suffix that binds to the *declarator* rather than the type — so
/// `int a[], b;` declares an `int[]` and an `int`. Both spellings appear in
/// locals, in `for` init clauses, and in the initializer that reads the
/// declarator before it.
fn g_decl(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    let b = pick(r, INTS);
    let d = pick(r, DIVS);
    let f = pick(r, DBLS);
    let s = pick(r, STRS);
    let c = pick(r, CHARS);
    match r.below(14) {
        0 => format!("{{ int x = {a}, y = {b}; System.out.println(x + \",\" + y + \",\" + (x + y)); }}"),
        1 => format!("{{ int x = {a}, y = x + {b}, z = y * 2; System.out.println(x + \",\" + y + \",\" + z); }}"),
        2 => format!("{{ int x, y = {b}, z; x = {a}; z = x + y; System.out.println(x + \",\" + y + \",\" + z); }}"),
        3 => format!("{{ final int x = {a}, y = {b}; System.out.println(x / {d} + \",\" + y % {d}); }}"),
        4 => format!("{{ int p[] = {{{a}, {b}}}, q = {d}; System.out.println(p.length + \",\" + p[1] + \",\" + q); }}"),
        5 => format!("{{ int p[] = {{{a}}}, q[][] = {{{{{b}}}, {{{d}, 9}}}}; System.out.println(p[0] + \",\" + q[1][1] + \",\" + q.length); }}"),
        6 => format!("{{ int[] u = {{{a}}}, v = {{{b}, {d}}}; System.out.println(u[0] + v.length); }}"),
        7 => format!("{{ double x = {f}, y = x * 2; System.out.println(x + \",\" + y); }}"),
        8 => format!("{{ String x = {s}, y = x + \"z\"; System.out.println(y + \",\" + y.length()); }}"),
        9 => format!("{{ long m = {a}, n = {b}; System.out.println(m * n + \",\" + (m - n)); }}"),
        10 => format!("{{ char c1 = '{c}', c2 = (char) (c1 + 1); System.out.println(\"\" + c1 + c2 + \",\" + (c1 + 0)); }}"),
        11 => "{ boolean t = true, u = false; System.out.println(t + \",\" + u + \",\" + (t & u)); }".to_string(),
        12 => format!("{{ int t = 0; for (int i = {a}, n = i + 3; i < n; i++) {{ t += i; }} System.out.println(t); }}"),
        _ => format!("{{ int t = 0; for (int i = 0, j = 4; i < j; i++, j--) {{ t += i * {d} + j; }} System.out.println(t); }}"),
    }
}

/// `new Object()` and the methods every class inherits from it. The identity
/// hash itself is never printed — Java's is a JVM value that differs run to run
/// — so the probes assert the properties a program can depend on: reference
/// identity, the shape of the default `toString`, the class name, and the way an
/// `Object` behaves as a key, an element, and a monitor.
fn g_object(r: &mut Rng) -> String {
    let a = pick(r, INTS);
    match r.below(12) {
        0 => "{ Object o = new Object(), p = new Object(); System.out.println((o == p) + \",\" + (o == o) + \",\" + o.equals(o) + \",\" + o.equals(p)); }".to_string(),
        1 => "{ Object o = new Object(); System.out.println(o.getClass().getName() + \",\" + o.getClass().getSimpleName()); }".to_string(),
        2 => "{ Object o = new Object(); System.out.println(o.toString().startsWith(\"java.lang.Object@\")); }".to_string(),
        3 => "{ Object o = new Object(); System.out.println((o.hashCode() == o.hashCode()) + \",\" + (o.hashCode() == new Object().hashCode())); }".to_string(),
        4 => "{ Object o = new Object(); System.out.println(String.valueOf(o).startsWith(\"java.lang.Object@\")); }".to_string(),
        5 => "{ Object o = new Object(), p = new Object(); List<Object> l = new ArrayList<>(); l.add(o); l.add(p); System.out.println(l.size() + \",\" + l.indexOf(p) + \",\" + l.contains(o)); }".to_string(),
        6 => "{ Object o = new Object(), p = new Object(); Set<Object> s = new HashSet<>(); s.add(o); s.add(o); s.add(p); System.out.println(s.size()); }".to_string(),
        7 => "{ Object o = new Object(), p = new Object(); Map<Object, String> m = new HashMap<>(); m.put(o, \"A\"); m.put(p, \"B\"); System.out.println(m.get(o) + m.get(p) + m.size()); }".to_string(),
        8 => format!("{{ Object lock = new Object(); int t = 0; synchronized (lock) {{ t += {a}; }} System.out.println(t); }}"),
        9 => format!("{{ Bare b1 = new Bare({a}), b2 = new Bare({a}); System.out.println(b1.equals(b1) + \",\" + b1.equals(b2) + \",\" + b1.toString().startsWith(\"Bare@\")); }}"),
        10 => format!("{{ Object[] xs = new Object[2]; xs[0] = new Object(); xs[1] = xs[0]; System.out.println((xs[0] == xs[1]) + \",\" + xs.length + \",\" + {a}); }}"),
        _ => format!("{{ Object miss = new Object(); Map<String, Object> m = new HashMap<>(); m.put(\"k\", miss); System.out.println((m.get(\"k\") == miss) + \",\" + (m.getOrDefault(\"z\", miss) == miss) + \",\" + {a}); }}"),
    }
}

/// Helper declarations the `finally`/`resource` probes call. Emitted into every
/// generated program (they are inert when unused).
/// A **qualified** static call, `C.m(args)`, where more than one class in the
/// program declares `m`.
///
/// Java resolves a qualified static in the receiver class's own declarations
/// first and then up its superclass chain; it never reaches an unrelated class.
/// The pre-existing modes could not observe that rule, because every probe they
/// emitted lived in a program whose static names were unique — with one name per
/// method a by-name-only resolver is indistinguishable from a correct one. These
/// probes put a same-named static in a *second* class and then ask which body
/// ran, which is the only shape that separates the two.
fn g_staticref(r: &mut Rng) -> String {
    let n = pick(r, &["0", "1", "2", "7", "-3"]);
    let s = pick(r, &["\"x\"", "\"\"", "\"ab\""]);
    match r.below(10) {
        // Same name, same signature, different class: the receiver alone decides.
        0 => p(format!("Qa.f({n})")),
        1 => p(format!("Qb.f({n})")),
        2 => p(format!("Qa.f({n}) + \",\" + Qb.f({n})")),
        // Same name, *different* parameter types: a resolver that scores
        // signatures across the whole program picks the closer one and crosses
        // classes; Java scores only inside the named class.
        3 => p(format!("Qa.g({s})")),
        4 => p(format!("Qb.g({s})")),
        5 => p(format!("Qa.g({s}) + Qb.g({s})")),
        // Zero-arg statics whose signatures are identical in every way but owner.
        6 => p("Qa.h() + Qb.h()".to_string()),
        // A subclass hides an inherited static; the name it does not redeclare
        // still resolves up the chain.
        7 => p("Qbase.kind() + \"/\" + Qderiv.kind()".to_string()),
        8 => p("Qderiv.only() + Qbase.only()".to_string()),
        // The chosen body's result feeding an expression, so a wrong target is
        // visible as a wrong number rather than only as a wrong label.
        _ => format!(
            "{{ int q = Qb.f({n}) * 2 + Qa.f({n}); System.out.println(q + Qbase.kind()); }}"
        ),
    }
}

/// `while` and `do`/`while` with `continue` and `break`.
///
/// `continue` lowers differently in each of Java's three loops — a `for` runs its
/// update clause first, a `while` jumps straight back to the condition, and a
/// `do`/`while` jumps *forward* to the trailing condition — so they are three
/// separate code paths in the compiler. Every loop probe that existed emitted a
/// `for` (the sole `while` was a `while (true)` with a `break`), which left two
/// of the three lowerings and the whole `do`/`while` statement ungenerated. A
/// sibling frontend shipped a `continue` that compiled to a jump-to-zero — an
/// infinite loop — under exactly this blind spot.
fn g_loopkind(r: &mut Rng) -> String {
    let n = 3 + r.below(4);
    let skip = r.below(3);
    match r.below(12) {
        // `continue` in a `while`: the condition is re-tested, nothing is stepped.
        0 => format!(
            "{{ int i = 0, acc = 0; while (i < {n}) {{ i++; if (i == {skip}) continue; acc += i; }} System.out.println(acc); }}"
        ),
        // `continue` in a `do`/`while`: jumps to the *trailing* condition.
        1 => format!(
            "{{ int i = 0, acc = 0; do {{ i++; if (i == {skip}) continue; acc += i; }} while (i < {n}); System.out.println(acc); }}"
        ),
        // `break` out of a `do`/`while`.
        2 => format!(
            "{{ int i = 0, acc = 0; do {{ i++; if (i == {skip}) break; acc += i; }} while (i < {n}); System.out.println(acc); }}"
        ),
        // The body of a `do`/`while` always runs once, however false the test.
        3 => "{ int k = 0; do { k++; } while (false); System.out.println(k); }".to_string(),
        // A labelled `continue` stepping an outer `while` from an inner one.
        4 => format!(
            "{{ int i = 0; String o = \"\"; L: while (i < {n}) {{ i++; int j = 0; while (j < 3) {{ j++; if (j == 2) continue L; o += i + \"\" + j + \" \"; }} }} System.out.println(o); }}"
        ),
        // A labelled `continue` on a `do`/`while`.
        5 => format!(
            "{{ int i = 0; String o = \"\"; D: do {{ i++; if (i % 2 == 0) continue D; o += i; }} while (i < {n}); System.out.println(o); }}"
        ),
        // A labelled `break` out of a `do`/`while` nest.
        6 => format!(
            "{{ int t = 0; U: do {{ int j = 0; while (j < {n}) {{ j++; if (j == 2) break U; t += j; }} }} while (t < 100); System.out.println(t); }}"
        ),
        // `continue` inside a `switch` inside a loop — the `switch` owns `break`
        // but not `continue`, so the jump has to pass through it.
        7 => format!(
            "{{ int acc = 0; for (int i = 0; i < {n}; i++) {{ switch (i) {{ case 1: continue; case 2: acc += 100; break; default: acc += i; }} }} System.out.println(acc); }}"
        ),
        8 => format!(
            "{{ int i = 0, acc = 0; while (i < {n}) {{ i++; switch (i) {{ case 2: continue; default: acc += i; }} }} System.out.println(acc); }}"
        ),
        // `continue` in a `while` whose body carries a `finally` — the cleanup
        // has to run on the way out of the iteration.
        9 => format!(
            "{{ int i = 0, acc = 0; while (i < {n}) {{ i++; try {{ if (i == {skip}) continue; acc += i; }} finally {{ System.out.print(\"f\" + i); }} }} System.out.println(\" \" + acc); }}"
        ),
        10 => format!(
            "{{ int i = 0, acc = 0; do {{ i++; try {{ if (i == {skip}) continue; acc += i; }} finally {{ System.out.print(\"g\" + i); }} }} while (i < {n}); System.out.println(\" \" + acc); }}"
        ),
        // Two unlabelled `continue`s nested two deep: each steps its own loop.
        _ => format!(
            "{{ String o = \"\"; int i = 0; while (i < {n}) {{ i++; if (i == 1) continue; int j = 0; while (j < 3) {{ j++; if (j == 2) continue; o += i + \"\" + j; }} }} System.out.println(o); }}"
        ),
    }
}

/// `byte` and `short` — the two integral widths narrower than `int`.
///
/// Every fusevm number is a 64-bit value with no width tag, so each of Java's
/// widths is a per-site narrowing the compiler has to emit. The `overflow` mode
/// covers `int` and the `char` mode covers the unsigned 16-bit one, but no probe
/// declared a `byte` or a `short` at all — and their signed 8/16-bit wraps are
/// separate emit sites. Compound assignment is the sharp edge: Java inserts an
/// *implicit* narrowing cast into `b += 100`, so it wraps where the equivalent
/// `b = b + 100` would not even compile.
fn g_narrow(r: &mut Rng) -> String {
    let k = pick(r, &["1", "2", "100", "127", "-128", "1000", "10000"]);
    match r.below(11) {
        // Compound assignment carries an implicit narrowing cast.
        0 => format!("{{ byte b = 100; b += {k}; System.out.println(b); }}"),
        1 => format!("{{ short s = 30000; s += {k}; System.out.println(s); }}"),
        2 => format!("{{ byte b = 100; b *= {k}; System.out.println(b); }}"),
        3 => format!("{{ short s = 1000; s *= {k}; System.out.println(s); }}"),
        // `++`/`--` at the width's boundary.
        4 => "{ byte b = 127; b++; System.out.println(b); }".to_string(),
        5 => "{ short s = 32767; s++; System.out.println(s); }".to_string(),
        6 => "{ byte b = -128; b--; System.out.println(b); }".to_string(),
        // An explicit cast past the width.
        7 => format!("System.out.println((byte) ({k} * 3) + \",\" + (short) ({k} * 700));"),
        // A `byte` promotes to `int` in arithmetic, so the *expression* does not
        // wrap even though the variable would.
        8 => format!("{{ byte b = 100; int w = b * 3 + {k}; System.out.println(w); }}"),
        // The sign-extension idiom, and the shifts a signed narrow type feeds.
        9 => "{ byte b = -1; System.out.println((b & 0xFF) + \",\" + (b >> 1) + \",\" + (b >>> 24)); }"
            .to_string(),
        // An array element is a storage site of the same width.
        _ => format!(
            "{{ byte[] ba = {{100}}; short[] sa = {{30000}}; ba[0] += {k}; sa[0] += {k}; System.out.println(ba[0] + \",\" + sa[0]); }}"
        ),
    }
}

/// Operations *on* a constructed collection, rather than its construction.
///
/// The `collection` mode builds lists and maps and prints them; what it does not
/// do is apply the methods whose meaning depends on the argument's static type.
/// `List` declares both `remove(int)` and `remove(Object)` and Java chooses
/// between them at compile time, so the same call text removes an *index* or a
/// *value* depending on how the argument was declared — a difference no
/// construction probe can see. Every probe here has a deterministic order
/// (`ArrayList`, `TreeMap`, `TreeSet`), never a `HashMap` iteration.
fn g_listop(r: &mut Rng) -> String {
    let i = r.below(3);
    let v = pick(r, &["10", "20", "30", "99"]);
    let s = pick(r, &["\"a\"", "\"b\"", "\"z\""]);
    match r.below(12) {
        // `remove(int)` — an `int`-typed argument is an index.
        0 => format!(
            "{{ List<Integer> l = new ArrayList<>(Arrays.asList(10, 20, 30)); l.remove({i}); System.out.println(l); }}"
        ),
        1 => format!(
            "{{ List<Integer> l = new ArrayList<>(Arrays.asList(10, 20, 30)); int ix = {i}; l.remove(ix); System.out.println(l); }}"
        ),
        // `remove(Object)` — a boxed or reference argument is a *value*, and the
        // call answers whether one was found.
        2 => format!(
            "{{ List<Integer> l = new ArrayList<>(Arrays.asList(10, 20, 30)); boolean hit = l.remove(Integer.valueOf({v})); System.out.println(hit + \" \" + l); }}"
        ),
        3 => format!(
            "{{ List<Integer> l = new ArrayList<>(Arrays.asList(10, 20, 30)); Integer k = {v}; System.out.println(l.remove(k) + \" \" + l); }}"
        ),
        4 => format!(
            "{{ List<String> l = new ArrayList<>(Arrays.asList(\"a\", \"b\", \"c\")); System.out.println(l.remove({s}) + \" \" + l); }}"
        ),
        // `String.join` over an *Iterable*, Java's second overload — the one that
        // joins elements rather than rendering the collection.
        5 => format!(
            "{{ List<String> l = new ArrayList<>(Arrays.asList(\"a\", \"b\", \"c\")); l.remove({s}); System.out.println(String.join(\"-\", l)); }}"
        ),
        6 => "{ Set<String> st = new TreeSet<>(Arrays.asList(\"q\", \"p\", \"q\")); System.out.println(String.join(\",\", st)); }"
            .to_string(),
        // Ordering, searching and in-place mutation of a built list.
        7 => format!(
            "{{ List<Integer> l = new ArrayList<>(Arrays.asList(30, 10, 20)); Collections.sort(l); l.set({i}, 5); System.out.println(l + \" \" + l.indexOf(5)); }}"
        ),
        8 => "{ List<Integer> l = new ArrayList<>(Arrays.asList(3, 1, 2)); Collections.reverse(l); System.out.println(l + \" \" + Collections.max(l) + Collections.min(l)); }"
            .to_string(),
        9 => format!(
            "{{ List<Integer> l = new ArrayList<>(Arrays.asList(1, 2)); l.add({i}, 9); System.out.println(l + \" \" + l.contains(9) + l.lastIndexOf(9)); }}"
        ),
        // A `TreeMap` keeps key order, so iterating it is deterministic.
        10 => format!(
            "{{ Map<String, Integer> m = new TreeMap<>(); m.put(\"b\", 2); m.put(\"a\", 1); m.remove({s}); int t = 0; for (String k : m.keySet()) t += m.get(k); System.out.println(m + \" \" + t); }}"
        ),
        // Removing while the value is absent must leave the list untouched.
        _ => format!(
            "{{ List<Integer> l = new ArrayList<>(Arrays.asList(10, 20)); System.out.println(l.remove(Integer.valueOf({v})) + \" \" + l.size() + \" \" + l); }}"
        ),
    }
}

/// Calls to **user-declared variable-arity** methods, constructors and instance
/// methods — a shape no other mode emits, because no other mode writes a `...`
/// parameter at all.
///
/// The interesting part is not that `sum(1, 2, 3)` runs; it is *which* of
/// several declarations a call selects, which Java answers with three ordered
/// resolution phases. A generator that only ever declared one variadic method
/// could not tell a correct resolver from one that ignores the ordering, so
/// every probe here calls into a set where at least two declarations compete:
/// a fixed-arity overload that must win outright, an array argument that must
/// pass through unpacked, and element types (`String…`/`Object…`, `int…`/
/// `double…`) whose specificity decides the winner.
fn g_varargs(r: &mut Rng) -> String {
    let n = pick(r, &["1", "2", "7", "-3"]);
    let s = pick(r, &["\"a\"", "\"b\"", "\"zz\""]);
    match r.below(16) {
        // Arity: none, one, several — the same declaration has to take all of
        // them, and `xs.length` proves what actually arrived.
        0 => format!("System.out.println(vsum({n}, {n}, {n}));"),
        1 => format!("System.out.println(vsum({n}));"),
        2 => "System.out.println(vsum());".to_string(),
        // An *array* argument matches the declared `int[]` in the fixed-arity
        // phase, so it is passed straight through rather than wrapped in a
        // one-element array.
        3 => format!("{{ int[] a = {{{n}, 4}}; System.out.println(vsum(a)); }}"),
        4 => format!("System.out.println(vsum(new int[]{{{n}, 5, 6}}));"),
        // A fixed-arity overload must beat the variadic one for the arity it
        // declares, and lose for every other.
        5 => format!("System.out.println(vpick({n}, 2));"),
        6 => format!("System.out.println(vpick({n}));"),
        7 => format!("System.out.println(vpick({n}, 2, 3));"),
        8 => "System.out.println(vpick());".to_string(),
        // Element-type specificity between two variadic candidates.
        9 => format!("System.out.println(vkind({s}, {s}));"),
        10 => format!("System.out.println(vkind({n}, {n}));"),
        11 => "System.out.println(vkind());".to_string(),
        // A fixed prefix ahead of the variadic tail, and the zero-length tail.
        12 => format!("System.out.println(vtag({s}, {n}, {n}));"),
        13 => format!("System.out.println(vtag({s}));"),
        // A constructor and an instance method, both variadic, plus the
        // `(Object[]) null` cast Java passes as the whole array.
        14 => format!(
            "{{ Bag b = new Bag({n}, {n}); System.out.println(b.total() + \" \" + b.plus({n})); }}"
        ),
        _ => "System.out.println(vnull((Object[]) null) + \" \" + vnull(1, 2));".to_string(),
    }
}

/// The `List.of`/`Set.of`/`Map.of` contract, which is three answers and not one.
///
/// The `listop` and `listview` modes build collections and read them back; both
/// stay on the *accepting* side of the factories, so the whole refusing side was
/// unreachable and three separate divergences hid behind clean sweeps:
///
///   * An out-of-range index does not name one exception. `ArrayList` raises
///     `IndexOutOfBoundsException`, `Arrays.asList` and a three-or-more-element
///     `List.of` let a backing array raise `ArrayIndexOutOfBoundsException`, and
///     a one-or-two-element `List.of` raises `IndexOutOfBoundsException` with a
///     different wording again (`Index: 5 Size: 2`). Only a probe that prints
///     `getClass().getName()` alongside `getMessage()` can see the difference —
///     printing the message alone agrees on two of the four.
///   * `List.of(1, null)` throws before the list exists.
///   * `List.of(1, 2).contains(null)` throws rather than answering `false`, and
///     so do `indexOf`/`lastIndexOf`, `Set.of.contains`, and `Map.of`'s
///     `get`/`containsKey`/`containsValue`.
///
/// Every probe reports through `getClass().getName()`, because the three list
/// shapes differ in the exception *class* well before they differ in its text,
/// and a `RuntimeException` catch that printed only the message would call two
/// of them equal. The receiver sizes are drawn to straddle the JDK's own
/// `List12`/`ListN` and `Set12`/`SetN` and `Map1`/`MapN` boundaries, since that
/// arity is what selects the reporting path.
fn g_immutable(r: &mut Rng) -> String {
    let idx = pick(r, &["3", "5", "-1", "-2", "9"]);
    let report =
        "catch (RuntimeException e) { System.out.println(e.getClass().getName() + \" \" + e.getMessage()); }";
    match r.below(16) {
        // bounds, one receiver shape per arm
        0 => format!("try {{ new ArrayList<>(List.of(1, 2)).get({idx}); }} {report}"),
        1 => format!("try {{ Arrays.asList(1, 2).get({idx}); }} {report}"),
        2 => format!("try {{ List.of(1).get({idx}); }} {report}"),
        3 => format!("try {{ List.of(1, 2).get({idx}); }} {report}"),
        4 => format!("try {{ List.of(1, 2, 3).get({idx}); }} {report}"),
        5 => format!("try {{ List.of(1, 2, 3, 4, 5).get({idx}); }} {report}"),
        6 => format!("try {{ List.of().get({idx}); }} {report}"),
        7 => format!("try {{ Arrays.asList(1, 2, 3).set({idx}, 0); }} {report}"),
        // a structural refusal outranks a bad index on an immutable receiver
        8 => format!("try {{ List.of(1, 2).set({idx}, 0); }} {report}"),
        9 => format!("try {{ List.of(1, 2).remove({idx}); }} {report}"),
        // a null the factory is built from
        10 => "try { List.of(1, null); } catch (NullPointerException e) { System.out.println(\"npe \" + e.getMessage()); }".to_string(),
        11 => "try { List.of(1, 2, null, 4); } catch (NullPointerException e) { System.out.println(\"npe \" + e.getMessage()); }".to_string(),
        // a null the collection is asked about — the JDK's message here is its
        // helpful-NPE text for a `Set12`/`Map1` receiver, which BUGS.md records
        // javars cannot reproduce, so those arities stay out of the pool and
        // the ones whose message is `requireNonNull`'s own stay in.
        12 => format!("try {{ List.of(1, 2).contains(null); }} {report}"),
        13 => format!("try {{ List.of(1, 2).indexOf(null); }} {report}"),
        14 => format!("try {{ Set.of(1, 2, 3).contains(null); }} {report}"),
        _ => format!("try {{ Map.of(\"a\", 1, \"b\", 2).containsKey(null); }} {report}"),
    }
}

/// `List.subList` **views**, whose defining property is that they alias their
/// backing list rather than copy it.
///
/// A copy answers every read correctly, so read-only probes cannot distinguish
/// one from a view — which is exactly why this mode writes through both ends.
/// Each probe either mutates the parent and reads the view, mutates the view
/// and reads the parent, or structurally modifies the parent and then touches
/// the view, where Java raises `ConcurrentModificationException`.
fn g_listview(r: &mut Rng) -> String {
    let v = pick(r, &["7", "8", "99"]);
    let init = "List<Integer> l = new ArrayList<>(Arrays.asList(10, 20, 30, 40, 50));";
    match r.below(14) {
        0 => format!("{{ {init} System.out.println(l.subList(1, 4)); }}"),
        1 => format!("{{ {init} System.out.println(l.subList(0, 0) + \" \" + l.subList(2, 2).isEmpty()); }}"),
        2 => format!("{{ {init} System.out.println(l.subList(1, 4).size() + \" \" + l.subList(1, 4).get(1)); }}"),
        // parent write → visible through the view
        3 => format!("{{ {init} List<Integer> s = l.subList(1, 4); l.set(2, {v}); System.out.println(s); }}"),
        4 => format!("{{ {init} List<Integer> s = l.subList(0, 3); l.set(0, {v}); System.out.println(s.get(0) + \" \" + s.contains({v})); }}"),
        // view write → visible in the parent
        5 => format!("{{ {init} List<Integer> s = l.subList(1, 3); s.set(0, {v}); System.out.println(l); }}"),
        6 => format!("{{ {init} List<Integer> s = l.subList(2, 5); s.add({v}); System.out.println(l + \" \" + s); }}"),
        7 => format!("{{ {init} List<Integer> s = l.subList(1, 4); s.remove(0); System.out.println(l + \" \" + s); }}"),
        8 => format!("{{ {init} List<Integer> s = l.subList(1, 3); s.clear(); System.out.println(l + \" \" + s.size()); }}"),
        // a view of a view still reaches the same backing list
        9 => format!("{{ {init} List<Integer> s = l.subList(0, 4).subList(1, 3); s.set(0, {v}); System.out.println(l + \" \" + s); }}"),
        // reads that must agree with the equivalent plain list
        10 => format!("{{ {init} List<Integer> s = l.subList(1, 4); System.out.println(s.indexOf(30) + \" \" + s.equals(Arrays.asList(20, 30, 40))); }}"),
        11 => format!("{{ {init} List<Integer> s = l.subList(1, 4); int t = 0; for (int x : s) t += x; System.out.println(t); }}"),
        // a structural change to the parent invalidates the view
        12 => format!("{{ {init} List<Integer> s = l.subList(1, 3); l.add({v}); try {{ System.out.println(s.get(0)); }} catch (RuntimeException e) {{ System.out.println(e); }} }}"),
        _ => format!("{{ {init} List<Integer> s = l.subList(1, 3); l.remove(0); try {{ System.out.println(s.size()); }} catch (RuntimeException e) {{ System.out.println(e); }} }}"),
    }
}

/// `super.member` — the qualified access that names the **superclass's**
/// implementation of something the receiver's own class overrides.
///
/// It is the one call in Java that must NOT dispatch virtually, and a generator
/// that never writes `super.` cannot tell a correct lowering from no lowering at
/// all: every probe here would still be reachable through a plain `this.`, and
/// most would then either recurse forever or answer the override's value. The
/// support chain (`SupA`/`SupB`/`SupC`) is built so each shape has a distinct
/// wrong answer — see its comment in [`SUPPORT_CLASS`].
fn g_super(r: &mut Rng) -> String {
    let n = pick(r, &["0", "1", "2", "7", "-3"]);
    let s = pick(r, &["\"x\"", "\"\"", "\"zz\""]);
    match r.below(16) {
        // The whole chain: `SupC.f` → `SupB.f` → `SupA.f`. A virtual `super`
        // re-enters `SupC.f` and never returns.
        0 => format!("System.out.println(new SupC().f({n}));"),
        // Entering the same chain through the *base* static type — the override
        // is selected virtually, and only then does `super` stop being virtual.
        1 => format!("{{ SupA a = new SupC(); System.out.println(a.f({n})); }}"),
        2 => format!("{{ SupB b = new SupC(); System.out.println(b.f({n}) + \" \" + new SupB().f({n})); }}"),
        // `super.toString()` at two levels, plus `super.tag()` reaching the
        // grandparent's body past a parent that does not declare it.
        3 => "System.out.println(new SupC().toString());".to_string(),
        4 => "System.out.println(new SupB() + \" \" + new SupA());".to_string(),
        // The callee reached by `super` still dispatches its own unqualified
        // calls virtually, so `kind()` sees `SupC`'s `tag()`.
        5 => "System.out.println(new SupC().kind() + \" \" + new SupB().kind());".to_string(),
        // Overload selection happens at the superclass: a `double` argument
        // picks `f(double)`, an `int` picks `f(int)`.
        6 => format!("System.out.println(new SupC().fd() + \" \" + new SupC().f({n}));"),
        // A variadic `super` call, both spellings: an array that passes through
        // unpacked and a loose argument list that packs.
        7 => format!("System.out.println(new SupC().vs({n}, 2));"),
        8 => format!("{{ int[] a = {{{n}, 4}}; System.out.println(new SupC().vs(a)); }}"),
        9 => "System.out.println(new SupC().vs());".to_string(),
        // `super.field`, read / compound-assigned / incremented.
        10 => "System.out.println(new SupC().bump());".to_string(),
        11 => format!("{{ SupC c = new SupC(); c.bump(); System.out.println(c.f({n}) + \" \" + c); }}"),
        // `super` inside a lambda body (which outlives the frame it captured)
        // and behind a method reference.
        12 => format!("System.out.println(new SupC().lam({n}).of());"),
        13 => format!("System.out.println(new SupC().mref().of({s}) + new SupC().echo({s}));"),
        // `super.equals` where the superclass is the implicit `java.lang.Object`
        // — reference identity, which is deterministic (its `toString` and
        // `hashCode` are not, and are left ungenerated).
        14 => format!("{{ SupObj o = new SupObj({n}); System.out.println(o.sameAs(o) + \" \" + o.sameAs(new SupObj({n}))); }}"),
        _ => format!("{{ SupA[] xs = {{new SupA(), new SupB(), new SupC()}}; String t = \"\"; for (SupA a : xs) t += a.f({n}) + \",\"; System.out.println(t); }}"),
    }
}

/// `instanceof` — the runtime type test, asked of every shape javars's value
/// model can name.
///
/// No probe in this generator wrote `instanceof` before this mode, so the whole
/// form was unreachable and every clean sweep above was silent about it.
///
/// Every probe prints a *true* and a *false* answer drawn from one target
/// family, so neither a blanket `true` nor a blanket `false` satisfies one.
/// That shape is the point: the test a single-answer implementation passes is
/// the one that only ever asks about a type the value is not, and asking both
/// halves of the same question is what separates a real supertype walk from a
/// constant.
///
/// Deliberately absent, because javars's value model cannot decide them and a
/// probe would only re-report a documented BUGS.md simplification rather than
/// find anything:
///   * `new LinkedList<>()` — modeled as the same mutable list an `ArrayList`
///     is, so no test can separate the two.
///   * `Set.of(…)` — modeled as a hash-ordered `Set`, indistinguishable from
///     `new HashSet<>()`, where Java's `ImmutableCollections.SetN` is not one.
///   * a lambda against its functional interface — the closure records the body
///     and its captures, not the interface it was assigned to.
///   * `Long`/`Float`/`Character` — `int` and `long` are one `Value::Int`, a
///     `double` and a `float` one `Value::Float`, and a boxed `char` is the
///     one-character `String` javars models it as.
fn g_instanceof(r: &mut Rng) -> String {
    let i = pick(r, INTS);
    let d = pick(r, DBLS);
    let s = pick(r, STRS);
    let b = pick(r, BOOLS);
    match r.below(16) {
        // Each boxed primitive against its own wrapper, the wrapper it is *not*,
        // and the `java.lang` interfaces the JLS gives it.
        0 => format!(
            "{{ Object v = {i}; System.out.println((v instanceof Integer) + \",\" + (v instanceof Double) + \",\" + (v instanceof Boolean) + \",\" + (v instanceof Number) + \",\" + (v instanceof Comparable) + \",\" + (v instanceof String) + \",\" + (v instanceof Object)); }}"
        ),
        1 => format!(
            "{{ Object v = {d}; System.out.println((v instanceof Double) + \",\" + (v instanceof Integer) + \",\" + (v instanceof Number) + \",\" + (v instanceof Comparable) + \",\" + (v instanceof CharSequence) + \",\" + (v instanceof Object)); }}"
        ),
        2 => format!(
            "{{ Object v = {b}; System.out.println((v instanceof Boolean) + \",\" + (v instanceof Number) + \",\" + (v instanceof Comparable) + \",\" + (v instanceof String) + \",\" + (v instanceof Object)); }}"
        ),
        3 => format!(
            "{{ Object v = {s}; System.out.println((v instanceof String) + \",\" + (v instanceof CharSequence) + \",\" + (v instanceof Comparable) + \",\" + (v instanceof Number) + \",\" + (v instanceof List) + \",\" + (v instanceof Object)); }}"
        ),
        // `instanceof Object` over every shape at once. Java answers it `true`
        // for every non-null reference and `false` for `null`, so one blanket
        // answer fails on the other end whichever way it is chosen.
        4 => "{ Object[] vs = { 1, 2.5, true, \"s\", new int[]{1}, new ArrayList<Integer>(), new HashMap<String, Integer>(), new HashSet<Integer>(), new Left(), Color.RED, new Pt(1, 2), new IllegalStateException(\"e\"), null }; String out = \"\"; for (Object v : vs) out += (v instanceof Object) ? \"T\" : \"F\"; System.out.println(out); }".to_string(),
        // A declared subclass chain plus an interface only one sibling carries.
        5 => {
            let v = pick(r, &["new Left()", "new Right()", "new Base()", "new Bare(1)"]);
            format!(
                "{{ Object v = {v}; System.out.println((v instanceof Base) + \",\" + (v instanceof Left) + \",\" + (v instanceof Right) + \",\" + (v instanceof Marker) + \",\" + (v instanceof Bare) + \",\" + (v instanceof Object)); }}"
            )
        }
        // An enum constant is an instance of its own enum, of `java.lang.Enum`,
        // and of `Comparable` — and never of a *different* enum in the program.
        6 => {
            let c = pick(r, &["Color.RED", "Color.BLUE", "Op.ADD", "Ops.TIMES"]);
            format!(
                "{{ Object v = {c}; System.out.println((v instanceof Color) + \",\" + (v instanceof Op) + \",\" + (v instanceof Enum) + \",\" + (v instanceof Comparable) + \",\" + (v instanceof Object)); }}"
            )
        }
        // A record is an instance of `java.lang.Record`, and of no other record.
        7 => {
            let v = pick(r, &["new Pt(1, 2)", "new Tag(\"t\", 1.5)"]);
            format!(
                "{{ Object v = {v}; System.out.println((v instanceof Pt) + \",\" + (v instanceof Tag) + \",\" + (v instanceof Record) + \",\" + (v instanceof Comparable) + \",\" + (v instanceof Object)); }}"
            )
        }
        // The throwable chain, asked as an expression rather than through
        // `catch` — the same builtin decides both, and only `catch` was reachable.
        8 => {
            let v = pick(
                r,
                &[
                    "new IllegalArgumentException(\"e\")",
                    "new IllegalStateException(\"e\")",
                    "new ArithmeticException(\"e\")",
                    "new NumberFormatException(\"e\")",
                ],
            );
            format!(
                "{{ Object v = {v}; System.out.println((v instanceof IllegalArgumentException) + \",\" + (v instanceof RuntimeException) + \",\" + (v instanceof Exception) + \",\" + (v instanceof Throwable) + \",\" + (v instanceof Error) + \",\" + (v instanceof Object)); }}"
            )
        }
        // A mutable list, against both the interfaces it implements and the
        // collection kinds it is not.
        9 => "{ Object v = new ArrayList<Integer>(); System.out.println((v instanceof List) + \",\" + (v instanceof Collection) + \",\" + (v instanceof Iterable) + \",\" + (v instanceof ArrayList) + \",\" + (v instanceof Map) + \",\" + (v instanceof Set) + \",\" + (v instanceof Object)); }".to_string(),
        // The list *views*: `List.of` and `Arrays.asList` are `List`s that are
        // not `ArrayList`s, which is the half a name-only answer gets wrong.
        10 => {
            let v = pick(
                r,
                &[
                    "List.of(1, 2)",
                    "Arrays.asList(1, 2)",
                    "new ArrayList<Integer>(List.of(1, 2, 3)).subList(0, 2)",
                ],
            );
            format!(
                "{{ Object v = {v}; System.out.println((v instanceof List) + \",\" + (v instanceof Collection) + \",\" + (v instanceof ArrayList) + \",\" + (v instanceof Set) + \",\" + (v instanceof Object)); }}"
            )
        }
        // The three map kinds. `LinkedHashMap` extends `HashMap` and `TreeMap`
        // does not, so the pair only agrees with Java if the *declared* graph is
        // walked rather than the name matched.
        11 => {
            let v = pick(
                r,
                &[
                    "new HashMap<String, Integer>()",
                    "new LinkedHashMap<String, Integer>()",
                    "new TreeMap<String, Integer>()",
                ],
            );
            format!(
                "{{ Object v = {v}; System.out.println((v instanceof Map) + \",\" + (v instanceof HashMap) + \",\" + (v instanceof LinkedHashMap) + \",\" + (v instanceof TreeMap) + \",\" + (v instanceof SortedMap) + \",\" + (v instanceof Collection) + \",\" + (v instanceof Object)); }}"
            )
        }
        // The three set kinds, the same way: `LinkedHashSet` extends `HashSet`,
        // `TreeSet` does not, and neither is a `List`.
        12 => {
            let v = pick(
                r,
                &[
                    "new HashSet<Integer>()",
                    "new LinkedHashSet<Integer>()",
                    "new TreeSet<Integer>()",
                ],
            );
            format!(
                "{{ Object v = {v}; System.out.println((v instanceof Set) + \",\" + (v instanceof HashSet) + \",\" + (v instanceof LinkedHashSet) + \",\" + (v instanceof TreeSet) + \",\" + (v instanceof SortedSet) + \",\" + (v instanceof List) + \",\" + (v instanceof Object)); }}"
            )
        }
        // An array is an `Object` and a `Cloneable`, and is not a collection —
        // the element type it erases decides none of those.
        13 => {
            let v = pick(
                r,
                &[
                    "new int[]{1, 2}",
                    "new String[]{\"a\"}",
                    "new Object[]{1, \"a\"}",
                    "new Base[]{new Left()}",
                ],
            );
            format!(
                "{{ Object v = {v}; System.out.println((v instanceof Object) + \",\" + (v instanceof Cloneable) + \",\" + (v instanceof List) + \",\" + (v instanceof String) + \",\" + (v instanceof Base)); }}"
            )
        }
        // `instanceof` driving control flow, where the answer picks a branch
        // rather than being printed — and `null`, which is an instance of
        // nothing at all, including `Object`.
        14 => {
            let v = pick(r, &["new Left()", "new Right()", "new Base()"]);
            format!(
                "{{ Object v = {v}; String out; if (v instanceof Left) {{ out = \"L\"; }} else if (v instanceof Right) {{ out = \"R\"; }} else if (v instanceof Base) {{ out = \"B\"; }} else {{ out = \"?\"; }} Object n = null; System.out.println(out + \",\" + (n instanceof Object) + \",\" + (n instanceof Base) + \",\" + (!(v instanceof Marker)) + \",\" + ((v instanceof Base) && !(v instanceof Bare))); }}"
            )
        }
        // The test inside a loop over a mixed array, so one call site sees every
        // shape in turn rather than a single value per program.
        _ => format!(
            "{{ Object[] vs = {{ {i}, {d}, {s}, {b}, new Left(), Color.GREEN, new Pt(1, 2), new ArrayList<Integer>(), new HashMap<String, Integer>(), new int[]{{1}} }}; String out = \"\"; for (Object v : vs) {{ out += (v instanceof Number) ? \"N\" : (v instanceof CharSequence) ? \"C\" : (v instanceof Base) ? \"B\" : (v instanceof Enum) ? \"E\" : (v instanceof Record) ? \"R\" : (v instanceof Collection) ? \"L\" : (v instanceof Map) ? \"M\" : (v instanceof Object) ? \"O\" : \"?\"; }} System.out.println(out); }}"
        ),
    }
}

/// `toString()` overrides reached through a receiver the compiler cannot type.
///
/// The compiler resolves an override statically whenever the operand's declared
/// type names the class, so every probe here deliberately loses that type — the
/// value goes into an `Object`, into a collection, or into a `Map` — which is
/// the only way to reach the host's runtime lookup. Each surface is asked twice
/// over, once by concatenation and once by a rendering call, because those are
/// two different code paths (fusevm's `Op::Add` versus a builtin) and the
/// failure this mode exists to catch is them disagreeing for the same object.
///
/// `Bare` is in the pool as the negative case: it declares no override, so a
/// lookup that answered *some* body for every class would print `B`/`L`/`R`
/// where Java prints `Bare@<hash>` — and the probes keep that one to the
/// `endsWith`/`startsWith` shape, since the hash is not reproducible.
fn g_render(r: &mut Rng) -> String {
    let v = pick(
        r,
        &[
            "new Base()",
            "new Left()",
            "new Right()",
            "new SupC()",
            "new Pt(1, 2)",
            "new Tag(\"t\", 1.5)",
            "Color.RED",
            "Ops.TIMES",
        ],
    );
    match r.below(10) {
        // An `Object`-typed local: concatenation, `println`, `String.valueOf`,
        // `%s`, and an explicit `toString()` must all answer the same text.
        0 => format!(
            "{{ Object o = {v}; System.out.println(\"\" + o); System.out.println(o); System.out.println(String.valueOf(o)); System.out.println(String.format(\"%s\", o)); System.out.println(o.toString()); }}"
        ),
        // An element of a list, which renders through the collection's own
        // `toString` — the element's static type is erased by `get`.
        1 => format!(
            "{{ List<Object> l = new ArrayList<>(); l.add({v}); System.out.println(l); System.out.println(\"\" + l); System.out.println(l.toString()); System.out.println(l.get(0).toString()); }}"
        ),
        // Depth: a list inside a list, and a list inside a map value.
        2 => format!(
            "{{ List<Object> in = new ArrayList<>(); in.add({v}); List<Object> out = new ArrayList<>(); out.add(in); System.out.println(out); System.out.println(\"\" + out); }}"
        ),
        3 => format!(
            "{{ Map<String, Object> m = new LinkedHashMap<>(); m.put(\"k\", {v}); System.out.println(m); System.out.println(\"\" + m); }}"
        ),
        // A `Set` element and a map *key*, which render on the other side of the
        // `=` from a value.
        4 => format!(
            "{{ Set<Object> s = new LinkedHashSet<>(); s.add({v}); System.out.println(s); System.out.println(\"\" + s); }}"
        ),
        5 => format!(
            "{{ Map<Object, String> m = new LinkedHashMap<>(); m.put({v}, \"x\"); System.out.println(m); System.out.println(\"\" + m); }}"
        ),
        // A reference array, through both `Arrays` renderings.
        6 => format!(
            "{{ Object[] a = {{ {v}, {v} }}; System.out.println(Arrays.toString(a)); System.out.println(Arrays.deepToString(new Object[][] {{ a }})); System.out.println(\"\" + a[0]); }}"
        ),
        // The `Formatter` conversions that call `toString`, including the
        // uppercasing one and the receiver-as-format-string spelling.
        7 => format!(
            "{{ Object o = {v}; System.out.println(String.format(\"%s|%S|%10s|%.1s\", o, o, o, o)); System.out.println(\"%s\".formatted(o)); }}"
        ),
        // The negative case: a class with no override still renders Java's
        // default form, and the two surfaces still agree about it.
        8 => "{ Object o = new Bare(1); String a = \"\" + o; String b = String.valueOf(o); System.out.println(a.equals(b)); System.out.println(a.startsWith(\"Bare@\")); }".to_string(),
        // A `null` reference is the text \"null\" at every surface, never a call.
        _ => "{ Object o = null; System.out.println(\"\" + o); System.out.println(String.valueOf(o)); System.out.println(String.format(\"%s\", o)); }".to_string(),
    }
}

/// A collection's membership tests, over elements whose `equals` is their own.
///
/// Every other collection mode draws its elements from `Integer` and `String`,
/// which javars models as scalars and compares structurally by value — so no
/// existing probe can reach the comparison a collection performs on a *heap*
/// element, and the whole class of divergence where `contains` answers identity
/// instead of `equals` was invisible to the harness.
///
/// The pool is three shapes, because Java's answer differs across them:
///
///   * `Eqh` and `Pt`/`Tag` (a `record`) declare `equals` *and* a consistent
///     hash, so every container finds an equal element.
///   * `Eqn` declares `equals` and no `hashCode`, so it keeps `Object`'s
///     identity hash: an `ArrayList` still finds it (no hashing), and a
///     `HashSet`/`HashMap` does not — two equal instances land in different
///     buckets and never meet. A membership test that consulted `equals`
///     unconditionally would report `true` where Java reports `false`.
///   * `Eqx` declares neither, so identity is the whole answer everywhere.
///
/// `Eqc` counts its own invocations, which pins the *number* of comparisons a
/// list scan performs: `indexOf` stops at the first hit, and an implementation
/// that resolved every element's verdict up front would run the body too many
/// times. Only list probes read the counter — a hash container's comparison
/// count follows bucket layout, which javars does not model.
///
/// Nothing here prints a `HashSet`/`HashMap` holding a user object: their
/// iteration order follows `hashCode`, and javars's identity hash is its heap
/// handle (see BUGS.md). Order-bearing output uses the insertion-ordered
/// `Linked*` forms; the hash forms are asked only for booleans, sizes and
/// looked-up values.
fn g_equals(r: &mut Rng) -> String {
    // (constructor for the element, a second equal instance, an unequal one)
    let (a, b, c) = *pick(
        r,
        &[
            ("new Eqh(1)", "new Eqh(1)", "new Eqh(2)"),
            ("new Eqn(1)", "new Eqn(1)", "new Eqn(2)"),
            ("new Pt(1, 2)", "new Pt(1, 2)", "new Pt(3, 4)"),
            (
                "new Tag(\"t\", 1.5)",
                "new Tag(\"t\", 1.5)",
                "new Tag(\"u\", 2.5)",
            ),
            ("new Eqx(1)", "new Eqx(1)", "new Eqx(2)"),
        ],
    );
    match r.below(14) {
        // `List` never hashes, so `equals` alone decides every one of these.
        0 => format!(
            "{{ List<Object> l = new ArrayList<>(); l.add({a}); l.add({c}); System.out.println(l.contains({b}) + \" \" + l.indexOf({b}) + \" \" + l.lastIndexOf({b}) + \" \" + l.contains({c})); }}"
        ),
        1 => format!(
            "{{ List<Object> l = new ArrayList<>(); l.add({a}); l.add({b}); System.out.println(l.indexOf({b}) + \" \" + l.lastIndexOf({b}) + \" \" + l.size()); }}"
        ),
        2 => format!(
            "{{ List<Object> l = new ArrayList<>(); l.add({a}); l.add({c}); Object q = {b}; System.out.println(l.remove(q) + \" \" + l.size() + \" \" + l.contains(q)); }}"
        ),
        3 => format!(
            "{{ List<Object> x = new ArrayList<>(); x.add({a}); List<Object> y = new ArrayList<>(); y.add({b}); List<Object> z = new ArrayList<>(); z.add({c}); System.out.println(x.equals(y) + \" \" + x.equals(z) + \" \" + x.equals(new ArrayList<>())); }}"
        ),
        4 => format!(
            "{{ List<Object> l = new ArrayList<>(); l.add({c}); l.add({a}); l.add({c}); System.out.println(l.subList(1, 3).contains({b}) + \" \" + l.subList(0, 2).indexOf({b})); }}"
        ),
        // The hash containers: `Eqn` is the one that must *not* be found.
        5 => format!(
            "{{ Set<Object> s = new HashSet<>(); System.out.println(s.add({a}) + \" \" + s.add({b}) + \" \" + s.size() + \" \" + s.contains({b})); }}"
        ),
        6 => format!(
            "{{ Set<Object> s = new HashSet<>(); s.add({a}); System.out.println(s.remove({b}) + \" \" + s.size() + \" \" + s.remove({c})); }}"
        ),
        7 => format!(
            "{{ Map<Object, Integer> m = new HashMap<>(); m.put({a}, 1); System.out.println(m.get({b}) + \" \" + m.containsKey({b}) + \" \" + m.size() + \" \" + m.getOrDefault({c}, -1)); }}"
        ),
        8 => format!(
            "{{ Map<Object, Integer> m = new HashMap<>(); m.put({a}, 1); m.put({b}, 2); System.out.println(m.size() + \" \" + m.get({a}) + \" \" + m.containsValue(2) + \" \" + m.remove({b})); }}"
        ),
        9 => format!(
            "{{ Map<Object, Integer> m = new HashMap<>(); m.put({a}, 1); System.out.println(m.putIfAbsent({b}, 9) + \" \" + m.size() + \" \" + m.putIfAbsent({c}, 9) + \" \" + m.size()); }}"
        ),
        // Insertion-ordered forms, where the contents can be printed.
        10 => format!(
            "{{ Set<Object> s = new LinkedHashSet<>(); s.add({a}); s.add({b}); s.add({c}); System.out.println(s.size() + \" \" + s); }}"
        ),
        11 => format!(
            "{{ Set<Object> s = new LinkedHashSet<>(); s.addAll(new ArrayList<>(Arrays.asList({a}, {b}, {c}))); System.out.println(s.size() + \" \" + s); }}"
        ),
        // Building a set from a sequence de-duplicates by the same rule.
        12 => format!(
            "{{ System.out.println(new HashSet<>(Arrays.asList({a}, {b}, {c})).size()); }}"
        ),
        // The comparison *count* a list scan performs, which only a
        // short-circuiting scan gets right.
        _ => {
            "{ Eqc.calls = 0; List<Object> l = new ArrayList<>(); l.add(new Eqc(1)); l.add(new Eqc(2)); l.add(new Eqc(3)); boolean h = l.contains(new Eqc(1)); int n = Eqc.calls; Eqc.calls = 0; int i = l.indexOf(new Eqc(3)); System.out.println(h + \" \" + n + \" \" + i + \" \" + Eqc.calls); }"
                .to_string()
        }
    }
}

const SUPPORT: &str = concat!(
    "    static int fin1() { try { return 1; } finally { System.out.println(\"f1\"); } }\n",
    "    static int fin2() { int x = 5; try { return x; } finally { x = 99; } }\n",
    "    static int fin3() { try { return 6; } finally { return 66; } }\n",
    "    static int resret() { try (Res a = new Res(\"r\")) { return 7; } }\n",
    "    static String shout(Color c) { return c.name() + \"!\"; }\n",
    "    static Color next(Color c) { return c == Color.BLUE ? Color.RED : Color.values()[c.ordinal() + 1]; }\n",
    "    static int useCalc(Calc c, int a, int b) { return c.of(a, b); }\n",
    "    static Calc mkAdder(int n) { return (x, y) -> x + y + n; }\n",
    // Variable-arity declarations for the `varargs` mode. They come in
    // competing sets on purpose: `vpick` pairs a fixed-arity overload with a
    // variadic one (the fixed one must win at its own arity and only there),
    // and `vkind` pairs two variadic ones whose element types decide which is
    // more specific. A single variadic declaration would be satisfied by a
    // resolver that ignores the phase ordering entirely.
    "    static int vsum(int... xs) { int t = 0; for (int v : xs) t += v; return t; }\n",
    "    static String vpick(int a, int b) { return \"fixed2\"; }\n",
    "    static String vpick(int... xs) { return \"var\" + xs.length; }\n",
    "    static String vkind(String... xs) { return \"str\" + xs.length; }\n",
    "    static String vkind(Object... xs) { return \"obj\" + xs.length; }\n",
    "    static String vtag(String tag, int... xs) { return tag + \":\" + xs.length + \":\" + Arrays.toString(xs); }\n",
    "    static String vnull(Object... xs) { return xs == null ? \"nullarray\" : \"len\" + xs.length; }\n",
    // The nested members the `nested` mode names. They sit *inside* `T`, which
    // is the whole point: `Nst` and `T.Nst` are two spellings of one type, and a
    // parser that steps over a lowercase package qualifier only accepts the
    // first and rejects the second.
    //
    // `Greeter` carries a `default` and a `static` member so that the probes
    // reach both without declaring a class to implement it — `of` returns the
    // lambda, and `greet`/`shout` are inherited bodies rather than the
    // abstract `name`.
    "    static class Nst {\n",
    "        final int x, y;\n",
    "        Nst(int x, int y) { this.x = x; this.y = y; }\n",
    "        int sum() { return x + y; }\n",
    "        public boolean equals(Object o) { return o instanceof Nst p && p.x == x && p.y == y; }\n",
    "        public int hashCode() { return x * 31 + y; }\n",
    "        public String toString() { return \"(\" + x + \",\" + y + \")\"; }\n",
    "    }\n",
    "    interface Greeter {\n",
    "        String name();\n",
    "        default String greet() { return \"Hello, \" + name(); }\n",
    "        default String shout() { return greet().toUpperCase() + \"!\"; }\n",
    "        static Greeter of(String n) { return () -> n; }\n",
    "    }\n",
);

/// The types the probes construct: the `AutoCloseable` the resource probes open
/// and close, the enums (bare, stateful, and body-carrying), the class holding
/// the `static` fields, and the records.
const SUPPORT_CLASS: &str = concat!(
    "enum Color { RED, GREEN, BLUE }\n",
    "enum Op {\n",
    "    ADD, SUB, MUL;\n",
    "    int apply(int a, int b) { switch (this) { case ADD: return a + b; case SUB: return a - b; default: return a * b; } }\n",
    "    boolean isMul() { return this == MUL; }\n",
    "}\n",
    // An enum whose constants carry constructor arguments (per-constant state).
    "enum Planet {\n",
    "    MERCURY(3.3), EARTH(5.97), JUPITER(1898.0);\n",
    "    private final double mass;\n",
    "    Planet(double m) { this.mass = m; }\n",
    "    double mass() { return mass; }\n",
    "    boolean heavy() { return mass > 100.0; }\n",
    "}\n",
    // An enum whose constants carry bodies — anonymous subclasses overriding an
    // abstract method (and, for one of them, a concrete one).
    "enum Ops {\n",
    "    PLUS { int apply(int a, int b) { return a + b; } },\n",
    "    MINUS { int apply(int a, int b) { return a - b; } },\n",
    "    TIMES { int apply(int a, int b) { return a * b; } String label() { return \"x\"; } };\n",
    "    abstract int apply(int a, int b);\n",
    "    String label() { return name().toLowerCase(); }\n",
    "}\n",
    "class St {\n",
    "    static int n = 1;\n",
    "    static final String LABEL = \"L\";\n",
    "    static int SIZE = 2 + 3;\n",
    "    static int INIT;\n",
    "    static int[] arr = {7, 8};\n",
    "    static { INIT = SIZE * 2; }\n",
    "    static int get() { return n; }\n",
    "    static void bump() { n = n * 2; }\n",
    "}\n",
    "class Sub2 extends St { }\n",
    "record Pt(int x, int y) { int sum() { return x + y; } }\n",
    "record Tag(String tag, double weight) { }\n",
    "record Ord(int lo, int hi) {\n",
    "    Ord { if (lo > hi) { throw new IllegalArgumentException(lo + \">\" + hi); } }\n",
    "}\n",
    // The functional interfaces the lambda probes target. A user-declared
    // single-abstract-method interface is exactly what the JDK's own
    // `java.util.function` types are, so these exercise the same path.
    // A hierarchy for the reference-cast probes: a base, two siblings, and an
    // interface only one of them implements, so a downcast can succeed or throw.
    // A class that declares neither `equals` nor `toString`, so both come from
    // `Object`: reference identity and `Bare@<hash>`.
    "class Bare { int v; Bare(int v) { this.v = v; } }\n",
    "class Base { public String toString() { return \"B\"; } }\n",
    "class Left extends Base { public String toString() { return \"L\"; } }\n",
    "class Right extends Base implements Marker { public String toString() { return \"R\"; } }\n",
    "interface Marker { }\n",
    "interface Calc { int of(int a, int b); }\n",
    "interface Str1 { String of(String s); }\n",
    "interface Pred1 { boolean of(int a); }\n",
    "interface Sup0 { int of(); }\n",
    // A *generic* supplier, for the `ctorref` and `anon` modes: a constructor
    // reference needs a target type whose method returns the constructed type,
    // and `Sup0` above is fixed to `int`.
    "interface Gen<T> { T get(); }\n",
    // An *instance* initializer block — a member-position `{ ... }`, which runs
    // before the constructor body. `static { }` was generated; this was not.
    "class Ini {\n",
    "    int v;\n",
    "    String seen = \"none\";\n",
    "    { seen = \"init\"; v = 1; }\n",
    "    Ini(int k) { v = v + k; }\n",
    "}\n",
    "class Res implements AutoCloseable {\n",
    "    String n;\n",
    "    Res(String n) { this.n = n; System.out.println(\"open \" + n); }\n",
    "    public void close() { System.out.println(\"close \" + n); }\n",
    "}\n",
    // A variable-arity *constructor* and a variable-arity *instance* method —
    // the two call sites besides a `static` that Java packs arguments at, and
    // the reason a statics-only implementation would make the same declaration
    // callable or not depending on where it sits.
    "class Bag {\n",
    "    int n;\n",
    "    Bag(int... xs) { for (int v : xs) n += v; }\n",
    "    int total() { return n; }\n",
    "    int plus(int... xs) { int t = n; for (int v : xs) t += v; return t; }\n",
    "}\n",
    // Two *unrelated* classes declaring statics of the same name — `Qa` and `Qb`
    // both spell `f`, `g` and `h`. A qualified `Qb.f(1)` must reach `Qb`'s body
    // and nothing else, which is only observable when a same-named static exists
    // somewhere else in the compilation unit. `g`'s two overloads differ in
    // parameter type, so a by-name-only resolver picks the *signature* that fits
    // best and silently crosses classes.
    "class Qa {\n",
    "    static int f(int x) { return x + 1; }\n",
    "    static String g(String s) { return \"a:\" + s; }\n",
    "    static int h() { return 1; }\n",
    "}\n",
    "class Qb {\n",
    "    static int f(int x) { return x + 100; }\n",
    "    static String g(Object o) { return \"b:\" + o; }\n",
    "    static int h() { return 2; }\n",
    "}\n",
    // A chain, so a subclass's static *hides* the one it inherits while the
    // names it does not redeclare still resolve up the chain.
    "class Qbase {\n",
    "    static String kind() { return \"base\"; }\n",
    "    static int only() { return 7; }\n",
    "}\n",
    "class Qderiv extends Qbase {\n",
    "    static String kind() { return \"deriv\"; }\n",
    "}\n",
    // A three-level chain for the `super` mode. Every member here exists to make
    // one wrong lowering of `super.m(...)` observable:
    //   * `f` is declared at all three levels, so dispatching `super.f` on the
    //     receiver's runtime class re-enters `SupC.f` and never terminates.
    //   * `tag` is declared on `SupA` and `SupC` but NOT on `SupB`, so
    //     `super.tag()` from `SupC` has to walk past the parent to the
    //     grandparent's body.
    //   * `kind`'s body calls an unqualified `tag()`, which must still dispatch
    //     *virtually* back down to `SupC` — `super` de-virtualizes exactly one
    //     call, not the whole callee.
    //   * `f(int)`/`f(double)` are an overload pair, `vs` is variadic, and `n`
    //     is a field, so `super.` is exercised at each of the forms that resolve
    //     differently from a plain `this.`.
    // No field is re-declared down the chain: field *hiding* is a documented
    // BUGS.md simplification, and generating it would only reproduce it.
    "class SupA {\n",
    "    int n = 3;\n",
    "    String tag() { return \"A\"; }\n",
    "    String kind() { return \"k:\" + tag(); }\n",
    "    String echo(String s) { return \"A\" + s; }\n",
    "    int f(int x) { return x + 1; }\n",
    "    int f(double x) { return 100; }\n",
    "    int vs(int... xs) { int t = 0; for (int v : xs) t += v; return t; }\n",
    "    public String toString() { return \"A<\" + n + \">\"; }\n",
    "}\n",
    "class SupB extends SupA {\n",
    "    int f(int x) { return super.f(x) * 10; }\n",
    "    public String toString() { return \"B[\" + super.toString() + \"]\"; }\n",
    "}\n",
    "class SupC extends SupB {\n",
    "    String tag() { return \"C\"; }\n",
    "    String kind() { return \"C/\" + super.kind(); }\n",
    "    String echo(String s) { return \"C\" + s; }\n",
    "    int f(int x) { return super.f(x) + 2; }\n",
    "    int vs(int... xs) { return super.vs(xs) + super.vs(1, 2); }\n",
    "    public String toString() { return \"C{\" + super.toString() + \",\" + super.tag() + \"}\"; }\n",
    "    int fd() { return super.f(2.5); }\n",
    "    int bump() { super.n += 4; super.n++; return super.n + this.n; }\n",
    "    Sup0 lam(int k) { return () -> super.f(k) + 7; }\n",
    "    Str1 mref() { return super::echo; }\n",
    "}\n",
    // A class whose superclass is the implicit `java.lang.Object`, so
    // `super.equals` is Object's reference identity. Its `toString`/`hashCode`
    // are deliberately not reachable here: both render an identity hash, which
    // differs between runs of the same JVM and so has no deterministic answer.
    "class SupObj {\n",
    "    int v;\n",
    "    SupObj(int v) { this.v = v; }\n",
    "    boolean sameAs(Object o) { return super.equals(o); }\n",
    "}\n",
    // The `equals` mode's element pool. `Eqh` is the correctly written pair;
    // `Eqn` deliberately omits `hashCode`, which is what makes a hash container
    // miss an element an `ArrayList` finds; `Eqc` counts its own invocations so
    // a probe can pin how many comparisons a scan performs.
    "class Eqh {\n",
    "    int v;\n",
    "    Eqh(int v) { this.v = v; }\n",
    "    public boolean equals(Object o) { return o instanceof Eqh && ((Eqh) o).v == v; }\n",
    "    public int hashCode() { return v; }\n",
    "    public String toString() { return \"Eqh\" + v; }\n",
    "}\n",
    "class Eqn {\n",
    "    int v;\n",
    "    Eqn(int v) { this.v = v; }\n",
    "    public boolean equals(Object o) { return o instanceof Eqn && ((Eqn) o).v == v; }\n",
    "    public String toString() { return \"Eqn\" + v; }\n",
    "}\n",
    // The negative case: neither `equals` nor `hashCode`, so identity is the
    // whole answer in every container. It carries a `toString` because the
    // probes print set contents, and `Object`'s default renders an identity hash
    // that differs between runs of the same JVM.
    "class Eqx {\n",
    "    int v;\n",
    "    Eqx(int v) { this.v = v; }\n",
    "    public String toString() { return \"Eqx\" + v; }\n",
    "}\n",
    "class Eqc {\n",
    "    static int calls;\n",
    "    int v;\n",
    "    Eqc(int v) { this.v = v; }\n",
    "    public boolean equals(Object o) { calls++; return o instanceof Eqc && ((Eqc) o).v == v; }\n",
    "    public int hashCode() { return v; }\n",
    "    public String toString() { return \"Eqc\" + v; }\n",
    "}\n",
);

#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
    All,
    Arith,
    IntDiv,
    DoubleArith,
    MixedDiv,
    DoubleFmt,
    Concat,
    Compare,
    Bool,
    Ternary,
    StrMethod,
    Math,
    Format,
    Integer,
    Loop,
    Switch,
    Array,
    Overflow,
    ForEach,
    Exception,
    Fault,
    Finally,
    Resource,
    Enum,
    Static,
    Record,
    Lambda,
    Collection,
    SwitchExpr,
    VarInfer,
    Bitwise,
    Shift,
    Cast,
    IncDec,
    Literal,
    Printf,
    LabelFlow,
    Char,
    Regex,
    Float,
    Decl,
    Object,
    StaticRef,
    LoopKind,
    Narrow,
    ListOp,
    Varargs,
    ListView,
    Immutable,
    Super,
    InstanceOf,
    Render,
    Equals,
    Bits,
    Objects,
    Deque,
    Mutate,
    Chars,
    Nested,
    Builder,
    MathFn,
    MapFn,
    CtorRef,
    Optional,
    Stream,
    ArraysFn,
    ParseFn,
    TextBlock,
    Anon,
    Clinit,
    TernProm,
    NullUnbox,
    IntCache,
    NumProm,
    FmtFlag,
    SBuild,
    HashIter,
    Exc,
    Overload,
    SwFall,
    Sealed,
    Capture,
    Generic,
    FailFast,
    View,
    Erased,
    Lru,
    BitsFloat,
    RecHash,
    StreamOps,
}

const CONCRETE: &[Mode] = &[
    Mode::Arith,
    Mode::IntDiv,
    Mode::DoubleArith,
    Mode::MixedDiv,
    Mode::DoubleFmt,
    Mode::Concat,
    Mode::Compare,
    Mode::Bool,
    Mode::Ternary,
    Mode::StrMethod,
    Mode::Math,
    Mode::Format,
    Mode::Integer,
    Mode::Loop,
    Mode::Switch,
    Mode::Array,
    Mode::Overflow,
    Mode::ForEach,
    Mode::Exception,
    Mode::Fault,
    Mode::Finally,
    Mode::Resource,
    Mode::Enum,
    Mode::Static,
    Mode::Record,
    Mode::Lambda,
    Mode::Collection,
    Mode::SwitchExpr,
    Mode::VarInfer,
    Mode::Bitwise,
    Mode::Shift,
    Mode::Cast,
    Mode::IncDec,
    Mode::Literal,
    Mode::Printf,
    Mode::LabelFlow,
    Mode::Char,
    Mode::Regex,
    Mode::Float,
    Mode::Decl,
    Mode::Object,
    Mode::StaticRef,
    Mode::LoopKind,
    Mode::Narrow,
    Mode::ListOp,
    Mode::Varargs,
    Mode::ListView,
    Mode::Immutable,
    Mode::Super,
    Mode::InstanceOf,
    Mode::Render,
    Mode::Equals,
    Mode::Bits,
    Mode::Objects,
    Mode::Deque,
    Mode::Mutate,
    Mode::Chars,
    Mode::Nested,
    Mode::Builder,
    Mode::MathFn,
    Mode::MapFn,
    Mode::CtorRef,
    Mode::Optional,
    Mode::Stream,
    Mode::ArraysFn,
    Mode::ParseFn,
    Mode::TextBlock,
    Mode::Anon,
    Mode::Clinit,
    Mode::TernProm,
    Mode::NullUnbox,
    Mode::IntCache,
    Mode::NumProm,
    Mode::FmtFlag,
    Mode::SBuild,
    Mode::HashIter,
    Mode::Exc,
    Mode::Overload,
    Mode::SwFall,
    Mode::Sealed,
    Mode::Capture,
    Mode::Generic,
    Mode::FailFast,
    Mode::View,
    Mode::Erased,
    Mode::Lru,
    Mode::BitsFloat,
    Mode::RecHash,
    Mode::StreamOps,
];

/// The `Integer`/`Long` bit-twiddling statics, at the boundaries where the two
/// widths disagree.
///
/// No probe in this generator named one before this mode: `bitCount`,
/// `rotateLeft`, `highestOneBit`, `numberOfLeadingZeros` and `reverseBytes` had
/// zero occurrences across the whole corpus, so a 24,480-probe sweep could not
/// see them. The operand pool is deliberately all edges — 0, -1, both MIN/MAX
/// values, a lone bit and a byte-asymmetric pattern — because every one of these
/// methods is exact everywhere else and only interesting at a boundary.
///
/// `sum`/`max`/`min` ride along for the same reason: they are the arms where an
/// `Integer` call must narrow to 32 bits and a `Long` call must not, and
/// sharing one 64-bit implementation between them is invisible until an operand
/// reaches `Integer.MAX_VALUE`.
fn g_bits(r: &mut Rng) -> String {
    let i = pick(
        r,
        &[
            "0",
            "-1",
            "1",
            "100",
            "0x12345678",
            "Integer.MIN_VALUE",
            "Integer.MAX_VALUE",
            "-2147483648",
        ],
    );
    let j = pick(
        r,
        &[
            "0L",
            "-1L",
            "1L",
            "255L",
            "Long.MIN_VALUE",
            "Long.MAX_VALUE",
            "4294967296L",
        ],
    );
    let d = pick(r, &["0", "1", "8", "31", "32", "33", "-1", "63", "64"]);
    let unary = pick(
        r,
        &[
            "bitCount",
            "reverse",
            "reverseBytes",
            "highestOneBit",
            "lowestOneBit",
            "numberOfLeadingZeros",
            "numberOfTrailingZeros",
            "signum",
        ],
    );
    match r.below(8) {
        0 => format!("System.out.println(Integer.{unary}({i}));"),
        1 => format!("System.out.println(Long.{unary}({j}));"),
        2 => format!("System.out.println(Integer.rotateLeft({i}, {d}) + \" \" + Integer.rotateRight({i}, {d}));"),
        3 => format!("System.out.println(Long.rotateLeft({j}, {d}) + \" \" + Long.rotateRight({j}, {d}));"),
        // The width test: `Integer.sum` wraps at 32 bits, `Long.sum` at 64.
        4 => format!("System.out.println(Integer.sum({i}, {d}) + \" \" + Long.sum({j}, {d}));"),
        5 => format!("System.out.println(Integer.max({i}, {d}) + \" \" + Integer.min({i}, {d}) + \" \" + Integer.compare({i}, {d}));"),
        6 => format!("System.out.println(Integer.toBinaryString(Integer.{unary}({i})) + \"|\" + Integer.toHexString({i}));"),
        // A method reference to a bit static, which is also the shape
        // `reduce`/`merge` is written with.
        _ => format!(
            "{{ java.util.function.IntBinaryOperator f = Integer::sum; System.out.println(f.applyAsInt({i}, {d})); }}"
        ),
    }
}

/// `java.util.Objects` — the class whose whole purpose is answering for a
/// `null` where the instance method throws.
///
/// `Objects.` appeared zero times in the generator before this mode. Half the
/// pool is `null` on purpose: `Objects.hashCode(null)` is 0,
/// `Objects.toString(null)` is the four-character string, and
/// `Objects.hash()` is 1 rather than 0 — three answers a plausible
/// implementation gets wrong in three different directions.
fn g_objects(r: &mut Rng) -> String {
    let v = pick(
        r,
        &["null", "\"a\"", "5", "1.5", "'c'", "true", "List.of(1, 2)"],
    );
    let w = pick(r, &["null", "\"a\"", "5", "\"b\""]);
    let report =
        "catch (RuntimeException e) { System.out.println(e.getClass().getName() + \" \" + e.getMessage()); }";
    // `requireNonNull` and `requireNonNullElse` return their type variable, so
    // a bare `null` argument leaves `T` to be inferred from the *enclosing*
    // `println` — and `println(char[])` and `println(String)` both match, which
    // `javac` reports as "reference to println is ambiguous". The whole program
    // then fails to compile and the harness counts it a skip: that is what
    // dropped 218 of 300 `--mode objects` programs. Naming `Object` pins `T`
    // without changing the value or the exception being probed. The other arms
    // need no cast — their results are already `int`, `String` or `boolean`.
    let vo = if *v == "null" { "(Object) null" } else { *v };
    let wo = if *w == "null" { "(Object) null" } else { *w };
    match r.below(10) {
        0 => format!("System.out.println(Objects.hashCode({v}));"),
        1 => format!("System.out.println(Objects.toString({v}));"),
        2 => format!("System.out.println(Objects.toString({v}, \"dflt\"));"),
        3 => format!("System.out.println(Objects.isNull({v}) + \" \" + Objects.nonNull({v}));"),
        4 => format!("System.out.println(Objects.equals({v}, {w}));"),
        5 => format!("System.out.println(Objects.hash({v}, {w}));"),
        // `Objects.hash()` seeds at 1 and folds, so the empty call is not 0.
        6 => {
            "System.out.println(Objects.hash() + \" \" + Objects.hash((Object) null));".to_string()
        }
        7 => format!("try {{ System.out.println(Objects.requireNonNull({vo})); }} {report}"),
        8 => format!(
            "try {{ System.out.println(Objects.requireNonNull({vo}, \"was null\")); }} {report}"
        ),
        _ => {
            format!(
                "try {{ System.out.println(Objects.requireNonNullElse({vo}, {wo})); }} {report}"
            )
        }
    }
}

/// `Deque`/`Queue` — the head-and-tail collection, and the three families of
/// empty-receiver behaviour a program can tell apart.
///
/// `ArrayDeque`, `addFirst`, `pollLast` and `peekFirst` all had zero
/// occurrences before this mode. The empty receiver is half the pool because
/// that is the only place `getFirst` (throws), `peekFirst` (null) and
/// `pollFirst` (null, and removes) stop agreeing.
fn g_deque(r: &mut Rng) -> String {
    let seed = pick(
        r,
        &[
            "new ArrayDeque<>()",
            "new ArrayDeque<>(List.of(1, 2, 3))",
            "new LinkedList<>()",
            "new LinkedList<>(List.of(7, 8))",
        ],
    );
    let v = pick(r, &["9", "0", "-4"]);
    let init = format!("Deque<Integer> q = {seed};");
    let report =
        "catch (RuntimeException e) { System.out.println(e.getClass().getName() + \" \" + e.getMessage()); }";
    match r.below(12) {
        // `push` is `addFirst`, so a stack built with it reads back reversed.
        0 => format!("{{ {init} q.push({v}); q.push(1); System.out.println(q); }}"),
        1 => format!("{{ {init} q.addLast({v}); q.addFirst(1); System.out.println(q + \" \" + q.size()); }}"),
        2 => format!("{{ {init} q.offer({v}); q.offerFirst(1); q.offerLast(2); System.out.println(q); }}"),
        // The null-answering readers on whatever the seed left.
        3 => format!("{{ {init} System.out.println(q.peek() + \" \" + q.peekFirst() + \" \" + q.peekLast()); }}"),
        4 => format!("{{ {init} System.out.println(q.poll() + \" \" + q + \" \" + q.pollLast() + \" \" + q); }}"),
        5 => format!("{{ {init} System.out.println(q.pollFirst() + \" \" + q.pollLast() + \" \" + q.isEmpty()); }}"),
        // The throwing readers, which is where an empty seed matters.
        6 => format!("{{ {init} try {{ System.out.println(q.getFirst() + \" \" + q.getLast()); }} {report} }}"),
        7 => format!("{{ {init} try {{ System.out.println(q.element()); }} {report} }}"),
        8 => format!("{{ {init} try {{ System.out.println(q.pop() + \" \" + q); }} {report} }}"),
        9 => format!("{{ {init} try {{ System.out.println(q.removeFirst() + \" \" + q.removeLast()); }} {report} }}"),
        // A deque is still a collection: iteration order is head to tail.
        10 => format!("{{ {init} q.addLast({v}); int t = 0; for (int x : q) t = t * 10 + x; System.out.println(t + \" \" + q.contains({v})); }}"),
        _ => format!("{{ {init} q.addFirst({v}); System.out.println(q.toString() + \" \" + q.size() + \" \" + q.isEmpty()); }}"),
    }
}

/// `removeIf` and `replaceAll` — the two `Collection` mutators that run a user
/// lambda per element, across all three list fixities and both set shapes.
///
/// Neither appeared before this mode (the seven `replaceAll` hits in the
/// generator were `String.replaceAll`, the regex one). The three receivers
/// answer differently and a `catch` can see it: `List.of` throws before it
/// looks at the argument, `Arrays.asList` runs the predicate and throws only if
/// something must actually go, and an `ArrayList` does the work — so a probe
/// that only used a mutable receiver would miss two thirds of the behaviour.
fn g_mutate(r: &mut Rng) -> String {
    let recv = pick(
        r,
        &[
            "new ArrayList<>(List.of(1, 2, 3, 4))",
            "new ArrayList<Integer>()",
            "Arrays.asList(1, 2, 3)",
            "List.of(1, 2, 3)",
        ],
    );
    let pred = pick(
        r,
        &["x -> x % 2 == 0", "x -> false", "x -> true", "x -> x > 2"],
    );
    let op = pick(r, &["x -> x * 2", "x -> x", "x -> -x"]);
    let set = pick(
        r,
        &[
            "new HashSet<>(List.of(1, 2, 3))",
            "new LinkedHashSet<>(List.of(1, 2, 3))",
            "new TreeSet<>(List.of(3, 1, 2))",
            "Set.of(1, 2)",
        ],
    );
    let report =
        "catch (RuntimeException e) { System.out.println(e.getClass().getName() + \" \" + e.getMessage()); }";
    match r.below(10) {
        0 => format!("{{ List<Integer> l = {recv}; try {{ System.out.println(l.removeIf({pred}) + \" \" + l); }} {report} }}"),
        1 => format!("{{ List<Integer> l = {recv}; try {{ l.replaceAll({op}); System.out.println(l); }} {report} }}"),
        // A null argument: the immutable receiver refuses before it sees it.
        2 => format!("{{ List<Integer> l = {recv}; try {{ l.removeIf(null); }} {report} }}"),
        3 => format!("{{ List<Integer> l = {recv}; try {{ l.replaceAll(null); }} {report} }}"),
        4 => format!("{{ Set<Integer> s = {set}; try {{ System.out.println(s.removeIf({pred}) + \" \" + s); }} {report} }}"),
        // A `removeIf` that removed something is a structural modification, so
        // an outstanding view goes stale; one that removed nothing does not.
        5 => format!("{{ List<Integer> l = new ArrayList<>(List.of(1, 2, 3)); List<Integer> v = l.subList(0, 2); l.removeIf({pred}); try {{ System.out.println(v); }} {report} }}"),
        // `replaceAll` bumps the modification count whether or not anything
        // changed, so the same view is stale after `x -> x`.
        6 => format!("{{ List<Integer> l = new ArrayList<>(List.of(1, 2, 3)); List<Integer> v = l.subList(0, 2); l.replaceAll({op}); try {{ System.out.println(v); }} {report} }}"),
        7 => format!("{{ List<Integer> l = {recv}; try {{ System.out.println(l.removeIf({pred}) + \" \" + l.removeIf({pred})); }} {report} }}"),
        // A `subList` view: the elements it removes are the parent's, and the
        // parent must show it. `keySet()`/`values()` are deliberately NOT
        // probed here — BUGS.md records them as copies rather than views, so a
        // `removeIf` through one would fail for a reason this mode is not
        // about and would sit permanently red.
        8 => format!("{{ List<Integer> l = new ArrayList<>(List.of(1, 2, 3, 4)); List<Integer> v = l.subList(1, 4); System.out.println(v.removeIf({pred}) + \" \" + v + \" \" + l); }}"),
        _ => format!("{{ List<Integer> l = {recv}; try {{ l.replaceAll({op}); System.out.println(l.removeIf({pred}) + \" \" + l); }} {report} }}"),
    }
}

/// `String.chars`/`codePoints`/`lines` — the three views of a string that are
/// streams rather than strings.
///
/// All three had zero coverage. `lines()` is the interesting one: it splits on
/// *terminators*, so a trailing newline ends the last line rather than starting
/// an empty one, and a lone `\r` terminates as well as `\r\n` does — three
/// rules an implementation built on a `split` gets wrong.
fn g_chars(r: &mut Rng) -> String {
    let s = pick(
        r,
        &[
            "\"abc\"",
            "\"\"",
            "\"a\"",
            "\"AaZz09\"",
            "\"  x \"",
            "\"\\u00e9\"",
        ],
    );
    let lined = pick(
        r,
        &[
            "\"a\\nb\"",
            "\"a\\nb\\n\"",
            "\"\"",
            "\"\\n\"",
            "\"a\\n\\nb\"",
            "\"a\\r\\nb\\rc\"",
            "\"x\"",
        ],
    );
    match r.below(9) {
        0 => format!("System.out.println({s}.chars().sum() + \" \" + {s}.chars().count());"),
        1 => format!("System.out.println({s}.codePoints().sum() + \" \" + {s}.codePoints().count());"),
        2 => format!("System.out.println({s}.chars().boxed().toList());"),
        3 => format!("System.out.println({s}.chars().max().isPresent() + \" \" + {s}.chars().min().isPresent());"),
        4 => format!("System.out.println({s}.chars().filter(c -> c > 'a').count());"),
        5 => format!("System.out.println({s}.chars().map(c -> c - 32).boxed().toList());"),
        6 => format!("System.out.println({lined}.lines().count());"),
        7 => format!("System.out.println({lined}.lines().toList());"),
        _ => format!("System.out.println({lined}.lines().map(x -> \"[\" + x + \"]\").toList());"),
    }
}

/// Nested types and the qualified names that reach them.
///
/// `T.Nst p = …` was a *parse* error before this mode: the type parser stepped
/// over a lowercase package qualifier only, so an enclosing class in front of
/// the type name ended the declaration. `static class` had zero occurrences in
/// the generator, and neither did any qualified type name whose first segment is
/// capitalised, which is why a saturated sweep never reached it.
///
/// The declarations live in `SUPPORT`/`SUPPORT_CLASS`; this mode only writes the
/// uses, in both the simple and the qualified spelling, so the two must agree.
fn g_nested(r: &mut Rng) -> String {
    let a = pick(r, &["1", "0", "-3", "7"]);
    let b = pick(r, &["2", "5", "-1"]);
    match r.below(10) {
        0 => format!("{{ Nst p = new Nst({a}, {b}); System.out.println(p + \" \" + p.sum()); }}"),
        1 => format!("{{ T.Nst p = new T.Nst({a}, {b}); System.out.println(p + \" \" + p.sum()); }}"),
        2 => format!("{{ T.Nst p = new Nst({a}, {b}); Nst q = new T.Nst({a}, {b}); System.out.println(p.equals(q) + \" \" + (p == q)); }}"),
        3 => format!("{{ List<T.Nst> l = new ArrayList<>(); l.add(new Nst({a}, {b})); System.out.println(l); }}"),
        4 => format!("{{ T.Nst p = new T.Nst({a}, {b}); System.out.println(p.getClass().getSimpleName()); }}"),
        // The interface's `default` and `static` members, reached both ways.
        5 => format!("{{ Greeter g = Greeter.of(\"n{a}\"); System.out.println(g.greet()); }}"),
        6 => format!("{{ T.Greeter g = () -> \"q{a}\"; System.out.println(g.greet() + \" \" + g.name()); }}"),
        7 => format!("{{ Greeter g = () -> \"z\"; System.out.println(g.shout()); }}"),
        8 => format!("{{ T.Nst p = new T.Nst({a}, {b}); Greeter g = () -> p.toString(); System.out.println(g.greet()); }}"),
        _ => format!("{{ T.Nst[] ps = {{ new Nst({a}, {b}), new T.Nst({b}, {a}) }}; System.out.println(Arrays.toString(ps)); }}"),
    }
}

/// `StringBuilder`/`StringBuffer`, which had **zero** coverage: the string
/// `StringBuilder` did not appear once in this generator, so 28 registered
/// methods and the whole mutable-string path were unreachable by any sweep.
///
/// The interesting arms are the ones where the builder is not a `String` in
/// disguise: `setLength` truncates *or* zero-pads, `insert`/`delete` take index
/// pairs whose out-of-range cases are `StringIndexOutOfBoundsException`, and
/// `reverse` is in place, so the receiver a later arm reads is the reversed one.
fn g_builder(r: &mut Rng) -> String {
    let init = pick(
        r,
        &["\"\"", "\"abc\"", "\"a\"", "\"hello world\"", "\"  \""],
    );
    let piece = pick(
        r,
        &[
            "\"x\"", "\"\"", "\"long\"", "'q'", "7", "-3", "2.5", "true", "9L",
        ],
    );
    let i = pick(r, &["0", "1", "2", "5", "-1"]);
    let j = pick(r, &["0", "1", "3", "9"]);
    match r.below(16) {
        0 => format!("{{ StringBuilder b = new StringBuilder({init}); b.append({piece}); System.out.println(b + \"|\" + b.length()); }}"),
        1 => format!("{{ StringBuilder b = new StringBuilder({init}); System.out.println(b.append({piece}).append({piece}).append({init})); }}"),
        2 => format!("{{ StringBuilder b = new StringBuilder({init}); System.out.println(b.reverse() + \"|\" + b); }}"),
        3 => format!("{{ StringBuilder b = new StringBuilder({init}); System.out.println(b.isEmpty() + \" \" + b.length() + \" \" + b.toString().equals({init})); }}"),
        4 => format!("{{ StringBuilder b = new StringBuilder({init}); try {{ System.out.println(b.charAt({i})); }} catch (RuntimeException e) {{ System.out.println(\"c:\" + e.getClass().getName()); }} }}"),
        5 => format!("{{ StringBuilder b = new StringBuilder({init}); try {{ System.out.println(b.insert({i}, {piece})); }} catch (RuntimeException e) {{ System.out.println(\"i:\" + e.getClass().getName()); }} }}"),
        6 => format!("{{ StringBuilder b = new StringBuilder({init}); try {{ System.out.println(b.deleteCharAt({i})); }} catch (RuntimeException e) {{ System.out.println(\"d:\" + e.getClass().getName()); }} }}"),
        7 => format!("{{ StringBuilder b = new StringBuilder({init}); try {{ System.out.println(b.delete({i}, {j})); }} catch (RuntimeException e) {{ System.out.println(\"D:\" + e.getClass().getName()); }} }}"),
        8 => format!("{{ StringBuilder b = new StringBuilder({init}); try {{ System.out.println(b.replace({i}, {j}, \"Z\")); }} catch (RuntimeException e) {{ System.out.println(\"r:\" + e.getClass().getName()); }} }}"),
        9 => format!("{{ StringBuilder b = new StringBuilder({init}); try {{ b.setCharAt({i}, 'w'); System.out.println(b); }} catch (RuntimeException e) {{ System.out.println(\"s:\" + e.getClass().getName()); }} }}"),
        10 => format!("{{ StringBuilder b = new StringBuilder({init}); try {{ b.setLength({j}); System.out.println(\"[\" + b + \"]\" + b.length()); }} catch (RuntimeException e) {{ System.out.println(\"L:\" + e.getClass().getName()); }} }}"),
        11 => format!("{{ StringBuilder b = new StringBuilder({init}); try {{ System.out.println(b.substring({i}) + \"|\" + b.substring(0, {i})); }} catch (RuntimeException e) {{ System.out.println(\"S:\" + e.getClass().getName()); }} }}"),
        12 => format!("{{ StringBuilder b = new StringBuilder({init}); System.out.println(b.indexOf(\"a\") + \" \" + b.lastIndexOf(\"a\") + \" \" + b.indexOf(\"zz\")); }}"),
        13 => format!("{{ StringBuilder b = new StringBuilder({init}); System.out.println(b.compareTo(new StringBuilder({init})) + \" \" + b.compareTo(new StringBuilder(\"m\"))); }}"),
        14 => format!("{{ StringBuffer b = new StringBuffer({init}); System.out.println(b.append({piece}) + \"|\" + b.length()); }}"),
        _ => format!("{{ StringBuilder b = new StringBuilder(); for (int k = 0; k < 3; k++) b.append(k).append({piece}); System.out.println(b + \"|\" + b.chars().count()); }}"),
    }
}

/// The 27 `Math` methods no probe named. Only `abs/max/min/floor/ceil/sqrt` were
/// generated, so the exact-arithmetic family — every member of which is a
/// no-op away from its boundary and an `ArithmeticException` at it — had no
/// coverage at all, and neither did the rounding and float-neighbour methods
/// whose whole content is their edge cases.
///
/// The operand pool is deliberately boundaries: both `MIN_VALUE`s, both
/// `MAX_VALUE`s, the halfway ties `round` resolves upward, and the signed zeros
/// that separate `signum`/`copySign` from a sign test.
fn g_mathfn(r: &mut Rng) -> String {
    let i = pick(
        r,
        &[
            "0",
            "1",
            "-1",
            "7",
            "-7",
            "Integer.MAX_VALUE",
            "Integer.MIN_VALUE",
            "2147483646",
        ],
    );
    let j = pick(r, &["1", "-1", "2", "-2", "0", "Integer.MAX_VALUE"]);
    let l = pick(
        r,
        &["0L", "1L", "-1L", "Long.MAX_VALUE", "Long.MIN_VALUE", "3L"],
    );
    let d = pick(
        r,
        &[
            "0.0",
            "-0.0",
            "2.5",
            "-2.5",
            "3.5",
            "0.49999999999999994",
            "1.0",
            "-1.5",
            "1e300",
            "Double.NaN",
            "Double.MIN_VALUE",
        ],
    );
    let e = pick(r, &["0.0", "1.0", "-1.0", "2.0", "0.5", "-0.0"]);
    match r.below(14) {
        0 => format!("System.out.println(Math.floorDiv({i}, {j} == 0 ? 1 : {j}) + \" \" + Math.floorMod({i}, {j} == 0 ? 1 : {j}));"),
        1 => format!("System.out.println(Math.round({d}) + \" \" + Math.round((float) {d}) + \" \" + Math.rint({d}));"),
        2 => format!("System.out.println(Math.pow({d}, {e}) + \" \" + Math.signum({d}) + \" \" + Math.copySign({d}, {e}));"),
        3 => format!("System.out.println(Math.ulp({d}) + \" \" + Math.nextUp({d}) + \" \" + Math.nextDown({d}) + \" \" + Math.nextAfter({d}, {e}));"),
        4 => format!("System.out.println(Math.fma({d}, {e}, 1.0) + \" \" + Math.toDegrees({d}) + \" \" + Math.toRadians({d}));"),
        5 => format!("System.out.println(Math.clamp({i}, -5, 5) + \" \" + Math.clamp({d}, -1.0, 1.0));"),
        6 => format!("try {{ System.out.println(Math.addExact({i}, {j})); }} catch (ArithmeticException ex) {{ System.out.println(\"ae:\" + ex.getMessage()); }}"),
        7 => format!("try {{ System.out.println(Math.subtractExact({i}, {j}) + \" \" + Math.multiplyExact({i}, {j})); }} catch (ArithmeticException ex) {{ System.out.println(\"se:\" + ex.getMessage()); }}"),
        8 => format!("try {{ System.out.println(Math.negateExact({i}) + \" \" + Math.absExact({i})); }} catch (ArithmeticException ex) {{ System.out.println(\"ne:\" + ex.getMessage()); }}"),
        9 => format!("try {{ System.out.println(Math.incrementExact({i}) + \" \" + Math.decrementExact({i})); }} catch (ArithmeticException ex) {{ System.out.println(\"ie:\" + ex.getMessage()); }}"),
        10 => format!("try {{ System.out.println(Math.toIntExact({l})); }} catch (ArithmeticException ex) {{ System.out.println(\"te:\" + ex.getMessage()); }}"),
        11 => format!("try {{ System.out.println(Math.divideExact({i}, {j} == 0 ? 1 : {j}) + \" \" + Math.floorDivExact({i}, {j} == 0 ? 1 : {j})); }} catch (ArithmeticException ex) {{ System.out.println(\"de:\" + ex.getMessage()); }}"),
        12 => format!("try {{ System.out.println(Math.addExact({l}, 1L) + \" \" + Math.multiplyExact({l}, 2L)); }} catch (ArithmeticException ex) {{ System.out.println(\"le:\" + ex.getMessage()); }}"),
        _ => format!("try {{ System.out.println(Math.ceilDivExact({i}, {j} == 0 ? 1 : {j})); }} catch (ArithmeticException ex) {{ System.out.println(\"ce:\" + ex.getMessage()); }}"),
    }
}

/// The compound `Map` methods — `compute`, `computeIfAbsent`,
/// `computeIfPresent`, `merge`, `replace`, `putAll` and a map's two-parameter
/// `replaceAll`. Every one was an `unsupported Map method` refusal before this
/// round, and none appeared in the generator.
///
/// The `HashMap` arms are the point: a key that these three *add* is linked at
/// the **head** of its hash bin where `put` links it at the tail, so a program
/// that fills the same map by `put` and by `merge` iterates it in two different
/// orders. Keys are drawn from a pool that collides under Java's spread
/// function, because nothing else can see the difference.
fn g_mapfn(r: &mut Rng) -> String {
    let ctor = pick(r, &["HashMap", "LinkedHashMap", "TreeMap"]);
    let k = pick(
        r,
        &[
            "\"one\"",
            "\"two\"",
            "\"three\"",
            "\"four\"",
            "\"a\"",
            "\"zz\"",
        ],
    );
    let v = pick(r, &["1", "0", "-3", "42"]);
    let f = pick(
        r,
        &[
            "(x, y) -> x + y",
            "(x, y) -> x * y",
            "(x, y) -> y",
            "(x, y) -> null",
        ],
    );
    let seed = "m.put(\"one\", 1); m.put(\"two\", 2);";
    match r.below(14) {
        0 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} System.out.println(m.computeIfAbsent({k}, s -> s.length()) + \" \" + m); }}"),
        1 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} System.out.println(m.computeIfAbsent({k}, s -> null) + \" \" + m + \" \" + m.containsKey({k})); }}"),
        2 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} System.out.println(m.computeIfPresent({k}, (s, x) -> x + {v}) + \" \" + m); }}"),
        3 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} System.out.println(m.computeIfPresent({k}, (s, x) -> null) + \" \" + m); }}"),
        4 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} System.out.println(m.compute({k}, (s, x) -> x == null ? {v} : x + {v}) + \" \" + m); }}"),
        5 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} System.out.println(m.compute({k}, (s, x) -> null) + \" \" + m); }}"),
        6 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} System.out.println(m.merge({k}, {v}, {f}) + \" \" + m); }}"),
        7 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} System.out.println(m.replace({k}, {v}) + \" \" + m); }}"),
        8 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} Map<String,Integer> n = new {ctor}<>(); n.put({k}, {v}); n.put(\"three\", 3); m.putAll(n); System.out.println(m); }}"),
        9 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} m.replaceAll((s, x) -> x * 10 + s.length()); System.out.println(m); }}"),
        // The head-insert arms: the same three keys, filled two ways.
        10 => format!("{{ Map<String,Integer> m = new {ctor}<>(); {seed} m.put(\"three\", 3); Map<String,Integer> n = new {ctor}<>(); n.put(\"one\", 1); n.put(\"two\", 2); n.merge(\"three\", 3, (x, y) -> x); System.out.println(m + \" \" + n + \" \" + m.equals(n)); }}"),
        11 => format!("{{ Map<String,Integer> m = new {ctor}<>(); for (int q = 0; q < 20; q++) m.computeIfAbsent(\"k\" + q, s -> s.length()); System.out.println(m); }}"),
        12 => format!("{{ Map<String,List<Integer>> m = new {ctor}<>(); for (String w : new String[] {{\"apple\", \"avocado\", \"banana\", \"cherry\"}}) m.computeIfAbsent(w.substring(0, 1), s -> new ArrayList<>()).add(w.length()); System.out.println(m); }}"),
        // Every refusal an immutable map answers with, and the null-argument NPEs.
        // The seed goes into `h`, not into `m`: `m` is the immutable map this
        // arm exists to probe, and seeding it would throw *outside* the `try`
        // and kill the whole program — which the harness counts as a skip, not
        // as a failure, and a skipped program is coverage that silently is not
        // there.
        _ => format!("{{ Map<String,Integer> m = Map.of(\"a\", 1); try {{ m.merge({k}, {v}, {f}); }} catch (RuntimeException e) {{ System.out.println(\"im:\" + e.getClass().getName()); }} Map<String,Integer> h = new {ctor}<>(); h.put(\"one\", 1); h.put(\"two\", 2); try {{ h.compute({k}, null); }} catch (RuntimeException e) {{ System.out.println(\"nf:\" + e.getClass().getName()); }} }}"),
    }
}

/// `T::new` on a *modeled stdlib* type. `ArrayList::new` was an unresolvable
/// receiver and `String::new` an unmodeled reference before this round, and the
/// generator named neither — it wrote only user-class constructor references,
/// which took a different path.
fn g_ctorref(r: &mut Rng) -> String {
    match r.below(9) {
        0 => "{ Gen<ArrayList<String>> s = ArrayList::new; ArrayList<String> l = s.get(); l.add(\"a\"); System.out.println(l + \" \" + (s.get() == s.get())); }".to_string(),
        1 => "{ Gen<StringBuilder> s = StringBuilder::new; System.out.println(\"[\" + s.get().append(\"q\") + \"]\" + s.get().length()); }".to_string(),
        2 => "{ Gen<String> s = String::new; System.out.println(\"[\" + s.get() + \"]\" + s.get().length() + \" \" + s.get().isEmpty()); }".to_string(),
        3 => "{ Gen<Object> s = Object::new; System.out.println(s.get() != null); }".to_string(),
        4 => "{ Gen<HashMap<String,Integer>> s = HashMap::new; Map<String,Integer> m = s.get(); m.put(\"k\", 1); System.out.println(m); }".to_string(),
        5 => "{ Gen<TreeSet<String>> s = TreeSet::new; Set<String> t = s.get(); t.add(\"b\"); t.add(\"a\"); System.out.println(t); }".to_string(),
        6 => "{ Gen<ArrayDeque<Integer>> s = ArrayDeque::new; Deque<Integer> d = s.get(); d.push(1); System.out.println(d); }".to_string(),
        7 => "{ Gen<LinkedList<Integer>> s = LinkedList::new; List<Integer> l = s.get(); l.add(3); System.out.println(l + \" \" + l.size()); }".to_string(),
        _ => "{ Gen<LinkedHashSet<String>> s = LinkedHashSet::new; Set<String> t = s.get(); t.add(\"z\"); t.add(\"a\"); System.out.println(t); }".to_string(),
    }
}

/// `java.util.Optional`. The string `Optional` did not appear once in this
/// generator; only `isPresent()` was reached at all, and only indirectly off an
/// `IntStream.max()`.
///
/// `Optional.toString` is the arm most worth having: it is `Optional[x]` and
/// `Optional.empty`, not the value, so any probe that prints one at all pins the
/// rendering as well as the contents.
fn g_optional(r: &mut Rng) -> String {
    let v = pick(r, &["\"hi\"", "\"\"", "\"a longer one\""]);
    let d = pick(r, &["\"z\"", "\"\""]);
    match r.below(10) {
        0 => format!("System.out.println(Optional.of({v}) + \" \" + Optional.empty() + \" \" + Optional.ofNullable(null));"),
        1 => format!("System.out.println(Optional.of({v}).get() + \" \" + Optional.of({v}).isPresent() + \" \" + Optional.empty().isEmpty());"),
        2 => format!("System.out.println(Optional.of({v}).orElse({d}) + \" \" + Optional.<String>empty().orElse({d}));"),
        3 => format!("System.out.println(Optional.of({v}).map(String::toUpperCase) + \" \" + Optional.<String>empty().map(String::toUpperCase));"),
        4 => format!("System.out.println(Optional.of({v}).filter(x -> x.length() > 1) + \" \" + Optional.of({v}).filter(x -> false));"),
        5 => format!("System.out.println(Optional.<String>empty().orElseGet(() -> {d}) + \" \" + Optional.of({v}).orElseGet(() -> {d}));"),
        6 => format!("System.out.println(Optional.of({v}).equals(Optional.of({v})) + \" \" + Optional.of({v}).equals(Optional.empty()) + \" \" + Optional.of({v}).hashCode());"),
        7 => format!("{{ Optional.of({v}).ifPresent(x -> System.out.println(\"p:\" + x)); Optional.<String>empty().ifPresent(x -> System.out.println(\"never\")); System.out.println(\"done\"); }}"),
        8 => format!("try {{ System.out.println(Optional.<String>empty().get()); }} catch (RuntimeException e) {{ System.out.println(e.getClass().getName() + \":\" + e.getMessage()); }}"),
        _ => format!("try {{ System.out.println(Optional.<String>empty().orElseThrow()); }} catch (RuntimeException e) {{ System.out.println(e.getClass().getName()); }}"),
    }
}

/// Streams reached through a *source that is not a string*, and the two APIs
/// that only exist to consume them.
///
/// The `chars` mode reaches a stream only through `String.chars`/`codePoints`/
/// `lines`; `Collection.stream()`, `Arrays.stream`, `Stream.of` and the
/// `IntStream` factories had zero occurrences, and `Collectors` and `Comparator`
/// did not appear in the generator at all — 7 collectors and 12 comparator
/// members with no probe between them.
fn g_stream(r: &mut Rng) -> String {
    let l = "List.of(\"bb\", \"a\", \"ccc\", \"dd\")";
    match r.below(14) {
        0 => format!("System.out.println({l}.stream().map(String::toUpperCase).toList());"),
        1 => format!("System.out.println({l}.stream().collect(Collectors.joining(\", \", \"[\", \"]\")));"),
        2 => format!("System.out.println({l}.stream().collect(Collectors.groupingBy(String::length)));"),
        3 => format!("System.out.println({l}.stream().collect(Collectors.toMap(x -> x, String::length)));"),
        4 => format!("System.out.println({l}.stream().collect(Collectors.counting()) + \" \" + {l}.stream().collect(Collectors.toSet()).size());"),
        5 => format!("{{ List<String> s = new ArrayList<>({l}); s.sort(Comparator.comparing(String::length)); System.out.println(s); }}"),
        6 => format!("{{ List<String> s = new ArrayList<>({l}); s.sort(Comparator.comparing(String::length).reversed()); System.out.println(s); }}"),
        7 => format!("{{ List<String> s = new ArrayList<>({l}); s.sort(Comparator.<String>naturalOrder()); System.out.println(s + \" \" + {l}.stream().sorted(Comparator.reverseOrder()).toList()); }}"),
        8 => format!("System.out.println({l}.stream().anyMatch(x -> x.length() > 2) + \" \" + {l}.stream().allMatch(x -> !x.isEmpty()) + \" \" + {l}.stream().noneMatch(String::isEmpty));"),
        9 => format!("System.out.println({l}.stream().reduce(\"\", (x, y) -> x + y) + \" \" + {l}.stream().findFirst().get());"),
        10 => format!("System.out.println({l}.stream().skip(1).limit(2).toList() + \" \" + {l}.stream().distinct().count());"),
        11 => format!("System.out.println(IntStream.range(0, 4).map(x -> x * x).boxed().toList() + \" \" + IntStream.rangeClosed(1, 3).sum());"),
        12 => format!("System.out.println(Stream.of(1, 2, 3).mapToInt(x -> x).max().getAsInt() + \" \" + IntStream.of(1, 2, 3).average().getAsDouble());"),
        _ => format!("System.out.println(Arrays.stream(new int[] {{3, 1, 2}}).sum() + \" \" + {l}.stream().mapToInt(String::length).sum());"),
    }
}

/// The `java.util.Arrays` statics past the three the generator wrote. `asList`,
/// `toString` and `deepToString` were the whole of its coverage; `sort`, `fill`,
/// `copyOf`, `copyOfRange`, `binarySearch`, `equals`, `hashCode` and `stream`
/// had none.
///
/// `binarySearch` on a value that is *not* present is the arm to keep: Java
/// answers `-(insertion point) - 1`, not `-1`.
fn g_arraysfn(r: &mut Rng) -> String {
    let a = pick(r, &["{5, 1, 4, 2}", "{}", "{7}", "{3, 3, 1}", "{-1, 0, 1}"]);
    let n = pick(r, &["0", "1", "3", "6"]);
    let k = pick(r, &["1", "4", "3", "-5"]);
    match r.below(10) {
        0 => format!("{{ int[] a = {a}; Arrays.sort(a); System.out.println(Arrays.toString(a)); }}"),
        1 => format!("{{ int[] a = {a}; Arrays.sort(a); System.out.println(Arrays.binarySearch(a, {k})); }}"),
        2 => format!("{{ int[] a = new int[{n}]; Arrays.fill(a, {k}); System.out.println(Arrays.toString(a)); }}"),
        3 => format!("{{ int[] a = {a}; System.out.println(Arrays.toString(Arrays.copyOf(a, {n}))); }}"),
        4 => format!("{{ int[] a = {a}; try {{ System.out.println(Arrays.toString(Arrays.copyOfRange(a, 0, {n}))); }} catch (RuntimeException e) {{ System.out.println(\"cr:\" + e.getClass().getName()); }} }}"),
        5 => format!("{{ int[] a = {a}; int[] b = {a}; System.out.println(Arrays.equals(a, b) + \" \" + (a == b) + \" \" + Arrays.hashCode(a)); }}"),
        6 => format!("{{ int[] a = {a}; System.out.println(Arrays.stream(a).sum() + \" \" + Arrays.stream(a).count()); }}"),
        7 => "{ String[] s = {\"b\", \"a\", \"c\"}; Arrays.sort(s); System.out.println(Arrays.toString(s) + \" \" + Arrays.binarySearch(s, \"b\")); }".to_string(),
        8 => "{ double[] d = {1.5, -0.0, 0.0, Double.NaN}; Arrays.sort(d); System.out.println(Arrays.toString(d)); }".to_string(),
        _ => format!("{{ long[] a = {{3L, 1L}}; Arrays.sort(a); System.out.println(Arrays.toString(a) + \" \" + Arrays.toString(Arrays.copyOf(a, {n}))); }}"),
    }
}

/// The wrapper statics and the boxed accessors. `Long`, `Double`, `Float`,
/// `Boolean` and most of `Character` had no static probed at all, and the nine
/// `Number` converters (`intValue`, `doubleValue`, …) had none either.
///
/// The identity arms are the ones a `HashMap`-backed cache can get wrong:
/// `Integer.valueOf` returns a shared object in `-128..=127` and a fresh one
/// outside it, so `==` between two boxes flips at exactly that boundary.
fn g_parsefn(r: &mut Rng) -> String {
    let s = pick(r, &["\"42\"", "\"-1\"", "\"0\"", "\"2147483647\""]);
    let d = pick(r, &["\"1.5\"", "\"-0.0\"", "\"1e300\"", "\"0\""]);
    let i = pick(r, &["127", "128", "-128", "-129", "0", "1000"]);
    let c = pick(r, &["'a'", "'Z'", "'7'", "' '", "'_'"]);
    match r.below(12) {
        0 => format!("System.out.println(Long.parseLong({s}) + \" \" + Long.valueOf({s}) + \" \" + Long.toString(9L) + \" \" + Long.compare(1L, 2L));"),
        1 => format!("System.out.println(Long.toHexString(255L) + \" \" + Long.toOctalString(64L) + \" \" + Long.toBinaryString(5L) + \" \" + Long.max(1L, 2L));"),
        2 => format!("System.out.println(Double.parseDouble({d}) + \" \" + Double.compare(1.0, 2.0) + \" \" + Double.toString(0.1) + \" \" + Double.valueOf({d}));"),
        3 => format!("System.out.println(Double.isNaN(0.0 / 0.0) + \" \" + Double.isInfinite(1.0 / 0.0) + \" \" + Double.hashCode(1.5));"),
        4 => format!("System.out.println(Float.parseFloat({d}) + \" \" + Float.compare(1.0f, 2.0f) + \" \" + Float.toString(0.1f) + \" \" + Float.isNaN(0.0f / 0.0f));"),
        5 => format!("System.out.println(Boolean.parseBoolean(\"TRUE\") + \" \" + Boolean.parseBoolean(\"yes\") + \" \" + Boolean.compare(true, false) + \" \" + Boolean.toString(false));"),
        6 => format!("System.out.println(Character.isLetter({c}) + \" \" + Character.isLetterOrDigit({c}) + \" \" + Character.isWhitespace({c}) + \" \" + Character.isUpperCase({c}) + \" \" + Character.isLowerCase({c}));"),
        7 => format!("System.out.println(Character.getNumericValue({c}) + \" \" + Character.toString({c}) + \" \" + Character.hashCode({c}));"),
        8 => format!("System.out.println(Integer.toOctalString(64) + \" \" + Integer.parseInt(\"ff\", 16) + \" \" + Integer.hashCode(7));"),
        9 => format!("{{ Integer a = {i}, b = {i}; System.out.println((a == b) + \" \" + a.equals(b) + \" \" + (Integer.valueOf({i}) == Integer.valueOf({i}))); }}"),
        10 => format!("{{ Integer a = {i}; System.out.println(a.intValue() + \" \" + a.longValue() + \" \" + a.doubleValue() + \" \" + a.byteValue() + \" \" + a.shortValue()); }}"),
        _ => format!("{{ Double a = 3.9; System.out.println(a.intValue() + \" \" + a.longValue() + \" \" + a.floatValue() + \" \" + a.hashCode()); }}"),
    }
}

/// Text blocks (JLS 3.10.6). The lexer has read them since before this round,
/// but no probe contained one, so the incidental-whitespace rule they exist for
/// was never checked against the reference.
///
/// The rule is that the common indentation of the content lines **and the
/// closing delimiter's line** is stripped, then each line's trailing whitespace
/// goes. So a closing `"""` outdented past the content changes the answer, and a
/// line of trailing spaces is not preserved unless `\s` holds it — which is why
/// the arms vary the delimiter's column rather than only the content.
///
/// Every arm is built from Rust string pieces rather than typed as one literal:
/// the escapes a text block probes (`\s`, a line-continuation `\`) have to reach
/// the generated file as two characters, and writing them inline is how they
/// stop being two.
fn g_textblock(r: &mut Rng) -> String {
    let q = "\"\"\"";
    let bs = '\\';
    match r.below(8) {
        0 => format!("System.out.println(\"[\" + {q}\n    alpha\n      beta\n    {q} + \"]\");"),
        1 => format!("System.out.println(\"[\" + {q}\n        x\n     y\n   z{q} + \"]\");"),
        2 => format!("System.out.println(\"[\" + {q}\n    kept   \n    or not\n    {q} + \"]\");"),
        3 => format!("System.out.println(\"[\" + {q}\n    a{bs}\n    b\n    {q} + \"]\");"),
        4 => format!("System.out.println(\"[\" + {q}\n    q{bs}s{bs}s\n    {q} + \"]\");"),
        5 => format!("System.out.println(\"[\" + {q}\n    {q}.length() + \"]\");"),
        6 => format!("System.out.println({q}\n    one\n    two\n    {q}.lines().count() + \" \" + {q}\n    one\n    two\n    {q}.length());"),
        _ => format!("System.out.println(\"[\" + {q}\n    tab{bs}there\n    q{bs}\"q{bs}\"\n    {q} + \"]\");"),
    }
}

/// Anonymous classes and the syntax around them that no probe wrote.
///
/// An anonymous class body is a *different* compiler path from the enum-constant
/// body the `enum` mode already reaches, and it had zero occurrences. So did
/// multi-catch, an instance initializer block, `X.class`, `%=`, `-=` and the
/// unary `+` that promotes a `char` to an `int`.
fn g_anon(r: &mut Rng) -> String {
    let a = pick(r, &["7", "-3", "0", "100"]);
    let b = pick(r, &["2", "-5", "3"]);
    match r.below(11) {
        0 => format!("{{ Gen<String> s = new Gen<String>() {{ public String get() {{ return \"anon{a}\"; }} }}; System.out.println(s.get()); }}"),
        // Not `new Object() { toString }`: an anonymous `Object` overrides an
        // inherited body rather than supplying an abstract method, so javars
        // refuses it by name — see the parser's `anonymous_class`.
        1 => format!("{{ Str1 f = new Str1() {{ public String of(String s) {{ return s + \"{a}\"; }} }}; System.out.println(f.of(\"o\")); }}"),
        2 => format!("{{ Calc c = new Calc() {{ public int of(int x, int y) {{ return x * y + {a}; }} }}; System.out.println(c.of({a}, {b})); }}"),
        3 => format!("{{ Greeter g = new Greeter() {{ public String name() {{ return \"n{a}\"; }} }}; System.out.println(g.greet() + \" \" + g.shout()); }}"),
        4 => format!("{{ int base = {a}; Gen<Integer> s = new Gen<Integer>() {{ public Integer get() {{ return base + {b}; }} }}; System.out.println(s.get()); }}"),
        5 => format!("try {{ if ({a} > 0) throw new IllegalStateException(\"s{a}\"); throw new IllegalArgumentException(\"a{a}\"); }} catch (IllegalArgumentException | IllegalStateException e) {{ System.out.println(e.getClass().getSimpleName() + \":\" + e.getMessage()); }}"),
        6 => format!("try {{ Object o = null; System.out.println(o.toString()); }} catch (NullPointerException | ClassCastException e) {{ System.out.println(\"mc:\" + e.getClass().getSimpleName()); }}"),
        7 => format!("{{ int v = {a}; v %= ({b} == 0 ? 1 : {b}); v -= {b}; System.out.println(v); }}"),
        8 => format!("{{ char c = 'A'; System.out.println(+c + \" \" + (+{a}) + \" \" + -(+{a})); }}"),
        9 => format!("System.out.println(String.class.getName() + \" \" + int.class + \" \" + Integer.class.getSimpleName());"),
        _ => format!("{{ Ini x = new Ini({a}); System.out.println(x.seen + \" \" + x.v); }}"),
    }
}

fn mode_name(m: Mode) -> &'static str {
    match m {
        Mode::All => "all",
        Mode::Arith => "arith",
        Mode::IntDiv => "intdiv",
        Mode::DoubleArith => "doublearith",
        Mode::MixedDiv => "mixeddiv",
        Mode::DoubleFmt => "doublefmt",
        Mode::Concat => "concat",
        Mode::Compare => "compare",
        Mode::Bool => "bool",
        Mode::Ternary => "ternary",
        Mode::StrMethod => "strmethod",
        Mode::Math => "math",
        Mode::Format => "format",
        Mode::Integer => "integer",
        Mode::Loop => "loop",
        Mode::Switch => "switch",
        Mode::Array => "array",
        Mode::Overflow => "overflow",
        Mode::ForEach => "foreach",
        Mode::Exception => "exception",
        Mode::Fault => "fault",
        Mode::Finally => "finally",
        Mode::Resource => "resource",
        Mode::Enum => "enum",
        Mode::Static => "static",
        Mode::Record => "record",
        Mode::Lambda => "lambda",
        Mode::Collection => "collection",
        Mode::SwitchExpr => "switchexpr",
        Mode::VarInfer => "varinfer",
        Mode::Bitwise => "bitwise",
        Mode::Shift => "shift",
        Mode::Cast => "cast",
        Mode::IncDec => "incdec",
        Mode::Literal => "literal",
        Mode::Printf => "printf",
        Mode::LabelFlow => "labelflow",
        Mode::Char => "char",
        Mode::Regex => "regex",
        Mode::Float => "float",
        Mode::Decl => "decl",
        Mode::Object => "object",
        Mode::StaticRef => "staticref",
        Mode::LoopKind => "loopkind",
        Mode::Narrow => "narrow",
        Mode::ListOp => "listop",
        Mode::Varargs => "varargs",
        Mode::ListView => "listview",
        Mode::Immutable => "immutable",
        Mode::Super => "super",
        Mode::InstanceOf => "instanceof",
        Mode::Render => "render",
        Mode::Equals => "equals",
        Mode::Bits => "bits",
        Mode::Objects => "objects",
        Mode::Deque => "deque",
        Mode::Mutate => "mutate",
        Mode::Chars => "chars",
        Mode::Nested => "nested",
        Mode::Builder => "builder",
        Mode::MathFn => "mathfn",
        Mode::MapFn => "mapfn",
        Mode::CtorRef => "ctorref",
        Mode::Optional => "optional",
        Mode::Stream => "stream",
        Mode::ArraysFn => "arraysfn",
        Mode::ParseFn => "parsefn",
        Mode::TextBlock => "textblock",
        Mode::Anon => "anon",
        Mode::Clinit => "clinit",
        Mode::TernProm => "ternprom",
        Mode::NullUnbox => "nullunbox",
        Mode::IntCache => "intcache",
        Mode::NumProm => "numprom",
        Mode::FmtFlag => "fmtflag",
        Mode::SBuild => "sbuild",
        Mode::HashIter => "hashiter",
        Mode::Exc => "exc",
        Mode::Overload => "overload",
        Mode::SwFall => "swfall",
        Mode::Sealed => "sealed",
        Mode::Capture => "capture",
        Mode::Generic => "generic",
        Mode::FailFast => "failfast",
        Mode::View => "view",
        Mode::Erased => "erased",
        Mode::Lru => "lru",
        Mode::BitsFloat => "bitsfloat",
        Mode::RecHash => "rechash",
        Mode::StreamOps => "streamops",
    }
}

fn parse_mode(s: &str) -> Option<Mode> {
    if s == "all" {
        return Some(Mode::All);
    }
    CONCRETE.iter().copied().find(|m| mode_name(*m) == s)
}

fn gen_probe(r: &mut Rng, mode: Mode) -> String {
    let m = if mode == Mode::All {
        *pick(r, CONCRETE)
    } else {
        mode
    };
    match m {
        Mode::Arith => g_arith(r),
        Mode::IntDiv => g_intdiv(r),
        Mode::DoubleArith => g_doublearith(r),
        Mode::MixedDiv => g_mixeddiv(r),
        Mode::DoubleFmt => g_doublefmt(r),
        Mode::Concat => g_concat(r),
        Mode::Compare => g_compare(r),
        Mode::Bool => g_bool(r),
        Mode::Ternary => g_ternary(r),
        Mode::StrMethod => g_strmethod(r),
        Mode::Math => g_math(r),
        Mode::Format => g_format(r),
        Mode::Integer => g_integer(r),
        Mode::Loop => g_loop(r),
        Mode::Switch => g_switch(r),
        Mode::Array => g_array(r),
        Mode::Overflow => g_overflow(r),
        Mode::ForEach => g_foreach(r),
        Mode::Exception => g_exception(r),
        Mode::Fault => g_fault(r),
        Mode::Finally => g_finally(r),
        Mode::Resource => g_resource(r),
        Mode::Enum => g_enum(r),
        Mode::Static => g_static(r),
        Mode::Record => g_record(r),
        Mode::Lambda => g_lambda(r),
        Mode::Collection => g_collection(r),
        Mode::SwitchExpr => g_switchexpr(r),
        Mode::VarInfer => g_varinfer(r),
        Mode::Bitwise => g_bitwise(r),
        Mode::Shift => g_shift(r),
        Mode::Cast => g_cast(r),
        Mode::IncDec => g_incdec(r),
        Mode::Literal => g_literal(r),
        Mode::Printf => g_printf(r),
        Mode::LabelFlow => g_labelflow(r),
        Mode::Char => g_char(r),
        Mode::Regex => g_regex(r),
        Mode::Float => g_float(r),
        Mode::Decl => g_decl(r),
        Mode::Object => g_object(r),
        Mode::StaticRef => g_staticref(r),
        Mode::LoopKind => g_loopkind(r),
        Mode::Narrow => g_narrow(r),
        Mode::ListOp => g_listop(r),
        Mode::Varargs => g_varargs(r),
        Mode::ListView => g_listview(r),
        Mode::Immutable => g_immutable(r),
        Mode::Super => g_super(r),
        Mode::InstanceOf => g_instanceof(r),
        Mode::Render => g_render(r),
        Mode::Equals => g_equals(r),
        Mode::Bits => g_bits(r),
        Mode::Objects => g_objects(r),
        Mode::Deque => g_deque(r),
        Mode::Mutate => g_mutate(r),
        Mode::Chars => g_chars(r),
        Mode::Nested => g_nested(r),
        Mode::Builder => g_builder(r),
        Mode::MathFn => g_mathfn(r),
        Mode::MapFn => g_mapfn(r),
        Mode::CtorRef => g_ctorref(r),
        Mode::Optional => g_optional(r),
        Mode::Stream => g_stream(r),
        Mode::ArraysFn => g_arraysfn(r),
        Mode::ParseFn => g_parsefn(r),
        Mode::TextBlock => g_textblock(r),
        Mode::Anon => g_anon(r),
        Mode::Clinit => round2::g_clinit(r),
        Mode::TernProm => round2::g_ternprom(r),
        Mode::NullUnbox => round2::g_nullunbox(r),
        Mode::IntCache => round2::g_intcache(r),
        Mode::NumProm => round2::g_numprom(r),
        Mode::FmtFlag => round2::g_fmtflag(r),
        Mode::SBuild => round2::g_sbuild(r),
        Mode::HashIter => round2::g_hashiter(r),
        Mode::Exc => round2::g_exc(r),
        Mode::Overload => round2::g_overload(r),
        Mode::SwFall => round2::g_swfall(r),
        Mode::Sealed => round2::g_sealed(r),
        Mode::Capture => round2::g_capture(r),
        Mode::Generic => round2::g_generic(r),
        Mode::FailFast => round2::g_failfast(r),
        Mode::View => round2::g_view(r),
        Mode::Erased => round2::g_erased(r),
        Mode::Lru => round2::g_lru(r),
        Mode::BitsFloat => round2::g_bitsfloat(r),
        Mode::RecHash => round2::g_rechash(r),
        Mode::StreamOps => round2::g_streamops(r),
        Mode::All => unreachable!("resolved above"),
    }
}

fn gen_probes(seed: u64, mode: Mode, n: usize) -> Vec<String> {
    let mut r = Rng::new(seed);
    (0..n).map(|_| gen_probe(&mut r, mode)).collect()
}

/// Wrap probes in the single-class shell both sides accept. The class must be
/// named for the file, so callers write it to `T.java`.
fn build_program(probes: &[String]) -> String {
    let mut s = String::from(
        "import java.util.*;\nimport java.util.stream.*;\npublic class T {\n    public static void main(String[] args) {\n",
    );
    for probe in probes {
        s.push_str("        ");
        s.push_str(probe);
        s.push('\n');
    }
    s.push_str("    }\n");
    s.push_str(SUPPORT);
    s.push_str(round2::SUPPORT);
    s.push_str("}\n");
    s.push_str(SUPPORT_CLASS);
    s.push_str(round2::SUPPORT_CLASS);
    s
}

struct RunOut {
    stdout: Vec<u8>,
    ok: bool,
}

static TMP_CTR: AtomicU64 = AtomicU64::new(0);

/// Environment variables that change what a `java` launcher does, cleared from
/// every JVM this harness spawns -- the probes AND the measured runs alike.
///
/// `JAVA_HOME` is not read by a real `java` binary, but the first `java` on a
/// developer `PATH` is routinely a version-manager shim that *is* a script and
/// does read it. On this machine it names a JDK 17, whose `Double.toString`
/// predates JDK 19's shortest-round-trip rewrite, so an inherited `JAVA_HOME`
/// silently selects a JVM that answers `1.0e23` with `9.999999999999999E22`.
/// [`require_modern_doubles`] catches that, but only because the probe runs
/// under the same environment as the measured programs; clearing the variable
/// removes the divergence at the source instead of detecting it after the fact.
///
/// The three `*OPTIONS` variables are read by the launcher itself and prepend
/// arbitrary flags to every invocation. `JDK_JAVA_OPTIONS` is the dangerous one
/// for a differential harness: it is honoured only by the *source-file*
/// launcher -- exactly the entry point this harness uses and the frozen corpus
/// replays -- so an ambient value alters the reference and nothing else, and
/// javars, which reads no environment variable at all, cannot follow it.
const JVM_ENV_TO_CLEAR: &[&str] = &[
    "JAVA_HOME",
    "JDK_JAVA_OPTIONS",
    "JAVA_TOOL_OPTIONS",
    "_JAVA_OPTIONS",
];

/// A `Command` for one side of the comparison, with [`JVM_ENV_TO_CLEAR`] removed.
///
/// Both sides are sanitized, not just the oracle: javars reads no environment
/// variable, so clearing them costs nothing there and keeps the two processes
/// running under one environment rather than two that differ in ways the report
/// would not name.
fn jvm_command(prog: &Path) -> Command {
    let mut c = Command::new(prog);
    for k in JVM_ENV_TO_CLEAR {
        c.env_remove(k);
    }
    c
}

/// The options the reference `java` is launched with, and javars is not.
///
/// An empty `user.language`/`user.country` is `Locale.ROOT` — the locale javars
/// formats in unconditionally, because it has no locale model and accepts no
/// `-D` to give it one (see BUGS.md). Without the pin the oracle formats in
/// whatever locale the *machine* is set to, so `%,d` and `%.2f` would be
/// compared against `1.234.567` / `3,50` on a German desktop and every format
/// probe would report a divergence that says nothing about javars. This does not
/// hide the locale gap: a javars program cannot select a locale at all, so there
/// is no javars behaviour on the other side of the pin to measure.
///
/// `-XX:-OmitStackTraceInFastThrow` is the same kind of pin, for the same kind
/// of reason. HotSpot replaces a *repeatedly* thrown implicit exception --
/// `ArrayIndexOutOfBoundsException`, `NullPointerException`, and the rest of the
/// set the JIT generates -- with a preallocated instance carrying no stack trace
/// and **no message**, once the throwing site is hot enough. So a probe that
/// prints `e.getMessage()` reports the real text early in a run and `null` later
/// in it, at a threshold that depends on how often the JIT reached that site.
/// Measured on openjdk 21.0.12.1: `List.of(1, 2, 3, 4, 5).get(-2)` in a loop
/// answers `Index -2 out of bounds for length 5` on iteration 0 and `null` on
/// iteration 199,999; with the flag it answers the message at both. That made a
/// sweep report a divergence for a program javars ran correctly, and made the
/// same program pass when run alone. It is a JIT timing artifact rather than
/// language behaviour, javars has no equivalent optimization to reproduce, and
/// the flag only restores the message the exception is specified to carry -- so
/// pinning it removes noise from the oracle without excusing anything on the
/// javars side.
const ORACLE_OPTS: &[&str] = &[
    "-Duser.language=",
    "-Duser.country=",
    "-XX:-OmitStackTraceInFastThrow",
];

/// javars takes no options before the source file.
const OURS_OPTS: &[&str] = &[];

/// Run one program through `prog`. The file must be named `T.java` for the JDK's
/// single-file source launcher, so each run gets its own directory.
fn run_prog(prog: &Path, opts: &[&str], src: &str, timeout: Duration) -> RunOut {
    let n = TMP_CTR.fetch_add(1, Ordering::Relaxed);
    let dir = std::env::temp_dir().join(format!("javars_parity_{}_{n}", std::process::id()));
    let _ = std::fs::create_dir_all(&dir);
    let path = dir.join("T.java");
    if std::fs::write(&path, src).is_err() {
        return RunOut {
            stdout: Vec::new(),
            ok: false,
        };
    }

    let mut child = match jvm_command(prog)
        .args(opts)
        .arg(&path)
        .current_dir(&dir)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            eprintln!("parity-fuzz: cannot spawn {}: {e}", prog.display());
            std::process::exit(2);
        }
    };

    // Poll for the timeout rather than blocking forever on a hung frontend.
    let deadline = std::time::Instant::now() + timeout;
    let status = loop {
        match child.try_wait() {
            Ok(Some(st)) => break Some(st),
            Ok(None) => {
                if std::time::Instant::now() >= deadline {
                    let _ = child.kill();
                    let _ = child.wait();
                    break None;
                }
                std::thread::sleep(Duration::from_millis(10));
            }
            Err(_) => break None,
        }
    };

    let out = child.wait_with_output().ok();
    let _ = std::fs::remove_dir_all(&dir);
    match (status, out) {
        (Some(st), Some(o)) => RunOut {
            stdout: o.stdout,
            ok: st.success(),
        },
        (_, Some(o)) => RunOut {
            stdout: o.stdout,
            ok: false,
        },
        _ => RunOut {
            stdout: Vec::new(),
            ok: false,
        },
    }
}

fn differs(oracle: &RunOut, ours: &RunOut) -> bool {
    oracle.stdout != ours.stdout || oracle.ok != ours.ok
}

fn render(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes).replace('\n', "\\n")
}

fn diverges(probes: &[String], ours: &Path, oracle: &Path, timeout: Duration) -> bool {
    let src = build_program(probes);
    let a = run_prog(oracle, ORACLE_OPTS, &src, timeout);
    let b = run_prog(ours, OURS_OPTS, &src, timeout);
    differs(&a, &b)
}

/// The literal spans of a probe, as `(start, end)` byte ranges of its source.
///
/// A run of digits that is not glued to an identifier, and the inside of a
/// double-quoted string. Both are found by a single left-to-right walk that
/// tracks whether it is inside a string or a character literal, so a `"5"` in a
/// message and an escaped quote do not read as code.
fn literal_spans(probe: &str) -> Vec<(usize, usize)> {
    let b = probe.as_bytes();
    let mut spans = Vec::new();
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b'"' => {
                let start = i + 1;
                i += 1;
                while i < b.len() && b[i] != b'"' {
                    i += if b[i] == b'\\' { 2 } else { 1 };
                }
                if i <= b.len() {
                    spans.push((start, i.min(b.len())));
                }
                i += 1;
            }
            // A character literal is skipped whole: its content is one code
            // point and replacing it with `0` or `""` never compiles.
            b'\'' => {
                i += 1;
                while i < b.len() && b[i] != b'\'' {
                    i += if b[i] == b'\\' { 2 } else { 1 };
                }
                i += 1;
            }
            c if c.is_ascii_digit() => {
                let start = i;
                // Glued to an identifier on the left (`arg0`, `List12`) it is
                // part of a name, not a number.
                let name =
                    start > 0 && (b[start - 1].is_ascii_alphanumeric() || b[start - 1] == b'_');
                while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'.') {
                    i += 1;
                }
                // A suffix (`5L`, `1.0f`) or a trailing identifier character
                // makes the span something other than a bare decimal.
                let suffixed = i < b.len() && (b[i].is_ascii_alphabetic() || b[i] == b'_');
                if !name && !suffixed {
                    spans.push((start, i));
                }
            }
            _ => i += 1,
        }
    }
    spans
}

/// Reduce one probe's *literals* while it keeps diverging.
///
/// [`minimize`] deletes whole probes, which is the only reduction a packed
/// program allows — but it stops at one probe, and that probe still carries the
/// operands the generator happened to draw. A report that reads
/// `List.of(47, 12, 99).get(-2)` says the same thing as `List.of(1, 1, 1).get(0)`
/// and takes longer to read: the reader has to establish for himself that 47 and
/// 99 are not load-bearing before he can see that the *arity* is. So each
/// literal is tried against a smaller stand-in and kept only when the divergence
/// survives, which turns the surviving operands into evidence — a `3` that
/// resists shrinking to `0` and `1` is a `3` the divergence depends on.
///
/// Every candidate is checked against the same predicate the search uses, and
/// the oracle's own success is part of it: a reduction that stops the reference
/// from compiling makes both sides fail, and while that is not a *divergence* it
/// would be one the moment javars accepted what javac refused. Requiring the
/// oracle to still run keeps a syntactically broken reduction from being
/// mistaken for a smaller reproducer.
fn shrink_literals(probe: &str, ours: &Path, oracle: &Path, timeout: Duration) -> String {
    let oracle_ran = run_prog(
        oracle,
        ORACLE_OPTS,
        &build_program(&[probe.to_string()]),
        timeout,
    )
    .ok;
    let still_diverges = |cand: &str| -> bool {
        let src = build_program(&[cand.to_string()]);
        let a = run_prog(oracle, ORACLE_OPTS, &src, timeout);
        if oracle_ran && !a.ok {
            return false;
        }
        differs(&a, &run_prog(ours, OURS_OPTS, &src, timeout))
    };
    let mut cur = probe.to_string();
    // Right to left, so an accepted replacement cannot shift the spans still to
    // be tried.
    let mut spans = literal_spans(&cur);
    spans.reverse();
    for (start, end) in spans {
        if end > cur.len() || start > end {
            continue;
        }
        let original = cur[start..end].to_string();
        for smaller in ["", "0", "1"] {
            if smaller == original {
                break;
            }
            let mut cand = cur.clone();
            cand.replace_range(start..end, smaller);
            if still_diverges(&cand) {
                cur = cand;
                break;
            }
        }
    }
    cur
}

/// Bisect a diverging probe list down to a minimal still-diverging subset.
fn minimize(probes: &[String], ours: &Path, oracle: &Path, timeout: Duration) -> Vec<String> {
    let mut cur = probes.to_vec();
    let mut chunk = cur.len() / 2;
    while chunk >= 1 {
        let mut i = 0;
        while i < cur.len() {
            let mut trial = cur.clone();
            let end = (i + chunk).min(trial.len());
            trial.drain(i..end);
            if !trial.is_empty() && diverges(&trial, ours, oracle, timeout) {
                cur = trial;
            } else {
                i += chunk;
            }
        }
        if chunk == 1 {
            break;
        }
        chunk /= 2;
    }
    cur
}

fn ours_bin() -> PathBuf {
    if let Ok(p) = std::env::var("JAVARS_BIN") {
        return PathBuf::from(p);
    }
    let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    for profile in ["debug", "release"] {
        let c = root.join("target").join(profile).join("java");
        if c.exists() {
            return c;
        }
    }
    root.join("target/debug/java")
}

/// Locate a real JDK `java` that is not our own binary.
///
/// Every candidate is *run* before it is accepted, twice over, because two
/// different wrong oracles live on a developer machine and neither announces
/// itself:
///
///   * A `java` on `PATH` is routinely a version-manager shim rather than a
///     launcher, and a broken shim exits non-zero without printing a banner —
///     which this harness would read as "the reference produced no output",
///     reporting a divergence on every single probe. Naming the executable is
///     not evidence that it launches a JVM; [`jdk_banner`] getting a version
///     out of it is.
///   * A launcher that *does* work may still be too old to be the reference.
///     `Double.toString` was reimplemented in JDK 19 to emit the shortest
///     round-tripping decimal, so a JDK 17 oracle answers `1.0e23` with
///     `9.999999999999999E22` where 19+ answers `1.0E23`. That is a *silent*
///     corruptor: the harness runs green and reports divergences on every
///     double-valued probe, or worse, blesses the old rendering into the frozen
///     corpus. [`renders_modern_doubles`] is the probe that catches it.
fn resolve_oracle(ours: &Path) -> PathBuf {
    if let Ok(p) = std::env::var("JAVA_ORACLE") {
        let p = PathBuf::from(p);
        match jdk_banner(&p) {
            Some(v) => announce_oracle(&p, &v),
            None => {
                eprintln!(
                    "parity-fuzz: JAVA_ORACLE={} does not run — `--version` failed",
                    p.display()
                );
                std::process::exit(2);
            }
        }
        return p;
    }
    let ours_canon = ours.canonicalize().ok();
    let mut rejected = Vec::new();
    if let Ok(path) = std::env::var("PATH") {
        for dir in path.split(':') {
            let cand = Path::new(dir).join("java");
            if !cand.exists() || cand.canonicalize().ok() == ours_canon {
                continue;
            }
            match jdk_banner(&cand) {
                Some(v) => {
                    announce_oracle(&cand, &v);
                    return cand;
                }
                None => rejected.push(cand.display().to_string()),
            }
        }
    }
    eprintln!("parity-fuzz: no working reference `java` on PATH (set JAVA_ORACLE=/path/to/java)");
    for r in &rejected {
        eprintln!("parity-fuzz:   rejected {r} — `--version` failed");
    }
    std::process::exit(2);
}

/// Accept a candidate as the reference, after measuring it, and say so.
///
/// The report is unconditional rather than reserved for failures. Which JVM
/// answered is the single fact that decides what every double-valued
/// comparison in the run means, and a harness that prints it only when it
/// rejects one leaves a *passing* sweep with no record of what it passed
/// against — the log then cannot distinguish a clean run against JDK 21 from a
/// clean run against a JVM whose renderings differ. The ambient `JAVA_HOME` is
/// named for the same reason: it is the variable that misdirects a shim, and
/// [`JVM_ENV_TO_CLEAR`] strips it, so the line records both what was present
/// and that it did not reach the JVM.
fn announce_oracle(prog: &Path, banner: &str) {
    require_modern_doubles(prog, banner);
    require_root_locale(prog, banner);
    eprintln!("parity-fuzz: oracle {} ({banner})", prog.display());
    eprintln!(
        "parity-fuzz: oracle verified — 1.0e23 renders as 1.0E23 (JDK 19+ Double.toString), \
         String.format is the root locale"
    );
    eprintln!(
        "parity-fuzz: ambient JAVA_HOME={} (cleared from every spawn)",
        std::env::var("JAVA_HOME").unwrap_or_else(|_| "<unset>".into())
    );
}

/// The first line `prog --version` prints, if it exits 0 and prints one.
/// `None` for anything that is not a working launcher.
fn jdk_banner(prog: &Path) -> Option<String> {
    let out = jvm_command(prog).arg("--version").output().ok()?;
    if !out.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&out.stdout);
    let line = text.lines().next()?.trim();
    (!line.is_empty()).then(|| line.to_string())
}

/// What the candidate answers for `1.0e23`. JDK 19 replaced `Double.toString`
/// with the shortest round-tripping decimal (`1.0E23`); every release before it
/// answers `9.999999999999999E22`.
fn renders_modern_doubles(prog: &Path) -> Option<bool> {
    let dir = std::env::temp_dir().join(format!("javars_oracle_probe_{}", std::process::id()));
    std::fs::create_dir_all(&dir).ok()?;
    let path = dir.join("D.java");
    std::fs::write(
        &path,
        "public class D { public static void main(String[] a) { System.out.println(1.0e23); } }\n",
    )
    .ok()?;
    let out = jvm_command(prog).arg(&path).current_dir(&dir).output().ok();
    let _ = std::fs::remove_dir_all(&dir);
    let out = out?;
    Some(String::from_utf8_lossy(&out.stdout).trim() == "1.0E23")
}

/// Whether the candidate, launched with [`ORACLE_OPTS`], formats in the root
/// locale — the one javars formats in unconditionally.
///
/// The pin is two `-D` options, and a launcher is free to ignore an option it
/// does not recognise, so the answer is *measured* rather than assumed: a JVM
/// that kept a German default would render `1.234.567` / `3,50` and turn every
/// `format`/`printf` probe into a divergence that says nothing about javars.
fn formats_in_root_locale(prog: &Path) -> Option<bool> {
    let dir = std::env::temp_dir().join(format!("javars_locale_probe_{}", std::process::id()));
    std::fs::create_dir_all(&dir).ok()?;
    let path = dir.join("L.java");
    std::fs::write(
        &path,
        "public class L { public static void main(String[] a) { System.out.print(String.format(\"%,d|%.2f\", 1234567, 3.5)); } }\n",
    )
    .ok()?;
    let out = jvm_command(prog)
        .args(ORACLE_OPTS)
        .arg(&path)
        .current_dir(&dir)
        .output()
        .ok();
    let _ = std::fs::remove_dir_all(&dir);
    Some(String::from_utf8_lossy(&out?.stdout).trim() == "1,234,567|3.50")
}

/// Exit rather than measure `String.format` against another locale's separators.
fn require_root_locale(prog: &Path, banner: &str) {
    if formats_in_root_locale(prog) == Some(true) {
        return;
    }
    eprintln!(
        "parity-fuzz: {} ({banner}) does not honour {ORACLE_OPTS:?} — its `String.format` is not the root locale",
        prog.display()
    );
    eprintln!("parity-fuzz: every `format`/`printf` probe would report a locale difference as a javars divergence");
    std::process::exit(2);
}

/// Exit rather than measure against a pre-JDK-19 `Double.toString`.
fn require_modern_doubles(prog: &Path, banner: &str) {
    if renders_modern_doubles(prog) == Some(true) {
        return;
    }
    eprintln!(
        "parity-fuzz: {} ({banner}) renders 1.0e23 the pre-JDK-19 way — too old to be the reference",
        prog.display()
    );
    eprintln!(
        "parity-fuzz: JAVA_HOME={}",
        std::env::var("JAVA_HOME").unwrap_or_else(|_| "<unset>".into())
    );
    eprintln!("parity-fuzz: set JAVA_ORACLE to a JDK 19 or newer `java`");
    std::process::exit(2);
}

struct Args {
    iters: usize,
    probes: usize,
    seed: Option<u64>,
    once: bool,
    mode: Mode,
    timeout: Duration,
    verbose: bool,
    jobs: usize,
}

fn parse_args() -> Args {
    let mut a = Args {
        iters: 50,
        probes: 40,
        seed: None,
        once: false,
        mode: Mode::All,
        timeout: Duration::from_secs(60),
        verbose: false,
        // One seed per core by default. A sweep is not compute-bound — nearly
        // all of its wall time is two process launches per program waiting on
        // each other — so the serial loop left the machine idle: 24 programs
        // took 2:35.82 at 28% CPU on this one. The floor is 1, not 0, since
        // `--jobs 0` would otherwise spawn no worker and report a clean sweep
        // over zero programs.
        jobs: std::thread::available_parallelism().map_or(1, |n| n.get()),
    };
    let argv: Vec<String> = std::env::args().skip(1).collect();
    let mut i = 0;
    while i < argv.len() {
        let next = |i: &mut usize| -> String {
            *i += 1;
            argv.get(*i).cloned().unwrap_or_default()
        };
        match argv[i].as_str() {
            "--iters" => a.iters = next(&mut i).parse().unwrap_or(a.iters),
            "--probes" => a.probes = next(&mut i).parse().unwrap_or(a.probes),
            "--seed" => a.seed = next(&mut i).parse().ok(),
            "--once" => a.once = true,
            "--verbose" | "-v" => a.verbose = true,
            "--timeout" => a.timeout = Duration::from_secs(next(&mut i).parse().unwrap_or(60)),
            "--jobs" | "-j" => a.jobs = next(&mut i).parse().unwrap_or(a.jobs).max(1),
            "--mode" => {
                let m = next(&mut i);
                match parse_mode(&m) {
                    Some(m) => a.mode = m,
                    None => {
                        eprintln!("parity-fuzz: unknown mode `{m}`");
                        std::process::exit(2);
                    }
                }
            }
            "--help" | "-h" => {
                println!("parity-fuzz [--iters N] [--probes N] [--seed N] [--once] [--mode M] [--timeout SECS] [--jobs N] [-v]");
                println!(
                    "modes: all {}",
                    CONCRETE
                        .iter()
                        .map(|m| mode_name(*m))
                        .collect::<Vec<_>>()
                        .join(" ")
                );
                std::process::exit(0);
            }
            other => {
                eprintln!("parity-fuzz: unknown option `{other}`");
                std::process::exit(2);
            }
        }
        i += 1;
    }
    a
}

fn main() {
    let args = parse_args();
    let ours = ours_bin();
    if !ours.exists() {
        eprintln!("parity-fuzz: {} not built (cargo build)", ours.display());
        std::process::exit(2);
    }
    let oracle = resolve_oracle(&ours);
    eprintln!(
        "parity-fuzz: oracle={} ours={} mode={} probes={}",
        oracle.display(),
        ours.display(),
        mode_name(args.mode),
        args.probes
    );

    let iters = if args.once { 1 } else { args.iters };
    let base = args.seed.unwrap_or(0x5EED);

    // One program per worker at a time, handed out from a shared cursor rather
    // than sliced up front: a program that diverges pays for minimization and
    // literal shrinking on top of its two launches, so a fixed split would
    // leave every other worker idle behind the one that found something.
    let next_index = AtomicUsize::new(0);
    let failures = AtomicUsize::new(0);
    let probes_run = AtomicUsize::new(0);
    let skipped = AtomicUsize::new(0);
    // Divergence reports are several lines each and interleaving two of them
    // would make both unreadable, so a report is assembled whole and printed
    // under the lock.
    let report = Mutex::new(());
    let jobs = args.jobs.min(iters.max(1));
    eprintln!("parity-fuzz: {jobs} job(s)");

    std::thread::scope(|scope| {
        for _ in 0..jobs {
            scope.spawn(|| loop {
                let k = next_index.fetch_add(1, Ordering::Relaxed);
                if k >= iters {
                    return;
                }
                let seed = if args.once {
                    base
                } else {
                    base.wrapping_add(k as u64)
                };
                let probes = gen_probes(seed, args.mode, args.probes);
                let src = build_program(&probes);
                let a = run_prog(&oracle, ORACLE_OPTS, &src, args.timeout);
                // A program the reference toolchain itself did not run is no
                // evidence about javars. Comparing anyway would let a probe the
                // JDK rejects be counted as agreement (both sides "fail"), which
                // silently inflates a clean sweep — so it is skipped and
                // reported under its own count.
                if !a.ok || a.stdout.is_empty() {
                    skipped.fetch_add(1, Ordering::Relaxed);
                    let _g = report.lock().unwrap_or_else(|e| e.into_inner());
                    eprintln!("seed {seed}: SKIPPED — reference `java` did not produce output");
                    // A skip is a claim about the *generator*, not about javars,
                    // so the program has to be inspectable — otherwise a mode
                    // that emits Java the JDK rejects would quietly shrink the
                    // verified count instead of being fixed.
                    if args.verbose {
                        eprintln!("{src}");
                    }
                    continue;
                }
                probes_run.fetch_add(probes.len(), Ordering::Relaxed);
                let b = run_prog(&ours, OURS_OPTS, &src, args.timeout);
                if !differs(&a, &b) {
                    if args.verbose {
                        let _g = report.lock().unwrap_or_else(|e| e.into_inner());
                        eprintln!("seed {seed}: ok ({} probes)", probes.len());
                    }
                    continue;
                }
                failures.fetch_add(1, Ordering::Relaxed);
                let mut minimal = minimize(&probes, &ours, &oracle, args.timeout);
                // Literal reduction only pays once the probe list is down to
                // one: with several probes left the divergence could move
                // between them and each candidate costs two JDK launches.
                if minimal.len() == 1 {
                    minimal[0] = shrink_literals(&minimal[0], &ours, &oracle, args.timeout);
                }
                let src = build_program(&minimal);
                let a = run_prog(&oracle, ORACLE_OPTS, &src, args.timeout);
                let b = run_prog(&ours, OURS_OPTS, &src, args.timeout);
                let mut out =
                    format!("=== DIVERGENCE seed {seed} (replay: --seed {seed} --once) ===\n");
                for probe in &minimal {
                    out.push_str(&format!("  {probe}\n"));
                }
                out.push_str(&format!(
                    "  oracle: ok={} out={}\n",
                    a.ok,
                    render(&a.stdout)
                ));
                out.push_str(&format!("  ours  : ok={} out={}", b.ok, render(&b.stdout)));
                let _g = report.lock().unwrap_or_else(|e| e.into_inner());
                println!("{out}");
            });
        }
    });

    let failures = failures.into_inner();
    let probes_run = probes_run.into_inner();
    let skipped = skipped.into_inner();

    eprintln!(
        "parity-fuzz: {} program(s) ({skipped} skipped), {probes_run} verified probe(s), {failures} divergence(s)",
        iters
    );
    if failures > 0 {
        std::process::exit(1);
    }
}

/// The regex pools' pairing invariant, checked against the JDK's own answer.
///
/// The generator used to draw a pattern and a replacement from independent
/// pools, so it emitted programs like `"aabbcc".replaceAll("[a-z]", "$1$1")`
/// that the reference `java` aborts with `IndexOutOfBoundsException: No group
/// 1`. The whole packed program then produced no comparable output and was
/// counted a *skip* — which reads in the summary exactly like coverage that
/// passed. These tests pin the group accounting that replaced it, so the pools
/// cannot drift back into generating a program the oracle refuses to run.
/// [`literal_spans`] finds the operands a report should shrink, and nothing else.
///
/// The walk decides what a run of digits *is* from its neighbours, and every
/// wrong answer costs a JDK launch on a candidate that cannot compile — or worse,
/// silently rewrites a name and reports a reproducer that does not reproduce.
/// These pin the four judgements it makes.
#[cfg(test)]
mod literal_spans_tests {
    use super::literal_spans;

    fn found(probe: &str) -> Vec<&str> {
        literal_spans(probe)
            .into_iter()
            .map(|(a, b)| &probe[a..b])
            .collect()
    }

    #[test]
    fn a_bare_decimal_is_a_literal_and_a_digit_inside_a_name_is_not() {
        // `List12` and `arg0` are names. Rewriting the `12` in `List12` to `0`
        // produces `List0`, which does not compile and burns two JDK launches
        // per candidate to discover it.
        assert_eq!(found("List.of(1, 2).get(5);"), ["1", "2", "5"]);
        assert_eq!(found("x = List12 + arg0;"), Vec::<&str>::new());
        assert_eq!(found("a1b2c3"), Vec::<&str>::new());
    }

    #[test]
    fn a_suffixed_or_fractional_literal_is_left_whole_or_left_alone() {
        // `5L` and `1.0f` carry a type in their suffix; replacing the digits
        // alone would leave a bare `L`/`f`. A `1.0` with no suffix is one span,
        // not two — shrinking `1` and `0` independently would emit `.0` and `1.`.
        assert_eq!(found("long v = 5L; float f = 1.0f;"), Vec::<&str>::new());
        assert_eq!(found("double d = 1.0;"), ["1.0"]);
    }

    #[test]
    fn digits_inside_a_string_are_the_strings_content_not_the_programs() {
        // The span is the *inside* of the quotes, so the replacement stays a
        // valid string literal. The digits within it are not separate spans;
        // reporting them too would rewrite `"a5"` to `"a"5""`.
        assert_eq!(found("System.out.println(\"idx 5\" + 7);"), ["idx 5", "7"]);
        assert_eq!(found("s = \"\";"), [""]);
    }

    #[test]
    fn a_char_literal_and_an_escaped_quote_do_not_open_a_string() {
        // `'\"'` and `\"\\\"\"` each contain a quote that does not start one. A
        // walk that took either as an opener would treat the rest of the probe
        // as string content and find no spans at all in it.
        assert_eq!(found("c = '\"'; n = 4;"), ["4"]);
        assert_eq!(found("s = \"a\\\"b\"; n = 4;"), ["a\\\"b", "4"]);
        assert_eq!(found("c = '5'; n = 4;"), ["4"]);
    }
}

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

    /// `Pattern.compile(p).matcher("").groupCount()` for every entry of
    /// [`PATTERNS`], in order, captured from a real JDK and re-verified against
    /// `openjdk 21.0.12` and `openjdk 26.0.2` (Homebrew), which agree on every
    /// entry. Frozen rather than recomputed so the invariant holds in CI without
    /// a JDK installed — the same reason `tests/data/parity_expected.txt` is
    /// frozen. Re-verify by feeding each pattern to
    /// `Pattern.compile(p).matcher("").groupCount()`; the values are the
    /// authority, and the JDK build that first produced them is not recorded
    /// because no build has ever disagreed.
    const JDK_GROUP_COUNTS: &[usize] = &[
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 1, 2,
    ];

    /// The counter agrees with the JDK on every pattern in the pool — including
    /// the three shapes a naive `(`-count gets wrong: `(?:ab)+` and `(?i)a` are
    /// not capturing, `(?<=a)b` is a lookbehind rather than a named group, and
    /// `(?<g>a)b` is a named group rather than a lookbehind.
    #[test]
    fn group_counts_match_the_jdk() {
        assert_eq!(
            PATTERNS.len(),
            JDK_GROUP_COUNTS.len(),
            "PATTERNS changed without recapturing JDK_GROUP_COUNTS from a real JDK"
        );
        let mut wrong = Vec::new();
        for (p, want) in PATTERNS.iter().zip(JDK_GROUP_COUNTS) {
            let got = pattern_groups(p).0;
            if got != *want {
                wrong.push(format!("`{p}`: jdk={want} ours={got}"));
            }
        }
        assert!(
            wrong.is_empty(),
            "group count diverged:\n  {}",
            wrong.join("\n  ")
        );
    }

    /// The lookaround/named-group boundary, stated directly rather than only
    /// via the pool, so a rewrite that collapses them is caught by name.
    #[test]
    fn lookbehind_is_not_a_named_group() {
        assert_eq!(pattern_groups("(?<=a)b"), (0, vec![]));
        assert_eq!(pattern_groups("(?<!a)b"), (0, vec![]));
        assert_eq!(pattern_groups("(?<g>a)b"), (1, vec!["g".to_string()]));
        assert_eq!(pattern_groups("(?:ab)+"), (0, vec![]));
        assert_eq!(pattern_groups("(?i)a"), (0, vec![]));
        // An escaped paren and a paren inside a character class are literal.
        assert_eq!(pattern_groups("\\\\(a\\\\)").0, 0);
        assert_eq!(pattern_groups("[()]").0, 0);
    }

    /// A `\`-escaped `$` is a literal dollar, not a reference — the pool entry
    /// that would otherwise look like a bare `$` and be rejected everywhere.
    #[test]
    fn replacement_references_are_read_through_both_escape_layers() {
        assert_eq!(replacement_refs("\"\\\\$\""), (0, vec![]));
        assert_eq!(replacement_refs("\"\\\\\\\\\""), (0, vec![]));
        assert_eq!(replacement_refs("\"[$0]\""), (0, vec![]));
        assert_eq!(replacement_refs("\"$1$1\""), (1, vec![]));
        assert_eq!(replacement_refs("\"$2$1\""), (2, vec![]));
        assert_eq!(replacement_refs("\"${g}\""), (0, vec!["g".to_string()]));
        assert_eq!(replacement_refs("\"[${g}]$0\""), (0, vec!["g".to_string()]));
    }

    /// Every replacement the generator can hand a pattern is legal against it,
    /// over the entire cross-product — the invariant the skips violated.
    #[test]
    fn every_reachable_pairing_is_legal() {
        let mut r = Rng::new(0xC0FFEE);
        for p in PATTERNS {
            let (count, names) = pattern_groups(p);
            // Sample enough draws that each legal replacement is hit; the check
            // is on what `pick_replacement` can return, not on the pool.
            for _ in 0..REPLACEMENTS.len() * 20 {
                let rep = pick_replacement(&mut r, p);
                let (max_num, refs) = replacement_refs(rep);
                assert!(
                    max_num <= count,
                    "`{p}` has {count} group(s) but was paired with `{rep}`"
                );
                for n in &refs {
                    assert!(
                        names.contains(n),
                        "`{p}` has no group named `{n}` but was paired with `{rep}`"
                    );
                }
            }
        }
    }

    /// The fix constrains the *pairing*, so it must not have cost coverage:
    /// every replacement in the pool is still reachable from some pattern, and
    /// every pattern still admits some replacement.
    #[test]
    fn no_replacement_and_no_pattern_became_unreachable() {
        for rep in REPLACEMENTS {
            assert!(
                PATTERNS.iter().any(|p| pairable(p, rep)),
                "replacement `{rep}` is no longer reachable from any pattern — \
                 the pairing fix would be trading skips for lost coverage"
            );
        }
        for p in PATTERNS {
            assert!(
                REPLACEMENTS.iter().any(|rep| pairable(p, rep)),
                "pattern `{p}` admits no replacement"
            );
        }
    }

    /// The pairing rule is what rejects the exact program that produced the
    /// skips, and it rejects it for the reason the JDK does.
    #[test]
    fn the_program_that_caused_the_skips_is_now_unpairable() {
        assert!(!pairable("[a-z]", "\"$1$1\""));
        assert!(!pairable("[a-z]", "\"<$1>\""));
        assert!(!pairable("(a)", "\"$2$1\""));
        assert!(!pairable("(a)", "\"${g}\""), "no group named g");
        // ...and admits the ones the JDK runs.
        assert!(pairable("[a-z]", "\"[$0]\""));
        assert!(pairable("(a)", "\"$1$1\""));
        assert!(pairable("(\\\\w)(\\\\w)", "\"$2$1\""));
        assert!(pairable("(?<g>a)", "\"${g}\""));
    }
}

/// A generator may not splice an operator onto a literal that already carries a
/// sign.
///
/// `g_cast` built its negated-operand probe as `-{d}` over a `DBLS` pool that
/// holds `-1.5`, producing `(int) --1.5`. Java lexes `--` as the decrement
/// operator, which requires a variable, so `javac` rejected the whole program
/// and the harness counted it a *skip* — 10 of 40 programs in `--mode cast`,
/// reported as "not compared" rather than as invalid Java. It is the same
/// defect class the regex pools had, reached the other way: there the oracle
/// aborted at run time, here it never compiled.
#[cfg(test)]
mod operand_splicing {
    use super::*;

    /// No mode may emit `--` or `++` against a numeric literal.
    ///
    /// Checked over every mode rather than over `cast` alone: the pools are
    /// shared, so any generator that grows a signed-operand probe inherits the
    /// same trap. `--x`/`x++` are ordinary and stay legal — it is only a digit
    /// or a `.` after the doubled operator that cannot be anything but the bug,
    /// since no literal is assignable.
    #[test]
    fn no_generator_prefixes_an_operator_onto_a_signed_literal() {
        let mut bad = Vec::new();
        for mode in CONCRETE {
            for seed in 0..400u64 {
                for probe in gen_probes(seed, *mode, 8) {
                    let cs: Vec<char> = probe.chars().collect();
                    for w in cs.windows(3) {
                        let doubled = (w[0] == '-' || w[0] == '+') && w[1] == w[0];
                        if doubled && (w[2].is_ascii_digit() || w[2] == '.') {
                            bad.push(format!("{}: {probe}", mode_name(*mode)));
                        }
                    }
                }
            }
        }
        bad.sort();
        bad.dedup();
        assert!(
            bad.is_empty(),
            "{} generator(s) spliced an operator onto a signed literal, which \
             `javac` rejects as a decrement of a non-variable:\n  {}",
            bad.len(),
            bad.join("\n  ")
        );
    }
}