rubylang 0.1.18

Ruby as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a RubyHost heap — the first compiled standalone Ruby runtime
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
//! Differential parity fuzzer: reference `ruby -e <s>` vs rubylang `ruby -e <s>`.
//!
//! Generates thousands of grammar-driven, deterministic-output Ruby snippets,
//! runs each through both interpreters, and reports every case where stdout OR
//! exit code diverge. Each case is produced from a per-index seed so any
//! divergence replays exactly: `parity-fuzz --seed <N> --once`.
//!
//! The ORACLE is resolved by `rubylang::oracle`, never by a PATH lookup for
//! `ruby`: rubylang installs its own binary under that name, so bare `ruby`
//! fuzzes rubylang against itself and reports perfect parity forever.
//!
//! Ported from the zshrs harness (`zshrs/bins/parity-fuzz.rs`): same RunOut /
//! render / differs / run_with_timeout infra, same seed→deterministic Mode
//! dispatch, same parallel workers, delta-debug `minimize`, `--verify`
//! K-consecutive re-check, `--baseline` allowlist + gap `signature`, `--once`
//! replay, and report file under `target/parity-fuzz/divergences.txt`. Only the
//! generators and the invocation (Ruby, not zsh) differ.
//!
//! The generators are biased toward the historically weak areas of a Ruby
//! frontend (float shortest-repr, integer division/modulo sign, format specs,
//! slicing, block-based enumerables, string methods). Pure random bytes only
//! produce mutual syntax errors that agree on both sides and teach nothing.
//!
//! Determinism invariant: the generator NEVER emits a construct whose output is
//! nondeterministic for reasons unrelated to parity — no `Time`, no `rand`, no
//! `object_id`/`hash`, no bare-object `#<...>` prints, no Set iteration-order
//! output (always sort first). Ruby Hash is insertion-ordered, so Hash literals
//! are safe. Every program prints something deterministic so an empty-vs-empty
//! run can never hide a gap.
//!
//! Build:  cargo build --bin parity-fuzz
//! Run:    ./target/debug/parity-fuzz --count 5000

use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

/// Also compare stderr (normalized) when set via `--stderr`.
static CMP_STDERR: AtomicBool = AtomicBool::new(false);

// ---------------------------------------------------------------------------
// PRNG — inline splitmix64, no `rand` dependency.
// ---------------------------------------------------------------------------

struct Rng(u64);

impl Rng {
    fn seed(s: u64) -> Rng {
        // Avoid a zero state degenerating; splitmix64 tolerates any seed but a
        // nonzero start keeps the first draw well-mixed.
        Rng(s ^ 0x9E37_79B9_7F4A_7C15)
    }

    fn next_u64(&mut self) -> u64 {
        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^ (z >> 31)
    }

    /// Uniform in `0..n` (n >= 1).
    fn below(&mut self, n: usize) -> usize {
        (self.next_u64() % n as u64) as usize
    }

    /// Inclusive range `lo..=hi`.
    fn range(&mut self, lo: i64, hi: i64) -> i64 {
        lo + (self.next_u64() % (hi - lo + 1) as u64) as i64
    }

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

// ---------------------------------------------------------------------------
// Interpreter locations / invocation.
// ---------------------------------------------------------------------------

/// The rubylang binary under test — a sibling of this harness exe. Always an
/// absolute path so it can never be confused with the reference `ruby` on PATH
/// (they share the name `ruby`).
fn ours_bin() -> PathBuf {
    if let Ok(p) = std::env::var("CARGO_BIN_EXE_ruby") {
        return PathBuf::from(p);
    }
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            let cand = dir.join("ruby");
            if cand.exists() {
                return cand;
            }
        }
    }
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("target")
        .join("debug")
        .join("ruby")
}

/// The ORACLE: the reference MRI `ruby`. Every divergence is "rubylang disagrees
/// with THIS ruby", so which ruby it is, is part of the result.
///
/// Resolution and verification live in [`rubylang::oracle`]. The candidate that
/// existence alone would have picked here — `/opt/homebrew/bin/ruby` — is a
/// symlink into rubylang's own Cellar on any machine where rubylang is
/// installed, so "first absolute system path that exists" selected rubylang and
/// fuzzed it against itself: zero divergences, forever, on a broken build.
/// `oracle::find` makes a candidate prove it is MRI before accepting it.
fn oracle() -> &'static rubylang::oracle::Oracle {
    static ORACLE: std::sync::OnceLock<rubylang::oracle::Oracle> = std::sync::OnceLock::new();
    ORACLE.get_or_init(|| rubylang::oracle::require_oracle("parity-fuzz"))
}

/// `<path> (<ruby --version>)`, for the run header and the report file so a
/// divergence record is attributable to the exact oracle that produced it.
fn oracle_id() -> String {
    oracle().id()
}

/// Raw bytes, never `String`: Ruby can emit output that is not valid UTF-8
/// (`"\xff"`, an 8-bit encoding). Comparing bytes keeps the surface honest;
/// lossy rendering is for the human-facing report only.
struct RunOut {
    stdout: Vec<u8>,
    stderr: Vec<u8>,
    exit: i32,
    timed_out: bool,
}

/// Render captured bytes for a report. Invalid UTF-8 is shown lossily AND
/// followed by a hex line, so two different invalid byte strings do not both
/// render to U+FFFD and hide a divergence.
fn render(bytes: &[u8]) -> String {
    let text = String::from_utf8_lossy(bytes);
    let text = text.trim_end_matches('\n');
    if std::str::from_utf8(bytes).is_err() {
        let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
        return format!("{text}\n  (hex) {}", hex.join(" "));
    }
    text.to_string()
}

/// Strip the leading `-e:LINE:` / `<path>:LINE:` location and the `ruby:` tag so
/// diagnostics can be compared for wording, not for the exact interpreter name
/// or line prefix.
fn norm_stderr(s: &[u8]) -> Vec<u8> {
    let text = String::from_utf8_lossy(s);
    let mut out = String::new();
    for (i, line) in text.split('\n').enumerate() {
        if i > 0 {
            out.push('\n');
        }
        // Drop a leading `-e:12:` / `foo.rb:12:in ...` location prefix.
        let l = match line.find(':') {
            Some(idx) if line[..idx].contains("-e") || line[..idx].ends_with(".rb") => {
                // strip `-e:NN:` (two colons in)
                let rest = &line[idx + 1..];
                match rest.find(": ") {
                    Some(j) => &rest[j + 2..],
                    None => line,
                }
            }
            _ => line,
        };
        let l = l.strip_prefix("ruby: ").unwrap_or(l);
        out.push_str(l);
    }
    out.into_bytes()
}

/// The divergence predicate. stdout + exit always; stderr only under `--stderr`.
fn differs(a: &RunOut, b: &RunOut) -> bool {
    if a.stdout != b.stdout || a.exit != b.exit {
        return true;
    }
    if CMP_STDERR.load(Ordering::Relaxed) {
        return norm_stderr(&a.stderr) != norm_stderr(&b.stderr);
    }
    false
}

/// Spawn `cmd` and wait up to `timeout`, killing it if it overruns.
fn run_with_timeout(mut cmd: Command, timeout: Duration) -> RunOut {
    cmd.stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = match cmd.spawn() {
        Ok(c) => c,
        Err(_) => {
            return RunOut {
                stdout: Vec::new(),
                stderr: Vec::new(),
                exit: -999,
                timed_out: false,
            }
        }
    };
    let start = Instant::now();
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                use std::io::Read;
                let mut buf = Vec::new();
                if let Some(mut out) = child.stdout.take() {
                    let _ = out.read_to_end(&mut buf);
                }
                let mut ebuf = Vec::new();
                if let Some(mut err) = child.stderr.take() {
                    let _ = err.read_to_end(&mut ebuf);
                }
                return RunOut {
                    stdout: buf,
                    stderr: ebuf,
                    exit: status.code().unwrap_or(-1),
                    timed_out: false,
                };
            }
            Ok(None) => {
                if start.elapsed() >= timeout {
                    let _ = child.kill();
                    let _ = child.wait();
                    return RunOut {
                        stdout: Vec::new(),
                        stderr: Vec::new(),
                        exit: -1,
                        timed_out: true,
                    };
                }
                std::thread::sleep(Duration::from_millis(2));
            }
            Err(_) => {
                return RunOut {
                    stdout: Vec::new(),
                    stderr: Vec::new(),
                    exit: -998,
                    timed_out: false,
                }
            }
        }
    }
}

fn run_oracle(script: &str, timeout: Duration) -> RunOut {
    let mut cmd = Command::new(&oracle().path);
    cmd.args(["-e", script]);
    run_with_timeout(cmd, timeout)
}

fn run_ours(script: &str, bin: &Path, timeout: Duration) -> RunOut {
    let mut cmd = Command::new(bin);
    cmd.args(["-e", script]);
    // A stale rkyv cache would let a chunk that once worked keep passing.
    cmd.env_remove("RUBYLANG_CACHE");
    run_with_timeout(cmd, timeout)
}

// ---------------------------------------------------------------------------
// Generators — one per Mode. Each returns a statement list; joined by newlines
// into a program. Most emit a single deterministic `p`/`puts` probe.
// ---------------------------------------------------------------------------

const INTS: &[&str] = &[
    "0", "1", "2", "7", "10", "-3", "-7", "42", "100", "-1", "5", "9",
];
const FLOATS: &[&str] = &[
    "0.1", "0.2", "1.5", "3.14", "2.0", "-1.5", "10.0", "0.0", "100.25", "-0.5", "1e10", "1.0",
];
const WORDS: &[&str] = &[
    "foo", "bar", "baz", "hello", "world", "abc", "xyz", "Ruby", "Lang",
];
/// Element literals drawn from DIFFERENT `<=>` domains. Most pairs of these
/// cannot be ranked at all -- `1 <=> "a"` is nil, and so is every cross-domain
/// pair -- while a few (`1`/`2.5`/`1r`/`2**70`) rank fine. Ruby's `sort`, `min`,
/// `max` and their `_by` forms are DEFINED by `<=>`, so an unrankable pair
/// raises ArgumentError from the caller rather than answering; keeping the
/// rankable numerics in the pool is what stops "make everything raise" from
/// looking like a fix. No `Object.new`: its `inspect` carries a heap address,
/// which would diverge on the cases that succeed.
const MIXED: &[&str] = &[
    "1",
    "\"a\"",
    "nil",
    ":s",
    "2.5",
    "[9]",
    "true",
    "1r",
    "Float::NAN",
    "2**70",
];

fn ii<'a>(r: &mut Rng) -> &'a str {
    r.pick(INTS)
}
fn mixed<'a>(r: &mut Rng) -> &'a str {
    r.pick(MIXED)
}
fn ff<'a>(r: &mut Rng) -> &'a str {
    r.pick(FLOATS)
}
fn ww<'a>(r: &mut Rng) -> &'a str {
    r.pick(WORDS)
}

fn one(s: String) -> Vec<String> {
    vec![s]
}

fn gen_arith(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let ops = ["+", "-", "*", "/", "%", "**"];
    let a = ii(r);
    let b = ii(r);
    let c = ii(r);
    let op1 = r.pick(&ops);
    let op2 = r.pick(&ops);
    // Guard divide/modulo by zero producing a mutual error is fine (both agree),
    // but keep the second operand nonzero often so real arithmetic is exercised.
    one(match r.below(4) {
        0 => format!("p {a} {op1} {b} {op2} {c}"),
        1 => format!("p ({a} {op1} {b}) {op2} {c}"),
        2 => format!("p -{a} {op1} {b}"),
        _ => format!("p {a}.fdiv({b})"),
    })
}

fn gen_bignum(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let e = r.range(20, 200);
    let base = r.pick(&["2", "3", "7", "10"]);
    one(match r.below(4) {
        0 => format!("p {base} ** {e}"),
        1 => format!("p (1..{}).reduce(1, :*)", r.range(15, 40)),
        2 => format!("p ({base} ** {e}).to_s.length"),
        _ => format!("p ({base} ** {e}) + 1"),
    })
}

fn gen_floatfmt(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let a = ff(r);
    let b = ff(r);
    let ops = ["+", "-", "*", "/"];
    let op = r.pick(&ops);
    one(match r.below(6) {
        0 => format!("p {a} {op} {b}"),
        1 => format!("p {}.0 / {}.0", r.range(1, 9), r.range(1, 9)),
        2 => format!("p ({a} {op} {b}).round({})", r.range(0, 6)),
        3 => format!("p {a}.to_s"),
        4 => format!("p 1e{}", r.range(-20, 300)),
        _ => format!("p {a} {op} {b} {op} {}", ff(r)),
    })
}

fn gen_strings(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let w = ww(r);
    let i = r.range(-4, 5);
    let j = r.range(-4, 5);
    one(match r.below(6) {
        0 => format!("p \"{w}\"[{i}]"),
        1 => format!("p \"{w}\"[{i}, {}]", r.range(0, 4)),
        2 => format!("p \"{w}\"[{i}..{j}]"),
        3 => format!("p \"{w}\"[{i}...{j}]"),
        4 => format!("p \"{w}\" * {}", r.range(0, 4)),
        _ => format!("p \"{w}\".include?(\"{}\")", &w[..1.min(w.len())]),
    })
}

fn gen_interp(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let w = ww(r);
    let n = ii(r);
    one(match r.below(5) {
        0 => format!("p \"val=#{{{n} + {}}}\"", ii(r)),
        1 => format!("p \"#{{'{w}'.upcase}}!\""),
        2 => format!(
            "p \"[#{{[1,2,3].map {{ |x| x * {} }}.join(',')}}]\"",
            r.range(1, 4)
        ),
        3 => format!("p \"#{{{n}}}-#{{'{w}'.length}}\""),
        _ => format!("puts \"a#{{{n} * 2}}b#{{'{w}'.reverse}}c\""),
    })
}

fn gen_ranges(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let a = r.range(-3, 5);
    let b = r.range(a, a + 8);
    one(match r.below(6) {
        0 => format!("p ({a}..{b}).to_a"),
        1 => format!("p ({a}...{b}).to_a"),
        2 => format!("p ({a}..{b}).sum"),
        3 => format!("p ({a}..{b}).step({}).to_a", r.range(2, 3)),
        4 => format!("p ({a}..{b}).map {{ |x| x * x }}"),
        _ => format!("p ({a}..{b}).select {{ |x| x % 2 == 0 }}"),
    })
}

fn arr_lit(r: &mut Rng) -> String {
    let n = r.range(3, 6) as usize;
    let items: Vec<String> = (0..n).map(|_| ii(r).to_string()).collect();
    format!("[{}]", items.join(", "))
}

fn gen_arraymeth(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let a = arr_lit(r);
    one(match r.below(12) {
        0 => format!("p {a}.map {{ |x| x + 1 }}"),
        1 => format!("p {a}.select {{ |x| x > 0 }}"),
        2 => format!("p {a}.reject {{ |x| x > 0 }}"),
        3 => format!("p {a}.reduce(:+)"),
        4 => format!("p {a}.uniq.sort"),
        5 => format!("p {a}.min"),
        6 => format!("p {a}.max"),
        7 => format!("p {a}.first({})", r.range(1, 3)),
        8 => format!("p {a}.last({})", r.range(1, 3)),
        9 => format!(
            "p {a}.take({}) + {a}.drop({})",
            r.range(1, 3),
            r.range(1, 3)
        ),
        10 => format!("p {a}.zip({a})"),
        _ => format!("p {a}.each_with_index.map {{ |x, i| x * i }}"),
    })
}

fn hash_lit(r: &mut Rng) -> String {
    let n = r.range(2, 4) as usize;
    let items: Vec<String> = (0..n)
        .map(|k| format!("{:?} => {}", format!("k{k}"), ii(r)))
        .collect();
    format!("{{{}}}", items.join(", "))
}

fn gen_hashmeth(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let h = hash_lit(r);
    one(match r.below(6) {
        0 => format!("p({h}.keys)"),
        1 => format!("p({h}.values)"),
        2 => format!("p({h}.map {{ |k, v| [k, v + 1] }})"),
        3 => format!("p({h}.select {{ |k, v| v > 0 }})"),
        4 => format!("p({h}.to_a.sort)"),
        _ => format!("p({h}.each_pair.map {{ |k, v| \"#{{k}}=#{{v}}\" }}.sort)"),
    })
}

fn gen_sorting(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let a = arr_lit(r);
    let w = format!(
        "[{}]",
        (0..4)
            .map(|_| format!("{:?}", ww(r)))
            .collect::<Vec<_>>()
            .join(", ")
    );
    // A pair, and a triple, from mixed `<=>` domains: most cannot be ranked.
    let (x, y, z) = (mixed(r), mixed(r), mixed(r));
    // Every ordering entry point, block-less and block-taking alike. They are
    // separate code paths in both interpreters, and each raises from its own
    // loop, so the message names its own pair.
    let m = r.pick(&["sort", "min", "max", "minmax"]);
    let mb = r.pick(&["sort_by", "min_by", "max_by", "minmax_by"]);
    // Print the exception rather than letting it reach stderr: stderr is only
    // compared under `--stderr`, so a raise-vs-answer gap would otherwise show
    // up as a bare exit-code difference with the message unchecked.
    let guard =
        |body: &str| format!("begin\n  p {body}\nrescue => e\n  p [e.class, e.message]\nend");
    // Three or more elements: assert the exception CLASS, not the message. MRI
    // picks its ordering loop by the receiver's length and element kinds, and
    // the loops disagree about WHICH pair they reach and which operand they
    // lead with — `[1, 2, "a", 3].min` names `"a"` and `1`, `.max` names `"a"`
    // and `2`, `.min(2)` names `"a"` and `2`. Dropping only the order does not
    // help either, because the order decides which operand is rendered by class
    // and which by inspect. The message IS pinned, exhaustively and in order,
    // by the two-element arms, which is where the rule is actually knowable.
    let guard3 = |body: &str| format!("begin\n  p {body}\nrescue => e\n  p e.class\nend");
    one(match r.below(12) {
        0 => format!("p {a}.sort"),
        1 => format!("p {a}.sort {{ |x, y| y <=> x }}"),
        2 => format!("p {a}.sort_by {{ |x| -x }}"),
        3 => format!("p {w}.sort_by(&:length)"),
        4 => format!("p {a}.min_by {{ |x| x.abs }}"),
        5 => format!("p {a}.max_by {{ |x| x.abs }}"),
        6 => guard(&format!("[{x}, {y}].{m}")),
        7 => guard3(&format!("[{x}, {y}, {z}].{m}")),
        8 => guard(&format!("[{x}, {y}].{mb} {{ |e| e }}")),
        9 => guard3(&format!("[{x}, {y}, {z}].{mb} {{ |e| e }}")),
        // `min(n)`/`max(n)` sort internally, a third path again.
        10 => guard3(&format!(
            "[{x}, {y}, {z}].{}({})",
            if r.below(2) == 0 { "min" } else { "max" },
            r.range(1, 3)
        )),
        // The block forms rank by what the BLOCK answers; a nil from the block
        // is the same unrankable pair, reported with the block's own operands.
        _ => guard(&format!(
            "[{x}, {y}].{} {{ |c, d| c <=> d }}",
            r.pick(&["sort", "min", "max", "minmax"])
        )),
    })
}

fn gen_formatspec(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(-100, 100);
    let f = ff(r);
    one(match r.below(8) {
        0 => format!("p format(\"%.3f\", {f})"),
        1 => format!("p \"%05d\" % {n}"),
        2 => format!("p \"%x\" % {}", n.abs()),
        3 => format!("p \"%b\" % {}", n.abs()),
        4 => format!("p \"%e\" % {f}"),
        5 => format!("p \"%o\" % {}", n.abs()),
        6 => format!("p \"%-8s|\" % \"{}\"", ww(r)),
        _ => format!("p sprintf(\"%+d %8.2f\", {n}, {f})"),
    })
}

fn gen_blocks(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(3, 6);
    one(match r.below(6) {
        0 => format!("p (1..{n}).map {{ |x| x ** 2 }}"),
        1 => format!("p (1..{n}).select(&:even?)"),
        2 => format!("p (1..{n}).reduce(0) {{ |acc, x| acc + x }}"),
        3 => format!("r = []; {n}.times {{ |i| r << i }}; p r"),
        4 => format!("r = []; 1.upto({n}) {{ |i| r << i * i }}; p r"),
        _ => format!("p (1..{n}).each_with_object([]) {{ |x, a| a << x + 1 }}"),
    })
}

fn gen_symbols(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let w = ww(r);
    one(match r.below(5) {
        0 => format!("p :{w}"),
        1 => format!("p \"{w}\".to_sym"),
        2 => format!("p :{w}.to_s"),
        3 => format!("h = {{ {w}: {} }}; p h[:{w}]", ii(r)),
        _ => format!("p %i[{} {} {}]", ww(r), ww(r), ww(r)),
    })
}

fn gen_ternary(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let a = ii(r);
    let b = ii(r);
    one(match r.below(5) {
        0 => format!("p {a} > {b} ? \"hi\" : \"lo\""),
        1 => format!("x = nil; x ||= {a}; p x"),
        2 => format!("x = {a}; x ||= {b}; p x"),
        3 => format!("x = {a}; x += {b}; p x"),
        _ => format!("x = {a}; x &&= {b}; p x"),
    })
}

fn gen_comparison(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let a = ii(r);
    let b = ii(r);
    // `clamp` and `between?` are both derived from `<=>`, and they disagree on
    // purpose: `clamp` rejects a min above its max up front and treats a nil
    // bound as "no bound", while `between?` has no min-vs-max check at all and
    // short-circuits to false below min without ever ranking max. Bounds are
    // drawn so both orders, nil bounds, and a cross-domain bound all appear.
    let bound = r.pick(&["1", "3", "nil", "\"s\"", "2.5", "Float::NAN"]);
    let recv = r.pick(&["5", "0", "2.5", "\"m\"", "Float::NAN"]);
    let guard =
        |body: &str| format!("begin\n  p {body}\nrescue => e\n  p [e.class, e.message]\nend");
    one(match r.below(10) {
        0 => format!("p {a} <=> {b}"),
        1 => format!("p {a}.0 == {a}"),
        2 => format!("p [{a}, {b}] <=> [{b}, {a}]"),
        3 => format!("p [{a}, {b}, {}].min", ii(r)),
        4 => format!("p ({a}..{b}).include?({})", ii(r)),
        5 => format!("p \"{}\" <=> \"{}\"", ww(r), ww(r)),
        6 => guard(&format!(
            "{recv}.clamp({bound}, {})",
            r.pick(&["1", "3", "nil"])
        )),
        7 => guard(&format!(
            "{recv}.between?({bound}, {})",
            r.pick(&["1", "3", "nil"])
        )),
        8 => guard(&format!(
            "{recv}.clamp({}{}{})",
            r.pick(&["1", "3"]),
            r.pick(&["..", "..."]),
            r.pick(&["1", "3"])
        )),
        _ => guard(&format!("{recv}.clamp({bound})")),
    })
}

fn gen_printf(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = ii(r);
    let a = arr_lit(r);
    one(match r.below(6) {
        0 => format!("printf(\"%d-%d\\n\", {n}, {})", ii(r)),
        1 => format!("puts {a}"),
        2 => format!("print {n}, \" \", {}, \"\\n\"", ii(r)),
        3 => format!("p {a}"),
        4 => format!("puts [{}, [{}, {}]].inspect", ii(r), ii(r), ii(r)),
        _ => format!("$stdout.write(\"{}\\n\")", ww(r)),
    })
}

fn gen_string_ops(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let w = ww(r);
    one(match r.below(11) {
        0 => format!("p \"{w}\".upcase"),
        1 => format!("p \"{w}\".reverse"),
        2 => format!("p \"{w} {w}\".split"),
        3 => format!("p [\"{w}\", \"{}\"].join(\"-\")", ww(r)),
        4 => format!("p \"{w}\".gsub(\"{}\", \"X\")", &w[..1.min(w.len())]),
        5 => format!("p \"{w}\".sub(/./, \"Q\")"),
        6 => format!("p \"  {w}  \".strip"),
        7 => format!("p \"{w}\".chars"),
        8 => format!("p \"{w}\".center({}, \"*\")", r.range(6, 12)),
        9 => format!("p \"{w}\".ljust({}, \".\")", r.range(6, 12)),
        _ => format!("p \"{w}\".tr(\"a-y\", \"b-z\")"),
    })
}

fn gen_caseexpr(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(0, 12);
    let w = ww(r);
    one(match r.below(4) {
        0 => format!(
            "x = {n}; p (case x; when 0..3 then \"lo\"; when 4..8 then \"mid\"; else \"hi\"; end)"
        ),
        1 => format!(
            "v = {n}; p (case v; when Integer then \"int\"; when String then \"str\"; else \"?\"; end)"
        ),
        2 => format!(
            "s = \"{w}\"; p (case s; when /^[a-c]/ then \"early\"; when /^[x-z]/ then \"late\"; else \"mid\"; end)"
        ),
        _ => format!(
            "x = {n}; r = case x when 0 then :zero when 1..5 then :small else :big end; p r"
        ),
    })
}

// ---------------------------------------------------------------------------

/// String CASE folding, trimming and padding — `downcase`/`upcase`/`capitalize`/
/// `swapcase`/`casecmp`, `chomp`/`chop`, `delete_prefix`/`delete_suffix`,
/// `succ`, and the three justifiers.
///
/// The word pool carries mixed case, a trailing `"\n"` and `"\r\n"`, an empty
/// string, and the carry-propagating `succ` inputs (`"az"`, `"zz"`, `"a9"`,
/// `"Zz"`) — without those last four the mode would exercise `succ` only on
/// inputs that never carry, which is the whole of what `succ` gets wrong.
/// `casecmp`'s argument pool includes NON-strings, because `casecmp(1)` is not
/// a comparison at all: MRI answers nil.
fn gen_strcase(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let w = r.pick(&[
        "Hello World",
        "hello",
        "HELLO",
        "hElLo",
        "",
        "a",
        "az",
        "zz",
        "a9",
        "Zz",
        "abc\n",
        "abc\r\n",
        "  pad  ",
        "ÉLan",
        "élan",
        "Mixed123",
    ]);
    let other = r.pick(&["hello", "HELLO", "Hello World", "zebra", "", "a"]);
    // Deliberately not all Strings: `casecmp` must answer nil for the rest.
    let cmparg = r.pick(&["\"HELLO\"", "\"hello\"", "1", "nil", ":sym", "[1]", "2.5"]);
    let aff = r.pick(&["he", "lo", "", "Hello", "xx", "\\n"]);
    let width = r.range(0, 12);
    let pad = r.pick(&["\" \"", "\"*\"", "\"12\"", "\"ab\""]);
    one(match r.below(18) {
        0 => format!("p {w:?}.downcase"),
        1 => format!("p {w:?}.upcase"),
        2 => format!("p {w:?}.capitalize"),
        3 => format!("p {w:?}.swapcase"),
        4 => format!("p {w:?}.casecmp({cmparg})"),
        5 => format!("p {w:?}.casecmp?({cmparg})"),
        6 => format!("p {w:?}.casecmp({other:?})"),
        7 => format!("p {w:?}.chomp"),
        8 => format!("p {w:?}.chomp({aff:?})"),
        9 => format!("p {w:?}.chop"),
        10 => format!("p {w:?}.delete_prefix({aff:?})"),
        11 => format!("p {w:?}.delete_suffix({aff:?})"),
        12 => format!("p {w:?}.succ"),
        13 => format!("p {w:?}.succ.succ"),
        14 => format!("p {w:?}.center({width}, {pad})"),
        15 => format!("p {w:?}.ljust({width}, {pad})"),
        16 => format!("p {w:?}.rjust({width}, {pad})"),
        _ => format!("p [{w:?}.start_with?({aff:?}), {w:?}.end_with?({aff:?})]"),
    })
}

/// String SEARCH and SPLITTING, over separators that are Strings AND Regexps:
/// `partition`/`rpartition`, `index`/`rindex`, `lines`/`each_line`.
///
/// The regexp half of the separator pool is the point of the mode. A separator
/// pool of plain strings would run, report no divergence, and be structurally
/// incapable of reaching the regexp path at all — which is exactly where both
/// `index`/`rindex` and `partition`/`rpartition` were found broken. The pool
/// therefore includes a zero-width pattern (`/a*/`), an anchored one, and one
/// with capture groups, since a regexp partition must also set `$~`.
///
/// The `lines` separators include `""` (paragraph mode, which is NOT "split on
/// the empty string"), an explicit `nil` (no separator: one line), and
/// multi-character separators, plus `chomp:`.
fn gen_strpart(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let w = r.pick(&[
        "hello world",
        "aaa",
        "a-b-c",
        "abcabc",
        "",
        "a\nb\nc",
        "a\n\nb\n\nc",
        "a,b,c",
        "a,b,",
        "aXXbXXc",
        "\n\na\n\nb",
        "one two  three",
    ]);
    let ssep = r.pick(&[
        "\"o\"", "\"-\"", "\"\"", "\"b\"", "\"zz\"", "\"XX\"", "\",\"",
    ]);
    let rsep = r.pick(&[
        "/o/", "/o./", "/a*/", "/[bc]/", "/(o)(.)/", "/z/", "/^a/", "/\\s+/", "/b|c/",
    ]);
    let sep = if r.below(2) == 0 { ssep } else { rsep };
    let lsep = r.pick(&["\",\"", "\"\"", "nil", "\"XX\"", "\"\\n\""]);
    let pos = r.range(-3, 8);
    one(match r.below(14) {
        0 => format!("p {w:?}.partition({sep})"),
        1 => format!("p {w:?}.rpartition({sep})"),
        2 => format!("p [{w:?}.partition({sep}), $~ && $~[0]]"),
        3 => format!("p [{w:?}.rpartition({sep}), $~ && $~[0]]"),
        4 => format!("p {w:?}.index({sep})"),
        5 => format!("p {w:?}.rindex({sep})"),
        6 => format!("p {w:?}.index({sep}, {pos})"),
        7 => format!("p {w:?}.rindex({sep}, {pos})"),
        8 => format!("p {w:?}.lines({lsep})"),
        9 => format!("p {w:?}.lines({lsep}, chomp: true)"),
        10 => format!("p {w:?}.each_line({lsep}).to_a"),
        11 => format!("r = []\n{w:?}.each_line({lsep}) {{ |l| r << l }}\np r"),
        12 => format!("p {w:?}.partition({sep}).join(\"|\")"),
        _ => format!("p [{w:?}.lines({lsep}).size, {w:?}.lines({lsep}).join]"),
    })
}

/// Array RESHAPING: `combination`, `permutation`, `product`, `transpose`,
/// `values_at`, `assoc`/`rassoc`, `bsearch`, `rotate`, `flatten`, `compact`.
///
/// `values_at` and `rotate` are given OUT-OF-RANGE and NEGATIVE indices on
/// purpose — in range they are uninteresting, and the answers differ (a
/// `values_at` miss is nil, a `rotate` wraps). The pair arrays feed
/// `assoc`/`rassoc`, and the ragged one makes `transpose` raise, which is a
/// real answer rather than a skip.
fn gen_arrreshape(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let a = r.pick(&[
        "[1, 2, 3]",
        "[1, 2, 3, 4, 5]",
        "[]",
        "[1]",
        "[1, nil, 2, nil]",
        "[[1, 2], [3, 4]]",
        "[[1, 2], [3, 4, 5]]",
        "[[1, :a], [2, :b], [3, :a]]",
        "[[1, [2, 3]], [4]]",
        "[3, 1, 2]",
    ]);
    let b = r.pick(&["[4, 5]", "[]", "[:x]", "[1, 2]"]);
    let n = r.range(0, 4);
    // Indices that MISS, and negative ones, not just valid ones.
    let i1 = r.range(-4, 7);
    let i2 = r.range(-4, 7);
    let key = r.pick(&["1", "2", ":a", ":b", "9", "nil"]);
    one(match r.below(19) {
        0 => format!("p {a}.combination({n}).to_a"),
        1 => format!("p {a}.permutation({n}).to_a"),
        2 => format!("p {a}.combination({n}).size"),
        3 => format!("p {a}.product({b})"),
        4 => format!("begin\n  p {a}.transpose\nrescue => e\n  p e.class\nend"),
        5 => format!("p {a}.values_at({i1}, {i2})"),
        // OPEN-bounded ranges too. A pool of only closed ranges cannot reach
        // the branch that resolves an absent bound — where an unresolved
        // `i64::MAX` end is not a wrong answer but a hang.
        6 => format!("p {a}.values_at({i1}..{i2})"),
        7 => format!("p {a}.assoc({key})"),
        8 => format!("p {a}.rassoc({key})"),
        9 => format!("p {a}.rotate({i1})"),
        10 => format!("p {a}.flatten"),
        11 => format!("p {a}.flatten({n})"),
        12 => format!("p {a}.compact"),
        13 => format!("p {a}.sort.bsearch {{ |x| x >= {n} }}"),
        14 => format!("p {a}.member?({key})"),
        15 => format!("p {a}.values_at({i1}...{i2})"),
        16 => format!("p {a}.values_at({i1}..)"),
        17 => format!("p {a}.values_at(..{i2})"),
        _ => format!("p [{a}.include?({key}), {a}.member?({key})]"),
    })
}

/// Integer/Float ROUNDING at a precision, and the integer-theoretic methods:
/// `round`/`ceil`/`floor`/`truncate` with a digit count, `divmod`/`remainder`/
/// `%`, `digits`, `gcd`/`lcm`, `bit_length`, `allbits?`/`anybits?`/`nobits?`.
///
/// The precision pool reaches NEGATIVE digits, so the value pool has to reach
/// past 100 for that to be observable at all: `7.round(-2)` is 0 whatever the
/// rounding rule, so a mode whose values stopped below the boundary would run a
/// `round(-2)` case that could not tell any implementation from any other. The
/// pool therefore carries 1234, 1250 and 999 — 1250 specifically because
/// half-way is where the rule itself is visible.
fn gen_numprec(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let iv = r.pick(&[
        "0", "7", "-7", "99", "100", "255", "999", "1234", "1250", "-1250", "12345", "2**70",
    ]);
    let fv = r.pick(&[
        "3.567",
        "-3.567",
        "2.5",
        "3.5",
        "-2.5",
        "0.125",
        "1234.5678",
        "1250.0",
        "0.0",
        "1e10",
    ]);
    // Reaches both signs, and 0, since `round(0)` and `round` differ in TYPE.
    let prec = r.range(-3, 4);
    let m = r.pick(&["3", "8", "12", "18", "1", "255"]);
    let mask = r.pick(&["1", "2", "4", "5", "255", "0"]);
    let base = r.pick(&["2", "8", "10", "16"]);
    one(match r.below(18) {
        0 => format!("p ({iv}).round({prec})"),
        1 => format!("p ({fv}).round({prec})"),
        2 => format!("p ({fv}).round"),
        3 => format!("p ({iv}).ceil({prec})"),
        4 => format!("p ({fv}).ceil({prec})"),
        5 => format!("p ({iv}).floor({prec})"),
        6 => format!("p ({fv}).floor({prec})"),
        7 => format!("p ({fv}).truncate({prec})"),
        8 => format!("p ({iv}).divmod({m})"),
        9 => format!("p ({fv}).divmod({m})"),
        10 => format!("p [({iv}).remainder({m}), ({iv}) % ({m})]"),
        11 => format!("p ({iv}).digits"),
        12 => format!("p ({iv}).abs.digits({base})"),
        13 => format!("p [({iv}).gcd({m}), ({iv}).lcm({m})]"),
        14 => format!("p ({iv}).bit_length"),
        15 => {
            format!("p [({iv}).allbits?({mask}), ({iv}).anybits?({mask}), ({iv}).nobits?({mask})]")
        }
        16 => format!("p ({iv}).abs.to_s({base})"),
        _ => format!("p ({fv}).divmod({m}).map {{ |x| x.round(3) }}"),
    })
}

/// OBJECT MODEL: what an anonymous class becomes once a constant names it, and
/// the reflection surface around it — `instance_variable_*` name validation,
/// `remove_instance_variable`, `respond_to?` with and without the private
/// surface, `equal?`/`object_id` of a class, and `String#succ` across
/// separators.
///
/// The naming cases create the instance BEFORE the constant assignment and read
/// the class back through the local that held the anonymous class: both are
/// holders of the old name, and a rename that only moves the class table leaves
/// them pointing at nothing.
fn gen_objmodel(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let cname = r.pick(&["Alpha", "Beta", "Gamma9", "Delta_x"]);
    let ivname = r.pick(&[
        "\"@a\"",
        ":@a",
        "\"a\"",
        "\"@\"",
        "\"@@a\"",
        "\"@1\"",
        ":\"@a b\"",
        "\"@\\u00e9\"",
        "3",
    ]);
    let recv = r.pick(&[
        "Object.new",
        "3",
        "\"s\"",
        "[]",
        "nil",
        "Class.new",
        "Comparable",
    ]);
    let meth = r.pick(&[
        ":puts",
        ":initialize",
        ":freeze",
        ":to_s",
        ":format",
        ":instance_variable_get",
        ":extend",
        ":new",
        ":attr_accessor",
        ":module_function",
        ":respond_to_missing?",
        ":binding",
    ]);
    let succ = r.pick(&[
        "-9",
        "a-9",
        "-a",
        "1.9.9",
        "9.9",
        "z.z",
        "Az-9",
        "$9",
        "1-9",
        "a--9",
        "zz99",
        "<<koala>>",
        "a!9",
        "9z",
        "--",
        "a.9",
    ]);
    one(match r.below(9) {
        0 => format!(
            "c = Class.new {{ attr_accessor :v; def hi = :hi }}\no = c.new\no.v = 1\n\
             {cname} = c\np [c.name, o.class, o.hi, o.v, {cname}.new.hi, c.equal?({cname})]"
        ),
        1 => format!(
            "m = Module.new {{ def hi = :hi }}\n{cname} = m\n\
             class Host_{cname}; include {cname}; end\np [m.name, Host_{cname}.new.hi, m.equal?({cname})]"
        ),
        2 => format!(
            "base = Class.new\nsub = Class.new(base)\n{cname} = base\n\
             p [sub.superclass, sub.superclass.name, {{base => 1}}[{cname}]]"
        ),
        3 => format!(
            "o = Object.new\no.instance_variable_set(:@a, 1)\n\
             [:instance_variable_get, :instance_variable_defined?, :remove_instance_variable].each do |m|\n  \
             begin\n    p [m, o.send(m, {ivname})]\n  rescue NameError, TypeError => e\n    \
             p [m, e.class, e.message]\n  end\nend\np o.instance_variables"
        ),
        4 => "o = Object.new\no.freeze\nbegin\n  o.remove_instance_variable(:@a)\nrescue => e\n  \
             p e.class\nend"
            .to_string(),
        5 => format!("p [{recv}.respond_to?({meth}), {recv}.respond_to?({meth}, true)]"),
        6 => "p [String.equal?(String), Object.object_id == Object.object_id, String.object_id == Object.object_id]".to_string(),
        7 => format!("p {succ:?}.succ"),
        _ => format!(
            "c = Class.new\n{cname} = c\np [{cname}.equal?(c), {cname}.object_id == c.object_id, \
             c.to_s, c.inspect]"
        ),
    })
}

/// Integer bit surface: `Integer#[]` (index, `(i, len)`, ranges, wide
/// receivers), `digits` radix validation, shifts by negative/wide counts,
/// bit operators against non-Integers, modular `pow`, `Integer()` of a
/// non-finite Float.
fn gen_intbits(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(-300, 300);
    let (i, len) = (r.range(0, 12), r.range(0, 6));
    let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
    one(match r.below(16) {
        0 => format!("p {n}[{i}]"),
        1 => format!("p {n}[{i}, {len}]"),
        2 => format!("p {n}[{i}..{}]", i + len),
        3 => format!("p {n}[{i}...{}]", i + len),
        4 => format!("p {n}[{i}..]"),
        5 => format!("p (2**70 + {n})[{}]", r.range(0, 80)),
        6 => format!("p (-(2**70) + {n})[{}, 4]", r.range(0, 80)),
        7 => guard(&format!(
            "{}.digits({})",
            n.abs(),
            r.pick(&["-2", "0", "1", "2", "16", "\"a\"", "2.5"])
        )),
        8 => format!("p [{n} << {i}, {n} >> {i}, {n} << -{i}, {n} >> -{i}]"),
        9 => format!("p [{n} >> 200, {n} << 0, 5 << {}]", r.range(-5, 5)),
        10 => guard(&format!(
            "{n} {} {}",
            r.pick(&["&", "|", "^"]),
            r.pick(&["3.0", "nil", "\"a\"", ":s", "2**70"])
        )),
        11 => guard(&format!(
            "{n} {} {}",
            r.pick(&["<<", ">>"]),
            r.pick(&["1.5", "nil", "\"a\"", "2**70", "-(2**70)"])
        )),
        12 => guard(&format!(
            "{}.pow({}, {})",
            r.range(-9, 9),
            r.range(-3, 40),
            r.range(-9, 9)
        )),
        13 => guard(&format!(
            "{n}.pow({}, 5)",
            r.pick(&["0.5", "nil", "\"a\"", "2"])
        )),
        14 => guard(&format!(
            "Integer({})",
            r.pick(&[
                "Float::NAN",
                "Float::INFINITY",
                "-Float::INFINITY",
                "1e30",
                "-1e20",
                "12.9"
            ])
        )),
        _ => guard(&format!("{n}.step({}, {})", r.range(-5, 5), r.range(-2, 2))),
    })
}

/// Struct/Data construction through a user `initialize` (and `super` into the
/// generated one), subclasses of struct classes, `values_at`, frozen writers.
fn gen_structinit(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (r.range(0, 9), r.range(0, 9));
    let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
    one(match r.below(16) {
        0 => format!(
            "class P < Struct.new(:a, :b)\n  def initialize(a, b = {b})\n    super\n  end\nend\np P.new({a}), P.new({a}, {b} + 1)"
        ),
        1 => format!(
            "S = Struct.new(:a) do\n  def initialize(a = {a}) = super(a * 2)\nend\np S.new, S.new({b})"
        ),
        2 => format!(
            "class Q < Struct.new(:x)\n  def initialize(*)\n    super\n    self.x ||= {a}\n  end\nend\np Q.new, Q.new({b})"
        ),
        3 => format!(
            "D = Data.define(:v) do\n  def initialize(v: {a}) = super(v: v * 2)\nend\np D.new, D.new({b}), D.new(v: {b})"
        ),
        4 => format!(
            "class A < Struct.new(:x); end\nclass B < A; def y = x * 2; end\np B.new({a}).y, B.new({a}) == B.new({a}), B.members"
        ),
        5 => format!("S = Struct.new(:a, :b)\np S.new({a}, {b}).values_at({})", r.pick(&["0", "-1", "0, 1", "0..1", "1..5", "-2..-1"])),
        6 => guard(&format!("S = Struct.new(:a, :b)\nS.new({a}, {b}).values_at({})", r.pick(&["2", "-3", "5", "0, 9"]))),
        7 => guard(&format!("S = Struct.new(:a)\ns = S.new({a}).freeze\ns.a = {b}")),
        8 => guard(&format!("D = Data.define(:a, :b)\nD.new({a}, {b}).{}", r.pick(&["a = 1", "to_a", "each", "size", "to_h", "members", "deconstruct", "inspect"]))),
        9 => guard(&format!("D = Data.define(:a, :b)\nD.new({})", r.pick(&["1", "1, 2, 3", "a: 1", "a: 1, b: 2, c: 3", "\"a\" => 1, \"b\" => 2", "b: 1, a: 2"]))),
        10 => guard(&format!("D = Data.define(:a, :b)\nD.new({a}, {b}).with({})", r.pick(&["", "a: 9", "c: 1", "9", "b: 0, a: 7"]))),
        11 => guard(&format!("Struct.new({}); :ok", r.pick(&[":a, :a", "1", "\"Foo\", :x", "\"foo\"", "", "keyword_init: true"]))),
        12 => guard(&format!("Data.define({}); :ok", r.pick(&[":a, :a", "\"a\"", ":a=", ":a?", ""]))),
        13 => guard(&format!("S = Struct.new(:a, :b)\nS.new({a}, {b}).deconstruct_keys({})", r.pick(&["nil", "[:a]", "[:a, :z]", "[:z, :a]", "1", "[:a, :b, :c]"]))),
        14 => "S = Struct.new(:a, :b)\np S.instance_methods(false).sort, S.method_defined?(:a=), S.new(1, 2).instance_variables".to_string(),
        _ => format!("D = Data.define(:a, :b)\np D.instance_methods(false).sort, D.method_defined?(:with), D.respond_to?(:new), D.new({a}, {b}).respond_to?(:a=)"),
    })
}

/// Hash default / default proc / `compare_by_identity` interplay and which
/// copying methods carry them over.
fn gen_hashdefault(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (r.range(0, 9), r.range(0, 9));
    let copy = r.pick(&[
        "merge({z: 1})",
        "select { true }",
        "reject { false }",
        "compact",
        "slice(:a)",
        "except(:b)",
        "transform_values { _1 }",
        "dup",
        "to_h",
        "invert",
        "sort_by { 0 }.to_h",
    ]);
    let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
    one(match r.below(12) {
        0 => format!("h = Hash.new({a}); h[:a] = {b}; r = h.{copy}; p [r.default, r.compare_by_identity?, r.size]"),
        1 => format!("h = Hash.new {{ |hh, k| {a} }}; h[:a] = {b}; r = h.{copy}; p [r.default_proc.nil?, r[:q], r.size]"),
        2 => format!("h = {{a: {a}, b: {b}}}.compare_by_identity; r = h.{copy}; p [r.compare_by_identity?, r.size]"),
        3 => format!("h = Hash.new({a}); p [h.dig(:x), h.dig(:q)]"),
        4 => format!("h = Hash.new {{ 1 }}; h.default = {a}; p [h.default_proc, h[:q], h.default]"),
        5 => format!("h = Hash.new({a}); h.default_proc = proc {{ {b} }}; p [h.default, h[:q]]"),
        6 => guard(&format!("h = {{}}; h.default_proc = {}; :ok", r.pick(&["5", "nil", "->(a) { 1 }", "->(a, b) { 1 }", "proc { |a| 1 }", "->(*a) { 1 }"]))),
        7 => guard(&format!("{{a: 1}}.freeze.{}", r.pick(&["default = 1", "compare_by_identity", "default_proc = nil", "store(:b, 1)", "merge(b: 1).frozen?"]))),
        8 => guard(&format!("{{a: {a}}}.dig(:a, {})", r.pick(&[":b", "0", "1"]))),
        9 => format!("p [{{a: {a}}}, [1, 2]].map {{ |x| x.zip({{b: {b}}}).size }}"),
        10 => format!("p [1, 2, 3].zip({}, {})", r.pick(&["{a: 1}", "1..", "(5..9)", "[7]", "Set[8, 9]"]), r.pick(&["[4]", "{}", "10..11"])),
        _ => format!("h = Hash.new({a}); h2 = h.merge({{a: {b}}}); p [h2.default, h2[:zz], h2[:a]]"),
    })
}

/// Refinements: `refine`/`using` activation, `super` into the refined method,
/// `send`/`&:sym`/`method` honoring them, and the argument errors.
fn gen_refinement(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(1, 9);
    let target = r.pick(&["String", "Integer", "Array", "Symbol"]);
    let recv = match *target {
        "String" => "\"ab\"",
        "Integer" => "7",
        "Array" => "[1, 2]",
        _ => ":ab",
    };
    let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
    let defn = format!(
        "module Ext\n  refine {target} do\n    def fz = {n}\n    def size = super + 100\n  end\nend\n"
    );
    one(match r.below(10) {
        0 => format!("{defn}p({recv}.fz) rescue p $!.class\nusing Ext\np {recv}.fz"),
        1 => format!("{defn}using Ext\np {recv}.size"),
        2 => format!("{defn}using Ext\np {recv}.send(:fz)"),
        3 => format!("{defn}using Ext\np [{recv}].map(&:fz)"),
        4 => format!("{defn}using Ext\np {recv}.method(:fz).call"),
        5 => format!("{defn}p Ext.refinements.size, Ext.refinements[0].target, Ext.refinements[0].class"),
        6 => guard("Module.new { refine(3) {} }"),
        7 => guard("Module.new { refine(String) }"),
        8 => guard("using Class"),
        _ => format!(
            "class Box\n  def v = {n}\nend\nmodule BoxExt\n  refine Box do\n    def v = super * 2\n    def w = v + 1\n  end\nend\nusing BoxExt\np Box.new.v, Box.new.w"
        ),
    })
}

/// Keyword-argument shapes: `**h` against literal keys in either order,
/// `**nil`, required/unknown keyword errors, trailing-comma block params.
fn gen_kwsplat(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (r.range(0, 9), r.range(0, 9));
    let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
    one(match r.below(10) {
        0 => format!("def m(*a, **k) = [a, k]\nh = {{k: {a}, z: {b}}}\np m(**h, k: {b}), m(k: {b}, **h)"),
        1 => format!("def m(k: 0, **o) = [k, o]\nh = {{k: {a}, z: {b}}}\np m(**h, k: {b}), m(k: {b}, **h), m(z: 1, **h, w: 2)"),
        2 => format!("def m(a, **nil) = a\np m({a}), m({{b: 1}})"),
        3 => guard(&format!("def m(a, **nil) = a\nm({a}, b: {b})")),
        4 => "def m(a, **nil) = a\np method(:m).parameters, method(:m).arity".to_string(),
        5 => format!("p proc {{ |a, | a }}.call([{a}, {b}]), proc {{ |a,| }}.arity, [[{a}, {b}]].map {{ |x,| x }}"),
        6 => format!("def m(a, k: {a}) = [a, k]\np m({b}), m({b}, k: 1), m({{k: 2}})"),
        7 => guard(&format!("def m(a, k:) = [a, k]\nm({})", r.pick(&["1", "k: 1", "1, k: 2, j: 3", "{k: 1}", "1, {k: 2}"]))),
        8 => guard("def bb(&b) = b\nbb(&5)"),
        _ => format!("def m(*, **, &) = n(*, **, &)\ndef n(*a, **k) = [a, k]\np m({a}, {b}, z: 1)"),
    })
}

/// Squiggly-heredoc dedent (spaces, tabs, blank lines, interpolation) and the
/// `<<` shift-versus-heredoc decision.
fn gen_heredoc(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let ind = r.pick(&["  ", "    ", "\t", "  \t", "      "]);
    let ind2 = r.pick(&["", "  ", "\t", "    "]);
    let n = r.range(0, 9);
    one(match r.below(9) {
        0 => format!("s = <<~EOS\n{ind}one\n{ind}{ind2}two\n{ind}three\nEOS\np s"),
        1 => format!("s = <<~EOS\n{ind}one\n\n{ind}{ind2}two\nEOS\np s"),
        2 => format!("s = <<~EOS\n{ind}a #{{{n}}}\n{ind2}{ind}b\nEOS\np s"),
        3 => format!("s = <<~'EOS'\n{ind}raw #{{x}}\n{ind}\\n\nEOS\np s"),
        4 => format!("s = <<~EOS\n{ind}x\n{ind2}\n{ind}y\nEOS\np s"),
        5 => format!("x = {n}\np x<<2, [x]<<3, {n}<<-1, {n}>>1"),
        6 => format!("a = [<<~A, <<~B]\n{ind}first\nA\n{ind}{ind2}second\nB\np a"),
        7 => format!("s = <<-EOS\n{ind}keep\n{ind}EOS\np s"),
        _ => format!("def m(s, t) = [s, t]\np m(<<~X, {n})\n{ind}xx\nX"),
    })
}

/// Top-level `def` is a private method of Object: `self.m` works, other
/// receivers and `public_send` get the private-method error.
fn gen_toplevelpriv(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(0, 9);
    let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
    let d = format!("def helper = {n}\nclass Foo\n  def t = helper\n  def u = self.helper\nend\n");
    one(match r.below(8) {
        0 => format!("{d}p self.helper, send(:helper), Foo.new.t, Foo.new.u"),
        1 => guard(&format!("{d}Foo.new.helper")),
        2 => guard(&format!("{d}Object.new.helper")),
        3 => guard(&format!("{d}public_send(:helper)")),
        4 => guard(&format!("{d}Foo.new.public_send(:helper)")),
        5 => format!("{d}p respond_to?(:helper), respond_to?(:helper, true), Foo.new.respond_to?(:helper)"),
        6 => format!("{d}p Foo.new.send(:helper), Foo.new.method(:helper).call"),
        _ => format!("o = Object.new\nbegin\n  def o.sing = {n}\nend\np o.sing\nf = Object.new.freeze\nbegin; def f.x; end; rescue => e; p e.class; end"),
    })
}

/// Every `raise` argument shape, `Exception#exception`, `cause:`, and the
/// Errno message composition.
fn gen_raiseforms(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let msg = r.pick(&["\"m\"", "\"two words\"", "nil", ":sym", "5"]);
    let cls = r.pick(&[
        "RuntimeError",
        "ArgumentError",
        "TypeError",
        "KeyError",
        "IOError",
        "Errno::ENOENT",
        "Errno::EEXIST",
        "SystemExit",
    ]);
    let shown = "[e.class, e.message]";
    let guard = |body: &str| {
        format!("begin\n  {body}\nrescue Exception => e\n  p {shown}\nelse\n  p :none\nend")
    };
    one(match r.below(14) {
        0 => guard(&format!("raise {cls}")),
        1 => guard(&format!("raise {cls}, {msg}")),
        2 => guard(&format!("raise {cls}.new({msg})")),
        3 => guard(&format!("raise {cls}.new, {msg}")),
        4 => guard(&format!("raise {msg}")),
        5 => guard(&format!("raise {}", r.pick(&["Class", "5", "nil", "Object.new", "String", ":sym", "[]"]))),
        6 => guard(&format!("raise {cls}, {msg}, cause: {}", r.pick(&["nil", "RuntimeError.new(\"c\")"]))),
        7 => guard("raise"),
        8 => format!("e = {cls}.new({msg})\np [e.exception.equal?(e), e.exception(\"z\").message, e.exception(e).equal?(e)]"),
        9 => format!("p {cls}.exception({msg}).message"),
        10 => guard(&format!("raise {cls}, {msg}, [\"bt:1\"]")),
        11 => guard(&format!("begin\n  raise \"in\"\nrescue\n  raise {cls}, {msg}\nend")).replace("p [e.class, e.message]", "p [e.class, e.message, e.cause&.message]"),
        12 => format!("p Errno::{}.new({msg}).message", r.pick(&["ENOENT", "EACCES", "EEXIST", "EPIPE", "EINVAL", "ENOTDIR"])),
        _ => guard(&format!("raise o = Object.new, {msg}; def o.exception(*a) = RuntimeError.new(\"obj\")")),
    })
}

/// Range construction/query edge cases: empty ranges, nil ends, mixed
/// numeric ends, bad endpoints, `count`/`size`, non-numeric `step`.
fn gen_rangeedge(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (r.range(-3, 6), r.range(-3, 6));
    let op = r.pick(&["..", "..."]);
    let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
    one(match r.below(14) {
        0 => format!("p (({a}{op}{b}).min), (({a}{op}{b}).max), (({a}{op}{b}).minmax)"),
        1 => format!("p (({a}{op}{b}).count), (({a}{op}{b}).count(&:even?)), (({a}{op}{b}).count({a}))"),
        2 => format!("p (({a}{op}{b}).sum), (({a}{op}{b}).size), (({a}{op}{b}).to_a)"),
        3 => format!("p (({a}{op}{b}).first), (({a}{op}{b}).last), (({a}{op}{b}).first(2)), (({a}{op}{b}).last(2))"),
        4 => format!("p ({a}{op}nil).size, ({a}{op}nil).first(2), ({a}{op}nil).inspect, (nil{op}{b}).inspect"),
        5 => guard(&format!("({a}..\"a\")")),
        6 => guard(&format!("Range.new({a}, {}, {})", r.pick(&["nil", "\"a\"", "Object.new", "2.5"]), r.pick(&["true", "false"]))),
        7 => format!("p (({a}..{b}) == ({a}..{b}.0)), (({a}..{b}).eql?({a}..{b})), (({a}..{b}).hash == ({a}..{b}).hash)"),
        8 => format!("p (({a}{op}{b}).step(2).to_a), (({a}{op}{b}) % 3).to_a"),
        9 => guard(&format!("({a}..{b}).step({})", r.pick(&["0", "-1", "0.5", "\"a\""]))),
        10 => format!("p [1, 2, 3, 4, 5].chunk {{ |x| {} }}.to_a", r.pick(&["x > 3 ? :_separator : true", "x.even? ? nil : :odd", "x == 3 ? :_alone : :k", "x % 3"])),
        11 => guard("[1, 2].chunk { :_other }.to_a"),
        12 => format!("a = [1, 2, 3]\np a.fill({a}, {}, {})", r.range(0, 5), r.range(0, 3)),
        _ => guard(&format!("a = [1, 2, 3]\na.insert({}, :x)\na", r.range(-6, 5))),
    })
}

// Mode plumbing.
// ---------------------------------------------------------------------------

#[derive(Clone, Copy)]
enum Mode {
    Arith,
    Bignum,
    Floatfmt,
    Strings,
    Interp,
    Ranges,
    Arraymeth,
    Hashmeth,
    Sorting,
    Formatspec,
    Blocks,
    Symbols,
    Ternary,
    Comparison,
    Printf,
    StringOps,
    Caseexpr,
    Intmeth,
    Regex,
    Enumerable,
    Exceptions,
    Struct,
    Rational,
    Patternmatch,
    Kernelconv,
    Loopflow,
    Hashenum,
    Enumext,
    Kwargs,
    Metaprog,
    Mixins,
    Lambda,
    Enumlazy,
    Setops,
    Frozen,
    Datacls,
    Strenc,
    Complexnum,
    Objintro,
    Blockflow,
    Methobj,
    Multiyield,
    Eqlident,
    Numwide,
    Typeerr,
    Timefmt,
    Bytestr,
    Packfmt,
    Trsets,
    Strcase,
    Strpart,
    Arrreshape,
    Numprec,
    Objmodel,
    Intbits,
    Structinit,
    Hashdefault,
    Refinement,
    Kwsplat,
    Heredoc,
    Toplevelpriv,
    Raiseforms,
    Rangeedge,
    /// Round-robin over every mode in `ALL_MODES`. Not itself a member of
    /// `ALL_MODES` (that would recurse), so adding a mode never changes any
    /// other mode's own seed→case mapping — but it DOES reshuffle which mode
    /// a given `all` seed lands on, so an `all` run is only comparable to
    /// another `all` run at the same `ALL_MODES` length.
    All,
}

const ALL_MODES: &[Mode] = &[
    Mode::Arith,
    Mode::Bignum,
    Mode::Floatfmt,
    Mode::Strings,
    Mode::Interp,
    Mode::Ranges,
    Mode::Arraymeth,
    Mode::Hashmeth,
    Mode::Sorting,
    Mode::Formatspec,
    Mode::Blocks,
    Mode::Symbols,
    Mode::Ternary,
    Mode::Comparison,
    Mode::Printf,
    Mode::StringOps,
    Mode::Caseexpr,
    Mode::Intmeth,
    Mode::Regex,
    Mode::Enumerable,
    Mode::Exceptions,
    Mode::Struct,
    Mode::Rational,
    Mode::Patternmatch,
    Mode::Kernelconv,
    Mode::Loopflow,
    Mode::Hashenum,
    Mode::Enumext,
    Mode::Kwargs,
    Mode::Metaprog,
    Mode::Mixins,
    Mode::Lambda,
    Mode::Enumlazy,
    Mode::Setops,
    Mode::Frozen,
    Mode::Datacls,
    Mode::Strenc,
    Mode::Complexnum,
    Mode::Objintro,
    Mode::Blockflow,
    Mode::Methobj,
    Mode::Multiyield,
    Mode::Eqlident,
    Mode::Numwide,
    Mode::Typeerr,
    Mode::Timefmt,
    Mode::Bytestr,
    Mode::Packfmt,
    Mode::Trsets,
    Mode::Strcase,
    Mode::Strpart,
    Mode::Arrreshape,
    Mode::Numprec,
    Mode::Objmodel,
    Mode::Intbits,
    Mode::Structinit,
    Mode::Hashdefault,
    Mode::Refinement,
    Mode::Kwsplat,
    Mode::Heredoc,
    Mode::Toplevelpriv,
    Mode::Raiseforms,
    Mode::Rangeedge,
];

fn gen_intmeth(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let a = ii(r);
    let b = ii(r);
    one(match r.below(14) {
        0 => format!("p {a}.gcd({b})"),
        1 => format!("p {a}.lcm({b})"),
        2 => format!("p {a}.abs"),
        3 => format!("p {a}.divmod({b})"),
        4 => format!("p {a}.abs.bit_length"),
        5 => format!("p {a}.abs.digits"),
        6 => format!("p {a}.to_s(2)"),
        7 => format!(
            "p {}.pow({}, {})",
            r.range(2, 9),
            r.range(1, 6),
            r.range(2, 9)
        ),
        8 => format!("p({a} & {b})"),
        9 => format!("p({a} | {b})"),
        10 => format!("p({a} ^ {b})"),
        11 => format!("p({a} << {})", r.range(0, 5)),
        12 => format!("p [{a}.even?, {a}.odd?, {a}.zero?]"),
        _ => format!(
            "p {a}.abs.to_s({}).to_i({})",
            r.range(2, 17),
            r.range(2, 17)
        ),
    })
}

/// Regexps as MATCHERS (cases 0-9) and as VALUES (cases 10-18).
///
/// The value half is the part a match-only generator cannot reach: Ruby defines
/// `Regexp#==` by source + options + encoding, so two separately-written
/// literals with the same source are the SAME value and collapse under `uniq`,
/// `-`, `include?` and as a Hash key. An implementation that leaves them on
/// object identity answers every one of those the other way, and no amount of
/// `=~`/`scan`/`gsub` fuzzing will show it.
///
/// The flag pool carries `im` and `mi` on purpose: options are a normalized
/// BITMASK in Ruby, so those two are equal, which a comparison written on the
/// raw flag TEXT gets wrong while still passing every single-flag case.
fn gen_regex(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let s = format!("{}{}", ww(r), ww(r));
    let pats = [
        "[a-c]+", "o+", "[aeiou]", "\\w+", "l+", "[a-z]{2}", "^.", ".$",
    ];
    let p = r.pick(&pats);
    // A second literal, drawn independently, so a pair is same-source about as
    // often as it is different-source.
    let q = r.pick(&pats);
    let flags = ["", "i", "m", "x", "im", "mi", "imx"];
    let (f, g) = (r.pick(&flags), r.pick(&flags));
    one(match r.below(19) {
        0 => format!("p(\"{s}\" =~ /{p}/)"),
        1 => format!("p \"{s}\".match?(/{p}/)"),
        2 => format!("p \"{s}\".scan(/{p}/)"),
        3 => format!("p \"{s}\".gsub(/{p}/, \"X\")"),
        4 => format!("p \"{s}\".sub(/{p}/, \"X\")"),
        5 => format!("p \"{s}\"[/{p}/]"),
        6 => format!("p \"{s}\".match(/{p}/) ? \"m\" : \"no\""),
        7 => format!("p \"{s}\".gsub(/([a-z])\\1/, \"D\")"),
        8 => format!("p \"{s}\".split(/{p}/)"),
        9 => format!("p \"{s}\".scan(/{p}/).length"),
        // --- Regexp as a value ---
        10 => format!("p(/{p}/{f} == /{q}/{g})"),
        11 => format!("p(/{p}/{f}.eql?(/{q}/{g}))"),
        // The hash VALUE is not comparable between two interpreters; whether two
        // hashes AGREE is.
        12 => format!("p(/{p}/{f}.hash == /{q}/{g}.hash)"),
        13 => format!("p([/{p}/{f}, /{q}/{g}, /{p}/{f}].uniq.size)"),
        14 => format!("p({{/{p}/{f} => 1}}[/{q}/{g}])"),
        15 => format!("p([/{p}/{f}].include?(/{q}/{g}))"),
        16 => format!("p(([/{p}/{f}, /{q}/{g}] - [/{p}/{f}]).size)"),
        17 => format!("p([/{p}/{f}.options, /{p}/{f}.inspect, /{p}/{f}.source])"),
        // Single-quoted: a double-quoted "\\w+" would collapse the escape in the
        // Ruby string literal before `Regexp.new` ever saw it.
        _ => format!("p(Regexp.new('{p}') == /{p}/)"),
    })
}

fn gen_enumerable(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let a = arr_lit(r);
    one(match r.below(14) {
        0 => format!("p {a}.each_slice(2).to_a"),
        1 => format!("p {a}.each_cons(2).to_a"),
        2 => format!("p {a}.partition {{ |x| x > 0 }}"),
        3 => format!("p {a}.group_by {{ |x| x % 2 }}"),
        4 => format!("p {a}.flat_map {{ |x| [x, -x] }}"),
        5 => format!("p {a}.chunk_while {{ |a, b| b > a }}.to_a"),
        6 => format!("p {a}.take_while {{ |x| x > 0 }}"),
        7 => format!("p {a}.drop_while {{ |x| x > 0 }}"),
        8 => format!("p {a}.each_with_object([]) {{ |x, m| m << x * 2 }}"),
        9 => format!("p {a}.tally"),
        10 => format!("p {a}.min_by {{ |x| x.abs }}"),
        11 => format!("p {a}.max_by {{ |x| x.abs }}"),
        12 => format!("p {a}.sum"),
        _ => format!("p {a}.sort_by {{ |x| -x }}"),
    })
}

fn gen_exceptions(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let w = ww(r);
    let n = ii(r);
    // A receiver with no `-@` and no arithmetic at all. MRI names the receiver
    // in the NoMethodError the same way everywhere -- `an instance of C`, or the
    // bare literal for nil/true/false -- never by its bare class name. Only
    // receivers MRI answers with NoMethodError (not TypeError) belong here.
    let bad_recv = r.pick(&["{}", "(1..2)", ":s", "nil", "true", "proc {}"]);
    one(match r.below(11) {
        0 => format!("p (begin; raise \"{w}\"; rescue => e; e.message; end)"),
        1 => format!("p (begin; Integer(\"{w}\"); rescue ArgumentError; :caught; end)"),
        2 => format!("p (begin; {n} / 0; rescue ZeroDivisionError => e; e.message; end)"),
        3 => "p (begin; [].fetch(9); rescue IndexError; :idx; end)".to_string(),
        4 => format!(
            "p (begin; raise ArgumentError, \"{w}\"; rescue => e; [e.class.to_s, e.message]; end)"
        ),
        5 => "r = []; begin; r << 1; raise \"x\"; rescue; r << 2; ensure; r << 3; end; p r"
            .to_string(),
        6 => format!("p (begin; {{}}.fetch(:{w}); rescue KeyError; :key; end)"),
        7 => "class E1 < StandardError; end; p (begin; raise E1; rescue E1; :custom; end)"
            .to_string(),
        8 => format!("p (begin; -{bad_recv}; rescue NoMethodError => e; e.message; end)"),
        9 => format!(
            "p (begin; {bad_recv} {} 1; rescue NoMethodError => e; e.message; end)",
            r.pick(&["+", "-", "*", "/"])
        ),
        _ => "p (begin; nil.foo; rescue NoMethodError; :nome; end)".to_string(),
    })
}

fn gen_struct(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (x, y) = (ii(r), ii(r));
    one(match r.below(8) {
        0 => format!("S = Struct.new(:a, :b); p S.new({x}, {y}).to_a"),
        1 => format!("S = Struct.new(:a, :b); p S.new({x}, {y}).to_h"),
        2 => format!("S = Struct.new(:a, :b); p S.new({x}, {y}).members"),
        3 => format!("S = Struct.new(:a, :b); p(S.new({x}, {y}) == S.new({x}, {y}))"),
        4 => format!("S = Struct.new(:a, :b); s = S.new({x}, {y}); p [s.a, s.b]"),
        5 => format!("S = Struct.new(:a, :b); s = S.new({x}, {y}); s.a = {y}; p s.a"),
        6 => format!("S = Struct.new(:a, :b, keyword_init: true); p S.new(a: {x}, b: {y}).to_h"),
        _ => format!("S = Struct.new(:a, :b); p S.new({x}, {y})[0]"),
    })
}

/// Loop control flow: `break`/`next`/`redo`/`retry` in every construct that owns
/// them, plus `for`'s no-scope rule (the loop variable AND any local the body
/// assigns outlive the loop, and every closure the body makes shares the one
/// binding). Every `redo`/`retry` is guarded by a counter so the program always
/// terminates — a hang is a divergence the harness reports as a timeout, not a
/// gap, so a non-terminating generator would silently teach nothing.
fn gen_loopflow(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(2, 5);
    let k = r.range(1, 3);
    one(match r.below(18) {
        0 => format!("c = 0; {n}.times {{ |i| c += 1; redo if c == {k} }}; p c"),
        1 => format!(
            "c = 0; r = []; [1, 2, 3].each {{ |x| c += 1; redo if c == {k}; r << [x, c] }}; p [r, c]"
        ),
        2 => format!(
            "i = 0; c = 0\nwhile i < {n}\n  c += 1\n  if c == {k}\n    i += 1\n    redo\n  end\n  i += 1\nend\np [i, c]"
        ),
        3 => format!("c = 0\nfor x in 1..{n}\n  c += 1\n  redo if c == {k}\nend\np [c, x]"),
        4 => format!(
            "c = 0\nuntil c >= {n}\n  c += 1\n  redo if c == {k}\nend\np c"
        ),
        5 => format!(
            "c = 0\ni = 0\nwhile i < {n}\n  begin\n    c += 1\n    redo if c == {k}\n  end\n  i += 1\nend\np [i, c]"
        ),
        6 => format!("r = []; [1, 2, 3].each {{ |x| next if x == {k}; r << x }}; p r"),
        7 => format!("p (while true do break {n} end)"),
        8 => format!("i = 0; while i < {n}; i += 1; break if i == {k}; end; p i"),
        9 => format!("for i in 1..{n}\n  sq = i * i\nend\np [i, sq, defined?(sq)]"),
        10 => format!("for i in []\n  z = {n}\nend\np [i, z, defined?(z)]"),
        11 => format!(
            "ps = []\nfor i in 0...{n}\n  t = i * 2\n  ps << -> {{ [i, t] }}\nend\np ps.map(&:call)"
        ),
        12 => format!(
            "for k, v in {{a: 1, b: {n}}}\n  s = \"#{{k}}=#{{v}}\"\nend\np [k, v, s]"
        ),
        13 => format!(
            "a = 0\nbegin\n  a += 1\n  raise \"x\" if a < {k}\nrescue\n  retry if a < {k}\nend\np a"
        ),
        14 => format!(
            "for i in 1..{n}\n  if i == {k}\n    m = i\n  end\nend\np [m, defined?(m)]"
        ),
        15 => format!(
            "out = []\nfor i in 1..{n}\n  for j in 1..2\n    out << i * j\n  end\nend\np [out, i, j]"
        ),
        16 => format!("c = 0; [1, 2].map {{ |x| c += 1; redo if c == {k}; x * 10 }}.then {{ |a| p [a, c] }}"),
        _ => format!(
            "r = []\n{n}.times do |i|\n  r << i\n  break if i == {k}\nend\np r"
        ),
    })
}

/// Hash through Enumerable. MRI derives these from `Hash#each`, which yields the
/// whole `[k, v]` pair as ONE value — so a one-parameter block sees the pair,
/// not the key. That distinction is invisible to a `{ |k, v| }` block (it
/// auto-splats), which is why it survived the original corpus.
fn gen_hashenum(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let h = hash_lit(r);
    one(match r.below(20) {
        0 => format!("r = []; {h}.each {{ |x| r << x }}; p r"),
        1 => format!("r = []; {h}.each_pair {{ |x| r << x }}; p r"),
        2 => format!("p({h}.map {{ |x| x }})"),
        3 => format!("p({h}.collect {{ |x| x }})"),
        4 => format!("p({h}.find {{ |x| x.is_a?(Array) }})"),
        5 => format!("p({h}.detect {{ |x| x[1] > 0 }})"),
        6 => format!("p({h}.count {{ |x| x.is_a?(Array) }})"),
        7 => format!("p({h}.count)"),
        8 => format!("p({h}.sum(0) {{ |x| x[1] }})"),
        9 => format!("p({h}.flat_map {{ |x| x }})"),
        10 => format!("p({h}.filter_map {{ |x| x[0] }})"),
        11 => format!("p [{h}.any? {{ |x| x.is_a?(Array) }}, {h}.all? {{ |x| x.size == 2 }}, {h}.none? {{ |x| x.nil? }}]"),
        12 => format!("p({h}.take_while {{ |x| x.is_a?(Array) }})"),
        13 => format!("p({h}.drop_while {{ |x| x.is_a?(Array) }})"),
        14 => format!("p({h}.find_index {{ |x| x[1] > 0 }})"),
        15 => format!("p({h}.min_by {{ |x| x[1] }})"),
        16 => format!("p({h}.sort_by {{ |x| x[0] }})"),
        17 => format!("p({h}.to_h {{ |k, v| [k.to_s, v] }})"),
        18 => format!("p({h}.each_with_object([]) {{ |x, a| a << x }})"),
        _ => format!("p [{h}.first, {h}.reverse_each.to_a, {h}.tally.size]"),
    })
}

/// `Enumerator.new { |y| ... }` external iteration. MRI runs the block on a
/// Fiber, so `next` advances exactly one `y <<` — a side effect or a raise after
/// the second yield must surface on the *third* `next`, and an endless generator
/// must answer `next` rather than hang. Endless generators are always consumed
/// by a bounded `next`/`first`/`take`, never by `to_a`.
fn gen_enumext(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(1, 4);
    let m = r.range(2, 5);
    one(match r.below(14) {
        0 => "e = Enumerator.new { |y| y << 1; y << 2; y << 3 }; p [e.next, e.next, e.next]".to_string(),
        1 => "e = Enumerator.new { |y| y << 1; y << 2 }; p [e.next, e.peek, e.next]".to_string(),
        2 => "log = []\ne = Enumerator.new { |y| log << :a; y << 1; log << :b; y << 2; log << :c }\np log\np e.next\np log\np e.next\np log"
            .to_string(),
        3 => "e = Enumerator.new { |y| y << 1; raise \"boom\" }\np e.next\nbegin\n  e.next\nrescue => ex\n  p [ex.class, ex.message]\nend"
            .to_string(),
        4 => "e = Enumerator.new { |y| y << 1; raise ArgumentError, \"bad\" }\np e.next\nbegin\n  e.next\nrescue ArgumentError => ex\n  p [ex.class, ex.is_a?(StandardError)]\nend"
            .to_string(),
        5 => "e = Enumerator.new { |y| i = 0; loop { y << i; i += 1 } }\np [e.next, e.next, e.next]"
            .to_string(),
        6 => format!(
            "e = Enumerator.new {{ |y| i = 0; loop {{ y << i; i += 1 }} }}\np e.first({m})\np e.take({n})"
        ),
        7 => format!(
            "e = Enumerator.new {{ |y| i = 0; loop {{ y << i * 2; i += 1 }} }}\np e.lazy.map {{ |x| x + 1 }}.first({m})"
        ),
        8 => format!(
            "e = Enumerator.new {{ |y| {n}.times {{ |i| y << i }} }}\nr = []\nloop {{ r << e.next }}\np r"
        ),
        9 => "e = Enumerator.new { |y| y << 1; y << 2 }\np e.next\ne.rewind\np e.next\np e.to_a"
            .to_string(),
        10 => "e = Enumerator.new { |y| y << 1 }\np e.next\nbegin\n  e.next\nrescue StopIteration => ex\n  p ex.class\nend"
            .to_string(),
        11 => format!(
            "a = Enumerator.new {{ |y| {m}.times {{ |i| y << \"a#{{i}}\" }} }}\nb = Enumerator.new {{ |y| {m}.times {{ |i| y << \"b#{{i}}\" }} }}\np [a.next, b.next, a.next, b.next]"
        ),
        12 => format!("e = Enumerator.new {{ |y| y.yield({n}, {m}); y << 9 }}; p [e.next, e.next]"),
        _ => "e = [1, 2, 3].each; p [e.next, e.peek, e.next, e.next]".to_string(),
    })
}

/// Keyword arguments: required / defaulted / `**rest`, the positional+keyword
/// split, and the double-splat call form.
fn gen_kwargs(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (ii(r), ii(r));
    one(match r.below(12) {
        0 => format!("def f(x:, y: {b}) = [x, y]\np f(x: {a})"),
        1 => format!("def f(x:, y:) = [x, y]\np f(y: {b}, x: {a})"),
        2 => format!("def f(a, x: {b}) = [a, x]\np f({a})"),
        3 => format!("def f(**o) = o\np f(a: {a}, b: {b})"),
        4 => format!("def f(x:, **o) = [x, o]\np f(x: {a}, z: {b})"),
        5 => format!("def f(x:, y: {b}) = [x, y]\nh = {{x: {a}, y: {b}}}\np f(**h)"),
        6 => format!("def f(a, b = {b}, *r, k:, **o) = [a, b, r, k, o]\np f({a}, k: {b})"),
        7 => "def f(x:) = x\nbegin\n  f\nrescue ArgumentError => e\n  p e.class\nend".to_string(),
        8 => format!("def f(x:) = x\nbegin\n  f(x: {a}, y: {b})\nrescue ArgumentError => e\n  p e.class\nend"),
        9 => format!("f = ->(x:, y: {b}) {{ [x, y] }}\np f.call(x: {a})"),
        10 => format!("def f(*a, **o) = [a, o]\np f({a}, {b}, k: {a})"),
        _ => format!("def f(x: {a}) = x\np [f, f(x: {b})]"),
    })
}

/// Metaprogramming hooks: `method_missing`/`respond_to_missing?`,
/// `define_method`, `Module#prepend` + `super`, singleton methods, and
/// `send`/`public_send`.
fn gen_metaprog(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (ii(r), ii(r));
    let w = ww(r);
    one(match r.below(14) {
        0 => format!(
            "class C\n  def method_missing(n, *a) = [n, a]\n  def respond_to_missing?(n, p = false) = true\nend\np C.new.{w}({a})"
        ),
        1 => format!(
            "class C\n  def method_missing(n, *a) = n.to_s\nend\np [C.new.respond_to?(:{w}), C.new.{w}]"
        ),
        2 => format!(
            "class C\n  define_method(:m) {{ |x| x + {a} }}\nend\np C.new.m({b})"
        ),
        3 => format!(
            "class C\n  [:a, :b].each {{ |n| define_method(n) {{ n.to_s * {} }} }}\nend\np [C.new.a, C.new.b]",
            r.range(1, 3)
        ),
        4 => "module M\n  def m = \"M\" + super\nend\nclass C\n  prepend M\n  def m = \"C\"\nend\np C.new.m"
            .to_string(),
        5 => "module M\n  def m = \"M\"\nend\nclass C\n  include M\n  def m = \"C\" + super\nend\np C.new.m"
            .to_string(),
        6 => format!("class C; def m = {a}; end\np [C.new.send(:m), C.new.public_send(:m)]"),
        7 => format!(
            "o = Object.new\ndef o.m = {a}\np [o.m, o.singleton_methods.sort]"
        ),
        8 => format!(
            "class C\n  def m = {a}\nend\nC.class_eval {{ def n = {b} }}\np [C.new.m, C.new.n]"
        ),
        9 => format!(
            "class C; end\nC.define_method(:m) {{ {a} }}\np C.new.m"
        ),
        10 => format!(
            "class C\n  def initialize; @x = {a}; end\nend\np C.new.instance_variable_get(:@x)"
        ),
        11 => format!(
            "class C; def m = {a}; end\np [C.instance_methods(false).sort, C.new.respond_to?(:m)]"
        ),
        12 => format!(
            "module M\n  def self.included(b) = b.const_set(:TAG, {a})\nend\nclass C\n  include M\nend\np C::TAG"
        ),
        _ => format!(
            "class C\n  def method_missing(n, *a)\n    n.to_s.start_with?(\"get_\") ? {a} : super\n  end\nend\nbegin\n  C.new.nope\nrescue NoMethodError => e\n  p e.class\nend\np C.new.get_x"
        ),
    })
}

/// `Comparable` / `Enumerable` mixed into a user class: every derived method has
/// to come from the single `<=>` / `each` the class defines.
fn gen_mixins(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (r.range(0, 9), r.range(0, 9));
    let cmp = "class N\n  include Comparable\n  attr_reader :v\n  def initialize(v) = @v = v\n  def <=>(o) = v <=> o.v\n  def to_s = \"N(#{v})\"\nend";
    let enu = "class Bag\n  include Enumerable\n  def initialize(*xs) = @xs = xs\n  def each(&b) = @xs.each(&b)\nend";
    one(match r.below(14) {
        0 => format!("{cmp}\np(N.new({a}) < N.new({b}))"),
        1 => format!("{cmp}\np(N.new({a}) >= N.new({b}))"),
        2 => format!("{cmp}\np N.new({a}).between?(N.new(0), N.new(9))"),
        3 => format!("{cmp}\np N.new({a}).clamp(N.new(2), N.new(6)).to_s"),
        4 => format!("{cmp}\np [N.new({a}), N.new({b})].max.to_s"),
        5 => format!("{cmp}\np [N.new({a}), N.new({b})].sort.map(&:to_s)"),
        6 => format!("{enu}\np Bag.new({a}, {b}, 3).map {{ |x| x * 2 }}"),
        7 => format!("{enu}\np Bag.new({a}, {b}, 3).select(&:even?)"),
        8 => format!("{enu}\np Bag.new({a}, {b}, 3).sort"),
        9 => format!("{enu}\np Bag.new({a}, {b}, 3).include?({a})"),
        10 => format!("{enu}\np Bag.new({a}, {b}, 3).each_with_index.to_a"),
        11 => format!(
            "{enu}\np [Bag.new({a}, {b}).min, Bag.new({a}, {b}).max, Bag.new({a}, {b}).sum]"
        ),
        12 => format!("{enu}\np Bag.new({a}, {b}, 3).partition(&:odd?)"),
        _ => format!("{enu}\np Bag.new({a}, {b}, 3).each_slice(2).to_a"),
    })
}

/// Rational arithmetic (cases 0-10) and ORDERING FAILURE (cases 11-16).
///
/// Rational gets `< <= > >=` from `Comparable`, so they are defined by `<=>`:
/// when `<=>` answers nil the operator raises `ArgumentError`, it does not
/// answer false. Two things make this worth generating rather than asserting:
///
/// - It is ASYMMETRIC. `Rational(1,2) < Float::NAN` raises, but
///   `Float::NAN < Rational(1,2)` is plain IEEE and answers false, because
///   `Float#<` is its own method and never consults `<=>`. An implementation
///   that "raises on a NaN operand" passes the first and fails the second, so
///   both directions are generated (cases 11/12) against the same operator.
/// - The operand's name in the message is not its class. MRI's `rb_cmperr`
///   prints `inspect` for a Float or a special constant (`NaN`, `nil`, `:sym`)
///   and the CLASS for everything else (`String`, `Array`), so case 13 draws
///   from both kinds.
fn gen_rational(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (r.range(1, 12), r.range(1, 12));
    let (c, d) = (r.range(1, 12), r.range(1, 12));
    let n = ii(r);
    let relop = r.pick(&["<", ">", "<=", ">="]);
    // Left column renders via `inspect` in the message, right column via class.
    let operand = r.pick(&["Float::NAN", "nil", ":sym", "\"s\"", "[1]", "Object.new"]);
    one(match r.below(19) {
        0 => format!("p(Rational({a}, {b}) + Rational({c}, {d}))"),
        1 => format!("p(Rational({a}, {b}) - Rational({c}, {d}))"),
        2 => format!("p(Rational({a}, {b}) * Rational({c}, {d}))"),
        3 => format!("p(Rational({a}, {b}) / Rational({c}, {d}))"),
        4 => format!("p(Rational({a}, {b}) % Rational({c}, {d}))"),
        5 => format!("p(Rational({a}, {b}) ** {})", r.range(-3, 4)),
        6 => format!("p(Rational({a}, {b}) <=> Rational({c}, {d}))"),
        7 => format!("p(Rational({a}, {b}) + {n})"),
        8 => format!("p(Rational({a}, {b}).to_f.round(6))"),
        9 => format!("p [Rational({a}, {b}).numerator, Rational({a}, {b}).denominator]"),
        10 => format!("p({n} / Rational({c}, {d}))"),
        // Rational on the LEFT: `<=>` is nil, so Comparable raises.
        11 => format!(
            "begin\n  p(Rational({a}, {b}) {relop} Float::NAN)\nrescue ArgumentError => e\n  p e.message\nend"
        ),
        // Float on the left: `Float#<` is IEEE and must NOT raise.
        12 => format!(
            "begin\n  p(Float::NAN {relop} Rational({a}, {b}))\nrescue ArgumentError => e\n  p e.message\nend"
        ),
        13 => format!(
            "begin\n  p(Rational({a}, {b}) {relop} {operand})\nrescue => e\n  p [e.class, e.message]\nend"
        ),
        // `<=>` itself answers nil rather than raising — the value the operators
        // are derived from, pinned separately so a fix can't satisfy the
        // operators by making `<=>` raise too.
        14 => format!("p(Rational({a}, {b}) <=> Float::NAN)"),
        // The same operator reached as a METHOD rather than as a native op.
        // `reduce(:<)` and `send` go through Rational dispatch while `r < x`
        // goes through the numeric hook, and the two used to be separate paths
        // that could disagree.
        15 => format!(
            "begin\n  p(Rational({a}, {b}).send(:{relop}, {operand}))\nrescue => e\n  p [e.class, e.message]\nend"
        ),
        // `between?` and `clamp` are Comparable's OTHER two `<=>` consumers, and
        // Rational reaches them through its own dispatch rather than through the
        // module. They disagree by design: `clamp` rejects a min above its max
        // before ranking anything and treats a nil bound as unbounded, while
        // `between?` has no min-vs-max check and short-circuits to false below
        // min without ever ranking max.
        16 => format!(
            "begin\n  p(Rational({a}, {b}).{}({}, {}))\nrescue => e\n  p [e.class, e.message]\nend",
            r.pick(&["between?", "clamp"]),
            r.pick(&["0", "1", "nil", "Rational(1, 2)", "\"s\""]),
            r.pick(&["0", "1", "nil", "Rational(9, 2)"])
        ),
        17 => format!(
            "begin\n  p(Rational({a}, {b}).clamp({}{}{}))\nrescue => e\n  p [e.class, e.message]\nend",
            r.pick(&["0", "1"]),
            r.pick(&["..", "..."]),
            r.pick(&["0", "3"])
        ),
        // Ordering that SUCCEEDS against every numeric class, pinned next to the
        // failures so a fix cannot satisfy them by making Rational refuse to
        // compare with anything.
        _ => format!(
            "p [Rational({a}, {b}) {relop} Rational({c}, {d}), Rational({a}, {b}) {relop} {c}, Rational({a}, {b}) {relop} {c}.0, Rational({a}, {b}) {relop} (10 ** 20)]"
        ),
    })
}

fn gen_patternmatch(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(0, 12);
    let (x, y) = (ii(r), ii(r));
    one(match r.below(8) {
        0 => format!("case [{x}, {y}]; in [a, b]; p a + b; end"),
        1 => format!("case {{a: {x}, b: {y}}}; in {{a:, b:}}; p [a, b]; end"),
        2 => format!("case [1, {x}, 3]; in [1, m, 3]; p m; in _; p :no; end"),
        3 => format!("case {n}; in 0..5; p :lo; in Integer; p :hi; end"),
        4 => format!("case [{x}, {y}]; in [Integer => a, Integer => b]; p a * b; end"),
        5 => format!("case [1, 2, {x}, {y}]; in [_, _, *rest]; p rest; end"),
        6 => format!(
            "case {{name: \"{}\", age: {n}}}; in {{name: String => s}}; p s; end",
            ww(r)
        ),
        _ => {
            format!("r = (case {n}; in 0 then :z; in n if n > 5 then :big; else :small; end); p r")
        }
    })
}

/// Non-local control flow **as the value of a block-taking call**.
///
/// `loopflow` already emits `break`/`next`/`redo`, but always as a statement
/// inside a loop whose result is thrown away (`arr.each { break }; p r`). The
/// value the block-taking call itself evaluates to was never probed, and that
/// is exactly where MRI's rule lives: a `break` ends the invocation the block
/// LITERAL was written on and becomes its value. Every case here therefore puts
/// the call in value position — `p(recv.meth { break v })` — and varies the
/// method, so a method that silently returns its receiver (or swallows the
/// statement's output entirely) cannot hide.
///
/// Also covers the shapes a per-method generator cannot reach: `break` crossing
/// a user-defined `yield`, blocks nested two deep, `break`/`next`/`return`
/// interacting with `begin/rescue/ensure`, and proc-vs-lambda `return`.
fn gen_blockflow(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let v = ii(r);
    let w = ww(r);
    // Block-taking methods whose value is observable. Each entry is
    // (receiver, method-call-prefix, block params).
    let arr_meths = [
        "each",
        "map",
        "select",
        "filter",
        "reject",
        "find",
        "detect",
        "find_index",
        "sort_by",
        "min_by",
        "max_by",
        "group_by",
        "partition",
        "take_while",
        "drop_while",
        "sum",
        "count",
        "flat_map",
        "each_with_index",
        "each_entry",
        "find_all",
        "filter_map",
        "reverse_each",
        "each_index",
        "any?",
        "all?",
        "none?",
        "one?",
        "delete_if",
        "keep_if",
    ];
    let hash_meths = [
        "each",
        "each_pair",
        "map",
        "select",
        "filter",
        "reject",
        "find",
        "detect",
        "each_with_index",
        "each_key",
        "each_value",
        "sort_by",
        "min_by",
        "max_by",
        "group_by",
        "partition",
        "sum",
        "count",
        "any?",
        "all?",
        "none?",
        "one?",
        "delete_if",
        "keep_if",
        "transform_values",
        "transform_keys",
        "filter_map",
        "flat_map",
        "each_entry",
        "find_all",
    ];
    one(match r.below(24) {
        // The core shape: the break value IS the call's value.
        0 => format!("p([1, 2, 3].{} {{ |x| break {v} }})", r.pick(&arr_meths)),
        1 => format!(
            "p({{a: 1, b: 2}}.{} {{ |k, vv| break {v} }})",
            r.pick(&hash_meths)
        ),
        // Conditional break — the loop runs partway, then yields the value.
        2 => format!(
            "p([1, 2, 3, 4].{} {{ |x| break x * 10 if x == {}; x }})",
            r.pick(&arr_meths),
            r.range(1, 4)
        ),
        // Arity-taking iterators that return the receiver without a break.
        3 => format!("p([1, 2, 3, 4].each_slice({}) {{ |s| break {v} }})", r.range(1, 3)),
        4 => format!("p([1, 2, 3, 4].each_cons({}) {{ |s| break {v} }})", r.range(1, 3)),
        5 => format!("p([1, 2, 3].each_with_object([]) {{ |x, acc| break {v} }})"),
        6 => format!("p(\"{w}\".each_char {{ |c| break {v} }})"),
        7 => format!("p(\"a\\nb\\nc\".each_line {{ |l| break {v} }})"),
        8 => format!("p((1..{}).each_with_index {{ |x, i| break {v} }})", r.range(2, 5)),
        9 => format!("p({}.times {{ |i| break {v} }})", r.range(1, 4)),
        10 => format!("p(1.upto({}) {{ |i| break {v} }})", r.range(2, 5)),
        // Break crossing a user-defined `yield`: the method ends and the value
        // belongs to the literal's call site.
        11 => format!(
            "def y\n  yield 1\n  :after\nend\np(y {{ |x| break {v} }})"
        ),
        12 => format!(
            "def y2\n  r = yield 1\n  [:got, r]\nend\np(y2 {{ |x| next {v} }})"
        ),
        // Nested two deep: only the inner call is the inner break's target.
        13 => format!(
            "p([1, 2].map {{ |a| [3, 4].each {{ |b| break {v} }} }})"
        ),
        14 => format!(
            "p([1, 2].each {{ |a| [3, 4].each {{ |b| break {v} }}; }})"
        ),
        // `return` from a block is non-local: it ends the defining method.
        15 => format!(
            "def m\n  [1, 2, 3].each {{ |x| return x + {} if x == 2 }}\n  :fell\nend\np m",
            r.range(0, 9)
        ),
        16 => "def m2\n  [1, 2].each { |a| [3, 4].each { |b| return [a, b] if b == 4 } }\n  :none\nend\np m2".to_string(),
        // proc vs lambda `return` differ; verify rather than assume.
        17 => format!(
            "def pr\n  q = Proc.new {{ return {v} }}\n  q.call\n  :after\nend\np pr"
        ),
        18 => format!(
            "def la\n  q = lambda {{ return {v} }}\n  q.call\n  :after\nend\np la"
        ),
        19 => format!("l = lambda {{ break {v} }}\np l.call"),
        // ensure must still run, and must not eat the value.
        20 => "def e\n  o = []\n  [1, 2, 3].each { |i| begin; o << i; break if i == 2; ensure; o << :E; end }\n  o\nend\np e".to_string(),
        21 => format!(
            "def e2\n  begin\n    [1, 2].each {{ |i| return {v} if i == 2 }}\n  ensure\n    nil\n  end\n  :no\nend\np e2"
        ),
        22 => format!(
            "def e3\n  r = begin\n    {v}\n  rescue\n    -1\n  ensure\n    -2\n  end\n  r\nend\np e3"
        ),
        // `for` does NOT create a scope; a block does.
        _ => format!(
            "for i in 1..{}\n  sq = i\nend\np [i, sq, defined?(sq)]\n[9].each {{ |jj| kk = jj }}\np [defined?(jj), defined?(kk)]",
            r.range(2, 4)
        ),
    })
}

fn gen_kernelconv(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = ii(r);
    let w = ww(r);
    one(match r.below(11) {
        0 => format!("p Integer(\"{}\")", r.range(0, 999)),
        1 => "p Integer(\"ff\", 16)".to_string(),
        2 => format!(
            "p Integer(\"{}\", 2)",
            if r.below(2) == 0 { "1010" } else { "1101" }
        ),
        3 => format!("p Float(\"{}.5\")", r.range(0, 99)),
        4 => "p Array(nil)".to_string(),
        5 => format!("p Array([{n}])"),
        6 => format!("p Array({n})"),
        7 => format!("p (begin; Integer(\"{w}\"); rescue ArgumentError; :bad; end)"),
        8 => format!("p String({n})"),
        9 => format!("p format(\"%05.2f\", {})", r.range(0, 99)),
        _ => format!("p Integer({n}.to_f)"),
    })
}

/// Sources that yield TWO values per iteration (`each_with_index`,
/// `each_with_object`, `y.yield a, b`) driven through every kind of consumer,
/// plus `.lazy` over a non-Array source.
///
/// The reshaping is per consumer and not derivable: `take_while`'s block sees the
/// first value while the element it keeps is the packed pair, `select`'s block
/// sees the pair, and `map`'s sees the first. A generator that varies only the
/// consumer, or only the block shape, cannot tell those apart — this one varies
/// both, and the block shapes include the ones with different binding rules
/// (`{ |x| }`, `{ |x, i| }`, `{ |*a| }`).
fn gen_multiyield(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    // Sources whose every iteration yields two values.
    let pair_srcs = [
        "[10, 20, 30].each_with_index",
        "[10, 20].each_with_object([])",
        "%w[a b c].each_with_index",
        "(1..3).each_with_index",
        "Enumerator.new { |y| y.yield 1, 2; y.yield 3, 4 }",
        "Enumerator.new { |y| y.yield 5, 6 }",
    ];
    // Sources whose iteration yields ONE value that happens to be an array — the
    // control group: their block must NOT see it unpacked.
    let pack_srcs = [
        "{a: 1, b: 2}",
        "[[1, 2], [3, 4]]",
        "[1, 2, 3, 4].each_slice(2)",
        "[1, 2, 3].each_cons(2)",
        "Enumerator.new { |y| y << [1, 2]; y << [3, 4] }",
    ];
    // Block bodies that DISCRIMINATE: their answer differs depending on whether
    // the block was handed the first value or the packed pair.
    let probes = [
        "{ |x| x.is_a?(Array) }",
        "{ |x| x.to_s.size > 1 }",
        "{ |x, i| x.is_a?(Array) }",
        "{ |*a| a.size > 1 }",
        "{ |x, i| i.nil? }",
    ];
    let src = if r.below(3) == 0 {
        r.pick(&pack_srcs)
    } else {
        r.pick(&pair_srcs)
    };
    let b = r.pick(&probes);
    // Consumers split three ways in MRI: block sees the first value and the
    // answer is the block's, block sees the first value but the answer is the
    // source element, block sees the packed pair.
    // `each_entry` is absent on purpose: its value is the Enumerator itself, and
    // a generator-backed one inspects with its address, which is not comparable.
    let consumers = [
        "map",
        "collect",
        "flat_map",
        "filter_map",
        "take_while",
        "count",
        "find_index",
        "any?",
        "all?",
        "none?",
        "one?",
        "select",
        "filter",
        "reject",
        "sort_by",
        "group_by",
        "partition",
        "drop_while",
        "find",
        "detect",
        "min_by",
        "max_by",
        "uniq",
        "find_all",
    ];
    one(match r.below(13) {
        // A lazy pipeline's own `inspect` — one `#<Enumerator::Lazy: …>` per
        // stage around the object `.lazy` was called on. Not for a generator
        // source: MRI shows the Generator's ADDRESS there, which is not
        // comparable between two interpreters.
        10 if !src.starts_with("Enumerator.new") => format!(
            "p({src}.lazy.{}{})",
            r.pick(&["map { |x| x }", "select { |x| x }", "take_while { |x| x }", "reject { |x| x }"]),
            r.pick(&["", ".take(2)", ".drop(1)", ".zip([1, 2])", ".map { |x| x }"])
        ),
        // `break` inside a block a lazy pipeline STORED: the call it was written
        // on already returned, so MRI raises `LocalJumpError` when the block
        // finally runs.
        11 => format!(
            "p({src}.lazy.{} {{ break {} }}.to_a)",
            r.pick(&["map", "select", "reject", "take_while", "drop_while", "filter_map"]),
            r.range(1, 9)
        ),
        12 => format!(
            "begin\n  {src}.lazy.{} {{ break }}.first(1)\nrescue LocalJumpError => e\n  p e.message\nend",
            r.pick(&["map", "select", "take_while", "filter_map"])
        ),
        0 | 10 => format!("p({src}.{} {b})", r.pick(&consumers)),
        1 => format!("p({src}.to_a)"),
        2 => format!("{src}.each {b}\np :done"),
        // `Enumerator#each` answers the object being iterated — except on a
        // generator, where MRI answers the generator block's own value (a
        // Yielder, which has no `to_a`, so the reference run only errors). See
        // BUGS.md; the case is not spent on a snippet MRI itself rejects.
        3 if !src.starts_with("Enumerator.new") => {
            format!("p({src}.each {} .to_a)", "{ |x| x }")
        }
        3 => format!("p({src}.to_a.size)"),
        4 => format!("p({src}.map {b})"),
        5 => format!("p({src}.take_while {b})"),
        6 => format!(
            "p({src}.lazy.{} {b}.first(2))",
            r.pick(&[
                "map",
                "select",
                "take_while",
                "reject",
                "filter_map",
                "drop_while"
            ])
        ),
        7 => format!("p({src}.lazy.map {} .to_a)", "{ |x| x }"),
        8 => format!("p({src}.each_with_object([]) {} )", "{ |x, acc| acc << x }"),
        _ => format!(
            "p({src}.{} {b})",
            r.pick(&[
                "count",
                "find_index",
                "any?",
                "all?",
                "none?",
                "one?",
                "take_while"
            ])
        ),
    })
}

/// `Method`/`UnboundMethod` reflection: `#arity`, `#owner`, `#parameters`,
/// `#name`, `#curry` over BUILT-IN methods as well as written ones.
///
/// A built-in has no written parameter list, so every one of those answers comes
/// out of a table of what MRI declares — which is exactly the kind of surface a
/// generator that only ever probes written `def`s reports zero divergences on.
/// The receiver list therefore spans the core classes, and the method list per
/// receiver spans fixed-arity, optional-argument and variadic built-ins, plus the
/// ones a MODULE defines (`Comparable#between?`, `Enumerable#each_slice`,
/// `Kernel#frozen?`) where the owner is not the receiver's own class.
///
/// Not emitted: `parameters` of a `define_method` body that takes `**rest` — the
/// parser desugars the collector into a synthetic capture param, so its name is
/// not recorded anywhere and rubylang reports an unnamed `[:keyrest]`.
fn gen_methobj(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    // (receiver literal, methods to probe on it). Mixed on purpose: fixed arity,
    // `-1` variadic, `-2` "one required then variadic", and module-owned ones.
    let recvs: &[(&str, &[&str])] = &[
        (
            "3",
            &[
                "+",
                "*",
                "divmod",
                "gcd",
                "times",
                "to_s",
                "round",
                "between?",
                "clamp",
                "digits",
                "fdiv",
                "pow",
                "abs",
                "upto",
                "coerce",
                "puts",
                "frozen?",
                "instance_of?",
            ],
        ),
        (
            "1.5",
            &[
                "+", "round", "floor", "divmod", "between?", "step", "to_i", "nan?", "coerce",
            ],
        ),
        (
            "\"ab\"",
            &[
                "upcase",
                "sub",
                "gsub",
                "split",
                "each_char",
                "center",
                "index",
                "between?",
                "start_with?",
                "delete",
                "count",
                "tr",
                "slice",
                "unpack",
                "%",
            ],
        ),
        (
            ":sym",
            &["to_proc", "to_s", "succ", "between?", "start_with?", "[]"],
        ),
        (
            "[1, 2]",
            &[
                "push",
                "map",
                "first",
                "include?",
                "each_slice",
                "inject",
                "flatten",
                "join",
                "rotate",
                "sample",
                "sum",
                "zip",
                "each_cons",
                "min_by",
                "take_while",
                "dig",
            ],
        ),
        (
            "{a: 1}",
            &[
                "each",
                "fetch",
                "map",
                "merge",
                "store",
                "dig",
                "any?",
                "each_with_object",
                "min_by",
                "group_by",
                "count",
                "to_a",
            ],
        ),
        (
            "(1..3)",
            &["step", "each", "cover?", "sum", "each_slice", "min", "to_a"],
        ),
        (
            "nil",
            &[
                "to_a",
                "to_s",
                "inspect",
                "&",
                "frozen?",
                "instance_variable_get",
            ],
        ),
        (
            "Object.new",
            &[
                "frozen?",
                "instance_variable_get",
                "respond_to?",
                "tap",
                "then",
                "send",
            ],
        ),
    ];
    // Class receivers: the owner is a singleton class (`#<Class:Integer>`) or,
    // for the inherited ones, `Class` / `Module` / `Kernel`.
    let classes: &[(&str, &[&str])] = &[
        (
            "Integer",
            &[
                "sqrt",
                "try_convert",
                "name",
                "instance_method",
                "ancestors",
            ],
        ),
        (
            "String",
            &["new", "try_convert", "name", "instance_methods"],
        ),
        ("Array", &["new", "[]", "try_convert", "superclass"]),
        ("Hash", &["new", "[]", "name", "include?"]),
        ("Math", &["sqrt", "hypot", "log", "atan2", "cbrt"]),
        ("Struct", &["new", "name"]),
    ];
    // Written parameter shapes — the `def` side of the same three answers.
    let defs = [
        ("def m(a); end", "m"),
        ("def m(a, b); end", "m"),
        ("def m(a, b = 1); end", "m"),
        ("def m(a, *b); end", "m"),
        ("def m(*a); end", "m"),
        ("def m(a, *b, c); end", "m"),
        ("def m(a, b: 1); end", "m"),
        ("def m(a, b:); end", "m"),
        ("def m(a, **b); end", "m"),
        ("def m(a, &b); end", "m"),
        ("def m(a, b = 1, *c, d:, e: 2, **f, &g); end", "m"),
        ("def m; end", "m"),
    ];
    let (rc, ms) = r.pick(recvs);
    let m = r.pick(ms);
    let (cls, cms) = r.pick(classes);
    let cm = r.pick(cms);
    let (d, dn) = r.pick(&defs);
    one(match r.below(20) {
        0 => format!("p({rc}.method(:{m}).arity)"),
        1 => format!("p({rc}.method(:{m}).owner.to_s)"),
        2 => format!("p({rc}.method(:{m}).parameters)"),
        3 => format!("p([{rc}.method(:{m}).arity, {rc}.method(:{m}).owner.to_s])"),
        4 => format!("p({rc}.method(:{m}).name)"),
        5 => format!("p {cls}.method(:{cm}).arity"),
        6 => format!("p {cls}.method(:{cm}).owner.to_s"),
        7 => format!("p {cls}.method(:{cm}).parameters"),
        8 => format!("class C\n  {d}\nend\np C.new.method(:{dn}).arity"),
        9 => format!("class C\n  {d}\nend\np C.new.method(:{dn}).parameters"),
        10 => format!("class C\n  {d}\nend\np C.new.method(:{dn}).owner.to_s"),
        11 => format!("class C\n  {d}\nend\np C.instance_method(:{dn}).owner.to_s"),
        12 => format!("class C\n  {d}\nend\np C.instance_method(:{dn}).arity"),
        13 => format!("class C\n  {d}\nend\np C.new.method(:{dn}).unbind.owner.to_s"),
        // A module-owned method: the owner is the module, never the class.
        14 => format!(
            "module M\n  {d}\nend\nclass C\n  {}\nend\np [C.new.method(:{dn}).owner.to_s, C.new.method(:{dn}).arity]",
            if r.below(2) == 0 { "include M" } else { "prepend M" }
        ),
        15 => format!(
            "class C\n  include Comparable\n  def <=>(o) = 0\nend\np [C.new.method(:{}).owner.to_s, C.new.method(:{}).arity]",
            r.pick(&["between?", "clamp", "<", ">="]),
            r.pick(&["between?", "clamp", "<", ">="])
        ),
        16 => format!(
            "class C\n  include Enumerable\n  def each; yield 1; end\nend\np [C.new.method(:{}).owner.to_s, C.new.method(:{}).arity]",
            r.pick(&["map", "each_slice", "sort_by", "include?", "first"]),
            r.pick(&["map", "each_slice", "sort_by", "include?", "first"])
        ),
        // `define_method` bodies report the block's shape, strictly.
        17 => format!(
            "class C\n  define_method(:d) {{ |{}| }}\nend\np [C.new.method(:d).arity, C.new.method(:d).parameters]",
            r.pick(&["x", "x, y", "x, y = 1", "x, *y", "", "x, k: 1"])
        ),
        // `curry` reads the same arity a built-in reports.
        18 => format!("p 3.method(:{}).curry[{}]", r.pick(&["+", "*", "-", "gcd"]), r.range(1, 9)),
        // A user subclass of a built-in inherits the built-in's owner. The method
        // names are per-parent: a name the parent does not have is a `NameError`
        // in MRI, which spends the case without comparing anything.
        _ => {
            let (parent, pms): &(&str, &[&str]) = r.pick(&[
                ("Array", &["each", "size", "first", "frozen?", "instance_of?", "to_s"] as &[&str]),
                ("Hash", &["each", "size", "frozen?", "instance_of?", "to_s", "fetch"]),
                ("String", &["size", "upcase", "frozen?", "instance_of?", "to_s", "sub"]),
            ]);
            format!(
                "class C < {parent}\nend\np [C.new.method(:{}).owner.to_s, C.new.method(:{}).arity]",
                r.pick(pms),
                r.pick(pms)
            )
        }
    })
}

/// Ruby has TWO equalities and they disagree: `==` coerces across numeric
/// classes (`1 == 1.0`) while `eql?`/`hash` — the pair Hash keys, `uniq`, the
/// Array set operators and `Set` are all defined in terms of — does not
/// (`1.eql?(1.0)` is false, and the two are distinct Hash keys). Every case
/// here prints the SAME operation over an `eql?`-equal pair and over a merely
/// `==`-equal pair, so an implementation that picks either equality for both
/// is caught: answering with `==` throughout collapses `[1, 1.0]`, answering
/// with identity throughout splits `[1, 1]`. The rule is recursive — a
/// container is `eql?` only when its elements are — so the pairs are also
/// nested one and two levels deep, and used as Hash/Set keys where the
/// identity is what selects the bucket.
fn gen_eqlident(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(1, 6);
    let m = r.range(1, 6);
    // `same` and `wide` hold equal numeric VALUES; only their classes differ,
    // so `==` cannot tell them apart and `eql?` must.
    let same = format!("{n}");
    let wide = format!("{n}.0");
    let pre = "require \"set\"";
    one(match r.below(24) {
        0 => format!("p [{same}.eql?({same}), {same}.eql?({wide}), {wide}.eql?({wide})]"),
        1 => format!("p [[{same}].eql?([{same}]), [{same}].eql?([{wide}])]"),
        2 => format!("p [[[{same}]].eql?([[{same}]]), [[{same}]].eql?([[{wide}]])]"),
        3 => format!("p [{{ a: {same} }}.eql?({{ a: {same} }}), {{ a: {same} }}.eql?({{ a: {wide} }})]"),
        4 => format!("p [{same}, {wide}, {same}, {m}].uniq"),
        5 => format!("p [[{same}], [{wide}], [{same}]].uniq"),
        6 => format!("p([{same}, {m}] | [{wide}])"),
        7 => format!("p([{same}, {m}] & [{wide}])"),
        8 => format!("p([{same}, {wide}] - [{same}])"),
        9 => format!("p [[{same}], [{m}]].intersect?([[{wide}]])"),
        10 => format!("h = {{}}\nh[{same}] = :i\nh[{wide}] = :f\np [h.size, h[{same}], h[{wide}]]"),
        11 => format!(
            "h = {{}}\nh[[{same}]] = :i\nh[[{wide}]] = :f\np [h.size, h[[{same}]], h[[{wide}]]]"
        ),
        12 => format!(
            "h = {{}}\nh[{{ a: {same} }}] = :i\nh[{{ a: {wide} }}] = :f\np [h.size, h[{{ a: {same} }}]]"
        ),
        13 => format!("h = {{}}\nh[{{ a: {same} }}] = :i\np h.keys"),
        14 => format!("{pre}\ns = Set.new\ns << {{ a: {same} }}\ns << {{ a: {same} }}\np [s.size, s.to_a]"),
        15 => format!("{pre}\np [(Set[{same}] & Set[{wide}]).to_a, (Set[{same}] - Set[{wide}]).to_a]"),
        16 => format!(
            "{pre}\np [Set[{same}].subset?(Set[{wide}]), Set[{same}].subset?(Set[{same}, {m}])]"
        ),
        17 => format!(
            "{pre}\np [Set[{same}].disjoint?(Set[{wide}]), Set[{same}].intersect?(Set[{same}])]"
        ),
        18 => format!("{pre}\nh = {{}}\nh[Set[{same}]] = :x\np [h[Set[{same}]], h.keys]"),
        19 => format!("p [{{ a: {n}, b: {m} }}.hash == {{ b: {m}, a: {n} }}.hash, {{ a: {n} }}.hash == {{ a: {n}.0 }}.hash]"),
        20 => format!("p [[{same}].hash == [{same}].hash, [{same}].hash == [{wide}].hash]"),
        21 => format!(
            "S = Struct.new(:a)\np [S.new({same}).eql?(S.new({same})), S.new({same}).eql?(S.new({wide}))]"
        ),
        22 => format!(
            "D = Data.define(:a)\np [D.new(a: {same}).eql?(D.new(a: {same})), D.new(a: {same}).eql?(D.new(a: {wide}))]"
        ),
        _ => format!("p [{same}.eql?({wide}), {same} == {wide}, [{same}] == [{wide}], [{same}].eql?([{wide}])]"),
    })
}

/// Comparison ACROSS the numeric classes, which `bignum` never reached — its
/// four arms only ever build one big integer and print it, so no case ever put
/// a BigInt, a Rational or a Complex on one side of a comparison and a Float on
/// the other. Ruby's rule is not "convert both to Float": `Integer == Float` is
/// EXACT, so `(10**23) == 1e23` is false while `(10**23).to_f == 1e23` is true,
/// and `Rational == Float` really is `to_f`-lossy, so `Rational(1, 3) == 1.0/3`
/// is true. Every case prints an equality beside the ordering of the same pair,
/// so an implementation that answers one with the other is caught.
fn gen_numwide(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let e = r.range(20, 90);
    let base = r.pick(&["2", "3", "7", "10"]);
    let big = format!("{base}**{e}");
    let (n, d) = (r.range(1, 9), r.range(2, 9));
    one(match r.below(18) {
        0 => format!("p [{big} == ({big}).to_f, ({big}).to_f == {big}]"),
        1 => format!("p [{big} == ({big}).to_f + 1, {big} + 1 == ({big}).to_f]"),
        2 => format!("p [{big} != ({big}).to_f, {big} != ({big}).to_f * 2]"),
        3 => format!("p [{big} <=> ({big}).to_f, {big} <=> ({big}).to_f * 2]"),
        4 => format!("p [({big}).to_f <=> {big}, {big} <=> {big}]"),
        5 => format!("p [{big} < ({big}).to_f * 2, {big} > ({big}).to_f / 2]"),
        6 => format!("p [{big} <= ({big}).to_f, {big} >= ({big}).to_f]"),
        7 => format!("p [{big} == Float::INFINITY, {big} < Float::INFINITY]"),
        8 => format!("p [{big} == Float::NAN, {big} <=> Float::NAN]"),
        9 => format!("p [Rational({n}, {d}) == {n}.0 / {d}, Rational({n}, {d}) == 0.0]"),
        10 => format!("p [{n}.0 / {d} == Rational({n}, {d}), Rational({n}, {d}) <=> {n}.0 / {d}]"),
        11 => format!("p [Rational({n}, 1) == {n}, Rational({n}, 1) == {n}.0]"),
        12 => format!("p [Complex({n}, 0) == {n}.0, Complex({n}, 1) == {n}.0]"),
        13 => format!("p [{n}.0 == Complex({n}, 0), Complex({n}.0, 0) == {n}]"),
        14 => format!("p [{big} == Rational({big}, 1), Rational({big}, 1) == ({big}).to_f]"),
        15 => format!("p [({big}).eql?(({big}).to_f), ({big}).eql?({big})]"),
        16 => format!("p [[{big}, ({big}).to_f].uniq.size, [{big}, {big}].uniq.size]"),
        _ => format!("p [({big}).coerce(1.0), ({big}).coerce(1)]"),
    })
}

fn gen_case(seed: u64, mode: Mode) -> Vec<String> {
    match mode {
        Mode::Arith => gen_arith(seed),
        Mode::Bignum => gen_bignum(seed),
        Mode::Floatfmt => gen_floatfmt(seed),
        Mode::Strings => gen_strings(seed),
        Mode::Interp => gen_interp(seed),
        Mode::Ranges => gen_ranges(seed),
        Mode::Arraymeth => gen_arraymeth(seed),
        Mode::Hashmeth => gen_hashmeth(seed),
        Mode::Sorting => gen_sorting(seed),
        Mode::Formatspec => gen_formatspec(seed),
        Mode::Blocks => gen_blocks(seed),
        Mode::Symbols => gen_symbols(seed),
        Mode::Ternary => gen_ternary(seed),
        Mode::Comparison => gen_comparison(seed),
        Mode::Printf => gen_printf(seed),
        Mode::StringOps => gen_string_ops(seed),
        Mode::Caseexpr => gen_caseexpr(seed),
        Mode::Intmeth => gen_intmeth(seed),
        Mode::Regex => gen_regex(seed),
        Mode::Enumerable => gen_enumerable(seed),
        Mode::Exceptions => gen_exceptions(seed),
        Mode::Struct => gen_struct(seed),
        Mode::Rational => gen_rational(seed),
        Mode::Patternmatch => gen_patternmatch(seed),
        Mode::Kernelconv => gen_kernelconv(seed),
        Mode::Loopflow => gen_loopflow(seed),
        Mode::Hashenum => gen_hashenum(seed),
        Mode::Enumext => gen_enumext(seed),
        Mode::Kwargs => gen_kwargs(seed),
        Mode::Metaprog => gen_metaprog(seed),
        Mode::Mixins => gen_mixins(seed),
        Mode::Lambda => gen_lambda(seed),
        Mode::Enumlazy => gen_enumlazy(seed),
        Mode::Setops => gen_setops(seed),
        Mode::Frozen => gen_frozen(seed),
        Mode::Datacls => gen_datacls(seed),
        Mode::Strenc => gen_strenc(seed),
        Mode::Complexnum => gen_complexnum(seed),
        Mode::Objintro => gen_objintro(seed),
        Mode::Blockflow => gen_blockflow(seed),
        Mode::Methobj => gen_methobj(seed),
        Mode::Multiyield => gen_multiyield(seed),
        Mode::Eqlident => gen_eqlident(seed),
        Mode::Numwide => gen_numwide(seed),
        Mode::Typeerr => gen_typeerr(seed),
        Mode::Timefmt => gen_timefmt(seed),
        Mode::Bytestr => gen_bytestr(seed),
        Mode::Packfmt => gen_packfmt(seed),
        Mode::Trsets => gen_trsets(seed),
        Mode::Strcase => gen_strcase(seed),
        Mode::Strpart => gen_strpart(seed),
        Mode::Arrreshape => gen_arrreshape(seed),
        Mode::Numprec => gen_numprec(seed),
        Mode::Objmodel => gen_objmodel(seed),
        Mode::Intbits => gen_intbits(seed),
        Mode::Structinit => gen_structinit(seed),
        Mode::Hashdefault => gen_hashdefault(seed),
        Mode::Refinement => gen_refinement(seed),
        Mode::Kwsplat => gen_kwsplat(seed),
        Mode::Heredoc => gen_heredoc(seed),
        Mode::Toplevelpriv => gen_toplevelpriv(seed),
        Mode::Raiseforms => gen_raiseforms(seed),
        Mode::Rangeedge => gen_rangeedge(seed),
        Mode::All => gen_case(seed, ALL_MODES[(seed as usize) % ALL_MODES.len()]),
    }
}

/// Lambda-vs-proc semantics: strict arity (a lambda raises where a block binds
/// nil), no auto-splat, keyword/splat/block parameters, `arity`, `curry`,
/// composition, `define_method` bodies, and `Method` objects. The arity check
/// runs before the body, so the probe distinguishes "raised" from "ran".
fn gen_lambda(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (r.range(0, 9), r.range(0, 9));
    let guard =
        |body: &str| format!("begin\n  p({body})\nrescue ArgumentError => e\n  p e.message\nend");
    one(match r.below(24) {
        0 => guard(&format!("->(x, y) {{ [x, y] }}.call({a})")),
        1 => guard(&format!("->(x, y) {{ [x, y] }}.call({a}, {b}, 1)")),
        2 => guard(&format!("->(x, y = {b}) {{ [x, y] }}.call({a})")),
        3 => guard(&format!("->(x, *r) {{ [x, r] }}.call({a}, {b})")),
        4 => guard("->(x, *r) { [x, r] }.call"),
        5 => guard(&format!("->(k:) {{ k }}.call(k: {a})")),
        6 => guard("->(k:) { k }.call"),
        7 => guard(&format!("->(k:) {{ k }}.call(k: {a}, j: {b})")),
        8 => guard(&format!("->(x, k: {b}) {{ [x, k] }}.call({a})")),
        9 => guard(&format!("->(x, **o) {{ [x, o] }}.call({a}, z: {b})")),
        10 => guard(&format!("proc {{ |x, y| [x, y] }}.call({a})")),
        11 => guard(&format!("proc {{ |x, y| [x, y] }}.call({a}, {b}, 1)")),
        12 => guard(&format!("lambda {{ |x, y| [x, y] }}.call({a})")),
        13 => guard(&format!("[[{a}, {b}]].map(&->(x, y) {{ x + y }})")),
        14 => guard(&format!("[[{a}, {b}]].map {{ |x, y| x + y }}")),
        15 => "p [->(){}.arity, ->(x){}.arity, ->(x, y = 1){}.arity, ->(*a){}.arity, ->(k:){}.arity, ->(k: 1){}.arity]".to_string(),
        16 => "p [proc{}.arity, proc{|x|}.arity, proc{|x, y = 1|}.arity, proc{|*a|}.arity, proc{|k: 1|}.arity]".to_string(),
        17 => format!("p ->(x, y) {{ x + y }}.curry[{a}][{b}]"),
        18 => guard(&format!("->(x, y) {{ x + y }}.curry.call({a}, {b}, 1)")),
        19 => format!("f = ->(x) {{ x + {a} }} >> ->(y) {{ y * 2 }}\np [f.call({b}), f.lambda?]"),
        20 => format!(
            "class C\n  define_method(:m) {{ |x, y| [x, y] }}\nend\nbegin\n  p C.new.m({a})\nrescue ArgumentError => e\n  p e.message\nend"
        ),
        21 => format!(
            "def m(x, y) = [x, y]\nbegin\n  p method(:m).call({a})\nrescue ArgumentError => e\n  p e.message\nend\np [method(:m).arity, method(:m).to_proc.lambda?]"
        ),
        22 => format!("p ->(&b) {{ b.call({a}) }}.call {{ |v| v * 2 }}"),
        _ => format!(
            "p [(->(x) {{ x > {a} }} === {b}), (case {b} when ->(x) {{ x > {a} }} then :hi else :lo end)]"
        ),
    })
}

/// Enumerator shape and laziness: which methods answer an Enumerator, the
/// grouping methods (`chunk`/`chunk_while`/`slice_when`/`each_slice`/
/// `each_cons`), — the part that used to hang — block-less enumerator
/// methods over an INFINITE source, bounded by `first`/`take`/`next`, and
/// `Enumerator::Lazy#uniq` (cases 22-25).
///
/// `uniq` is the one lazy stage that has to carry state ACROSS elements, so it
/// cannot be expressed by the per-element map/filter shape the other stages
/// share. Over an infinite source (`(1..)` mapped into a small residue set) it
/// is also the case that proves the stage stays lazy: a `uniq` that materializes
/// its source first cannot terminate at all, so it fails by hanging rather than
/// by answering wrong. The block form (`uniq { }`) keys on the block's value but
/// yields the ORIGINAL element, which a keyless implementation gets wrong.
fn gen_enumlazy(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let n = r.range(1, 3);
    let k = r.range(2, 4);
    let arr = "[1, 2, 4, 5, 7]";
    let gen = "e = Enumerator.new { |y| i = 0; loop { y << i; i += 1 } }";
    // Modulus of the residue map feeding the infinite-source uniq cases.
    // `x % m` over `(1..)` yields exactly `m` distinct values, and the case that
    // also rejects one yields `m - 1`, so the bound below asks for FEWER than
    // that. Asking for more does not diverge — it does not terminate, in MRI as
    // much as here, and the run is spent on two timeouts instead of a result.
    let m = r.range(3, 6);
    let j = k.min(m - 1);
    one(match r.below(26) {
        0 => format!("p {arr}.each_slice({k}).class"),
        1 => format!("p {arr}.each_cons({k}).class"),
        2 => format!("p {arr}.chunk_while {{ |a, b| b == a + 1 }}.class"),
        3 => format!("p {arr}.slice_when {{ |a, b| b > a + 1 }}.class"),
        4 => format!("p {arr}.chunk {{ |x| x.even? }}.class"),
        5 => format!("p {arr}.each_slice({k}).to_a"),
        6 => format!("p {arr}.each_cons({k}).to_a"),
        7 => format!("p {arr}.chunk_while {{ |a, b| b == a + 1 }}.to_a"),
        8 => format!("p {arr}.slice_when {{ |a, b| b > a + 1 }}.to_a"),
        9 => format!("p {arr}.chunk {{ |x| x.even? }}.to_a"),
        10 => {
            format!("begin\n  p {arr}.chunk_while\nrescue ArgumentError => e\n  p e.message\nend")
        }
        11 => format!("begin\n  p {arr}.slice_when\nrescue ArgumentError => e\n  p e.message\nend"),
        12 => format!("{gen}\np e.first({k})"),
        13 => format!("{gen}\np e.take({k})"),
        14 => format!("{gen}\np e.each_slice({n}).first({k})"),
        15 => format!("{gen}\np e.each_cons({n}).first({k})"),
        16 => format!("{gen}\np e.each_with_index.first({k})"),
        17 => format!("{gen}\np e.map.first({k})"),
        18 => format!("{gen}\np e.each_with_object([]).first({n})"),
        19 => format!("p (1..).each_slice({n}).first({k})"),
        20 => format!("p (1..).each_with_index.first({k})"),
        21 => format!("p (1..Float::INFINITY).each_cons({n}).first({k})"),
        // Finite source: `to_a` forces the whole pipeline, so the stage's output
        // ORDER is pinned too (Ruby keeps first-occurrence order).
        22 => "p [1, 1, 2, 4, 2, 1, 5].lazy.uniq.to_a".to_string(),
        // Keyed by the block, yielding the original element.
        23 => format!("p {arr}.lazy.uniq {{ |x| x % {m} }}.to_a"),
        // Infinite source, bounded by `first`: only a genuinely lazy `uniq`
        // terminates.
        24 => format!("p (1..).lazy.map {{ |x| x % {m} }}.uniq.first({j})"),
        // Composed with the stages either side of it.
        _ => format!(
            "p (1..).lazy.map {{ |x| x % {m} }}.uniq.map {{ |x| x * 2 }}.reject {{ |x| x == 0 }}.first({j})"
        ),
    })
}

/// `Set`: construction, the algebra operators, mutation, and the predicates —
/// plus `<=>` (cases 16-20).
///
/// `Set#<=>` is a SUBSET-RELATION comparison, not an ordering: `0` when the sets
/// are equal, `-1`/`1` for a proper subset/superset, and `nil` whenever neither
/// contains the other or the operand is not a Set. The subset PREDICATES
/// (`subset?`/`<=`, case 6) can all be right while `<=>` is wrong, because a
/// Set that falls through to `Array#<=>` still answers `-1`/`0`/`1` — just
/// element-wise and ordered, and it never answers `nil`. So the incomparable
/// pair and the non-Set operand are the two cases that actually discriminate.
fn gen_setops(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (r.range(1, 5), r.range(1, 5));
    let pre = "require \"set\"";
    one(match r.below(21) {
        0 => format!("{pre}\np Set.new([{a}, {b}, {a}]).to_a.sort"),
        1 => format!("{pre}\np (Set[{a}, {b}] | Set[3, 4]).to_a.sort"),
        2 => format!("{pre}\np (Set[{a}, {b}, 3] & Set[3, 4]).to_a.sort"),
        3 => format!("{pre}\np (Set[{a}, {b}, 3] - Set[3]).to_a.sort"),
        4 => format!("{pre}\np (Set[{a}, {b}] ^ Set[{b}, 9]).to_a.sort"),
        5 => format!("{pre}\np Set[{a}, {b}].include?({a})"),
        6 => {
            format!("{pre}\np [Set[{a}].subset?(Set[{a}, {b}]), Set[{a}, {b}].superset?(Set[{a}])]")
        }
        7 => {
            format!("{pre}\ns = Set.new\ns << {a}\ns.add({b})\ns.add({a})\np [s.size, s.to_a.sort]")
        }
        8 => format!("{pre}\ns = Set[{a}, {b}, 3]\ns.delete({a})\np s.to_a.sort"),
        9 => format!("{pre}\np Set[{a}, {b}].map {{ |x| x * 2 }}.sort"),
        10 => format!("{pre}\np Set[{a}, {b}].select(&:even?).to_a.sort"),
        11 => format!("{pre}\np [Set[{a}].empty?, Set.new.empty?]"),
        12 => format!("{pre}\np (Set[{a}, {b}] == Set[{b}, {a}])"),
        13 => format!("{pre}\np Set[{a}, {b}].disjoint?(Set[7, 8])"),
        14 => format!("{pre}\np Set[{a}, {b}].to_a.sum"),
        15 => format!("{pre}\np Set.new([{a}, {b}]).each_with_object([]) {{ |x, m| m << x }}.sort"),
        // Proper subset / proper superset / equal-ignoring-order.
        16 => format!("{pre}\np (Set[{a}, {b}] <=> Set[{a}, {b}, 9])"),
        17 => format!("{pre}\np (Set[{a}, {b}, 9] <=> Set[{a}, {b}])"),
        18 => format!("{pre}\np (Set[{a}, {b}] <=> Set[{b}, {a}])"),
        // Incomparable unless a == b — the case an ordered fallback gets wrong.
        19 => format!("{pre}\np [Set[{a}, 7] <=> Set[{b}, 8], Set[] <=> Set[{a}]]"),
        // A non-Set operand is `nil`, never an Array comparison.
        _ => format!("{pre}\np [Set[{a}, {b}] <=> [{a}, {b}], Set[{a}] <=> {b}]"),
    })
}

/// `freeze`/`frozen?` and the `FrozenError` a mutation of a frozen object
/// raises, plus how `dup`/`clone` carry (or drop) the frozen flag.
fn gen_frozen(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, w) = (r.range(1, 9), ww(r));
    one(match r.below(16) {
        0 => format!("p [{a}.frozen?, :{w}.frozen?, nil.frozen?, true.frozen?]"),
        1 => format!("p \"{w}\".freeze.frozen?"),
        2 => format!("p [{a}, {a}].freeze.frozen?"),
        3 => format!("p({{ a: {a} }}.freeze.frozen?)"),
        4 => format!("begin\n  [{a}] .freeze << 1\nrescue => e\n  p e.class\nend"),
        5 => format!("begin\n  \"{w}\".freeze << \"x\"\nrescue => e\n  p e.class\nend"),
        6 => format!("begin\n  h = {{ a: {a} }}.freeze\n  h[:b] = 1\nrescue => e\n  p e.class\nend"),
        7 => format!("s = \"{w}\".freeze\np [s.dup.frozen?, s.clone.frozen?]"),
        8 => format!("s = \"{w}\".freeze\np s.clone(freeze: false).frozen?"),
        9 => format!("a = [{a}].freeze\np [a.dup.frozen?, a.frozen?]"),
        10 => format!("class C; end\nc = C.new.freeze\nbegin\n  c.instance_variable_set(:@x, {a})\nrescue => e\n  p e.class\nend"),
        11 => format!("p \"{w}\".frozen?"),
        12 => format!("p [{a}.freeze.equal?({a}), :{w}.freeze.equal?(:{w})]"),
        13 => format!("a = [{a}, {a} + 1].freeze\np a.map {{ |x| x * 2 }}"),
        14 => format!("p [(1..{a}).frozen?, ({a}..).frozen?]"),
        _ => format!("s = \"{w}\"\ns.freeze\np [s.frozen?, s.upcase.frozen?]"),
    })
}

/// A TYPE-MISMATCHED operand — the question no other generator asks.
///
/// Every generator in this file builds a well-typed program, so a builtin that
/// silently coerced a bad operand agreed with the reference on every case they
/// can emit. `"ab" * nil` answered `""`, `[1,2].first(nil)` answered `[]`,
/// `1 / "a"` answered `Infinity`: wrong values on a ZERO exit status, which is
/// exactly what `differs` compares — the generators, not the comparison, were
/// the blind spot.
///
/// The probe prints the exception class AND its message, so a divergence in
/// either lands on stdout where it is compared by default, rather than only in
/// stderr (off unless `--stderr`). Operands are restricted to values whose
/// `inspect` is stable: no bare `Object.new`, whose address would differ.
fn gen_typeerr(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let bad = ["nil", "\"x\"", ":s", "true", "false", "[]", "{}", "1.5"];
    let b = *r.pick(&bad);
    let w = ww(r);
    let n = r.range(1, 4);
    // Wrap so BOTH outcomes reach stdout: a raise prints class + message, and a
    // wrong-but-successful answer prints the value the call produced.
    let probe =
        |expr: &str| format!("begin\n  p({expr})\nrescue => e\n  p [e.class, e.message]\nend");
    one(match r.below(22) {
        0 => probe(&format!("\"{w}\" * {b}")),
        1 => probe(&format!("\"{w}\" + {b}")),
        2 => probe(&format!("\"{w}\".dup << {b}")),
        3 => probe(&format!("\"{w}\"[{b}]")),
        4 => probe(&format!("\"{w}\".center({b})")),
        5 => probe(&format!("\"{w}\".ljust({b})")),
        6 => probe(&format!("\"{w}\".rjust({b})")),
        7 => probe(&format!("[{n}, {n} + 1] * {b}")),
        8 => probe(&format!("[{n}, {n} + 1][{b}]")),
        9 => probe(&format!("[{n}, {n} + 1].first({b})")),
        10 => probe(&format!("[{n}, {n} + 1].last({b})")),
        11 => probe(&format!("[{n}, {n} + 1].take({b})")),
        12 => probe(&format!("[{n}, {n} + 1].drop({b})")),
        13 => probe(&format!("[{n}, {n} + 1].fetch({b})")),
        14 => probe(&format!("[{n}, {n} + 1].rotate({b})")),
        15 => probe(&format!("[{n}] + {b}")),
        16 => probe(&format!("{{ a: {n} }}.merge({b})")),
        17 => probe(&format!("{n} + {b}")),
        18 => probe(&format!("{n} / {b}")),
        19 => probe(&format!("{n} % {b}")),
        20 => probe(&format!("{n}.gcd({b})")),
        _ => probe(&format!("Array.new({b})")),
    })
}

/// `Time` formatting over a FIXED epoch.
///
/// The determinism invariant at the top of this file bans `Time`, and that ban
/// was read as covering the whole class — so no generator ever produced one,
/// and ten `strftime` directives sat unimplemented, `%c` emitting the two
/// characters `%c`. But only the CLOCK is nondeterministic: `Time.at(<const>)`
/// is as fixed as any integer literal. Every case here pins the epoch and calls
/// `.utc`, which also keeps the machine's `TZ` out of the comparison.
fn gen_timefmt(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    // Epochs chosen to cover ISO-week year boundaries, a leap day, and a
    // single-digit day/hour (where `%c`/`%v`/`%e` space-pad).
    const EPOCHS: &[&str] = &[
        "0",
        "1234567890",
        "946684800",
        "1104537600",
        "1230768000",
        "1262304000",
        "1609459200",
        "1709164800",
        "-86400",
        "2147483647",
        "1199059200",
        "1451606400",
    ];
    const DIRECTIVES: &[&str] = &[
        "%Y-%m-%d",
        "%H:%M:%S",
        "%c",
        "%x",
        "%X",
        "%r",
        "%v",
        "%N",
        "%L",
        "%U",
        "%W",
        "%V",
        "%G",
        "%g",
        "%j",
        "%u",
        "%w",
        "%a %b",
        "%A %B",
        "%F %T",
        "%D",
        "%R",
        "%e",
        "%k",
        "%l",
        "%I %p",
        "%C",
        "%y",
        "%s",
        "%-d/%-m",
        "%_d|%0e",
        "%G-W%V-%u",
        "%%Y",
        "%n%t",
    ];
    let e = *r.pick(EPOCHS);
    let d = *r.pick(DIRECTIVES);
    let t = format!("Time.at({e}).utc");
    one(match r.below(6) {
        0 => format!("p {t}.strftime({d:?})"),
        1 => format!("p [{t}.year, {t}.month, {t}.day]"),
        2 => format!("p [{t}.hour, {t}.min, {t}.sec]"),
        3 => format!("p [{t}.wday, {t}.yday, {t}.leap?]"),
        4 => format!("p [{t}.to_i, {t}.utc?, {t}.monday?]"),
        _ => format!("p {t}.strftime({:?})", format!("{d}|{d}")),
    })
}

/// `Data.define` value objects (Ruby 3.2+): construction both ways, `with`,
/// equality, deconstruction and the errors a bad call raises.
fn gen_datacls(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (r.range(0, 9), r.range(0, 9));
    let d = "P = Data.define(:x, :y)";
    one(match r.below(14) {
        0 => format!("{d}\np P.new(x: {a}, y: {b}).to_h"),
        1 => format!("{d}\np P.new({a}, {b}).to_h"),
        2 => format!("{d}\np [P.new({a}, {b}).x, P.new({a}, {b}).y]"),
        3 => format!("{d}\np P.new({a}, {b}) == P.new({a}, {b})"),
        4 => format!("{d}\np P.new({a}, {b}).with(y: {b} + 1).to_h"),
        5 => format!("{d}\np P.members"),
        6 => format!("{d}\nbegin\n  P.new({a})\nrescue ArgumentError => e\n  p e.class\nend"),
        7 => {
            format!("{d}\nbegin\n  P.new({a}, {b}, 1)\nrescue ArgumentError => e\n  p e.class\nend")
        }
        8 => format!("{d}\np(case P.new({a}, {b})\n  in {{ x:, y: }} then [x, y]\n  end)"),
        9 => format!("{d}\np P.new({a}, {b}).frozen?"),
        10 => format!("{d}\np P.new({a}, {b}).deconstruct_keys([:x])"),
        11 => format!("{d}\np P.new({a}, {b}).inspect.include?(\"x=\")"),
        12 => format!("{d}\np [P.new({a}, {b}).hash == P.new({a}, {b}).hash]"),
        _ => format!(
            "{d}\nbegin\n  P.new(x: {a}, z: {b})\nrescue ArgumentError => e\n  p e.class\nend"
        ),
    })
}

/// String bytes/chars/encoding: the places a multibyte string makes character
/// count, byte count and index disagree.
fn gen_strenc(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let s = r.pick(&["héllo", "naïve", "日本語", "aéb", "straße", "abc"]);
    let n = r.range(0, 3);
    one(match r.below(16) {
        0 => format!("p \"{s}\".length"),
        1 => format!("p \"{s}\".bytesize"),
        2 => format!("p \"{s}\".bytes.size"),
        3 => format!("p \"{s}\".chars"),
        4 => format!("p \"{s}\".encoding.to_s"),
        5 => format!("p \"{s}\".valid_encoding?"),
        6 => format!("p \"{s}\"[{n}]"),
        7 => format!("p \"{s}\".reverse"),
        8 => format!("p \"{s}\".upcase"),
        9 => format!("p \"{s}\".each_char.to_a.size"),
        10 => format!("p \"{s}\".each_byte.to_a.size"),
        11 => format!("p \"{s}\".b.encoding.to_s"),
        12 => format!("p \"{s}\".codepoints.size"),
        13 => format!("p \"{s}\".sub(/./, \"X\")"),
        14 => format!("p \"{s}\".scan(/./).size"),
        _ => format!("p \"{s}\".slice({n}, 2)"),
    })
}

/// Byte strings and the encoding TAG that rides along with them: `Integer#chr`,
/// `Array#pack`, `String#b` and `force_encoding`, plus the derived strings
/// (`dup`, `+`, `*`, `split`, `[]`, …) that have to carry the tag forward.
///
/// The tag is observable two ways and both are probed, because they fail
/// independently: `#encoding.to_s` names it, and `#inspect` picks its escape
/// form from it — MRI writes `\xNN` for a non-UTF-8 string where it writes
/// `\uXXXX` for UTF-8, so `p 255.chr` is `"\xFF"` while `p "ÿ"` is `"ÿ"`.
/// A mode that only printed `.encoding` would miss every inspect divergence,
/// and one that only printed the string would miss a tag that is wrong but
/// invisible on ASCII content.
///
/// Byte values span the three ranges MRI treats differently: 0..0x1f (control,
/// some with named escapes), 0x20..0x7e (printed literally), and 0x7f..0xff
/// (never printable, and the half that separates US-ASCII from ASCII-8BIT).
fn gen_bytestr(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    // A byte from a range chosen first, so the low/printable/high classes each
    // get sampled instead of high bytes dominating 8:1.
    let byte = match r.below(3) {
        0 => r.range(0, 0x1f),
        1 => r.range(0x20, 0x7e),
        _ => r.range(0x7f, 0xff),
    };
    let b2 = r.range(0, 255);
    let enc = r.pick(&["BINARY", "ASCII-8BIT", "US-ASCII", "UTF-8"]);
    // NON-ASCII text is the point of half these cases. An ASCII-only `txt` makes
    // the two readings of a byte string agree, so it can never catch the bug the
    // byte-string representation invariant exists to prevent: `"é".b` must count
    // 2 bytes (`[195, 169]`) while `233.chr` counts 1 (`[233]`), and both are
    // `U+00E9`-adjacent. The first grammar sampled only `abc`-shaped words and so
    // reported a saturated mode over a surface it never reached.
    let txt = r.pick(&[
        "abc", "a b", "a,b", "hi", "Az", "héllo", "é", "aé,b", "日本",
    ]);
    let n = r.range(0, 3);
    one(match r.below(36) {
        0 => format!("p {byte}.chr"),
        1 => format!("p {byte}.chr.encoding.to_s"),
        2 => format!("p {byte}.chr.ord"),
        3 => format!("p [{byte}, {b2}].pack(\"C*\")"),
        4 => format!("p [{byte}, {b2}].pack(\"C*\").encoding.to_s"),
        5 => format!("p [{byte}, {b2}].pack(\"C*\").unpack(\"C*\")"),
        6 => format!("p [{byte}].pack(\"C*\").dup"),
        7 => format!("p [{byte}].pack(\"C*\") * 2"),
        8 => format!("p {byte}.chr + {b2}.chr"),
        9 => format!("p {byte}.chr.dup.encoding.to_s"),
        10 => format!("p \"{txt}\".b"),
        11 => format!("p \"{txt}\".b.encoding.to_s"),
        12 => format!("p \"{txt}\".force_encoding(\"{enc}\").encoding.to_s"),
        13 => format!("p \"{txt}\".b.upcase.encoding.to_s"),
        14 => format!("p \"{txt}\".b.reverse"),
        15 => format!("p \"{txt}\".b[{n}].to_s.encoding.to_s"),
        16 => format!("p \"{txt}\".b.split(\",\").map {{ |x| x.encoding.to_s }}"),
        17 => format!("p \"{txt}\".b.chars.map {{ |x| x.encoding.to_s }}"),
        18 => format!("p \"{txt}\".b.inspect.encoding.to_s"),
        19 => format!("p ([{byte}].pack(\"C*\") + \"{txt}\").encoding.to_s"),
        20 => format!("p [{byte}, {b2}].pack(\"C*\").bytes.size"),
        21 => format!("p {byte}.chr.b"),
        22 => format!("p \"{txt}\".b.sub(\"a\", \"z\")"),
        23 => format!("p [{byte}].pack(\"C*\").length"),
        // The byte readers. Each one reads the byte VIEW rather than the
        // storage, and they disagree with the storage exactly on the non-ASCII
        // `txt` values above.
        24 => format!("p \"{txt}\".b.bytes"),
        25 => format!("p [\"{txt}\".b.bytesize, \"{txt}\".bytesize]"),
        26 => format!("p [\"{txt}\".b.length, \"{txt}\".b.size]"),
        27 => format!("p \"{txt}\".b.each_byte.to_a"),
        28 => format!("p \"{txt}\".b.getbyte({n})"),
        29 => format!("p \"{txt}\".b.unpack(\"C*\")"),
        30 => format!("p \"{txt}\".b.byteslice({n}, 2)"),
        // Round trips: the storage must survive a tag it did not start with.
        31 => format!("p \"{txt}\".force_encoding(\"{enc}\").bytes"),
        32 => format!("p \"{txt}\".b.force_encoding(\"UTF-8\")"),
        // Character-oriented methods, which a byte string answers byte-wise.
        33 => format!("p [\"{txt}\".b == \"{txt}\", \"{txt}\".b.index(\"b\")]"),
        34 => format!("s = \"{txt}\".b\ns.setbyte(0, {byte})\np [s, s.bytes]"),
        // `rb_enc_compatible`'s failure case: two non-ASCII operands whose
        // encodings differ is a raise, not a negotiated answer.
        _ => format!("p(begin; ({byte}.chr + \"{txt}\"); rescue; $!.class.to_s; end)"),
    })
}

/// `Array#pack` / `String#unpack` across the DIRECTIVE surface, not just `C*`.
/// Each directive has its own width, endianness, padding and truncation rules,
/// and the string-valued ones (`a`/`A`/`Z`/`m`/`H`) are where a byte string
/// crosses back into text.
fn gen_packfmt(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b) = (r.range(0, 255), r.range(0, 65535));
    let big = r.range(0, 1 << 30);
    let neg = r.range(-128, 128);
    let w = r.pick(&["abc", "hi", "a", "abcdef", ""]);
    let count = r.pick(&["", "*", "2", "3"]);
    let intdir = r.pick(&[
        "C", "c", "S", "s", "L", "l", "Q", "q", "N", "n", "V", "v", "w",
    ]);
    let strdir = r.pick(&["a", "A", "Z", "H", "h", "B", "b", "m", "M", "u"]);
    one(match r.below(16) {
        0 => format!("p [{a}, {b}].pack(\"{intdir}{count}\").bytes"),
        1 => format!("p [{a}, {b}].pack(\"{intdir}{count}\").unpack(\"{intdir}{count}\")"),
        2 => format!("p [{neg}].pack(\"{intdir}\").bytes rescue p $!.class.to_s"),
        3 => format!("p [\"{w}\"].pack(\"{strdir}{count}\").bytes"),
        4 => format!("p [\"{w}\"].pack(\"{strdir}{count}\").unpack(\"{strdir}{count}\")"),
        5 => format!("p [{a}, {b}].pack(\"CN\").bytes"),
        6 => format!("p [{big}].pack(\"N\").unpack1(\"N\")"),
        7 => format!("p [{big}].pack(\"V\").bytes"),
        8 => format!("p [{a}].pack(\"C\").encoding.to_s"),
        9 => format!("p [\"{w}\"].pack(\"m0\")"),
        10 => format!("p [\"{w}\"].pack(\"m0\").unpack1(\"m0\")"),
        11 => format!("p [{a}, {b}].pack(\"x{intdir}\").bytes"),
        12 => format!("p [{big}].pack(\"{intdir}\").bytes rescue p $!.class.to_s"),
        13 => format!("p \"{w}\".unpack(\"{strdir}{count}\")"),
        14 => format!("p \"{w}\".unpack(\"C*\")"),
        _ => format!("p [{a}].pack(\"{intdir}\") * 2"),
    })
}

/// The `tr`/`delete`/`squeeze`/`count` family, whose argument is a character SET
/// with its own mini-language: `a-z` ranges, a leading `^` negation, `\\`
/// escapes, and a replacement string that is padded with its own last character
/// when it is shorter than the search set.
fn gen_trsets(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let w = r.pick(&[
        "hello",
        "aabbcc",
        "Mississippi",
        "a-b-c",
        "abc123",
        "AaBbCc",
        "  x  ",
        "^abc",
    ]);
    let from = r.pick(&[
        "a-y", "abc", "^abc", "a-z", "^a-z", "l", "aeiou", "A-Z", "-",
    ]);
    let to = r.pick(&["b-z", "*", "xyz", "ABC", "", "A-Z"]);
    let set = r.pick(&["a-z", "^a-z", "lo", "abc", "A-Za-z", "^ ", "s"]);
    one(match r.below(12) {
        0 => format!("p \"{w}\".tr(\"{from}\", \"{to}\")"),
        1 => format!("p \"{w}\".tr_s(\"{from}\", \"{to}\")"),
        2 => format!("p \"{w}\".delete(\"{set}\")"),
        3 => format!("p \"{w}\".squeeze"),
        4 => format!("p \"{w}\".squeeze(\"{set}\")"),
        5 => format!("p \"{w}\".count(\"{set}\")"),
        6 => format!("p \"{w}\".count(\"{set}\", \"{from}\")"),
        7 => format!("p \"{w}\".delete(\"{set}\", \"{from}\")"),
        8 => format!("s = \"{w}\".dup\np [s.tr!(\"{from}\", \"{to}\"), s]"),
        9 => format!("s = \"{w}\".dup\np [s.squeeze!, s]"),
        10 => format!("s = \"{w}\".dup\np [s.delete!(\"{set}\"), s]"),
        _ => format!("p \"{w}\".tr(\"{from}\", \"{to}\").tr(\"{to}\", \"{from}\")"),
    })
}

/// `Complex` arithmetic and conversion, where the real/imaginary parts keep
/// their own numeric types.
fn gen_complexnum(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, b, c, d) = (r.range(-4, 5), r.range(-4, 5), r.range(1, 5), r.range(1, 5));
    one(match r.below(14) {
        0 => format!("p Complex({a}, {b}) + Complex({c}, {d})"),
        1 => format!("p Complex({a}, {b}) - Complex({c}, {d})"),
        2 => format!("p Complex({a}, {b}) * Complex({c}, {d})"),
        3 => format!("p Complex({a}, {b}) / Complex({c}, {d})"),
        4 => format!("p [Complex({a}, {b}).real, Complex({a}, {b}).imaginary]"),
        5 => format!("p Complex({a}, {b}).conjugate"),
        6 => format!("p Complex({a}, {b}).abs2"),
        7 => format!("p Complex({a}, {b}) == Complex({a}, {b})"),
        8 => format!("p Complex({a}, {b}).to_s"),
        9 => format!("p ({a} + {b}i)"),
        10 => format!("p Complex({a}, 0).to_i"),
        11 => format!("p Complex({a}, {b}).rectangular"),
        12 => format!("p [Complex({a}, {b}).zero?, Complex(0, 0).zero?]"),
        _ => format!("p Complex({a}, {b}) * {c}"),
    })
}

/// Object introspection that needs no `ObjectSpace`: class/ancestry queries,
/// instance variables, method lists, and the `tap`/`then` value pipeline.
fn gen_objintro(seed: u64) -> Vec<String> {
    let r = &mut Rng::seed(seed);
    let (a, w) = (r.range(1, 9), ww(r));
    let cls =
        format!("class C\n  def initialize; @x = {a}; @y = \"{w}\"; end\n  def m(z) = z\nend");
    one(match r.below(18) {
        0 => format!("{cls}\np C.new.instance_variables.sort"),
        1 => format!("{cls}\np C.new.instance_variable_get(:@x)"),
        2 => format!("{cls}\np C.new.instance_variable_defined?(:@z)"),
        3 => format!("{cls}\np C.instance_methods(false).sort"),
        4 => format!("{cls}\np C.new.respond_to?(:m)"),
        5 => format!("{cls}\np [C.new.is_a?(C), C.new.is_a?(Object), C.new.kind_of?(Comparable)]"),
        6 => format!("{cls}\np C.ancestors.first(2).map(&:to_s)"),
        7 => format!("{cls}\np C.new.class.name"),
        8 => format!("p [{a}.class, \"{w}\".class, :{w}.class, nil.class, (1..2).class]"),
        9 => format!("p {a}.then {{ |x| x * 2 }}"),
        10 => format!("p [{a}].tap {{ |x| x << {a} }}"),
        11 => format!("{cls}\np C.new.methods.include?(:m)"),
        12 => format!("{cls}\np [C.new.respond_to?(:m), C.new.respond_to?(:nope)]"),
        13 => format!("{cls}\np C.superclass.to_s"),
        14 => "p Integer.ancestors.include?(Comparable)".to_string(),
        15 => format!(
            "{cls}\nc = C.new\nc.instance_variable_set(:@z, {a})\np c.instance_variable_get(:@z)"
        ),
        16 => format!("p [{a}.singleton_class.to_s.start_with?(\"#<Class\"), Integer.name]"),
        _ => format!("{cls}\np C.new.public_methods(false).sort"),
    })
}

fn mode_name(m: Mode) -> &'static str {
    match m {
        Mode::Arith => "arith",
        Mode::Bignum => "bignum",
        Mode::Floatfmt => "floatfmt",
        Mode::Strings => "strings",
        Mode::Interp => "interp",
        Mode::Ranges => "ranges",
        Mode::Arraymeth => "arraymeth",
        Mode::Hashmeth => "hashmeth",
        Mode::Sorting => "sorting",
        Mode::Formatspec => "formatspec",
        Mode::Blocks => "blocks",
        Mode::Symbols => "symbols",
        Mode::Ternary => "ternary",
        Mode::Comparison => "comparison",
        Mode::Printf => "printf",
        Mode::StringOps => "string_ops",
        Mode::Caseexpr => "caseexpr",
        Mode::Intmeth => "intmeth",
        Mode::Regex => "regex",
        Mode::Enumerable => "enumerable",
        Mode::Exceptions => "exceptions",
        Mode::Struct => "struct",
        Mode::Rational => "rational",
        Mode::Patternmatch => "patternmatch",
        Mode::Kernelconv => "kernelconv",
        Mode::Loopflow => "loopflow",
        Mode::Hashenum => "hashenum",
        Mode::Enumext => "enumext",
        Mode::Kwargs => "kwargs",
        Mode::Metaprog => "metaprog",
        Mode::Mixins => "mixins",
        Mode::Lambda => "lambda",
        Mode::Enumlazy => "enumlazy",
        Mode::Setops => "setops",
        Mode::Frozen => "frozen",
        Mode::Datacls => "datacls",
        Mode::Strenc => "strenc",
        Mode::Complexnum => "complexnum",
        Mode::Objintro => "objintro",
        Mode::Blockflow => "blockflow",
        Mode::Methobj => "methobj",
        Mode::Multiyield => "multiyield",
        Mode::Eqlident => "eqlident",
        Mode::Numwide => "numwide",
        Mode::Typeerr => "typeerr",
        Mode::Timefmt => "timefmt",
        Mode::Bytestr => "bytestr",
        Mode::Packfmt => "packfmt",
        Mode::Trsets => "trsets",
        Mode::Strcase => "strcase",
        Mode::Strpart => "strpart",
        Mode::Arrreshape => "arrreshape",
        Mode::Numprec => "numprec",
        Mode::Objmodel => "objmodel",
        Mode::Intbits => "intbits",
        Mode::Structinit => "structinit",
        Mode::Hashdefault => "hashdefault",
        Mode::Refinement => "refinement",
        Mode::Kwsplat => "kwsplat",
        Mode::Heredoc => "heredoc",
        Mode::Toplevelpriv => "toplevelpriv",
        Mode::Raiseforms => "raiseforms",
        Mode::Rangeedge => "rangeedge",
        Mode::All => "all",
    }
}

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

fn build_program(stmts: &[String]) -> String {
    stmts.join("\n")
}

/// True iff oracle and rubylang disagree on stdout or exit for `script`. Infra
/// failures (spawn/wait errors, timeouts) are NOT parity gaps.
fn diverges(script: &str, bin: &Path, timeout: Duration) -> bool {
    let o = run_oracle(script, timeout);
    if o.timed_out {
        return false;
    }
    let r = run_ours(script, bin, timeout);
    if r.exit == -999 || r.exit == -998 || r.timed_out || o.exit == -999 || o.exit == -998 {
        return false;
    }
    differs(&o, &r)
}

/// Delta-debug a diverging statement list to a locally-minimal one: repeatedly
/// drop any single statement whose removal preserves the divergence, to a
/// fixpoint.
fn minimize(stmts: Vec<String>, bin: &Path, timeout: Duration) -> Vec<String> {
    let mut cur = stmts;
    loop {
        let mut removed = false;
        let mut i = 0;
        while i < cur.len() {
            let mut cand = cur.clone();
            cand.remove(i);
            if !cand.is_empty() && diverges(&build_program(&cand), bin, timeout) {
                cur = cand;
                removed = true;
            } else {
                i += 1;
            }
        }
        if !removed {
            break;
        }
    }
    cur
}

/// Normalize a reproducer to a stable gap-class signature: keep the last
/// non-empty line (the probe), mask numeric literals and quoted words so many
/// instances of the same gap collapse to one signature.
fn signature(program: &str) -> String {
    let body = program
        .lines()
        .map(|l| l.trim())
        .rfind(|l| !l.is_empty())
        .unwrap_or("")
        .to_string();
    let mut s = body;
    for (pat, rep) in [
        (r"[0-9]+\.[0-9]+([eE][-+]?[0-9]+)?", "F"),
        (r"[0-9]+[eE][-+]?[0-9]+", "F"),
        (r"-?[0-9]+", "N"),
        ("\"[^\"]*\"", "W"),
        ("'[^']*'", "W"),
    ] {
        s = regex_lite_replace(&s, pat, rep);
    }
    s
}

fn regex_lite_replace(s: &str, pat: &str, rep: &str) -> String {
    match regex::Regex::new(pat) {
        Ok(re) => re.replace_all(s, rep).into_owned(),
        Err(_) => s.to_string(),
    }
}

// ---------------------------------------------------------------------------
// CLI.
// ---------------------------------------------------------------------------

struct Args {
    count: u64,
    base_seed: u64,
    once: bool,
    dump: bool,
    timeout_ms: u64,
    out_path: PathBuf,
    max_report: usize,
    jobs: usize,
    mode: Mode,
    verify: usize,
    baseline: Option<PathBuf>,
}

fn parse_args() -> Args {
    let mut count = 2000u64;
    let mut base_seed = 1u64;
    let mut once = false;
    let mut dump = false;
    let mut timeout_ms = 5000u64;
    let mut max_report = 200usize;
    let mut mode = Mode::Arith;
    let mut verify = 1usize;
    let mut baseline: Option<PathBuf> = None;
    let mut jobs = std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4);
    let mut out_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("target")
        .join("parity-fuzz")
        .join("divergences.txt");

    let argv: Vec<String> = std::env::args().skip(1).collect();
    let mut i = 0;
    while i < argv.len() {
        match argv[i].as_str() {
            "--count" | "-c" => {
                i += 1;
                count = argv.get(i).and_then(|s| s.parse().ok()).unwrap_or(count);
            }
            "--seed" | "-s" => {
                i += 1;
                base_seed = argv
                    .get(i)
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(base_seed);
            }
            "--once" => once = true,
            "--dump" => dump = true,
            "--timeout-ms" => {
                i += 1;
                timeout_ms = argv
                    .get(i)
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(timeout_ms);
            }
            "--out" | "-o" => {
                i += 1;
                if let Some(p) = argv.get(i) {
                    out_path = PathBuf::from(p);
                }
            }
            "--max-report" => {
                i += 1;
                max_report = argv
                    .get(i)
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(max_report);
            }
            "--jobs" | "-j" => {
                i += 1;
                jobs = argv
                    .get(i)
                    .and_then(|s| s.parse().ok())
                    .filter(|&j| j >= 1)
                    .unwrap_or(jobs);
            }
            "--mode" | "-m" => {
                i += 1;
                match argv.get(i).and_then(|s| mode_from_name(s)) {
                    Some(m) => mode = m,
                    None => {
                        eprintln!(
                            "unknown --mode '{}'",
                            argv.get(i).map(|s| s.as_str()).unwrap_or("")
                        );
                        std::process::exit(2);
                    }
                }
            }
            a if a.starts_with("--") && mode_from_name(&a[2..]).is_some() => {
                mode = mode_from_name(&a[2..]).unwrap();
            }
            "--verify" => {
                i += 1;
                verify = argv
                    .get(i)
                    .and_then(|s| s.parse().ok())
                    .filter(|&k| k >= 1)
                    .unwrap_or(verify);
            }
            "--baseline" => {
                i += 1;
                baseline = argv.get(i).map(PathBuf::from);
            }
            "--stderr" => {
                CMP_STDERR.store(true, Ordering::Relaxed);
            }
            "--help" | "-h" => {
                let modes: Vec<&str> = ALL_MODES.iter().copied().map(mode_name).collect();
                eprintln!(
                    "parity-fuzz — differential ruby/rubylang parity fuzzer\n\
                     \n\
                     --count N        number of cases (default 2000)\n\
                     --seed N         base seed; case i uses seed+i (default 1)\n\
                     --mode M         one of: {}\n\
                     --mode all       round-robin over every mode above\n\
                     (each also accepted as a `--<mode>` shorthand)\n\
                     --stderr         also require the diagnostics to match\n\
                     --once           run a single case (seed) and print both outputs\n\
                     --dump           print the generated programs and exit; runs\n\
                     \u{20}                nothing, so it cannot affect any result\n\
                     --timeout-ms N   per-interpreter wall-clock timeout (default 5000)\n\
                     --out PATH       divergence corpus file\n\
                     --max-report N   stop after N divergences (default 200)\n\
                     --jobs N         parallel workers (default = CPU count)\n\
                     --verify K       require K consecutive divergences to report (default 1)\n\
                     --baseline FILE  allowlist of known-gap signatures; only a NEW\n\
                                      divergence fails the run (exit 1)\n\
                     \n\
                     env  RUBYLANG_FUZZ_RUBY=PATH  the reference ruby to compare against.\n\
                                      The oracle is part of the result; every run prints it.",
                    modes.join(", ")
                );
                std::process::exit(0);
            }
            _ => {}
        }
        i += 1;
    }
    Args {
        count,
        base_seed,
        once,
        dump,
        timeout_ms,
        out_path,
        max_report,
        jobs,
        mode,
        verify,
        baseline,
    }
}

/// Warn when `bin` is older than the newest source file under `src/`.
///
/// A stale binary is the quietest way for a fuzz run to be meaningless: it
/// exercises the LAST build, so a fix made since then shows up as a divergence
/// that is already fixed, and a regression introduced since then does not show
/// up at all. Neither looks like an error — the run completes and prints a
/// number — so it is reported here rather than left to be noticed.
///
/// This warns rather than exits: running a deliberately older binary (bisecting
/// a regression, comparing two builds) is legitimate. It is the SILENCE that is
/// not.
fn warn_if_stale(bin: &Path) {
    let Ok(bin_time) = std::fs::metadata(bin).and_then(|m| m.modified()) else {
        return;
    };
    let src = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src");
    let mut newest: Option<(std::time::SystemTime, PathBuf)> = None;
    let mut stack = vec![src];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                // `src/bin/` holds the dev harnesses (this file included), which
                // are separate binaries: editing one does not make `ruby` stale,
                // and warning about it would cry wolf on every harness change.
                if path.file_name().map(|n| n != "bin").unwrap_or(true) {
                    stack.push(path);
                }
                continue;
            }
            if path.extension().map(|e| e != "rs").unwrap_or(true) {
                continue;
            }
            let Ok(t) = entry.metadata().and_then(|m| m.modified()) else {
                continue;
            };
            if newest.as_ref().map(|(n, _)| t > *n).unwrap_or(true) {
                newest = Some((t, path));
            }
        }
    }
    if let Some((t, path)) = newest {
        if t > bin_time {
            eprintln!(
                "parity-fuzz: WARNING — {} is OLDER than {}.\n\
                 parity-fuzz: this run measures the previous build; \
                 `cargo build` first for results about the current source.",
                bin.display(),
                path.display()
            );
        }
    }
}

fn main() {
    let args = parse_args();
    let bin = ours_bin();
    let timeout = Duration::from_millis(args.timeout_ms);

    if !bin.exists() {
        eprintln!(
            "rubylang binary not found at {}; run `cargo build` first",
            bin.display()
        );
        std::process::exit(2);
    }
    warn_if_stale(&bin);
    // Resolved and PRINTED before any case runs, not just in the closing
    // summary. The oracle is what every result means, so a run that resolved
    // the wrong one — or cannot resolve one at all, which exits here — must say
    // so at the point the run could still be stopped, rather than after the
    // last case. `--once` prints it too, for the same reason.
    eprintln!("parity-fuzz: oracle = {}", oracle_id());
    eprintln!("parity-fuzz: under test = {}", bin.display());

    // --dump: print what the generator PRODUCES, without running either
    // interpreter. A mode can look busy while every program it emits raises the
    // same error on both sides — which the differential loop scores as a pass,
    // because the two sides do agree. Reading the corpus is the only way to see
    // that, so this exists purely to be read. It spawns nothing and reports no
    // divergence count, so it cannot flatter a result.
    if args.dump {
        for i in 0..args.count {
            let seed = args.base_seed + i;
            let mode = if matches!(args.mode, Mode::All) {
                ALL_MODES[(i as usize) % ALL_MODES.len()]
            } else {
                args.mode
            };
            println!("=== seed {seed} mode {} ===", mode_name(mode));
            println!("{}", build_program(&gen_case(seed, mode)));
        }
        return;
    }

    // --once: replay a single seed, minimize if it diverges, dump both sides.
    if args.once {
        let stmts = gen_case(args.base_seed, args.mode);
        let script = build_program(&stmts);
        let o = run_oracle(&script, timeout);
        let r = run_ours(&script, &bin, timeout);
        let diverged = !o.timed_out && differs(&o, &r);
        println!("seed   : {}", args.base_seed);
        println!("mode   : {}", mode_name(args.mode));
        println!("oracle : {}", oracle_id());
        let (show, o, r) = if diverged && stmts.len() > 1 {
            let m = minimize(stmts, &bin, timeout);
            let ms = build_program(&m);
            let mo = run_oracle(&ms, timeout);
            let mr = run_ours(&ms, &bin, timeout);
            (ms, mo, mr)
        } else {
            (script, o, r)
        };
        println!("program:\n  {}", show.replace('\n', "\n  "));
        println!("--- ruby     exit={} timeout={} ---", o.exit, o.timed_out);
        let _ = std::io::stdout().write_all(&o.stdout);
        println!("--- rubylang exit={} timeout={} ---", r.exit, r.timed_out);
        let _ = std::io::stdout().write_all(&r.stdout);
        println!("--- {} ---", if diverged { "DIVERGE" } else { "match" });
        std::process::exit(if diverged { 1 } else { 0 });
    }

    use std::sync::atomic::AtomicU64;
    use std::sync::Mutex;

    let next = AtomicU64::new(0);
    let checked = AtomicU64::new(0);
    let timeouts = AtomicU64::new(0);
    let stop = AtomicBool::new(false);
    let divergences: Mutex<Vec<(u64, String)>> = Mutex::new(Vec::new());
    let start = Instant::now();

    eprintln!(
        "fuzzing {} cases across {} workers (mode {})…",
        args.count,
        args.jobs,
        mode_name(args.mode)
    );

    std::thread::scope(|scope| {
        for _ in 0..args.jobs {
            scope.spawn(|| loop {
                if stop.load(Ordering::Relaxed) {
                    break;
                }
                let idx = next.fetch_add(1, Ordering::Relaxed);
                if idx >= args.count {
                    break;
                }
                let seed = args.base_seed.wrapping_add(idx);
                let stmts = gen_case(seed, args.mode);
                let script = build_program(&stmts);
                let o = run_oracle(&script, timeout);
                let r = run_ours(&script, &bin, timeout);
                let done = checked.fetch_add(1, Ordering::Relaxed) + 1;
                if o.timed_out || r.timed_out {
                    timeouts.fetch_add(1, Ordering::Relaxed);
                }
                // oracle-side timeout ⇒ pathological case; not a parity gap.
                if !o.timed_out && differs(&o, &r) {
                    let minimal = minimize(stmts, &bin, timeout);
                    let mscript = build_program(&minimal);
                    let mo = run_oracle(&mscript, timeout);
                    let mr = run_ours(&mscript, &bin, timeout);
                    // Re-verify: a real gap diverges every time; a transient
                    // won't reproduce. Require `verify` consecutive divergences.
                    let mut confirmed = differs(&mo, &mr);
                    for _ in 1..args.verify.max(1) {
                        if !confirmed {
                            break;
                        }
                        confirmed = diverges(&mscript, &bin, timeout);
                    }
                    if !confirmed {
                        return; // continue loop iteration
                    }
                    let err_of = |o: &RunOut| -> String {
                        if CMP_STDERR.load(Ordering::Relaxed) {
                            format!(
                                "\n  stderr: {}",
                                render(&norm_stderr(&o.stderr)).replace('\n', "\n  ")
                            )
                        } else {
                            String::new()
                        }
                    };
                    let rec = format!(
                        "==== seed {seed} ====\n\
                         program:\n  {}\n\
                         ruby     : exit={} timeout={}{}\n{}\n\
                         rubylang : exit={} timeout={}{}\n{}\n",
                        mscript.replace('\n', "\n  "),
                        mo.exit,
                        mo.timed_out,
                        err_of(&mo),
                        render(&mo.stdout),
                        mr.exit,
                        mr.timed_out,
                        err_of(&mr),
                        render(&mr.stdout),
                    );
                    let mut d = divergences.lock().unwrap();
                    d.push((seed, rec));
                    if d.len() >= args.max_report {
                        stop.store(true, Ordering::Relaxed);
                    }
                }
                if done % 500 == 0 {
                    let n = divergences.lock().unwrap().len();
                    eprintln!(
                        "  {done}/{} checked, {n} divergences, {:.0}/s",
                        args.count,
                        done as f64 / start.elapsed().as_secs_f64().max(0.001)
                    );
                }
            });
        }
    });

    let checked = checked.load(Ordering::Relaxed);
    let timeouts = timeouts.load(Ordering::Relaxed);
    let mut divergences: Vec<(u64, String)> = divergences.into_inner().unwrap();
    divergences.sort_by_key(|(seed, _)| *seed);
    let divergences: Vec<String> = divergences.into_iter().map(|(_, r)| r).collect();
    let elapsed = start.elapsed();

    let sig_of = |rec: &str| -> String {
        let prog = rec
            .split("program:\n")
            .nth(1)
            .and_then(|s| s.split("\nruby     :").next())
            .unwrap_or(rec);
        signature(prog)
    };

    let allowed: std::collections::HashSet<String> = match &args.baseline {
        Some(bp) => std::fs::read_to_string(bp)
            .unwrap_or_default()
            .lines()
            .map(|l| l.trim().to_string())
            .filter(|l| !l.is_empty() && !l.starts_with('#'))
            .collect(),
        None => std::collections::HashSet::new(),
    };
    let mut new_records: Vec<&String> = Vec::new();
    let mut new_sigs: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    let mut known = 0usize;
    for rec in &divergences {
        let sig = sig_of(rec);
        if args.baseline.is_some() && allowed.contains(&sig) {
            known += 1;
        } else {
            new_records.push(rec);
            new_sigs.insert(sig);
        }
    }

    let oracle = oracle_id();
    println!(
        "\nfuzzed {checked} cases in {:.1}s ({:.0}/s)\n\
         oracle      : {}\n\
         divergences : {} ({} known / {} new)\n\
         timeouts    : {}",
        elapsed.as_secs_f64(),
        checked as f64 / elapsed.as_secs_f64().max(0.001),
        oracle,
        divergences.len(),
        known,
        new_records.len(),
        timeouts,
    );

    if !divergences.is_empty() {
        if let Some(parent) = args.out_path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        if let Ok(mut f) = std::fs::File::create(&args.out_path) {
            let _ = writeln!(f, "# oracle: {oracle}");
            for d in &divergences {
                let _ = writeln!(f, "{d}");
            }
            println!(
                "wrote {} divergences to {}",
                divergences.len(),
                args.out_path.display()
            );
        }
    }

    if !new_records.is_empty() {
        println!(
            "\n--- {} NEW gap signature(s) (add to baseline once triaged) ---",
            new_sigs.len()
        );
        for s in &new_sigs {
            println!("{s}");
        }
        println!(
            "\n--- first {} new divergence record(s) ---",
            new_records.len().min(5)
        );
        for d in new_records.iter().take(5) {
            println!("{d}");
        }
        std::process::exit(1);
    }
    if known > 0 {
        println!("all {known} divergences are known (in baseline) — OK");
    }
}