ferroni 1.3.3

Pure-Rust Oniguruma regex engine with SIMD-accelerated search
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
// regcomp.rs - Port of regcomp.c
// Compiler: converts AST (Node trees) into bytecode (Operation arrays).
//
// This is a 1:1 port of oniguruma's regcomp.c (~8,500 LOC).
// Structure mirrors the C original: operation management → string compilation →
// cclass compilation → quantifier compilation → bag compilation → anchor compilation →
// tree compilation → entry point.

#![allow(non_upper_case_globals)]
#![allow(unused_variables)]
#![allow(unused_assignments)]
#![allow(unused_mut)]

use std::sync::atomic::{AtomicU32, Ordering};

use crate::oniguruma::*;
use crate::regenc::*;
use crate::regint::*;
use crate::regparse_types::*;

// ============================================================================
// Global Default Case Fold Flag (port of C's OnigDefaultCaseFoldFlag)
// ============================================================================

static DEFAULT_CASE_FOLD_FLAG: AtomicU32 = AtomicU32::new(ONIGENC_CASE_FOLD_MIN);

#[cfg_attr(coverage_nightly, coverage(off))]
pub fn onig_get_default_case_fold_flag() -> OnigCaseFoldType {
    DEFAULT_CASE_FOLD_FLAG.load(Ordering::Relaxed)
}

#[cfg_attr(coverage_nightly, coverage(off))]
pub fn onig_set_default_case_fold_flag(flag: OnigCaseFoldType) -> i32 {
    DEFAULT_CASE_FOLD_FLAG.store(flag, Ordering::Relaxed);
    0
}

/// Maximum `{n}` exact count that gets unrolled into flat bytecode.
/// Beyond this threshold we fall back to the REPEAT/REPEAT_INC loop.
const EXACT_REPEAT_UNROLL_THRESHOLD: i32 = 16;

/// Maximum bytecode size of a finite greedy range that is expanded inline.
///
/// This mirrors Oniguruma's `QUANTIFIER_EXPAND_LIMIT_SIZE` guard. Larger
/// `{n,m}` ranges use the bounded REPEAT/REPEAT_INC bytecode instead.
const QUANTIFIER_EXPAND_LIMIT_SIZE: OnigLen = 10;

/// Get encoded character length from a byte slice (for optimization functions).
fn enclen(enc: OnigEncoding, p: &[u8], _offset: usize) -> usize {
    if p.is_empty() {
        return 1;
    }
    enc.mbc_enc_len(p)
}

// ============================================================================
// Constants (matching C OPSIZE_* and SIZE_INC)
// ============================================================================

// All operations are 1 slot in the ops array (matching C where every OPSIZE_* = 1)
const SIZE_INC: i32 = 1;

const OPSIZE_ANYCHAR_STAR: i32 = 1;
const OPSIZE_ANYCHAR_STAR_PEEK_NEXT: i32 = 1;
const OPSIZE_JUMP: i32 = 1;
const OPSIZE_PUSH: i32 = 1;
const OPSIZE_PUSH_SUPER: i32 = 1;
const OPSIZE_POP: i32 = 1;
const OPSIZE_POP_TO_MARK: i32 = 1;
const OPSIZE_PUSH_OR_JUMP_EXACT1: i32 = 1;
const OPSIZE_PUSH_IF_PEEK_NEXT: i32 = 1;
const OPSIZE_REPEAT: i32 = 1;
const OPSIZE_REPEAT_INC: i32 = 1;
const OPSIZE_REPEAT_INC_NG: i32 = 1;
const OPSIZE_WORD_BOUNDARY: i32 = 1;
const OPSIZE_BACKREF: i32 = 1;
const OPSIZE_FAIL: i32 = 1;
const OPSIZE_MEM_START: i32 = 1;
const OPSIZE_MEM_START_PUSH: i32 = 1;
const OPSIZE_MEM_END_PUSH: i32 = 1;
const OPSIZE_MEM_END_PUSH_REC: i32 = 1;
const OPSIZE_MEM_END: i32 = 1;
const OPSIZE_MEM_END_REC: i32 = 1;
const OPSIZE_EMPTY_CHECK_START: i32 = 1;
const OPSIZE_EMPTY_CHECK_END: i32 = 1;
const OPSIZE_CHECK_POSITION: i32 = 1;
const OPSIZE_CALL: i32 = 1;
const OPSIZE_RETURN: i32 = 1;
const OPSIZE_MOVE: i32 = 1;
const OPSIZE_STEP_BACK_START: i32 = 1;
const OPSIZE_STEP_BACK_NEXT: i32 = 1;
const OPSIZE_CUT_TO_MARK: i32 = 1;
const OPSIZE_MARK: i32 = 1;
const OPSIZE_SAVE_VAL: i32 = 1;
const OPSIZE_UPDATE_VAR: i32 = 1;

// ============================================================================
// Operation management
// ============================================================================

/// Add an operation with the given opcode and payload to the regex's ops array.
/// Returns the index of the newly added operation.
fn add_op(reg: &mut RegexType, opcode: OpCode, payload: OperationPayload) -> i32 {
    let idx = reg.ops.len();
    reg.ops.push(Operation { opcode, payload });
    idx as i32
}

/// Get the index of the current (last) operation.
#[cfg_attr(coverage_nightly, coverage(off))]
fn ops_curr_offset(reg: &RegexType) -> i32 {
    (reg.ops.len() as i32) - 1
}

// ============================================================================
// Utility functions
// ============================================================================

/// Safe multiplication comparison: a * b > limit
#[cfg_attr(coverage_nightly, coverage(off))]
fn len_multiply_cmp(a: OnigLen, b: i32, limit: OnigLen) -> bool {
    if a == 0 || b == 0 {
        return false;
    }
    if a > limit / (b as OnigLen) {
        return true;
    }
    a * (b as OnigLen) > limit
}

/// Whether a finite greedy range can use inline expansion without producing
/// excessive bytecode. Port of the expansion guard in `compile_quantifier_node`.
fn can_expand_finite_greedy_quantifier(body_len: i32, upper: i32) -> bool {
    upper == 1
        || (body_len >= 0
            && upper >= 0
            && !len_multiply_cmp(
                body_len as OnigLen + OPSIZE_PUSH as OnigLen,
                upper,
                QUANTIFIER_EXPAND_LIMIT_SIZE,
            ))
}

/// Whether a quantifier body contains a recursive subexpression call.
///
/// The REPEAT VM path is not yet equivalent for recursive calls, but an
/// unrelated call elsewhere in the pattern must not disable the finite-range
/// expansion limit. Recursion is annotated during the call-resolution pass
/// before compilation starts.
fn quantifier_body_contains_recursion(node: &Node) -> bool {
    if node.has_status(ND_ST_RECURSION) {
        return true;
    }

    match &node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            quantifier_body_contains_recursion(&cons.car)
                || cons
                    .cdr
                    .as_deref()
                    .is_some_and(quantifier_body_contains_recursion)
        }
        NodeInner::Quant(qn) => qn
            .body
            .as_deref()
            .is_some_and(quantifier_body_contains_recursion),
        NodeInner::Anchor(an) => an
            .body
            .as_deref()
            .is_some_and(quantifier_body_contains_recursion),
        NodeInner::Call(cn) => cn
            .body
            .as_deref()
            .is_some_and(quantifier_body_contains_recursion),
        NodeInner::Bag(bag) => {
            bag.body
                .as_deref()
                .is_some_and(quantifier_body_contains_recursion)
                || match &bag.bag_data {
                    BagData::IfElse {
                        then_node,
                        else_node,
                    } => {
                        then_node
                            .as_deref()
                            .is_some_and(quantifier_body_contains_recursion)
                            || else_node
                                .as_deref()
                                .is_some_and(quantifier_body_contains_recursion)
                    }
                    _ => false,
                }
        }
        _ => false,
    }
}

/// Add two lengths safely, capping at INFINITE_LEN.
pub fn distance_add(d1: OnigLen, d2: OnigLen) -> OnigLen {
    if d1 == INFINITE_LEN || d2 == INFINITE_LEN {
        INFINITE_LEN
    } else if d1 <= INFINITE_LEN - d2 {
        d1 + d2
    } else {
        INFINITE_LEN
    }
}

/// Multiply a length by a count safely, capping at INFINITE_LEN.
fn distance_multiply(d: OnigLen, m: i32) -> OnigLen {
    if m == 0 {
        return 0;
    }
    if d >= INFINITE_LEN / (m as OnigLen) {
        return INFINITE_LEN;
    }
    d * (m as OnigLen)
}

/// Check if a bitset is empty (all zeros).
fn bitset_is_empty(bs: &BitSet) -> bool {
    bs.iter().all(|&slot| slot == 0)
}

/// Check if a node is a "strict real" node (actually matches characters).
fn is_strict_real_node(node: &Node) -> bool {
    matches!(
        node.inner,
        NodeInner::String(_) | NodeInner::CClass(_) | NodeInner::CType(_)
    )
}

// ============================================================================
// get_tree_head_literal / is_exclusive / tune_next (C lines 3043-4743)
// ============================================================================

/// Walk the AST to find the leading literal node.
/// If `exact` is true, only String nodes (not IGNORECASE) qualify.
/// If `exact` is false, CType and CClass nodes also qualify.
/// Returns a reference to the found node, or None.
fn get_tree_head_literal<'a>(node: &'a Node, exact: bool, _reg: &RegexType) -> Option<&'a Node> {
    match &node.inner {
        NodeInner::BackRef(_) | NodeInner::Alt(_) | NodeInner::Call(_) => None,

        NodeInner::CType(ct) => {
            if ct.ctype == CTYPE_ANYCHAR {
                None
            } else if !exact {
                Some(node)
            } else {
                None
            }
        }

        NodeInner::CClass(_) => {
            if !exact {
                Some(node)
            } else {
                None
            }
        }

        NodeInner::List(cons) => get_tree_head_literal(&cons.car, exact, _reg),

        NodeInner::String(sn) => {
            if sn.s.is_empty() {
                return None;
            }
            // ND_IS_REAL_IGNORECASE = IGNORECASE && !CRUDE
            let is_real_ic = (node.status & ND_ST_IGNORECASE) != 0 && !sn.is_crude();
            if !exact || !is_real_ic {
                Some(node)
            } else {
                None
            }
        }

        NodeInner::Quant(qn) => {
            if qn.lower > 0 {
                if let Some(he) = qn.head_exact {
                    // head_exact is already extracted; but it's a u8, not a node ref.
                    // For the recursive case, re-derive from body.
                    None // Fall through to body check
                } else {
                    qn.body
                        .as_ref()
                        .and_then(|b| get_tree_head_literal(b, exact, _reg))
                }
            } else {
                None
            }
        }

        NodeInner::Bag(bn) => match bn.bag_type {
            BagType::Option | BagType::Memory | BagType::StopBacktrack => bn
                .body
                .as_ref()
                .and_then(|b| get_tree_head_literal(b, exact, _reg)),
            _ => None,
        },

        NodeInner::Anchor(an) => {
            if an.anchor_type == ANCR_PREC_READ {
                an.body
                    .as_ref()
                    .and_then(|b| get_tree_head_literal(b, exact, _reg))
            } else {
                None
            }
        }

        _ => None,
    }
}

/// Extract the first byte from a head literal node (String only, for exact matching).
fn get_head_literal_byte(node: &Node, exact: bool, reg: &RegexType) -> Option<u8> {
    let n = get_tree_head_literal(node, exact, reg)?;
    if let NodeInner::String(sn) = &n.inner {
        if !sn.s.is_empty() && sn.s[0] != 0 {
            return Some(sn.s[0]);
        }
    }
    None
}

/// Check if a codepoint is in a character class.
fn onig_is_code_in_cc(enc: OnigEncoding, code: OnigCodePoint, cc: &CClassNode) -> bool {
    let in_bs = if (code as usize) < SINGLE_BYTE_SIZE {
        bitset_at(&cc.bs, code as usize)
    } else {
        false
    };

    let in_mbuf = if let Some(ref mbuf) = cc.mbuf {
        onig_is_in_code_range_bbuf(mbuf, code)
    } else {
        false
    };

    let result = in_bs || in_mbuf;
    if cc.is_not() {
        !result
    } else {
        result
    }
}

/// Check if code ranges in a BBuf contain a codepoint.
/// BBuf stores code ranges as packed u32 values in native-endian bytes.
fn onig_is_in_code_range_bbuf(mbuf: &BBuf, code: OnigCodePoint) -> bool {
    let data = &mbuf.data;
    if data.len() < 4 {
        return false;
    }

    let read_u32 = |offset: usize| -> u32 {
        if offset + 4 > data.len() {
            return 0;
        }
        u32::from_ne_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ])
    };

    let n = read_u32(0) as usize;
    let mut low = 0usize;
    let mut high = n;
    while low < high {
        let mid = (low + high) / 2;
        let from = read_u32((mid * 2 + 1) * 4);
        let to = read_u32((mid * 2 + 2) * 4);
        if code < from {
            high = mid;
        } else if code > to {
            low = mid + 1;
        } else {
            return true;
        }
    }
    false
}

/// Check if two head-literal nodes are mutually exclusive.
/// If they are, a quantifier before x followed by y can be made possessive.
fn is_exclusive(x: &Node, y: &Node, reg: &RegexType) -> bool {
    // Dispatch on x type, with swap for certain y types
    match (&x.inner, &y.inner) {
        // CType × CType
        (NodeInner::CType(xct), NodeInner::CType(yct)) => {
            if xct.ctype == CTYPE_ANYCHAR || yct.ctype == CTYPE_ANYCHAR {
                return false;
            }
            xct.ctype == yct.ctype && xct.not != yct.not && xct.ascii_mode == yct.ascii_mode
        }

        // CType × CClass or CType × String → swap and retry
        (NodeInner::CType(_), NodeInner::CClass(_)) => is_exclusive(y, x, reg),
        (NodeInner::CType(_), NodeInner::String(_)) => is_exclusive(y, x, reg),

        // CClass × CType
        (NodeInner::CClass(xc), NodeInner::CType(yct)) => {
            if yct.ctype == CTYPE_ANYCHAR {
                return false;
            }
            if yct.ctype != ONIGENC_CTYPE_WORD as i32 {
                return false;
            }
            if !yct.not {
                // \w: check if any word chars are in the class
                if xc.mbuf.is_some() || xc.is_not() {
                    return false;
                }
                let range = if yct.ascii_mode {
                    128
                } else {
                    SINGLE_BYTE_SIZE
                };
                for i in 0..range {
                    if bitset_at(&xc.bs, i) && is_code_word(reg.enc, i as OnigCodePoint) {
                        return false;
                    }
                }
                true
            } else {
                // \W: check if any non-word chars are in the class
                if xc.mbuf.is_some() || xc.is_not() {
                    return false;
                }
                let range = if yct.ascii_mode {
                    128
                } else {
                    SINGLE_BYTE_SIZE
                };
                for i in 0..range {
                    if !is_code_word(reg.enc, i as OnigCodePoint) && bitset_at(&xc.bs, i) {
                        return false;
                    }
                }
                for i in range..SINGLE_BYTE_SIZE {
                    if bitset_at(&xc.bs, i) {
                        return false;
                    }
                }
                true
            }
        }

        // CClass × CClass
        (NodeInner::CClass(xc), NodeInner::CClass(yc)) => {
            for i in 0..SINGLE_BYTE_SIZE {
                let xv = bitset_at(&xc.bs, i);
                let x_in = if xc.is_not() { !xv } else { xv };
                if x_in {
                    let yv = bitset_at(&yc.bs, i);
                    let y_in = if yc.is_not() { !yv } else { yv };
                    if y_in {
                        return false;
                    }
                }
            }
            // If either has no mbuf and is not negated, they can't overlap on multi-byte
            if (xc.mbuf.is_none() && !xc.is_not()) || (yc.mbuf.is_none() && !yc.is_not()) {
                return true;
            }
            false
        }

        // CClass × String → swap
        (NodeInner::CClass(_), NodeInner::String(_)) => is_exclusive(y, x, reg),

        // String × CType
        (NodeInner::String(xs), NodeInner::CType(yct)) => {
            if xs.s.is_empty() {
                return false;
            }
            if yct.ctype == CTYPE_ANYCHAR {
                return false;
            }
            if yct.ctype == ONIGENC_CTYPE_WORD as i32 {
                let is_word = if !yct.ascii_mode {
                    is_mbc_word(reg.enc, &xs.s)
                } else {
                    is_mbc_word_ascii(reg.enc, &xs.s)
                };
                return if is_word { yct.not } else { !yct.not };
            }
            false
        }

        // String × CClass
        (NodeInner::String(xs), NodeInner::CClass(yc)) => {
            if xs.s.is_empty() {
                return false;
            }
            let code = reg.enc.mbc_to_code(&xs.s, xs.s.len());
            !onig_is_code_in_cc(reg.enc, code, yc)
        }

        // String × String
        (NodeInner::String(xs), NodeInner::String(ys)) => {
            if xs.s.is_empty() || ys.s.is_empty() {
                return false;
            }
            let len = xs.s.len().min(ys.s.len());
            for i in 0..len {
                if xs.s[i] != ys.s[i] {
                    return true;
                }
            }
            false
        }

        _ => false,
    }
}

/// Check if a character is a "word" character.
fn is_code_word(enc: OnigEncoding, code: OnigCodePoint) -> bool {
    if code < 128 {
        let c = code as u8;
        c.is_ascii_alphanumeric() || c == b'_'
    } else {
        enc.is_code_ctype(code, ONIGENC_CTYPE_WORD)
    }
}

/// Check if the first character in buf is a word character.
fn is_mbc_word(enc: OnigEncoding, buf: &[u8]) -> bool {
    if buf.is_empty() {
        return false;
    }
    let code = enc.mbc_to_code(buf, buf.len());
    is_code_word(enc, code)
}

/// Check if the first character in buf is an ASCII word character.
fn is_mbc_word_ascii(_enc: OnigEncoding, buf: &[u8]) -> bool {
    if buf.is_empty() {
        return false;
    }
    let c = buf[0];
    c.is_ascii_alphanumeric() || c == b'_'
}

/// tune_next: propagate next-node info to optimize quantifiers.
/// Sets qn.next_head_exact for PushIfPeekNext optimization.
/// Auto-possessifies when body and next are exclusive.
fn tune_next(node: &mut Node, next_node: &Node, reg: &RegexType) -> i32 {
    tune_next_inner(node, next_node, reg, false)
}

fn tune_next_inner(node: &mut Node, next_node: &Node, reg: &RegexType, called: bool) -> i32 {
    let status = node.status;
    match &mut node.inner {
        NodeInner::Quant(qn) => {
            let mut replacement = None;
            if qn.greedy && is_infinite_repeat(qn.upper) {
                if !called {
                    if let Some(byte) = get_head_literal_byte(next_node, true, reg) {
                        qn.next_head_exact = Some(byte);
                    }
                }

                if qn.lower <= 1 {
                    let should_possessify = qn.body.as_ref().is_some_and(|body| {
                        is_strict_real_node(body)
                            && get_tree_head_literal(body, false, reg).is_some_and(|x| {
                                get_tree_head_literal(next_node, false, reg)
                                    .is_some_and(|y| is_exclusive(x, y, reg))
                            })
                    });
                    if should_possessify {
                        let body = qn.body.take().expect("quantifier body was checked above");
                        replacement = Some(NodeInner::Bag(BagNode {
                            body: Some(Box::new(Node {
                                inner: NodeInner::Quant(QuantNode {
                                    body: Some(body),
                                    lower: qn.lower,
                                    upper: qn.upper,
                                    greedy: qn.greedy,
                                    emptiness: qn.emptiness,
                                    head_exact: qn.head_exact.take(),
                                    next_head_exact: qn.next_head_exact.take(),
                                    include_referred: qn.include_referred,
                                    empty_status_mem: qn.empty_status_mem,
                                }),
                                status,
                                parent: std::ptr::null_mut(),
                            })),
                            bag_type: BagType::StopBacktrack,
                            bag_data: BagData::StopBacktrack,
                            min_len: 0,
                            max_len: INFINITE_LEN,
                            min_char_len: 0,
                            max_char_len: INFINITE_LEN,
                            opt_count: 0,
                        }));
                    }
                }
            }
            if let Some(inner) = replacement {
                node.inner = inner;
                node.status |= ND_ST_STRICT_REAL_REPEAT;
            }
            0
        }
        NodeInner::Bag(bn) if bn.bag_type == BagType::Memory => {
            let called = called || (status & ND_ST_CALLED) != 0;
            match bn.body.as_mut() {
                Some(body) => tune_next_inner(body, next_node, reg, called),
                None => 0,
            }
        }
        _ => 0,
    }
}

// ============================================================================
// String compilation
// ============================================================================

/// Select the opcode for a string of given byte length and encoding char width.
fn select_str_opcode(mb_len: i32, str_len: i32) -> OpCode {
    if mb_len == 1 {
        match str_len {
            1 => OpCode::Str1,
            2 => OpCode::Str2,
            3 => OpCode::Str3,
            4 => OpCode::Str4,
            5 => OpCode::Str5,
            _ => OpCode::StrN,
        }
    } else if mb_len == 2 {
        match str_len {
            1 => OpCode::StrMb2n1,
            2 => OpCode::StrMb2n2,
            3 => OpCode::StrMb2n3,
            _ => OpCode::StrMb2n,
        }
    } else if mb_len == 3 {
        OpCode::StrMb3n
    } else {
        OpCode::StrMbn
    }
}

/// Calculate bytecode length for adding a compiled string segment.
fn add_compile_string_length(_s: &[u8], mb_len: i32, str_len: i32) -> i32 {
    SIZE_INC
}

/// Add a compiled string segment to the bytecode.
fn add_compile_string(reg: &mut RegexType, s: &[u8], mb_len: i32, str_len: i32) -> i32 {
    let op = select_str_opcode(mb_len, str_len);
    let byte_len = mb_len * str_len;

    let payload = if mb_len == 1 && str_len <= 5 {
        // Single-byte encoding, Str1-Str5: use compact Exact payload
        let mut buf = [0u8; 16];
        buf[..byte_len as usize].copy_from_slice(&s[..byte_len as usize]);
        OperationPayload::Exact { s: buf }
    } else if mb_len == 1 {
        // Single-byte encoding, StrN: use ExactN payload
        OperationPayload::ExactN {
            s: s[..byte_len as usize].to_vec(),
            n: str_len,
        }
    } else {
        // Multi-byte encoding: always use ExactLenN with byte count
        OperationPayload::ExactLenN {
            s: s[..byte_len as usize].to_vec(),
            n: byte_len, // total byte count
            len: mb_len, // bytes per character
        }
    };

    add_op(reg, op, payload);
    0
}

/// Calculate bytecode length for a string node.
fn compile_length_string_node(node: &Node, reg: &RegexType) -> i32 {
    let sn = node.as_str().unwrap();
    let enc = reg.enc;

    if sn.s.is_empty() {
        return 0;
    }

    let mut len = 0i32;
    let mut pos = 0usize;
    let slen = sn.s.len();

    while pos < slen {
        let first_len = enc.mbc_enc_len(&sn.s[pos..]);
        let mut run = 1;
        let next = pos + first_len;
        let mut p = next;

        // Group consecutive characters with the same mb_len
        while p < slen {
            let enc_len = enc.mbc_enc_len(&sn.s[p..]);
            if enc_len != first_len {
                break;
            }
            run += 1;
            p += enc_len;
        }

        len += add_compile_string_length(&sn.s[pos..], first_len as i32, run);
        pos = p;
    }

    len
}

/// Calculate bytecode length for a "crude" string node.
fn compile_length_string_crude_node(node: &Node, reg: &RegexType) -> i32 {
    let sn = node.as_str().unwrap();
    if sn.s.is_empty() {
        return 0;
    }
    SIZE_INC
}

/// Compile a string node to bytecode.
fn compile_string_node(node: &Node, reg: &mut RegexType) -> i32 {
    let sn = node.as_str().unwrap();
    let enc = reg.enc;

    if sn.s.is_empty() {
        return 0;
    }

    let mut pos = 0usize;
    let slen = sn.s.len();

    while pos < slen {
        let first_len = enc.mbc_enc_len(&sn.s[pos..]);
        let mut run = 1;
        let next = pos + first_len;
        let mut p = next;

        while p < slen {
            let enc_len = enc.mbc_enc_len(&sn.s[p..]);
            if enc_len != first_len {
                break;
            }
            run += 1;
            p += enc_len;
        }

        let r = add_compile_string(reg, &sn.s[pos..], first_len as i32, run);
        if r != 0 {
            return r;
        }
        pos = p;
    }

    0
}

/// Compile a crude string node to bytecode.
fn compile_string_crude_node(node: &Node, reg: &mut RegexType) -> i32 {
    let sn = node.as_str().unwrap();
    if sn.s.is_empty() {
        return 0;
    }

    let byte_len = sn.s.len();
    let payload = if byte_len <= 16 {
        let mut buf = [0u8; 16];
        buf[..byte_len].copy_from_slice(&sn.s[..byte_len]);
        OperationPayload::Exact { s: buf }
    } else {
        OperationPayload::ExactN {
            s: sn.s.clone(),
            n: byte_len as i32,
        }
    };

    add_op(reg, select_str_opcode(1, byte_len as i32), payload);
    0
}

// ============================================================================
// Character class compilation
// ============================================================================

/// Calculate bytecode length for a character class node.
fn compile_length_cclass_node(cc: &CClassNode, reg: &RegexType) -> i32 {
    SIZE_INC
}

/// Convert a BBuf byte buffer to a Vec<u32> for direct indexing at execution time.
/// BBuf stores code ranges as packed u32 values in native-endian bytes.
fn bbuf_to_u32_vec(data: &[u8]) -> Vec<u32> {
    data.chunks_exact(4)
        .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
        .collect()
}

fn detect_cclass_ascii_fast(bs: &BitSet) -> CClassAsciiFastKind {
    let mut first: Option<u8> = None;
    let mut second: Option<u8> = None;

    for i in 0..SINGLE_BYTE_SIZE {
        if bitset_at(bs, i) {
            let b = i as u8;
            if first.is_none() {
                first = Some(b);
            } else if second.is_none() {
                second = Some(b);
            } else {
                return CClassAsciiFastKind::None;
            }
        }
    }

    match (first, second) {
        (Some(a), None) if a < 0x80 => CClassAsciiFastKind::Eq(a),
        (Some(a), Some(b))
            if a < 0x80
                && b < 0x80
                && a.is_ascii_alphabetic()
                && b.is_ascii_alphabetic()
                && (a ^ b) == 0x20 =>
        {
            CClassAsciiFastKind::EqFoldLower(a | 0x20)
        }
        _ => CClassAsciiFastKind::None,
    }
}

/// Compile a character class node to bytecode.
fn compile_cclass_node(cc: &CClassNode, reg: &mut RegexType) -> i32 {
    let has_mb = cc.mbuf.is_some();
    let has_sb = !bitset_is_empty(&cc.bs);

    if has_mb && has_sb {
        // Mixed single-byte and multi-byte
        let opcode = if cc.is_not() {
            OpCode::CClassMixNot
        } else {
            OpCode::CClassMix
        };
        let mb_data = cc
            .mbuf
            .as_ref()
            .map(|b| bbuf_to_u32_vec(&b.data))
            .unwrap_or_default();
        add_op(
            reg,
            opcode,
            OperationPayload::CClassMix {
                mb: mb_data,
                bsp: Box::new(cc.bs),
            },
        );
    } else if has_mb {
        // Multi-byte only
        let opcode = if cc.is_not() {
            OpCode::CClassMbNot
        } else {
            OpCode::CClassMb
        };
        let mb_data = cc
            .mbuf
            .as_ref()
            .map(|b| bbuf_to_u32_vec(&b.data))
            .unwrap_or_default();
        add_op(reg, opcode, OperationPayload::CClassMb { mb: mb_data });
    } else {
        // Single-byte only
        let opcode = if cc.is_not() {
            OpCode::CClassNot
        } else {
            OpCode::CClass
        };
        let ascii_fast = detect_cclass_ascii_fast(&cc.bs);
        add_op(
            reg,
            opcode,
            OperationPayload::CClass {
                bsp: Box::new(cc.bs),
                ascii_fast,
            },
        );
    }

    0
}

// ============================================================================
// Repeat range management
// ============================================================================

/// Register a repeat range entry. Returns the repeat ID.
fn entry_repeat_range(reg: &mut RegexType, lower: i32, upper: i32) -> Result<i32, i32> {
    let id = reg.num_repeat;
    reg.num_repeat += 1;

    reg.repeat_range.push(RepeatRange {
        lower,
        upper,
        u_offset: 0,
    });

    Ok(id)
}

// ============================================================================
// Quantifier compilation
// ============================================================================

/// Compile a quantifier body wrapped with empty-match check if needed.
/// Collect a bitmask of capture group regnums present in a node tree.
fn collect_mem_status(node: &Node) -> u32 {
    let mut status: u32 = 0;
    match &node.inner {
        NodeInner::List(_) | NodeInner::Alt(_) => {
            let mut cur = node;
            loop {
                let (car, cdr) = match &cur.inner {
                    NodeInner::List(cons) => (&cons.car, &cons.cdr),
                    NodeInner::Alt(cons) => (&cons.car, &cons.cdr),
                    _ => break,
                };
                status |= collect_mem_status(car);
                match cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(ref body) = qn.body {
                status |= collect_mem_status(body);
            }
        }
        NodeInner::Bag(bn) => {
            if bn.bag_type == BagType::Memory {
                if let BagData::Memory { regnum, .. } = bn.bag_data {
                    if regnum > 0 && regnum < 31 {
                        status |= 1u32 << regnum;
                    }
                }
            }
            if let Some(ref body) = bn.body {
                status |= collect_mem_status(body);
            }
        }
        _ => {}
    }
    status
}

fn compile_quant_body_with_empty_check(
    node: &Node,
    reg: &mut RegexType,
    env: &ParseEnv,
    emptiness: BodyEmptyType,
    qn_empty_status_mem: u32,
) -> i32 {
    let is_empty = emptiness != BodyEmptyType::NotEmpty;
    let saved_mem = reg.num_empty_check;

    if is_empty {
        reg.num_empty_check += 1;
        add_op(
            reg,
            OpCode::EmptyCheckStart,
            OperationPayload::EmptyCheckStart { mem: saved_mem },
        );
    }

    let r = compile_tree(node, reg, env);
    if r != 0 {
        return r;
    }

    if is_empty {
        let mem = saved_mem;
        let empty_status_mem = if emptiness == BodyEmptyType::MayBeEmptyMem
            || emptiness == BodyEmptyType::MayBeEmptyRec
        {
            if qn_empty_status_mem != 0 {
                qn_empty_status_mem
            } else {
                collect_mem_status(node)
            }
        } else {
            0
        };
        let opcode = match emptiness {
            BodyEmptyType::MayBeEmptyMem => {
                if qn_empty_status_mem != 0 {
                    OpCode::EmptyCheckEndMemst
                } else {
                    // No external backrefs to tracked captures → use plain empty check
                    OpCode::EmptyCheckEnd
                }
            }
            BodyEmptyType::MayBeEmptyRec => OpCode::EmptyCheckEndMemstPush,
            _ => OpCode::EmptyCheckEnd,
        };
        add_op(
            reg,
            opcode,
            OperationPayload::EmptyCheckEnd {
                mem,
                empty_status_mem,
            },
        );
    }

    0
}

/// Compile a node N times (for expanding small-count quantifiers).
fn compile_tree_n_times(node: &Node, n: i32, reg: &mut RegexType, env: &ParseEnv) -> i32 {
    for _ in 0..n {
        let r = compile_tree(node, reg, env);
        if r != 0 {
            return r;
        }
    }
    0
}

/// Check if this is a greedy infinite repeat of a character class [class]* / [class]+
fn is_cclass_infinite_greedy(qn: &QuantNode) -> bool {
    qn.greedy
        && is_infinite_repeat(qn.upper)
        && qn.lower <= 1
        && qn
            .body
            .as_ref()
            .is_some_and(|b| matches!(b.inner, NodeInner::CClass(_)))
}

/// Check if this is a greedy infinite repeat of \w or \W.
/// Returns Some((not, ascii_mode)) if match.
fn is_word_ctype_infinite_greedy(qn: &QuantNode) -> Option<(bool, bool)> {
    if qn.greedy && is_infinite_repeat(qn.upper) && qn.lower <= 1 {
        if let Some(body) = &qn.body {
            if let NodeInner::CType(ct) = &body.inner {
                if ct.ctype == ONIGENC_CTYPE_WORD as i32 {
                    return Some((ct.not, ct.ascii_mode));
                }
            }
        }
    }
    None
}

/// Check if this is a greedy infinite repeat of `(?:CClass|...)`
/// where the first alternative is a non-negated character class.
/// Returns the CClass and the remaining alternatives (cdr) if matched.
fn is_alt_cclass_first_infinite_greedy(qn: &QuantNode) -> Option<(&CClassNode, &Node)> {
    if !qn.greedy || !is_infinite_repeat(qn.upper) || qn.lower > 1 {
        return None;
    }
    if qn.emptiness != BodyEmptyType::NotEmpty {
        return None;
    }
    let body = qn.body.as_ref()?;
    if let NodeInner::Alt(cons) = &body.inner {
        if let NodeInner::CClass(cc) = &cons.car.inner {
            if !cc.is_not() {
                if let Some(cdr) = &cons.cdr {
                    return Some((cc, cdr));
                }
            }
        }
    }
    None
}

/// Compile a character class star node (CClassStar/CClassMixStar/CClassMbStar).
/// Returns 0 on success, -1 if the class is negated (caller should fall through).
fn compile_cclass_star_node(cc: &CClassNode, reg: &mut RegexType) -> i32 {
    if cc.is_not() {
        return -1;
    }
    let has_mb = cc.mbuf.is_some();
    let has_sb = !bitset_is_empty(&cc.bs);

    if has_mb && has_sb {
        let mb_data = cc
            .mbuf
            .as_ref()
            .map(|b| bbuf_to_u32_vec(&b.data))
            .unwrap_or_default();
        add_op(
            reg,
            OpCode::CClassMixStar,
            OperationPayload::CClassMix {
                mb: mb_data,
                bsp: Box::new(cc.bs),
            },
        );
    } else if has_mb {
        let mb_data = cc
            .mbuf
            .as_ref()
            .map(|b| bbuf_to_u32_vec(&b.data))
            .unwrap_or_default();
        add_op(
            reg,
            OpCode::CClassMbStar,
            OperationPayload::CClassMb { mb: mb_data },
        );
    } else {
        let ascii_fast = detect_cclass_ascii_fast(&cc.bs);
        add_op(
            reg,
            OpCode::CClassStar,
            OperationPayload::CClass {
                bsp: Box::new(cc.bs),
                ascii_fast,
            },
        );
    }
    0
}

/// Check if a quantifier node represents .* or .+ (anychar infinite greedy).
///
/// Keep backref-bearing patterns on the generic quantifier path. The specialized
/// ANYCHAR_STAR opcodes precompute all exit points up front, which is unsafe for
/// backref-heavy patterns like `(.*)a\\1f` that rely on conservative backtracking.
fn is_anychar_infinite_greedy(qn: &QuantNode, env: &ParseEnv) -> bool {
    if env.backref_num == 0 && qn.greedy && is_infinite_repeat(qn.upper) && qn.lower <= 1 {
        if let Some(body) = &qn.body {
            return matches!(body.inner, NodeInner::CType(ref ct) if ct.ctype == CTYPE_ANYCHAR);
        }
    }
    false
}

/// Check if the body of a CType node has MULTILINE flag set.
fn is_anychar_multiline(body: &Node) -> bool {
    matches!(&body.inner, NodeInner::CType(_) if (body.status & ND_ST_MULTILINE) != 0)
}

/// Calculate bytecode length for a quantifier node.
fn compile_length_quantifier_node(qn: &QuantNode, reg: &RegexType, env: &ParseEnv) -> i32 {
    let body = qn.body.as_ref().unwrap();

    if qn.upper == 0 {
        if qn.include_referred != 0 {
            // {0} with CALLED group: JUMP + body
            let tlen = compile_length_tree(body, reg, env);
            return OPSIZE_JUMP + tlen;
        }
        // {0} matches nothing
        if is_anychar_infinite_greedy(qn, env) {
            return SIZE_INC;
        }
        return 0;
    }

    // AnyChar star/plus optimization
    if is_anychar_infinite_greedy(qn, env) {
        let tlen = compile_length_tree(body, reg, env);
        if qn.next_head_exact.is_some() {
            return OPSIZE_ANYCHAR_STAR_PEEK_NEXT + tlen * qn.lower;
        }
        return SIZE_INC + tlen * qn.lower;
    }

    // CClass star/plus optimization: [class]* or [class]+
    if is_cclass_infinite_greedy(qn) {
        if let Some(cc) = body.as_cclass() {
            if !cc.is_not() {
                let tlen = compile_length_tree(body, reg, env);
                return SIZE_INC + tlen * qn.lower;
            }
        }
    }

    // Word ctype star/plus optimization: \w* or \w+
    if let Some((not, _ascii_mode)) = is_word_ctype_infinite_greedy(qn) {
        if !not {
            let tlen = compile_length_tree(body, reg, env);
            return SIZE_INC + tlen * qn.lower;
        }
    }

    // Alt-CClass fusion: (?:CClass|B)* or (?:CClass|B)+
    if let Some((_cc, cdr)) = is_alt_cclass_first_infinite_greedy(qn) {
        let cdr_len = compile_length_tree(cdr, reg, env);
        let body_len = compile_length_tree(body, reg, env);
        // Layout: [body × lower] + CClassStar(1) + PUSH(1) + cdr + JUMP(1)
        return body_len * qn.lower + SIZE_INC + OPSIZE_PUSH + cdr_len + OPSIZE_JUMP;
    }

    let is_empty = qn.emptiness != BodyEmptyType::NotEmpty;
    let body_len = compile_length_tree(body, reg, env);
    if body_len < 0 {
        return body_len;
    }

    let empty_len = if is_empty {
        OPSIZE_EMPTY_CHECK_START + OPSIZE_EMPTY_CHECK_END
    } else {
        0
    };
    let mod_tlen = body_len + empty_len;

    if is_infinite_repeat(qn.upper) {
        if qn.lower <= 1 {
            // *, +, *?, +?
            // Use appropriate opsize based on head_exact/next_head_exact
            let push_size = if qn.greedy && qn.head_exact.is_some() {
                OPSIZE_PUSH_OR_JUMP_EXACT1
            } else if qn.greedy && qn.next_head_exact.is_some() {
                OPSIZE_PUSH_IF_PEEK_NEXT
            } else {
                OPSIZE_PUSH
            };
            body_len * qn.lower + push_size + mod_tlen + OPSIZE_JUMP
        } else {
            // {n,} or {n,}?
            let n_body_len = compile_length_tree_n_times(body, qn.lower, reg, env);
            n_body_len + OPSIZE_PUSH + mod_tlen + OPSIZE_JUMP
        }
    } else if qn.upper == 0 {
        0
    } else if !is_infinite_repeat(qn.upper) && qn.lower == qn.upper {
        // {n,n} exact repeat
        if qn.lower == 1 {
            body_len
        } else if !is_empty && qn.include_referred == 0 && qn.lower <= EXACT_REPEAT_UNROLL_THRESHOLD
        {
            // Unroll small exact repeats into flat bytecode
            body_len * qn.lower
        } else {
            // Use REPEAT opcodes for larger exact counts
            OPSIZE_REPEAT + mod_tlen + OPSIZE_REPEAT_INC
        }
    } else if !qn.greedy && qn.upper == 1 && qn.lower == 0 {
        // ?? path: PUSH + JUMP + body
        OPSIZE_PUSH + OPSIZE_JUMP + body_len
    } else if qn.greedy
        && !is_infinite_repeat(qn.upper)
        // The REPEAT VM path has not yet reached parity for recursive calls.
        // Preserve the established expansion behavior for those expressions.
        && (quantifier_body_contains_recursion(body)
            || can_expand_finite_greedy_quantifier(body_len, qn.upper))
    {
        // Greedy expansion: lower*body + (upper-lower)*(PUSH+body)
        let n = qn.upper - qn.lower;
        let iteration_len = match body_len.checked_add(OPSIZE_PUSH) {
            Some(len) => len,
            None => return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE,
        };
        let mandatory_len = match body_len.checked_mul(qn.lower) {
            Some(len) => len,
            None => return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE,
        };
        let optional_len = match iteration_len.checked_mul(n) {
            Some(len) => len,
            None => return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE,
        };
        match mandatory_len.checked_add(optional_len) {
            Some(len) => len,
            None => ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE,
        }
    } else {
        // {n,m} range repeat (lazy non-trivial)
        OPSIZE_REPEAT + mod_tlen + OPSIZE_REPEAT_INC
    }
}

/// Calculate compile length for N repetitions of a node.
fn compile_length_tree_n_times(node: &Node, n: i32, reg: &RegexType, env: &ParseEnv) -> i32 {
    let len = compile_length_tree(node, reg, env);
    if len < 0 {
        return len;
    }
    len * n
}

/// Compile a quantifier node to bytecode.
fn compile_quantifier_node(qn: &QuantNode, reg: &mut RegexType, env: &ParseEnv) -> i32 {
    let body = qn.body.as_ref().unwrap();

    if qn.upper == 0 {
        if qn.include_referred != 0 {
            // {0} with CALLED group: JUMP over body, then compile body
            let tlen = compile_length_tree(body, reg, env);
            add_op(
                reg,
                OpCode::Jump,
                OperationPayload::Jump {
                    addr: tlen + SIZE_INC,
                },
            );
            return compile_tree(body, reg, env);
        }
        return 0;
    }

    // AnyChar star/plus with peek optimization: .* or .+
    if is_anychar_infinite_greedy(qn, env) {
        let r = compile_tree_n_times(body, qn.lower, reg, env);
        if r != 0 {
            return r;
        }
        if let Some(c) = qn.next_head_exact {
            let opcode = if is_anychar_multiline(body) {
                OpCode::AnyCharMlStarPeekNext
            } else {
                OpCode::AnyCharStarPeekNext
            };
            add_op(reg, opcode, OperationPayload::AnyCharStarPeekNext { c });
        } else {
            let opcode = if is_anychar_multiline(body) {
                OpCode::AnyCharMlStar
            } else {
                OpCode::AnyCharStar
            };
            add_op(reg, opcode, OperationPayload::None);
        }
        return 0;
    }

    // CClass star/plus optimization: [class]* or [class]+
    if is_cclass_infinite_greedy(qn) {
        if let Some(cc) = body.as_cclass() {
            if !cc.is_not() {
                let r = compile_tree_n_times(body, qn.lower, reg, env);
                if r != 0 {
                    return r;
                }
                // Use PeekNext variant for ASCII-only classes when next byte is known
                if let Some(c) = qn.next_head_exact {
                    let has_mb = cc.mbuf.is_some();
                    if !has_mb {
                        // ASCII-only bitset: use CClassStarPeekNext
                        add_op(
                            reg,
                            OpCode::CClassStarPeekNext,
                            OperationPayload::CClassStarPeekNext {
                                bsp: Box::new(cc.bs),
                                c,
                            },
                        );
                        return 0;
                    }
                }
                compile_cclass_star_node(cc, reg);
                return 0;
            }
        }
    }

    // Word ctype star/plus optimization: \w* or \w+
    if let Some((not, ascii_mode)) = is_word_ctype_infinite_greedy(qn) {
        if !not {
            let r = compile_tree_n_times(body, qn.lower, reg, env);
            if r != 0 {
                return r;
            }
            if ascii_mode {
                if let Some(c) = qn.next_head_exact {
                    add_op(
                        reg,
                        OpCode::WordAsciiStarPeekNext,
                        OperationPayload::WordAsciiStarPeekNext { c },
                    );
                    return 0;
                }
            }
            let opcode = if ascii_mode {
                OpCode::WordAsciiStar
            } else {
                OpCode::WordStar
            };
            add_op(reg, opcode, OperationPayload::None);
            return 0;
        }
    }

    // Alt-CClass fusion: (?:CClass|B)* → CClassStar + PUSH exit + [B] + JUMP loop
    if let Some((cc, cdr)) = is_alt_cclass_first_infinite_greedy(qn) {
        // For +: compile one mandatory match of the full alternation first
        if qn.lower == 1 {
            let r = compile_tree(body, reg, env);
            if r != 0 {
                return r;
            }
        }

        // Emit CClassStar for the first branch's character class
        compile_cclass_star_node(cc, reg);

        // PUSH exit: skip over cdr + JUMP to exit the loop
        let cdr_len = compile_length_tree(cdr, reg, env);
        let push_addr = SIZE_INC + cdr_len + OPSIZE_JUMP;
        add_op(
            reg,
            OpCode::Push,
            OperationPayload::Push { addr: push_addr },
        );

        // Compile remaining alternation branches (B, or B|C|...)
        let r = compile_tree(cdr, reg, env);
        if r != 0 {
            return r;
        }

        // JUMP back to CClassStar
        let jump_addr = -(SIZE_INC + OPSIZE_PUSH + cdr_len);
        add_op(
            reg,
            OpCode::Jump,
            OperationPayload::Jump { addr: jump_addr },
        );

        return 0;
    }

    let is_empty = qn.emptiness != BodyEmptyType::NotEmpty;
    let body_len = compile_length_tree(body, reg, env);
    if body_len < 0 {
        return body_len;
    }

    let empty_len = if is_empty {
        OPSIZE_EMPTY_CHECK_START + OPSIZE_EMPTY_CHECK_END
    } else {
        0
    };
    let mod_tlen = body_len + empty_len;

    if is_infinite_repeat(qn.upper) {
        if qn.lower <= 1 {
            if qn.greedy {
                // a* or a+
                if qn.lower == 1 {
                    // a+ : body first, then loop
                    compile_tree_n_times(body, 1, reg, env);
                }

                // Emit PUSH variant based on head_exact / next_head_exact
                let addr;
                if let Some(c) = qn.head_exact {
                    // PushOrJumpExact1: push alt if char matches, else jump
                    add_op(
                        reg,
                        OpCode::PushOrJumpExact1,
                        OperationPayload::PushOrJumpExact1 {
                            addr: SIZE_INC + mod_tlen + OPSIZE_JUMP,
                            c,
                        },
                    );
                    let r = compile_quant_body_with_empty_check(
                        body,
                        reg,
                        env,
                        qn.emptiness,
                        qn.empty_status_mem,
                    );
                    if r != 0 {
                        return r;
                    }
                    addr = -(mod_tlen + OPSIZE_PUSH_OR_JUMP_EXACT1);
                } else if let Some(c) = qn.next_head_exact {
                    // PushIfPeekNext: push alt only if next char matches peek
                    add_op(
                        reg,
                        OpCode::PushIfPeekNext,
                        OperationPayload::PushIfPeekNext {
                            addr: SIZE_INC + mod_tlen + OPSIZE_JUMP,
                            c,
                        },
                    );
                    let r = compile_quant_body_with_empty_check(
                        body,
                        reg,
                        env,
                        qn.emptiness,
                        qn.empty_status_mem,
                    );
                    if r != 0 {
                        return r;
                    }
                    addr = -(mod_tlen + OPSIZE_PUSH_IF_PEEK_NEXT);
                } else {
                    // Regular PUSH
                    add_op(
                        reg,
                        OpCode::Push,
                        OperationPayload::Push {
                            addr: SIZE_INC + mod_tlen + OPSIZE_JUMP,
                        },
                    );
                    let r = compile_quant_body_with_empty_check(
                        body,
                        reg,
                        env,
                        qn.emptiness,
                        qn.empty_status_mem,
                    );
                    if r != 0 {
                        return r;
                    }
                    addr = -(mod_tlen + OPSIZE_PUSH);
                }
                add_op(reg, OpCode::Jump, OperationPayload::Jump { addr });
            } else {
                // a*? or a+?
                if qn.lower == 1 {
                    compile_tree_n_times(body, 1, reg, env);
                }
                // JUMP forward → body → PUSH back
                // C: COP(reg)->jump.addr = mod_tlen + SIZE_INC;
                add_op(
                    reg,
                    OpCode::Jump,
                    OperationPayload::Jump {
                        addr: mod_tlen + SIZE_INC,
                    },
                );
                let r = compile_quant_body_with_empty_check(
                    body,
                    reg,
                    env,
                    qn.emptiness,
                    qn.empty_status_mem,
                );
                if r != 0 {
                    return r;
                }
                // C: COP(reg)->push.addr = -mod_tlen;
                add_op(
                    reg,
                    OpCode::Push,
                    OperationPayload::Push { addr: -mod_tlen },
                );
            }
        } else {
            // {n,} with n >= 2
            // Compile body n times, then loop
            let r = compile_tree_n_times(body, qn.lower, reg, env);
            if r != 0 {
                return r;
            }

            if qn.greedy {
                add_op(
                    reg,
                    OpCode::Push,
                    OperationPayload::Push {
                        addr: SIZE_INC + mod_tlen + OPSIZE_JUMP,
                    },
                );
                let r = compile_quant_body_with_empty_check(
                    body,
                    reg,
                    env,
                    qn.emptiness,
                    qn.empty_status_mem,
                );
                if r != 0 {
                    return r;
                }
                // C: addr = -(mod_tlen + (int)OPSIZE_PUSH);
                add_op(
                    reg,
                    OpCode::Jump,
                    OperationPayload::Jump {
                        addr: -(mod_tlen + OPSIZE_PUSH),
                    },
                );
            } else {
                // C: COP(reg)->jump.addr = mod_tlen + SIZE_INC;
                add_op(
                    reg,
                    OpCode::Jump,
                    OperationPayload::Jump {
                        addr: mod_tlen + SIZE_INC,
                    },
                );
                let r = compile_quant_body_with_empty_check(
                    body,
                    reg,
                    env,
                    qn.emptiness,
                    qn.empty_status_mem,
                );
                if r != 0 {
                    return r;
                }
                // C: COP(reg)->push.addr = -mod_tlen;
                add_op(
                    reg,
                    OpCode::Push,
                    OperationPayload::Push { addr: -mod_tlen },
                );
            }
        }
    } else if qn.lower == qn.upper {
        // {n} exact repeat
        if qn.lower == 1 {
            return compile_tree(body, reg, env);
        }
        // Unroll small exact repeats into flat bytecode (no REPEAT/REPEAT_INC overhead)
        if !is_empty && qn.include_referred == 0 && qn.lower <= EXACT_REPEAT_UNROLL_THRESHOLD {
            return compile_tree_n_times(body, qn.lower, reg, env);
        }
        // Use REPEAT opcode for large or empty-body repeats
        let id = entry_repeat_range(reg, qn.lower, qn.upper);
        if let Err(e) = id {
            return e;
        }
        let id = id.unwrap();

        add_op(
            reg,
            OpCode::Repeat,
            OperationPayload::Repeat {
                id,
                addr: SIZE_INC + mod_tlen + OPSIZE_REPEAT_INC,
            },
        );
        // Patch u_offset to point to the body start (op after REPEAT)
        reg.repeat_range[id as usize].u_offset = reg.ops.len() as i32;
        let r =
            compile_quant_body_with_empty_check(body, reg, env, qn.emptiness, qn.empty_status_mem);
        if r != 0 {
            return r;
        }
        add_op(
            reg,
            if qn.greedy {
                OpCode::RepeatInc
            } else {
                OpCode::RepeatIncNg
            },
            OperationPayload::RepeatInc { id },
        );
    } else if !qn.greedy && qn.upper == 1 && qn.lower == 0 {
        // ?? path: PUSH(skip JUMP + SIZE_INC) + JUMP(skip body + SIZE_INC) + body
        // C: COP(reg)->push.addr = SIZE_INC + OPSIZE_JUMP;
        add_op(
            reg,
            OpCode::Push,
            OperationPayload::Push {
                addr: SIZE_INC + OPSIZE_JUMP,
            },
        );
        // C: COP(reg)->jump.addr = body_len + SIZE_INC;
        add_op(
            reg,
            OpCode::Jump,
            OperationPayload::Jump {
                addr: body_len + SIZE_INC,
            },
        );
        let r = compile_tree(body, reg, env);
        if r != 0 {
            return r;
        }
    } else if qn.greedy
        && !is_infinite_repeat(qn.upper)
        // Keep this in sync with compile_length_quantifier_node above.
        && (quantifier_body_contains_recursion(body)
            || can_expand_finite_greedy_quantifier(body_len, qn.upper))
    {
        // Greedy expansion: body*lower + (upper-lower) * (PUSH + body)
        let r = compile_tree_n_times(body, qn.lower, reg, env);
        if r != 0 {
            return r;
        }
        let n = qn.upper - qn.lower;
        let iteration_len = match body_len.checked_add(OPSIZE_PUSH) {
            Some(len) => len,
            None => return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE,
        };
        for i in 0..n {
            let push_addr = match (n - i).checked_mul(iteration_len) {
                Some(addr) => addr,
                None => return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE,
            };
            add_op(
                reg,
                OpCode::Push,
                OperationPayload::Push { addr: push_addr },
            );
            let r = compile_tree(body, reg, env);
            if r != 0 {
                return r;
            }
        }
    } else {
        // {n,m} range repeat (lazy non-trivial)
        let id = entry_repeat_range(reg, qn.lower, qn.upper);
        if let Err(e) = id {
            return e;
        }
        let id = id.unwrap();

        let opcode = if qn.greedy {
            OpCode::Repeat
        } else {
            OpCode::RepeatNg
        };
        add_op(
            reg,
            opcode,
            OperationPayload::Repeat {
                id,
                addr: SIZE_INC + mod_tlen + OPSIZE_REPEAT_INC,
            },
        );
        // Patch u_offset to point to the body start (op after REPEAT)
        reg.repeat_range[id as usize].u_offset = reg.ops.len() as i32;
        let r =
            compile_quant_body_with_empty_check(body, reg, env, qn.emptiness, qn.empty_status_mem);
        if r != 0 {
            return r;
        }
        add_op(
            reg,
            if qn.greedy {
                OpCode::RepeatInc
            } else {
                OpCode::RepeatIncNg
            },
            OperationPayload::RepeatInc { id },
        );
    }

    0
}

// ============================================================================
// Bag (group) compilation
// ============================================================================

/// Calculate bytecode length for a bag node.
fn compile_length_bag_node(
    bag: &BagNode,
    node_status: u32,
    reg: &RegexType,
    env: &ParseEnv,
) -> i32 {
    let body = bag.body.as_ref();

    match bag.bag_type {
        BagType::Memory => {
            let body_len = if let Some(b) = body {
                compile_length_tree(b, reg, env)
            } else {
                0
            };
            if body_len < 0 {
                return body_len;
            }
            let regnum = match &bag.bag_data {
                BagData::Memory { regnum, .. } => *regnum,
                _ => 0,
            };
            if regnum == 0 && (node_status & ND_ST_CALLED) != 0 {
                // \g<0> wrapper: CALL + JUMP + body + RETURN (no MEM_START/END)
                return OPSIZE_CALL + OPSIZE_JUMP + body_len + OPSIZE_RETURN;
            }
            let mut len = OPSIZE_MEM_START + body_len + OPSIZE_MEM_END;
            if (node_status & ND_ST_CALLED) != 0 {
                // Called group: CALL + JUMP + (MEM_START + body + MEM_END + RETURN)
                len += OPSIZE_CALL + OPSIZE_JUMP + OPSIZE_RETURN;
            }
            len
        }
        BagType::StopBacktrack => {
            let body_len = if let Some(b) = body {
                compile_length_tree(b, reg, env)
            } else {
                0
            };
            if body_len < 0 {
                return body_len;
            }
            // MARK + body + CUT_TO_MARK
            OPSIZE_MARK + body_len + OPSIZE_CUT_TO_MARK
        }
        BagType::Option => {
            let body_len = if let Some(b) = body {
                compile_length_tree(b, reg, env)
            } else {
                0
            };
            if body_len < 0 {
                return body_len;
            }
            body_len
        }
        BagType::IfElse => {
            // Conditional: MARK + PUSH + condition + CUT_TO_MARK + then + JUMP + CUT_TO_MARK + else
            let cond_len = if let Some(b) = body {
                compile_length_tree(b, reg, env)
            } else {
                0
            };
            if cond_len < 0 {
                return cond_len;
            }

            let mut len = OPSIZE_PUSH + OPSIZE_MARK + cond_len + OPSIZE_CUT_TO_MARK;

            if let BagData::IfElse {
                ref then_node,
                ref else_node,
            } = bag.bag_data
            {
                if let Some(ref then_n) = then_node {
                    let tlen = compile_length_tree(then_n, reg, env);
                    if tlen < 0 {
                        return tlen;
                    }
                    len += tlen;
                }

                len += OPSIZE_JUMP + OPSIZE_CUT_TO_MARK;

                if let Some(ref else_n) = else_node {
                    let elen = compile_length_tree(else_n, reg, env);
                    if elen < 0 {
                        return elen;
                    }
                    len += elen;
                }
            }

            len
        }
    }
}

/// Compile a bag memory (capture group) node.
fn compile_bag_memory_node(
    bag: &BagNode,
    node_status: u32,
    reg: &mut RegexType,
    env: &ParseEnv,
) -> i32 {
    let regnum = match &bag.bag_data {
        BagData::Memory { regnum, .. } => *regnum,
        _ => return ONIGERR_TYPE_BUG,
    };

    let is_called = (node_status & ND_ST_CALLED) != 0;

    if is_called {
        // Called group: emit CALL + JUMP wrapper
        let body_len = if let Some(body) = &bag.body {
            compile_length_tree(body, reg, env)
        } else {
            0
        };
        if body_len < 0 {
            return body_len;
        }

        if regnum == 0 {
            // \g<0> wrapper: simpler layout without MEM_START/END
            // Layout: CALL(entry) + JUMP(skip) + [entry: body + RETURN]
            let callable_len = body_len + OPSIZE_RETURN;

            let call_idx = reg.ops.len();
            let entry_addr = (call_idx + 2) as i32;
            add_op(
                reg,
                OpCode::Call,
                OperationPayload::Call { addr: entry_addr },
            );

            add_op(
                reg,
                OpCode::Jump,
                OperationPayload::Jump {
                    addr: callable_len + SIZE_INC,
                },
            );

            let called_addr = reg.ops.len() as i32;
            if reg.called_addrs.is_empty() {
                reg.called_addrs.resize(1, -1);
            }
            reg.called_addrs[0] = called_addr;

            if let Some(body) = &bag.body {
                let r = compile_tree(body, reg, env);
                if r != 0 {
                    return r;
                }
            }

            add_op(reg, OpCode::Return, OperationPayload::Return);
            return 0;
        }

        // Regular called group: CALL + JUMP + MEM_START + body + MEM_END + RETURN
        let callable_len = OPSIZE_MEM_START + body_len + OPSIZE_MEM_END + OPSIZE_RETURN;

        let call_idx = reg.ops.len();
        let entry_addr = (call_idx + 2) as i32;
        add_op(
            reg,
            OpCode::Call,
            OperationPayload::Call { addr: entry_addr },
        );

        add_op(
            reg,
            OpCode::Jump,
            OperationPayload::Jump {
                addr: callable_len + SIZE_INC,
            },
        );

        let called_addr = reg.ops.len() as i32;
        if reg.called_addrs.len() <= regnum as usize {
            reg.called_addrs.resize(regnum as usize + 1, -1);
        }
        reg.called_addrs[regnum as usize] = called_addr;
    }

    // Determine if we need push variants
    let need_push = mem_status_at(reg.push_mem_start, regnum as usize);

    if need_push {
        add_op(
            reg,
            OpCode::MemStartPush,
            OperationPayload::MemoryStart { num: regnum },
        );
    } else {
        add_op(
            reg,
            OpCode::MemStart,
            OperationPayload::MemoryStart { num: regnum },
        );
    }

    if let Some(body) = &bag.body {
        let r = compile_tree(body, reg, env);
        if r != 0 {
            return r;
        }
    }

    let need_push_end = mem_status_at(reg.push_mem_end, regnum as usize);
    let is_recursion = (node_status & ND_ST_RECURSION) != 0;
    if need_push_end {
        let opcode = if is_recursion {
            OpCode::MemEndPushRec
        } else {
            OpCode::MemEndPush
        };
        add_op(reg, opcode, OperationPayload::MemoryEnd { num: regnum });
    } else {
        let opcode = if is_recursion {
            OpCode::MemEndRec
        } else {
            OpCode::MemEnd
        };
        add_op(reg, opcode, OperationPayload::MemoryEnd { num: regnum });
    }

    if is_called {
        add_op(reg, OpCode::Return, OperationPayload::Return);
    }

    0
}

/// Compile a bag node to bytecode.
fn compile_bag_node(bag: &BagNode, node_status: u32, reg: &mut RegexType, env: &ParseEnv) -> i32 {
    match bag.bag_type {
        BagType::Memory => compile_bag_memory_node(bag, node_status, reg, env),
        BagType::StopBacktrack => {
            let id = reg.num_call; // use call count as mark ID
            reg.num_call += 1;

            add_op(
                reg,
                OpCode::Mark,
                OperationPayload::Mark { id, save_pos: true },
            );

            if let Some(body) = &bag.body {
                let r = compile_tree(body, reg, env);
                if r != 0 {
                    return r;
                }
            }

            add_op(
                reg,
                OpCode::CutToMark,
                OperationPayload::CutToMark {
                    id,
                    restore_pos: false,
                },
            );

            0
        }
        BagType::Option => {
            // Option change: just compile the body with the option set.
            // The option was already applied to the parse env during parsing.
            if let Some(body) = &bag.body {
                return compile_tree(body, reg, env);
            }
            0
        }
        BagType::IfElse => {
            let id = reg.num_call;
            reg.num_call += 1;

            // Emit MARK
            add_op(
                reg,
                OpCode::Mark,
                OperationPayload::Mark {
                    id,
                    save_pos: false,
                },
            );

            // Calculate condition and then lengths for PUSH address
            let cond_len = if let Some(body) = &bag.body {
                compile_length_tree(body, reg, env)
            } else {
                0
            };
            if cond_len < 0 {
                return cond_len;
            }

            let then_len = if let BagData::IfElse { ref then_node, .. } = bag.bag_data {
                then_node
                    .as_ref()
                    .map_or(0, |then_n| compile_length_tree(then_n, reg, env))
            } else {
                0
            };
            if then_len < 0 {
                return then_len;
            }

            let jump_len = cond_len + OPSIZE_CUT_TO_MARK + then_len + OPSIZE_JUMP;

            // Emit PUSH to else section
            add_op(
                reg,
                OpCode::Push,
                OperationPayload::Push {
                    addr: SIZE_INC + jump_len,
                },
            );

            // Emit condition
            if let Some(body) = &bag.body {
                let r = compile_tree(body, reg, env);
                if r != 0 {
                    return r;
                }
            }

            // On condition success, cut mark
            add_op(
                reg,
                OpCode::CutToMark,
                OperationPayload::CutToMark {
                    id,
                    restore_pos: false,
                },
            );

            // Emit then branch
            if let BagData::IfElse {
                ref then_node,
                ref else_node,
            } = bag.bag_data
            {
                if let Some(ref then_n) = then_node {
                    let r = compile_tree(then_n, reg, env);
                    if r != 0 {
                        return r;
                    }
                }

                // Calculate else length for JUMP
                let else_len = if let Some(ref else_n) = else_node {
                    compile_length_tree(else_n, reg, env)
                } else {
                    0
                };
                if else_len < 0 {
                    return else_len;
                }

                // Jump over else
                add_op(
                    reg,
                    OpCode::Jump,
                    OperationPayload::Jump {
                        addr: OPSIZE_CUT_TO_MARK + else_len + SIZE_INC,
                    },
                );

                // On condition failure, cut mark
                add_op(
                    reg,
                    OpCode::CutToMark,
                    OperationPayload::CutToMark {
                        id,
                        restore_pos: false,
                    },
                );

                // Emit else branch
                if let Some(ref else_n) = else_node {
                    let r = compile_tree(else_n, reg, env);
                    if r != 0 {
                        return r;
                    }
                }
            }

            0
        }
    }
}

// ============================================================================
// Anchor compilation
// ============================================================================

/// Calculate bytecode length for an anchor node.
fn compile_length_anchor_node(an: &AnchorNode, reg: &RegexType, env: &ParseEnv) -> i32 {
    let at = an.anchor_type;

    if at == ANCR_PREC_READ {
        // (?=...) positive lookahead: MARK + body + CUT_TO_MARK
        let body_len = if let Some(body) = &an.body {
            compile_length_tree(body, reg, env)
        } else {
            0
        };
        if body_len < 0 {
            return body_len;
        }
        OPSIZE_MARK + body_len + OPSIZE_CUT_TO_MARK
    } else if at == ANCR_PREC_READ_NOT {
        // (?!...) negative lookahead: PUSH + MARK + body + POP_TO_MARK + POP + FAIL
        let body_len = if let Some(body) = &an.body {
            compile_length_tree(body, reg, env)
        } else {
            0
        };
        if body_len < 0 {
            return body_len;
        }
        OPSIZE_PUSH + OPSIZE_MARK + body_len + OPSIZE_POP_TO_MARK + OPSIZE_POP + OPSIZE_FAIL
    } else if at == ANCR_LOOK_BEHIND {
        // (?<=...) positive lookbehind
        let body_len = if let Some(body) = &an.body {
            compile_length_tree(body, reg, env)
        } else {
            0
        };
        if body_len < 0 {
            return body_len;
        }
        if an.char_min_len == an.char_max_len {
            // Fixed-length
            OPSIZE_MARK + OPSIZE_STEP_BACK_START + body_len + OPSIZE_CUT_TO_MARK
        } else {
            // Variable-length: SAVE_VAL + UPDATE_VAR + MARK + PUSH + JUMP +
            //   UPDATE_VAR + FAIL + [SAVE_VAL] + STEP_BACK_START + STEP_BACK_NEXT +
            //   body + [UPDATE_VAR] + CHECK_POSITION + CUT_TO_MARK + UPDATE_VAR
            let mut len = OPSIZE_SAVE_VAL
                + OPSIZE_UPDATE_VAR
                + OPSIZE_MARK
                + OPSIZE_PUSH
                + OPSIZE_JUMP
                + OPSIZE_UPDATE_VAR
                + OPSIZE_FAIL
                + OPSIZE_STEP_BACK_START
                + OPSIZE_STEP_BACK_NEXT
                + body_len
                + OPSIZE_CHECK_POSITION
                + OPSIZE_CUT_TO_MARK
                + OPSIZE_UPDATE_VAR;
            if (env.flags & PE_FLAG_HAS_ABSENT_STOPPER) != 0 {
                len += OPSIZE_SAVE_VAL + OPSIZE_UPDATE_VAR;
            }
            len
        }
    } else if at == ANCR_LOOK_BEHIND_NOT {
        // (?<!...) negative lookbehind
        let body_len = if let Some(body) = &an.body {
            compile_length_tree(body, reg, env)
        } else {
            0
        };
        if body_len < 0 {
            return body_len;
        }
        if an.char_min_len == an.char_max_len {
            // Fixed-length
            OPSIZE_MARK
                + OPSIZE_PUSH
                + OPSIZE_STEP_BACK_START
                + body_len
                + OPSIZE_POP_TO_MARK
                + OPSIZE_FAIL
                + OPSIZE_POP
        } else {
            // Variable-length: SAVE_VAL + UPDATE_VAR + MARK + PUSH +
            //   [SAVE_VAL] + STEP_BACK_START + STEP_BACK_NEXT + body + [UPDATE_VAR] +
            //   CHECK_POSITION + POP_TO_MARK + UPDATE_VAR + POP + FAIL +
            //   UPDATE_VAR + POP + POP
            let mut len = OPSIZE_SAVE_VAL
                + OPSIZE_UPDATE_VAR
                + OPSIZE_MARK
                + OPSIZE_PUSH
                + OPSIZE_STEP_BACK_START
                + OPSIZE_STEP_BACK_NEXT
                + body_len
                + OPSIZE_CHECK_POSITION
                + OPSIZE_POP_TO_MARK
                + OPSIZE_UPDATE_VAR
                + OPSIZE_POP
                + OPSIZE_FAIL
                + OPSIZE_UPDATE_VAR
                + OPSIZE_POP
                + OPSIZE_POP;
            if (env.flags & PE_FLAG_HAS_ABSENT_STOPPER) != 0 {
                len += OPSIZE_SAVE_VAL + OPSIZE_UPDATE_VAR;
            }
            len
        }
    } else {
        // Simple anchors: ^, $, \b, \B, \A, \z, etc.
        SIZE_INC
    }
}

/// Compile an anchor node to bytecode.
fn compile_anchor_node(
    an: &AnchorNode,
    node_status: u32,
    reg: &mut RegexType,
    env: &ParseEnv,
) -> i32 {
    let at = an.anchor_type;

    if at == ANCR_PREC_READ {
        // (?=...) positive lookahead
        let id = reg.num_call;
        reg.num_call += 1;

        add_op(
            reg,
            OpCode::Mark,
            OperationPayload::Mark { id, save_pos: true },
        );

        if let Some(body) = &an.body {
            let r = compile_tree(body, reg, env);
            if r != 0 {
                return r;
            }
        }

        add_op(
            reg,
            OpCode::CutToMark,
            OperationPayload::CutToMark {
                id,
                restore_pos: true,
            },
        );
        return 0;
    }

    if at == ANCR_PREC_READ_NOT {
        // (?!...) negative lookahead
        let body_len = if let Some(body) = &an.body {
            compile_length_tree(body, reg, env)
        } else {
            0
        };

        let id = reg.num_call;
        reg.num_call += 1;

        // PUSH past the fail section (C: SIZE_INC + MARK + body + POP_TO_MARK + POP + FAIL)
        let push_addr =
            SIZE_INC + OPSIZE_MARK + body_len + OPSIZE_POP_TO_MARK + OPSIZE_POP + OPSIZE_FAIL;
        add_op(
            reg,
            OpCode::Push,
            OperationPayload::Push { addr: push_addr },
        );

        add_op(
            reg,
            OpCode::Mark,
            OperationPayload::Mark {
                id,
                save_pos: false,
            },
        );

        if let Some(body) = &an.body {
            let r = compile_tree(body, reg, env);
            if r != 0 {
                return r;
            }
        }

        add_op(reg, OpCode::PopToMark, OperationPayload::PopToMark { id });
        add_op(reg, OpCode::Pop, OperationPayload::None);
        add_op(reg, OpCode::Fail, OperationPayload::None);
        return 0;
    }

    if at == ANCR_LOOK_BEHIND {
        if an.char_min_len == an.char_max_len {
            // (?<=...) positive lookbehind — fixed-length
            let id = reg.num_call;
            reg.num_call += 1;

            add_op(
                reg,
                OpCode::Mark,
                OperationPayload::Mark { id, save_pos: true },
            );

            let char_len = an.char_min_len as i32;
            add_op(
                reg,
                OpCode::StepBackStart,
                OperationPayload::StepBackStart {
                    initial: char_len,
                    remaining: 0,
                    addr: 1,
                },
            );

            if let Some(body) = &an.body {
                let r = compile_tree(body, reg, env);
                if r != 0 {
                    return r;
                }
            }

            add_op(
                reg,
                OpCode::CutToMark,
                OperationPayload::CutToMark {
                    id,
                    restore_pos: true,
                },
            );
        } else {
            // (?<=...) positive lookbehind — variable-length
            let mid1 = reg.num_call;
            reg.num_call += 1;
            let mid2 = reg.num_call;
            reg.num_call += 1;

            // SAVE_VAL(RightRange, mid1)
            add_op(
                reg,
                OpCode::SaveVal,
                OperationPayload::SaveVal {
                    save_type: SaveType::RightRange,
                    id: mid1,
                },
            );
            // UPDATE_VAR(RightRangeToS)
            add_op(
                reg,
                OpCode::UpdateVar,
                OperationPayload::UpdateVar {
                    var_type: UpdateVarType::RightRangeToS,
                    id: 0,
                    clear: false,
                },
            );
            // MARK(mid2, save_pos=false)
            add_op(
                reg,
                OpCode::Mark,
                OperationPayload::Mark {
                    id: mid2,
                    save_pos: false,
                },
            );
            // PUSH(addr → JUMP instruction, i.e. skip past JUMP to UPDATE_VAR)
            // PUSH is at position X, JUMP at X+1, UPDATE_VAR at X+2
            // So alt target = X + SIZE_INC + OPSIZE_JUMP = X + 2 → UPDATE_VAR
            add_op(
                reg,
                OpCode::Push,
                OperationPayload::Push {
                    addr: SIZE_INC + OPSIZE_JUMP,
                },
            );
            // JUMP(addr → past UPDATE_VAR + FAIL to STEP_BACK_START)
            add_op(
                reg,
                OpCode::Jump,
                OperationPayload::Jump {
                    addr: SIZE_INC + OPSIZE_UPDATE_VAR + OPSIZE_FAIL,
                },
            );
            // UPDATE_VAR(RightRangeFromStack, mid1, clear=false) — fail path restores right_range
            add_op(
                reg,
                OpCode::UpdateVar,
                OperationPayload::UpdateVar {
                    var_type: UpdateVarType::RightRangeFromStack,
                    id: mid1,
                    clear: false,
                },
            );
            // FAIL
            add_op(reg, OpCode::Fail, OperationPayload::None);

            // Absent stopper: save right-range before step-back
            let mid3 = if (env.flags & PE_FLAG_HAS_ABSENT_STOPPER) != 0 {
                let mid3 = reg.num_call;
                reg.num_call += 1;
                add_op(
                    reg,
                    OpCode::SaveVal,
                    OperationPayload::SaveVal {
                        save_type: SaveType::RightRange,
                        id: mid3,
                    },
                );
                mid3
            } else {
                0
            };

            // STEP_BACK_START(initial=min, remaining=max-min, addr=2)
            let diff = if an.char_max_len != INFINITE_LEN {
                (an.char_max_len - an.char_min_len) as i32
            } else {
                INFINITE_LEN as i32
            };
            add_op(
                reg,
                OpCode::StepBackStart,
                OperationPayload::StepBackStart {
                    initial: an.char_min_len as i32,
                    remaining: diff,
                    addr: 2,
                },
            );
            // STEP_BACK_NEXT
            add_op(reg, OpCode::StepBackNext, OperationPayload::None);

            // <body>
            if let Some(body) = &an.body {
                let r = compile_tree(body, reg, env);
                if r != 0 {
                    return r;
                }
            }

            // Absent stopper: restore right-range after body
            if (env.flags & PE_FLAG_HAS_ABSENT_STOPPER) != 0 {
                add_op(
                    reg,
                    OpCode::UpdateVar,
                    OperationPayload::UpdateVar {
                        var_type: UpdateVarType::RightRangeFromStack,
                        id: mid3,
                        clear: false,
                    },
                );
            }

            // CHECK_POSITION(CurrentRightRange)
            add_op(
                reg,
                OpCode::CheckPosition,
                OperationPayload::CheckPosition {
                    check_type: CheckPositionType::CurrentRightRange,
                },
            );
            // CUT_TO_MARK(mid2, restore_pos=false)
            add_op(
                reg,
                OpCode::CutToMark,
                OperationPayload::CutToMark {
                    id: mid2,
                    restore_pos: false,
                },
            );
            // UPDATE_VAR(RightRangeFromStack, mid1, clear=true)
            add_op(
                reg,
                OpCode::UpdateVar,
                OperationPayload::UpdateVar {
                    var_type: UpdateVarType::RightRangeFromStack,
                    id: mid1,
                    clear: true,
                },
            );
        }
        return 0;
    }

    if at == ANCR_LOOK_BEHIND_NOT {
        let body_len = if let Some(body) = &an.body {
            compile_length_tree(body, reg, env)
        } else {
            0
        };

        if an.char_min_len == an.char_max_len {
            // (?<!...) negative lookbehind — fixed-length
            let id = reg.num_call;
            reg.num_call += 1;

            add_op(
                reg,
                OpCode::Mark,
                OperationPayload::Mark {
                    id,
                    save_pos: false,
                },
            );

            let push_addr =
                SIZE_INC + OPSIZE_STEP_BACK_START + body_len + OPSIZE_POP_TO_MARK + OPSIZE_FAIL;
            add_op(
                reg,
                OpCode::Push,
                OperationPayload::Push { addr: push_addr },
            );

            let char_len = an.char_min_len as i32;
            add_op(
                reg,
                OpCode::StepBackStart,
                OperationPayload::StepBackStart {
                    initial: char_len,
                    remaining: 0,
                    addr: 1,
                },
            );

            if let Some(body) = &an.body {
                let r = compile_tree(body, reg, env);
                if r != 0 {
                    return r;
                }
            }

            add_op(reg, OpCode::PopToMark, OperationPayload::PopToMark { id });
            add_op(reg, OpCode::Fail, OperationPayload::None);
            add_op(reg, OpCode::Pop, OperationPayload::None);
        } else {
            // (?<!...) negative lookbehind — variable-length
            let mid1 = reg.num_call;
            reg.num_call += 1;
            let mid2 = reg.num_call;
            reg.num_call += 1;

            // SAVE_VAL(RightRange, mid1)
            add_op(
                reg,
                OpCode::SaveVal,
                OperationPayload::SaveVal {
                    save_type: SaveType::RightRange,
                    id: mid1,
                },
            );
            // UPDATE_VAR(RightRangeToS)
            add_op(
                reg,
                OpCode::UpdateVar,
                OperationPayload::UpdateVar {
                    var_type: UpdateVarType::RightRangeToS,
                    id: 0,
                    clear: false,
                },
            );
            // MARK(mid2, save_pos=false)
            add_op(
                reg,
                OpCode::Mark,
                OperationPayload::Mark {
                    id: mid2,
                    save_pos: false,
                },
            );
            // PUSH(addr → success path past body-matched-fail section)
            // From PUSH: skip [SAVE_VAL] + STEP_BACK_START + STEP_BACK_NEXT + body +
            //   [UPDATE_VAR] + CHECK_POSITION + POP_TO_MARK + UPDATE_VAR + POP + FAIL
            let mut push_addr = SIZE_INC
                + OPSIZE_STEP_BACK_START
                + OPSIZE_STEP_BACK_NEXT
                + body_len
                + OPSIZE_CHECK_POSITION
                + OPSIZE_POP_TO_MARK
                + OPSIZE_UPDATE_VAR
                + OPSIZE_POP
                + OPSIZE_FAIL;
            if (env.flags & PE_FLAG_HAS_ABSENT_STOPPER) != 0 {
                push_addr += OPSIZE_SAVE_VAL + OPSIZE_UPDATE_VAR;
            }
            add_op(
                reg,
                OpCode::Push,
                OperationPayload::Push { addr: push_addr },
            );

            // Absent stopper: save right-range before step-back
            let mid3 = if (env.flags & PE_FLAG_HAS_ABSENT_STOPPER) != 0 {
                let mid3 = reg.num_call;
                reg.num_call += 1;
                add_op(
                    reg,
                    OpCode::SaveVal,
                    OperationPayload::SaveVal {
                        save_type: SaveType::RightRange,
                        id: mid3,
                    },
                );
                mid3
            } else {
                0
            };

            // STEP_BACK_START(initial=min, remaining=max-min, addr=2)
            let diff = if an.char_max_len != INFINITE_LEN {
                (an.char_max_len - an.char_min_len) as i32
            } else {
                INFINITE_LEN as i32
            };
            add_op(
                reg,
                OpCode::StepBackStart,
                OperationPayload::StepBackStart {
                    initial: an.char_min_len as i32,
                    remaining: diff,
                    addr: 2,
                },
            );
            // STEP_BACK_NEXT
            add_op(reg, OpCode::StepBackNext, OperationPayload::None);

            // <body>
            if let Some(body) = &an.body {
                let r = compile_tree(body, reg, env);
                if r != 0 {
                    return r;
                }
            }

            // Absent stopper: restore right-range after body
            if (env.flags & PE_FLAG_HAS_ABSENT_STOPPER) != 0 {
                add_op(
                    reg,
                    OpCode::UpdateVar,
                    OperationPayload::UpdateVar {
                        var_type: UpdateVarType::RightRangeFromStack,
                        id: mid3,
                        clear: false,
                    },
                );
            }

            // CHECK_POSITION(CurrentRightRange) — body matched here, verify position
            add_op(
                reg,
                OpCode::CheckPosition,
                OperationPayload::CheckPosition {
                    check_type: CheckPositionType::CurrentRightRange,
                },
            );
            // POP_TO_MARK(mid2) — body succeeded: clean up mark
            add_op(
                reg,
                OpCode::PopToMark,
                OperationPayload::PopToMark { id: mid2 },
            );
            // UPDATE_VAR(RightRangeFromStack, mid1, clear=false) — restore right_range
            add_op(
                reg,
                OpCode::UpdateVar,
                OperationPayload::UpdateVar {
                    var_type: UpdateVarType::RightRangeFromStack,
                    id: mid1,
                    clear: false,
                },
            );
            // POP — discard outer PUSH's SaveVal
            add_op(reg, OpCode::Pop, OperationPayload::None);
            // FAIL — negative lookbehind: body match = overall failure
            add_op(reg, OpCode::Fail, OperationPayload::None);

            // === Success path (body failed at all positions) ===
            // UPDATE_VAR(RightRangeFromStack, mid1, clear=false) — restore right_range
            add_op(
                reg,
                OpCode::UpdateVar,
                OperationPayload::UpdateVar {
                    var_type: UpdateVarType::RightRangeFromStack,
                    id: mid1,
                    clear: false,
                },
            );
            // POP — discard Mark
            add_op(reg, OpCode::Pop, OperationPayload::None);
            // POP — discard SaveVal
            add_op(reg, OpCode::Pop, OperationPayload::None);
        }
        return 0;
    }

    // Simple anchors
    match at {
        ANCR_BEGIN_BUF => {
            add_op(reg, OpCode::BeginBuf, OperationPayload::None);
        }
        ANCR_END_BUF => {
            add_op(reg, OpCode::EndBuf, OperationPayload::None);
        }
        ANCR_BEGIN_LINE => {
            add_op(reg, OpCode::BeginLine, OperationPayload::None);
        }
        ANCR_END_LINE => {
            add_op(reg, OpCode::EndLine, OperationPayload::None);
        }
        ANCR_SEMI_END_BUF => {
            add_op(reg, OpCode::SemiEndBuf, OperationPayload::None);
        }
        ANCR_BEGIN_POSITION => {
            add_op(
                reg,
                OpCode::CheckPosition,
                OperationPayload::CheckPosition {
                    check_type: CheckPositionType::SearchStart,
                },
            );
        }
        ANCR_WORD_BOUNDARY => {
            let mode = if an.ascii_mode { 1 } else { 0 };
            add_op(
                reg,
                OpCode::WordBoundary,
                OperationPayload::WordBoundary { mode },
            );
        }
        ANCR_NO_WORD_BOUNDARY => {
            let mode = if an.ascii_mode { 1 } else { 0 };
            add_op(
                reg,
                OpCode::NoWordBoundary,
                OperationPayload::WordBoundary { mode },
            );
        }
        ANCR_WORD_BEGIN => {
            let mode = if an.ascii_mode { 1 } else { 0 };
            add_op(
                reg,
                OpCode::WordBegin,
                OperationPayload::WordBoundary { mode },
            );
        }
        ANCR_WORD_END => {
            let mode = if an.ascii_mode { 1 } else { 0 };
            add_op(
                reg,
                OpCode::WordEnd,
                OperationPayload::WordBoundary { mode },
            );
        }
        ANCR_TEXT_SEGMENT_BOUNDARY | ANCR_NO_TEXT_SEGMENT_BOUNDARY => {
            let boundary_type = if (node_status & ND_ST_TEXT_SEGMENT_WORD) != 0 {
                TextSegmentBoundaryType::Word
            } else {
                TextSegmentBoundaryType::ExtendedGraphemeCluster
            };
            let not = at == ANCR_NO_TEXT_SEGMENT_BOUNDARY;
            add_op(
                reg,
                OpCode::TextSegmentBoundary,
                OperationPayload::TextSegmentBoundary { boundary_type, not },
            );
        }
        _ => {
            return ONIGERR_TYPE_BUG;
        }
    }

    0
}

// ============================================================================
// Gimmick compilation
// ============================================================================

/// Calculate bytecode length for a gimmick node.
fn compile_length_gimmick_node(gn: &GimmickNode) -> i32 {
    match gn.gimmick_type {
        GimmickType::Fail => SIZE_INC,
        GimmickType::Save => OPSIZE_SAVE_VAL,
        GimmickType::UpdateVar => OPSIZE_UPDATE_VAR,
        GimmickType::Callout => SIZE_INC,
    }
}

/// Compile a gimmick node to bytecode.
fn compile_gimmick_node(gn: &GimmickNode, reg: &mut RegexType, env: &ParseEnv) -> i32 {
    match gn.gimmick_type {
        GimmickType::Fail => {
            add_op(reg, OpCode::Fail, OperationPayload::None);
        }
        GimmickType::Save => {
            let save_type = match gn.detail_type {
                1 => SaveType::S,
                2 => SaveType::RightRange,
                _ => SaveType::Keep,
            };
            add_op(
                reg,
                OpCode::SaveVal,
                OperationPayload::SaveVal {
                    save_type,
                    id: gn.id,
                },
            );
        }
        GimmickType::UpdateVar => {
            let var_type = match gn.detail_type {
                1 => UpdateVarType::SFromStack,
                2 => UpdateVarType::RightRangeFromStack,
                3 => UpdateVarType::RightRangeFromSStack,
                4 => UpdateVarType::RightRangeToS,
                5 => UpdateVarType::RightRangeInit,
                _ => UpdateVarType::KeepFromStackLast,
            };
            add_op(
                reg,
                OpCode::UpdateVar,
                OperationPayload::UpdateVar {
                    var_type,
                    id: gn.id,
                    clear: false,
                },
            );
        }
        GimmickType::Callout => {
            if gn.detail_type == OnigCalloutOf::Name as i32 {
                add_op(
                    reg,
                    OpCode::CalloutName,
                    OperationPayload::CalloutName {
                        num: gn.num,
                        id: gn.id,
                    },
                );
            } else {
                add_op(
                    reg,
                    OpCode::CalloutContents,
                    OperationPayload::CalloutContents { num: gn.num },
                );
            }
        }
    }
    0
}

// ============================================================================
// Main compilation passes
// ============================================================================

/// Pass 1: Calculate the bytecode length needed for a node tree.
/// Returns the number of operations that will be generated.
pub fn compile_length_tree(node: &Node, reg: &RegexType, env: &ParseEnv) -> i32 {
    // Literal alternation trie: single AltLiterals opcode.
    if node.has_status(ND_ST_LITERAL_ALT) {
        return SIZE_INC;
    }

    match &node.inner {
        NodeInner::List(cons) => {
            let mut len = 0i32;
            // Compile car
            len += compile_length_tree(&cons.car, reg, env);
            // Walk cdr chain
            let mut cur = cons.cdr.as_ref();
            while let Some(next) = cur {
                if let NodeInner::List(c) = &next.inner {
                    len += compile_length_tree(&c.car, reg, env);
                    cur = c.cdr.as_ref();
                } else {
                    len += compile_length_tree(next, reg, env);
                    break;
                }
            }
            len
        }

        NodeInner::Alt(cons) => {
            // For alternation, each branch needs PUSH + body + JUMP (except last)
            let mut total = 0i32;
            let mut n_alts = 0i32;

            // First alternative
            let first_len = compile_length_tree(&cons.car, reg, env);
            total += first_len;
            n_alts += 1;

            let mut cur = cons.cdr.as_ref();
            while let Some(next) = cur {
                if let NodeInner::Alt(c) = &next.inner {
                    let branch_len = compile_length_tree(&c.car, reg, env);
                    total += branch_len;
                    n_alts += 1;
                    cur = c.cdr.as_ref();
                } else {
                    let branch_len = compile_length_tree(next, reg, env);
                    total += branch_len;
                    n_alts += 1;
                    cur = None;
                }
            }

            // Each branch except the last needs PUSH + JUMP
            total += (n_alts - 1) * (OPSIZE_PUSH + OPSIZE_JUMP);
            total
        }

        NodeInner::String(_) => {
            let sn = node.as_str().unwrap();
            if sn.is_crude() {
                compile_length_string_crude_node(node, reg)
            } else {
                compile_length_string_node(node, reg)
            }
        }

        NodeInner::CClass(cc) => compile_length_cclass_node(cc, reg),

        NodeInner::CType(ct) => SIZE_INC,

        NodeInner::BackRef(_br) => OPSIZE_BACKREF,

        NodeInner::Quant(qn) => compile_length_quantifier_node(qn, reg, env),

        NodeInner::Bag(bag) => compile_length_bag_node(bag, node.status, reg, env),

        NodeInner::Anchor(an) => compile_length_anchor_node(an, reg, env),

        NodeInner::Gimmick(gn) => compile_length_gimmick_node(gn),

        NodeInner::Call(_) => OPSIZE_CALL,
    }
}

/// Pass 2: Generate bytecode operations from the node tree.
/// Returns 0 on success or a negative error code.
pub fn compile_tree(node: &Node, reg: &mut RegexType, env: &ParseEnv) -> i32 {
    // Literal alternation trie: emit single AltLiterals opcode.
    if node.has_status(ND_ST_LITERAL_ALT) {
        if let NodeInner::String(ref sn) = node.inner {
            let trie_idx = u32::from_le_bytes([sn.s[0], sn.s[1], sn.s[2], sn.s[3]]);
            add_op(
                reg,
                OpCode::AltLiterals,
                OperationPayload::AltLiterals { trie_idx },
            );
            return 0;
        }
    }

    match &node.inner {
        NodeInner::List(cons) => {
            let r = compile_tree(&cons.car, reg, env);
            if r != 0 {
                return r;
            }
            let mut cur = cons.cdr.as_ref();
            while let Some(next) = cur {
                if let NodeInner::List(c) = &next.inner {
                    let r = compile_tree(&c.car, reg, env);
                    if r != 0 {
                        return r;
                    }
                    cur = c.cdr.as_ref();
                } else {
                    return compile_tree(next, reg, env);
                }
            }
            0
        }

        NodeInner::Alt(cons) => {
            // Check if this Alt has SUPER status (used by absent function)
            let is_super = node.has_status(ND_ST_SUPER);
            let push_opcode = if is_super {
                OpCode::PushSuper
            } else {
                OpCode::Push
            };

            // Collect all alternatives to calculate lengths
            let mut branches: Vec<&Node> = Vec::new();
            branches.push(&cons.car);

            let mut cur = cons.cdr.as_ref();
            while let Some(next) = cur {
                if let NodeInner::Alt(c) = &next.inner {
                    branches.push(&c.car);
                    cur = c.cdr.as_ref();
                } else {
                    branches.push(next);
                    cur = None;
                }
            }

            let n = branches.len();
            if n == 1 {
                return compile_tree(branches[0], reg, env);
            }

            // Pre-calculate branch lengths
            let mut branch_lens: Vec<i32> = Vec::with_capacity(n);
            for b in &branches {
                branch_lens.push(compile_length_tree(b, reg, env));
            }

            // Calculate total length to find goal position
            // Layout: for each branch i < n-1: PUSH + body_i + JUMP; last branch: body_{n-1}
            let mut total_len = 0i32;
            for (i, branch_len) in branch_lens.iter().enumerate() {
                total_len += branch_len;
                if i < n - 1 {
                    total_len += OPSIZE_PUSH + OPSIZE_JUMP;
                }
            }

            let goal = reg.ops.len() as i32 + total_len;

            for (i, branch) in branches.iter().enumerate() {
                if i < n - 1 {
                    // PUSH to next alternative (skip over body + JUMP)
                    let push_addr = SIZE_INC + branch_lens[i] + OPSIZE_JUMP;
                    add_op(reg, push_opcode, OperationPayload::Push { addr: push_addr });
                }

                let r = compile_tree(branch, reg, env);
                if r != 0 {
                    return r;
                }

                if i < n - 1 {
                    // JUMP to end of alternation (goal position)
                    let jump_addr = goal - reg.ops.len() as i32;
                    add_op(
                        reg,
                        OpCode::Jump,
                        OperationPayload::Jump { addr: jump_addr },
                    );
                }
            }
            0
        }

        NodeInner::String(_) => {
            let sn = node.as_str().unwrap();
            if sn.is_crude() {
                compile_string_crude_node(node, reg)
            } else {
                compile_string_node(node, reg)
            }
        }

        NodeInner::CClass(cc) => compile_cclass_node(cc, reg),

        NodeInner::CType(ct) => {
            let opcode = match ct.ctype as u32 {
                ONIGENC_CTYPE_WORD => {
                    if ct.not {
                        if ct.ascii_mode {
                            OpCode::NoWordAscii
                        } else {
                            OpCode::NoWord
                        }
                    } else {
                        if ct.ascii_mode {
                            OpCode::WordAscii
                        } else {
                            OpCode::Word
                        }
                    }
                }
                _ => {
                    // Anychar type
                    if node.has_status(ND_ST_MULTILINE) {
                        OpCode::AnyCharMl
                    } else {
                        OpCode::AnyChar
                    }
                }
            };
            add_op(reg, opcode, OperationPayload::None);
            0
        }

        NodeInner::BackRef(br) => {
            let refs = br.back_refs();

            if node.has_status(ND_ST_CHECKER) {
                // BackRef checker for conditionals: (?(1)then|else)
                let ns = refs.to_vec();
                let opcode = if node.has_status(ND_ST_NEST_LEVEL) {
                    OpCode::BackRefCheckWithLevel
                } else {
                    OpCode::BackRefCheck
                };
                add_op(
                    reg,
                    opcode,
                    OperationPayload::BackRefGeneral {
                        num: refs.len() as i32,
                        ns,
                        nest_level: br.nest_level,
                    },
                );
            } else if node.has_status(ND_ST_NEST_LEVEL) {
                // Level-based backref for recursion: \k<1+3>
                let ns = refs.to_vec();
                let opcode = if node.has_status(ND_ST_IGNORECASE) {
                    OpCode::BackRefWithLevelIc
                } else {
                    OpCode::BackRefWithLevel
                };
                add_op(
                    reg,
                    opcode,
                    OperationPayload::BackRefGeneral {
                        num: refs.len() as i32,
                        ns,
                        nest_level: br.nest_level,
                    },
                );
            } else if refs.len() == 1 {
                let n = refs[0];
                if node.has_status(ND_ST_IGNORECASE) {
                    add_op(
                        reg,
                        OpCode::BackRefNIc,
                        OperationPayload::BackRefN { n1: n },
                    );
                } else {
                    match n {
                        1 => {
                            add_op(reg, OpCode::BackRef1, OperationPayload::None);
                        }
                        2 => {
                            add_op(reg, OpCode::BackRef2, OperationPayload::None);
                        }
                        _ => {
                            add_op(reg, OpCode::BackRefN, OperationPayload::BackRefN { n1: n });
                        }
                    }
                }
            } else {
                // Multi backref
                let ns = refs.to_vec();
                if node.has_status(ND_ST_IGNORECASE) {
                    add_op(
                        reg,
                        OpCode::BackRefMultiIc,
                        OperationPayload::BackRefGeneral {
                            num: refs.len() as i32,
                            ns,
                            nest_level: 0,
                        },
                    );
                } else {
                    add_op(
                        reg,
                        OpCode::BackRefMulti,
                        OperationPayload::BackRefGeneral {
                            num: refs.len() as i32,
                            ns,
                            nest_level: 0,
                        },
                    );
                }
            }
            0
        }

        NodeInner::Quant(qn) => compile_quantifier_node(qn, reg, env),

        NodeInner::Bag(bag) => compile_bag_node(bag, node.status, reg, env),

        NodeInner::Anchor(an) => compile_anchor_node(an, node.status, reg, env),

        NodeInner::Gimmick(gn) => compile_gimmick_node(gn, reg, env),

        NodeInner::Call(call) => {
            // Look up the called_addr for this group
            let gnum = call.called_gnum as usize;
            let addr = if gnum < reg.called_addrs.len() && reg.called_addrs[gnum] >= 0 {
                reg.called_addrs[gnum]
            } else {
                0 // Will be patched later if not yet compiled
            };
            add_op(reg, OpCode::Call, OperationPayload::Call { addr });
            // Record for later patching if the group hasn't been compiled yet
            if gnum >= reg.called_addrs.len() || reg.called_addrs[gnum] < 0 {
                // Store the index of this OP_CALL for patching
                let call_idx = reg.ops.len() - 1;
                reg.unset_call_addrs.push((call_idx, gnum as i32));
            }
            0
        }
    }
}

// ============================================================================
// Entry points
// ============================================================================

/// Helper: check if mem_status bit 0 is on (meaning "all on")
#[inline]
fn mem_status_is_all_on(stats: MemStatusType) -> bool {
    (stats & 1) != 0
}

// ============================================================================
// tune_tree state flags (matching C's IN_* defines from regcomp.c:4481)
// ============================================================================
const IN_ALT: i32 = 1 << 0;
const IN_NOT: i32 = 1 << 1;
const IN_REAL_REPEAT: i32 = 1 << 2;
const IN_VAR_REPEAT: i32 = 1 << 3;
const IN_MULTI_ENTRY: i32 = 1 << 5;
const IN_ZERO_REPEAT: i32 = 1 << 4;
const IN_PREC_READ: i32 = 1 << 6;
const IN_LOOK_BEHIND: i32 = 1 << 7;
const IN_PEEK: i32 = 1 << 8;

/// Calculate minimum byte length a node can match.
/// Mirrors C's node_min_byte_len() from regcomp.c.
fn node_min_byte_len(node: &Node, env: &ParseEnv) -> OnigLen {
    match &node.inner {
        NodeInner::String(sn) => sn.s.len() as OnigLen,

        NodeInner::CType(_) | NodeInner::CClass(_) => env.enc.min_enc_len() as OnigLen,

        NodeInner::List(_) => {
            let mut len: OnigLen = 0;
            let mut cur = node;
            while let NodeInner::List(cons) = &cur.inner {
                let tmin = node_min_byte_len(&cons.car, env);
                len = distance_add(len, tmin);
                match &cons.cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
            len
        }

        NodeInner::Alt(_) => {
            let mut len: OnigLen = 0;
            let mut first = true;
            let mut cur = node;
            while let NodeInner::Alt(cons) = &cur.inner {
                let tmin = node_min_byte_len(&cons.car, env);
                if first {
                    len = tmin;
                    first = false;
                } else if len > tmin {
                    len = tmin;
                }
                match &cons.cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
            len
        }

        NodeInner::Quant(qn) => {
            if qn.lower > 0 {
                if let Some(ref body) = qn.body {
                    let len = node_min_byte_len(body, env);
                    distance_multiply(len, qn.lower)
                } else {
                    0
                }
            } else {
                0
            }
        }

        NodeInner::Bag(bn) => {
            match bn.bag_type {
                BagType::Option | BagType::StopBacktrack => {
                    if let Some(ref body) = bn.body {
                        node_min_byte_len(body, env)
                    } else {
                        0
                    }
                }
                BagType::Memory => {
                    // Do not cache through a shared node reference. Calls are
                    // conservatively treated as empty below, so this ownership-tree
                    // traversal cannot recurse through a self-reference.
                    if let Some(body) = &bn.body {
                        node_min_byte_len(body, env)
                    } else {
                        0
                    }
                }
                BagType::IfElse => {
                    if let BagData::IfElse {
                        ref then_node,
                        ref else_node,
                    } = bn.bag_data
                    {
                        let mut len = if let Some(ref body) = bn.body {
                            node_min_byte_len(body, env)
                        } else {
                            0
                        };
                        if let Some(ref then_n) = then_node {
                            len += node_min_byte_len(then_n, env);
                        }
                        let elen = if let Some(ref else_n) = else_node {
                            node_min_byte_len(else_n, env)
                        } else {
                            0
                        };
                        if elen < len {
                            elen
                        } else {
                            len
                        }
                    } else {
                        0
                    }
                }
            }
        }

        NodeInner::BackRef(br) => {
            if node.has_status(ND_ST_CHECKER) {
                0
            } else {
                // Simplified: return 0 for backrefs (safe minimum)
                0
            }
        }

        // Following a call would re-enter a self-referential raw pointer. Zero is
        // a conservative minimum and merely prevents unsound optimizations.
        NodeInner::Call(_) => 0,

        NodeInner::Anchor(_) | NodeInner::Gimmick(_) => 0,
    }
}

/// Check if a quantifier body contains capture groups (Memory bags).
/// Returns the appropriate emptiness type. Mirrors C's quantifiers_memory_node_info().
fn quantifiers_memory_node_info(node: &Node) -> BodyEmptyType {
    let mut r = BodyEmptyType::MayBeEmpty;

    match &node.inner {
        NodeInner::List(_) | NodeInner::Alt(_) => {
            let mut cur = node;
            loop {
                let (car, cdr) = match &cur.inner {
                    NodeInner::List(cons) => (&cons.car, &cons.cdr),
                    NodeInner::Alt(cons) => (&cons.car, &cons.cdr),
                    _ => break,
                };
                let v = quantifiers_memory_node_info(car);
                if v as i32 > r as i32 {
                    r = v;
                }
                match cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
        }
        NodeInner::Quant(qn) => {
            if qn.upper != 0 {
                if let Some(ref body) = qn.body {
                    r = quantifiers_memory_node_info(body);
                }
            }
        }
        NodeInner::Bag(bn) => match bn.bag_type {
            BagType::Memory => {
                return BodyEmptyType::MayBeEmptyMem;
            }
            BagType::Option | BagType::StopBacktrack => {
                if let Some(ref body) = bn.body {
                    r = quantifiers_memory_node_info(body);
                }
            }
            BagType::IfElse => {
                if let Some(ref body) = bn.body {
                    r = quantifiers_memory_node_info(body);
                }
                if let BagData::IfElse {
                    ref then_node,
                    ref else_node,
                } = bn.bag_data
                {
                    if let Some(ref then_n) = then_node {
                        let v = quantifiers_memory_node_info(then_n);
                        if v as i32 > r as i32 {
                            r = v;
                        }
                    }
                    if let Some(ref else_n) = else_node {
                        let v = quantifiers_memory_node_info(else_n);
                        if v as i32 > r as i32 {
                            r = v;
                        }
                    }
                }
            }
        },
        _ => {}
    }

    r
}

/// Get min and max byte_len across case-fold items.
/// Mirrors C's get_min_max_byte_len_case_fold_items().
fn get_min_max_byte_len_case_fold_items(
    n: i32,
    items: &[OnigCaseFoldCodeItem],
) -> (OnigLen, OnigLen) {
    let mut min_len: OnigLen = INFINITE_LEN;
    let mut max_len: OnigLen = 0;
    for item in items.iter().take(n as usize) {
        let len = item.byte_len as OnigLen;
        if len < min_len {
            min_len = len;
        }
        if len > max_len {
            max_len = len;
        }
    }
    (min_len, max_len)
}

/// Expand a case-insensitive string node into CClass/List nodes.
/// Mirrors C's unravel_case_fold_string() from regcomp.c.
///
/// For each character in the string:
/// - If it has case-fold alternatives (e.g. 'c' -> 'C'), create a CClass node [cC]
/// - Otherwise, accumulate into a plain string node
/// - Combine all resulting nodes into a List
fn unravel_case_fold_string(node: &mut Node, reg: &mut RegexType, state: i32) -> i32 {
    let enc = reg.enc;
    let in_look_behind = (state & IN_LOOK_BEHIND) != 0;

    // Extract string bytes and clear ignorecase flag
    let s_bytes = if let NodeInner::String(ref sn) = node.inner {
        sn.s.clone()
    } else {
        return ONIG_NORMAL;
    };
    node.status_remove(ND_ST_IGNORECASE);

    let mut items = vec![
        OnigCaseFoldCodeItem {
            byte_len: 0,
            code_len: 0,
            code: [0; ONIGENC_MAX_COMP_CASE_FOLD_CODE_LEN]
        };
        ONIGENC_GET_CASE_FOLD_CODES_MAX_NUM
    ];

    let mut nodes: Vec<Box<Node>> = Vec::new();
    let mut pending: Vec<u8> = Vec::new(); // accumulate non-foldable chars

    let mut pos = 0;
    while pos < s_bytes.len() {
        let one_len = enc.mbc_enc_len(&s_bytes[pos..]);
        let mut n = enc.get_case_fold_codes_by_str(
            reg.case_fold_flag,
            &s_bytes[pos..],
            s_bytes.len(),
            &mut items,
        );

        if n > 0 {
            // Flush pending plain string
            if !pending.is_empty() {
                nodes.push(node_new_str(&pending));
                pending.clear();
            }

            if in_look_behind {
                // In lookbehind: only allow same-byte-length single-codepoint folds
                let q = pos + one_len;
                // If first item's byte_len differs from one_len, re-query with shorter end
                if items[0].byte_len != one_len as i32 {
                    n = enc.get_case_fold_codes_by_str(
                        reg.case_fold_flag,
                        &s_bytes[pos..q],
                        q - pos,
                        &mut items,
                    );
                }

                // Check if any same-byte-length single-code fold exists
                let found = items
                    .iter()
                    .take(n as usize)
                    .any(|item| item.byte_len == one_len as i32 && item.code_len == 1);

                if !found {
                    // No valid fold for lookbehind — keep as plain string
                    pending.extend_from_slice(&s_bytes[pos..q]);
                    pos = q;
                } else {
                    // Build CClass with original + same-length folds
                    let mut cc_node = node_new_cclass();
                    let cc = cc_node.as_cclass_mut().unwrap();
                    let code = enc.mbc_to_code(&s_bytes[pos..], s_bytes.len() - pos);
                    crate::regparse::add_code_into_cc(cc, code, enc);
                    for item in items.iter().take(n as usize) {
                        if item.byte_len == one_len as i32 && item.code_len == 1 {
                            crate::regparse::add_code_into_cc(cc, item.code[0], enc);
                        }
                    }
                    nodes.push(cc_node);
                    pos = q;
                }
            } else {
                // Normal (non-lookbehind) case fold

                // Check if all items are single-codepoint folds
                let all_single = items.iter().take(n as usize).all(|item| item.code_len == 1);

                if all_single {
                    // All single-char: create CClass with original + alternatives
                    let mut cc_node = node_new_cclass();
                    let cc = cc_node.as_cclass_mut().unwrap();
                    let code = enc.mbc_to_code(&s_bytes[pos..], s_bytes.len() - pos);
                    crate::regparse::add_code_into_cc(cc, code, enc);
                    for item in items.iter().take(n as usize) {
                        crate::regparse::add_code_into_cc(cc, item.code[0], enc);
                    }
                    nodes.push(cc_node);
                    pos += one_len;
                } else {
                    // Multi-char folds present: create Alt with string alternatives
                    let (min_byte_len, max_byte_len_val) =
                        get_min_max_byte_len_case_fold_items(n, &items);
                    if min_byte_len != max_byte_len_val {
                        return ONIGERR_PARSER_BUG;
                    }
                    let max_byte_len = max_byte_len_val as usize;

                    // First alternative: original string bytes
                    let orig_str = &s_bytes[pos..pos + max_byte_len];
                    let mut alt_node: Box<Node> = node_new_alt(node_new_str(orig_str), None);
                    let mut curr = &mut alt_node;

                    for item in items.iter().take(n as usize) {
                        // Convert codepoints to string bytes
                        let mut buf = Vec::new();
                        let mut tmp = [0u8; 6]; // max UTF-8 bytes per codepoint
                        for ci in 0..(item.code_len as usize) {
                            let blen = enc.code_to_mbc(item.code[ci], &mut tmp);
                            buf.extend_from_slice(&tmp[..blen as usize]);
                        }
                        let new_alt = node_new_alt(node_new_str(&buf), None);
                        // Append to chain
                        if let NodeInner::Alt(ref mut ca) = curr.inner {
                            ca.cdr = Some(new_alt);
                            curr = ca.cdr.as_mut().unwrap();
                        }
                    }

                    nodes.push(alt_node);
                    pos += max_byte_len;
                }
            }
        } else {
            // No case fold: accumulate into pending string
            pending.extend_from_slice(&s_bytes[pos..pos + one_len]);
            pos += one_len;
        }
    }

    // Flush any remaining pending string
    if !pending.is_empty() {
        nodes.push(node_new_str(&pending));
    }

    // Build result: single node or List
    if nodes.is_empty() {
        node.inner = NodeInner::String(StrNode {
            s: Vec::new(),
            flag: 0,
        });
    } else if nodes.len() == 1 {
        let n = nodes.pop().unwrap();
        *node = *n;
    } else {
        // Build List from right to left
        let mut list: Option<Box<Node>> = None;
        for n in nodes.into_iter().rev() {
            list = Some(node_new_list(n, list));
        }
        *node = *list.unwrap();
    }

    ONIG_NORMAL
}

// ============================================================================
// Lookbehind support: node_char_len, tune_look_behind, divide_look_behind_alternatives
// ============================================================================

/// Result of computing character length for a node subtree.
enum CharLenResult {
    Fixed(OnigLen),
    Variable(OnigLen, OnigLen),
}

/// Compute character count (not byte count) for a node subtree.
fn node_char_len(node: &Node, enc: OnigEncoding) -> CharLenResult {
    match &node.inner {
        NodeInner::String(sn) => {
            let n = onigenc_strlen(enc, &sn.s, 0, sn.s.len());
            CharLenResult::Fixed(n as OnigLen)
        }
        NodeInner::CType(_) | NodeInner::CClass(_) => CharLenResult::Fixed(1),
        NodeInner::List(_) => {
            let mut sum: OnigLen = 0;
            let mut variable = false;
            let mut min_sum: OnigLen = 0;
            let mut max_sum: OnigLen = 0;
            let mut cur = node;
            while let NodeInner::List(cons) = &cur.inner {
                match node_char_len(&cons.car, enc) {
                    CharLenResult::Fixed(n) => {
                        if variable {
                            min_sum = distance_add(min_sum, n);
                            max_sum = distance_add(max_sum, n);
                        } else {
                            sum = distance_add(sum, n);
                        }
                    }
                    CharLenResult::Variable(mn, mx) => {
                        if !variable {
                            min_sum = sum;
                            max_sum = sum;
                            variable = true;
                        }
                        min_sum = distance_add(min_sum, mn);
                        max_sum = distance_add(max_sum, mx);
                    }
                }
                match &cons.cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
            if variable {
                CharLenResult::Variable(min_sum, max_sum)
            } else {
                CharLenResult::Fixed(sum)
            }
        }
        NodeInner::Alt(_) => {
            let mut min: OnigLen = OnigLen::MAX;
            let mut max: OnigLen = 0;
            let mut cur = node;
            while let NodeInner::Alt(cons) = &cur.inner {
                let (mn, mx) = match node_char_len(&cons.car, enc) {
                    CharLenResult::Fixed(n) => (n, n),
                    CharLenResult::Variable(mn, mx) => (mn, mx),
                };
                if mn < min {
                    min = mn;
                }
                if mx > max {
                    max = mx;
                }
                match &cons.cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
            if min == max {
                CharLenResult::Fixed(min)
            } else {
                CharLenResult::Variable(min, max)
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(ref body) = qn.body {
                match node_char_len(body, enc) {
                    CharLenResult::Fixed(n) => {
                        let lo = distance_multiply(n, qn.lower);
                        let hi = if qn.upper == INFINITE_REPEAT {
                            INFINITE_LEN
                        } else {
                            distance_multiply(n, qn.upper)
                        };
                        if lo == hi {
                            CharLenResult::Fixed(lo)
                        } else {
                            CharLenResult::Variable(lo, hi)
                        }
                    }
                    CharLenResult::Variable(mn, mx) => {
                        let lo = distance_multiply(mn, qn.lower);
                        let hi = if qn.upper == INFINITE_REPEAT {
                            INFINITE_LEN
                        } else {
                            distance_multiply(mx, qn.upper)
                        };
                        CharLenResult::Variable(lo, hi)
                    }
                }
            } else {
                CharLenResult::Fixed(0)
            }
        }
        NodeInner::Bag(bn) => {
            if let BagData::IfElse {
                ref then_node,
                ref else_node,
            } = bn.bag_data
            {
                // Condition (body) may consume input (non-backref pattern conditions)
                // or be zero-width (backref checker conditions).
                let cond_len = if let Some(ref body) = bn.body {
                    if body.has_status(ND_ST_CHECKER) {
                        // Backref checker: zero length
                        (0 as OnigLen, 0 as OnigLen)
                    } else {
                        match node_char_len(body, enc) {
                            CharLenResult::Fixed(n) => (n, n),
                            CharLenResult::Variable(mn, mx) => (mn, mx),
                        }
                    }
                } else {
                    (0, 0)
                };
                let then_len = if let Some(ref n) = then_node {
                    match node_char_len(n, enc) {
                        CharLenResult::Fixed(n) => (n, n),
                        CharLenResult::Variable(mn, mx) => (mn, mx),
                    }
                } else {
                    (0, 0)
                };
                let else_len = if let Some(ref n) = else_node {
                    match node_char_len(n, enc) {
                        CharLenResult::Fixed(n) => (n, n),
                        CharLenResult::Variable(mn, mx) => (mn, mx),
                    }
                } else {
                    (0, 0)
                };
                // Success path: condition + then; Failure path: else
                let success_min = distance_add(cond_len.0, then_len.0);
                let success_max = distance_add(cond_len.1, then_len.1);
                let min = std::cmp::min(success_min, else_len.0);
                let max = std::cmp::max(success_max, else_len.1);
                if min == max {
                    CharLenResult::Fixed(min)
                } else {
                    CharLenResult::Variable(min, max)
                }
            } else if let Some(ref body) = bn.body {
                node_char_len(body, enc)
            } else {
                CharLenResult::Fixed(0)
            }
        }
        NodeInner::Anchor(_) => CharLenResult::Fixed(0),
        NodeInner::BackRef(_) => CharLenResult::Variable(0, INFINITE_LEN),
        NodeInner::Call(ref cn) => {
            // Follow the call target to compute the character length of the called group
            if !cn.target_node.is_null() {
                // SAFETY: `target_node` is non-null (checked above) and was set by
                // resolve_call_references/refresh_call_targets to the called group's
                // Bag node inside this same live tree; only shared reads follow.
                let target = unsafe { &*cn.target_node };
                node_char_len(target, enc)
            } else {
                CharLenResult::Fixed(0)
            }
        }
        _ => CharLenResult::Fixed(0),
    }
}

/// Divide variable-length lookbehind with Alt body into per-branch fixed-length lookbehinds.
/// For positive: Alt(Anchor(LB,a), Anchor(LB,b)) — any branch must match (OR).
/// For negative: List(Anchor(LB_NOT,a), Anchor(LB_NOT,b)) — all branches must pass (AND).
fn divide_look_behind_alt(node: &mut Node, anchor_type: i32, enc: OnigEncoding) -> i32 {
    // Extract anchor fields
    let (body, ascii_mode) = if let NodeInner::Anchor(ref mut an) = node.inner {
        (an.body.take().unwrap(), an.ascii_mode)
    } else {
        return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
    };

    // Collect all Alt branches
    let mut branches: Vec<Box<Node>> = Vec::new();
    let mut cur = body;
    loop {
        if let NodeInner::Alt(cons) = cur.inner {
            branches.push(cons.car);
            match cons.cdr {
                Some(next) => cur = next,
                None => break,
            }
        } else {
            branches.push(cur);
            break;
        }
    }

    let use_list = anchor_type == ANCR_LOOK_BEHIND_NOT;

    // Build new node tree of anchors, from last to first
    let mut result: Option<Box<Node>> = None;
    for branch in branches.into_iter().rev() {
        let char_len = match node_char_len(&branch, enc) {
            CharLenResult::Fixed(n) => n,
            CharLenResult::Variable(_, _) => return ONIGERR_INVALID_LOOK_BEHIND_PATTERN,
        };

        let mut anchor = node_new_anchor(anchor_type);
        if let NodeInner::Anchor(ref mut an) = anchor.inner {
            an.body = Some(branch);
            an.char_min_len = char_len;
            an.char_max_len = char_len;
            an.ascii_mode = ascii_mode;
        }

        if use_list {
            // Negative lookbehind: ALL branches must pass (List = AND)
            result = Some(node_new_list(anchor, result));
        } else {
            // Positive lookbehind: ANY branch must match (Alt = OR)
            result = Some(node_new_alt(anchor, result));
        }
    }

    // Replace the original node with the new tree
    if let Some(new_node) = result {
        *node = *new_node;
    }

    ONIG_NORMAL
}

/// Check if a node is an Alt where all top-level branches are individually fixed-length.
/// Returns true only if: node is Alt, and every branch has CharLenResult::Fixed.
fn is_alt_all_branches_fixed(node: &Node, enc: OnigEncoding) -> bool {
    let mut cur = node;
    loop {
        if let NodeInner::Alt(cons) = &cur.inner {
            match node_char_len(&cons.car, enc) {
                CharLenResult::Fixed(_) => {}
                CharLenResult::Variable(_, _) => return false,
            }
            match &cons.cdr {
                Some(next) => cur = next,
                None => return true,
            }
        } else {
            return false;
        }
    }
}

/// Check if a node tree contains absent stoppers (ND_ST_ABSENT_WITH_SIDE_EFFECTS).
/// Returns true if invalid nodes are found inside lookbehind.
/// C: check_node_in_look_behind (simplified — we only need the absent stopper check).
// Allowed node types in lookbehind (C: ALLOWED_TYPE_IN_LB)
const ALLOWED_TYPE_IN_LB: u32 = ND_BIT_LIST
    | ND_BIT_ALT
    | ND_BIT_STRING
    | ND_BIT_CCLASS
    | ND_BIT_CTYPE
    | ND_BIT_ANCHOR
    | ND_BIT_BAG
    | ND_BIT_QUANT
    | ND_BIT_CALL
    | ND_BIT_BACKREF
    | ND_BIT_GIMMICK;

// Allowed bag types: positive lookbehind allows Memory; negative does not
const ALLOWED_BAG_IN_LB: u32 = (1 << BagType::Memory as u32)
    | (1 << BagType::Option as u32)
    | (1 << BagType::StopBacktrack as u32)
    | (1 << BagType::IfElse as u32);
const ALLOWED_BAG_IN_LB_NOT: u32 = (1 << BagType::Option as u32)
    | (1 << BagType::StopBacktrack as u32)
    | (1 << BagType::IfElse as u32);

// Allowed anchor types in positive/negative lookbehind
const ALLOWED_ANCHOR_IN_LB: i32 = ANCR_LOOK_BEHIND
    | ANCR_BEGIN_LINE
    | ANCR_END_LINE
    | ANCR_BEGIN_BUF
    | ANCR_BEGIN_POSITION
    | ANCR_WORD_BOUNDARY
    | ANCR_NO_WORD_BOUNDARY
    | ANCR_WORD_BEGIN
    | ANCR_WORD_END
    | ANCR_TEXT_SEGMENT_BOUNDARY
    | ANCR_NO_TEXT_SEGMENT_BOUNDARY;

const ALLOWED_ANCHOR_IN_LB_NOT: i32 = ANCR_LOOK_BEHIND
    | ANCR_LOOK_BEHIND_NOT
    | ANCR_BEGIN_LINE
    | ANCR_END_LINE
    | ANCR_BEGIN_BUF
    | ANCR_BEGIN_POSITION
    | ANCR_WORD_BOUNDARY
    | ANCR_NO_WORD_BOUNDARY
    | ANCR_WORD_BEGIN
    | ANCR_WORD_END
    | ANCR_TEXT_SEGMENT_BOUNDARY
    | ANCR_NO_TEXT_SEGMENT_BOUNDARY;

/// Check if node tree is valid within a lookbehind call target.
/// Returns 0 = ok, 1 = forbidden.
fn check_called_node_in_look_behind(node: &Node, _not: bool) -> i32 {
    match &node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            let mut r = check_called_node_in_look_behind(&cons.car, _not);
            if r == 0 {
                if let Some(ref cdr) = cons.cdr {
                    r = check_called_node_in_look_behind(cdr, _not);
                }
            }
            r
        }
        NodeInner::Quant(qn) => {
            if let Some(ref body) = qn.body {
                check_called_node_in_look_behind(body, _not)
            } else {
                0
            }
        }
        NodeInner::Bag(en) => {
            if en.bag_type == BagType::Memory {
                if node.has_status(ND_ST_MARK1) {
                    return 0;
                }
                // Note: can't mutate here to add MARK1, but recursion cycles are
                // already broken by tune_call. Just check the body.
                if let Some(ref body) = en.body {
                    return check_called_node_in_look_behind(body, _not);
                }
                0
            } else {
                let mut r = 0;
                if let Some(ref body) = en.body {
                    r = check_called_node_in_look_behind(body, _not);
                }
                if r == 0 {
                    if let BagData::IfElse {
                        ref then_node,
                        ref else_node,
                    } = en.bag_data
                    {
                        if let Some(ref tn) = then_node {
                            r = check_called_node_in_look_behind(tn, _not);
                            if r != 0 {
                                return r;
                            }
                        }
                        if let Some(ref en) = else_node {
                            r = check_called_node_in_look_behind(en, _not);
                        }
                    }
                }
                r
            }
        }
        NodeInner::Anchor(an) => {
            if let Some(ref body) = an.body {
                check_called_node_in_look_behind(body, _not)
            } else {
                0
            }
        }
        NodeInner::Gimmick(_) => {
            if node.has_status(ND_ST_ABSENT_WITH_SIDE_EFFECTS) {
                1
            } else {
                0
            }
        }
        _ => 0,
    }
}

/// Full validation of nodes in lookbehind. Returns 0 = ok, 1 = forbidden.
/// `not`: true for negative lookbehind.
/// `used`: set to true if the body contains backrefs, called groups, or SAVE_KEEP.
fn check_node_in_look_behind(
    node: &Node,
    not: bool,
    used: &mut bool,
    syntax: &OnigSyntaxType,
) -> i32 {
    let type_bit = node.node_type_bit();
    if (type_bit & ALLOWED_TYPE_IN_LB) == 0 {
        return 1;
    }

    match &node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            let mut r = check_node_in_look_behind(&cons.car, not, used, syntax);
            if r == 0 {
                if let Some(ref cdr) = cons.cdr {
                    r = check_node_in_look_behind(cdr, not, used, syntax);
                }
            }
            r
        }
        NodeInner::Quant(qn) => {
            if let Some(ref body) = qn.body {
                check_node_in_look_behind(body, not, used, syntax)
            } else {
                0
            }
        }
        NodeInner::Bag(en) => {
            let mut bag_mask = if not {
                ALLOWED_BAG_IN_LB_NOT
            } else {
                ALLOWED_BAG_IN_LB
            };
            if not && is_syntax_bv(syntax, FERRONI_SYN_ALLOW_CAPTURE_IN_NEGATIVE_LOOK_BEHIND) {
                bag_mask |= 1 << BagType::Memory as u32;
            }
            if ((1 << en.bag_type as u32) & bag_mask) == 0 {
                return 1;
            }

            let mut r = 0;
            if let Some(ref body) = en.body {
                r = check_node_in_look_behind(body, not, used, syntax);
                if r != 0 {
                    return r;
                }
            }

            if en.bag_type == BagType::Memory {
                if node.has_status(ND_ST_BACKREF)
                    || node.has_status(ND_ST_CALLED)
                    || node.has_status(ND_ST_REFERENCED)
                {
                    *used = true;
                }
            } else if let BagData::IfElse {
                ref then_node,
                ref else_node,
            } = en.bag_data
            {
                if let Some(ref tn) = then_node {
                    r = check_node_in_look_behind(tn, not, used, syntax);
                    if r != 0 {
                        return r;
                    }
                }
                if let Some(ref en) = else_node {
                    r = check_node_in_look_behind(en, not, used, syntax);
                }
            }
            r
        }
        NodeInner::Anchor(an) => {
            let mut anchor_mask = if not {
                ALLOWED_ANCHOR_IN_LB_NOT
            } else {
                ALLOWED_ANCHOR_IN_LB
            };
            if not && is_syntax_bv(syntax, FERRONI_SYN_ALLOW_LOOK_AHEAD_IN_NEGATIVE_LOOK_BEHIND) {
                anchor_mask |= ANCR_PREC_READ | ANCR_PREC_READ_NOT;
            }
            if (an.anchor_type & anchor_mask) == 0 {
                return 1;
            }
            if let Some(ref body) = an.body {
                check_node_in_look_behind(body, not, used, syntax)
            } else {
                0
            }
        }
        NodeInner::Call(ref cn) => {
            if node.has_status(ND_ST_RECURSION) {
                *used = true;
                0
            } else if !cn.target_node.is_null() {
                // SAFETY: `target_node` is non-null (checked above) and was set by
                // resolve_call_references/refresh_call_targets to the called group's
                // Bag node inside this same live tree; only shared reads follow.
                let target = unsafe { &*cn.target_node };
                check_called_node_in_look_behind(target, not)
            } else {
                0
            }
        }
        NodeInner::Gimmick(ref gn) => {
            if node.has_status(ND_ST_ABSENT_WITH_SIDE_EFFECTS) {
                return 1;
            }
            if gn.gimmick_type == GimmickType::Save && gn.detail_type == SaveType::Keep as i32 {
                *used = true;
            }
            0
        }
        _ => 0,
    }
}

/// Reduce quantifiers in lookbehind: set upper = lower for simple body quantifiers.
/// C: node_reduce_in_look_behind — returns true if node should be removed (upper==0).
fn node_reduce_in_look_behind(node: &mut Node) -> bool {
    if let NodeInner::Quant(ref mut qn) = node.inner {
        if let Some(ref body) = qn.body {
            let reducible = matches!(
                body.inner,
                NodeInner::String(_)
                    | NodeInner::CType(_)
                    | NodeInner::CClass(_)
                    | NodeInner::BackRef(_)
            );
            if reducible {
                qn.upper = qn.lower;
                return qn.upper == 0;
            }
        }
    }
    false
}

/// C: list_reduce_in_look_behind
fn list_reduce_in_look_behind(node: &mut Node) {
    match node.inner {
        NodeInner::Quant(_) => {
            node_reduce_in_look_behind(node);
        }
        NodeInner::List(_) => {
            // Walk the list, reducing each car
            let mut cur = node as *mut Node;
            loop {
                // SAFETY: `cur` starts as the exclusive `&mut node` argument and is
                // only advanced to the boxed cdr of the cons it points to, so it
                // always points to a live node in the exclusively borrowed chain.
                unsafe {
                    if let NodeInner::List(ref mut cons) = (*cur).inner {
                        let removed = node_reduce_in_look_behind(&mut cons.car);
                        if !removed {
                            // Only continue if the current node was reduced (removed)
                            // C: "if (r <= 0) break" — r>0 means removed, keep going
                            break;
                        }
                        if let Some(ref mut cdr) = cons.cdr {
                            cur = cdr.as_mut() as *mut Node;
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }
                }
            }
        }
        _ => {}
    }
}

/// C: alt_reduce_in_look_behind
fn alt_reduce_in_look_behind(node: &mut Node) {
    match node.inner {
        NodeInner::Alt(_) => {
            let mut cur = node as *mut Node;
            loop {
                // SAFETY: `cur` starts as the exclusive `&mut node` argument and is
                // only advanced to the boxed cdr of the cons it points to, so it
                // always points to a live node in the exclusively borrowed chain.
                unsafe {
                    if let NodeInner::Alt(ref mut cons) = (*cur).inner {
                        list_reduce_in_look_behind(&mut cons.car);
                        if let Some(ref mut cdr) = cons.cdr {
                            cur = cdr.as_mut() as *mut Node;
                        } else {
                            break;
                        }
                    } else {
                        break;
                    }
                }
            }
        }
        _ => {
            list_reduce_in_look_behind(node);
        }
    }
}

/// Strip redundant multi-char case-fold alternatives from a CClass body in a lookbehind.
///
/// When `(?i)` is active, the parser wraps a CClass into `Alt(CClass, str1, str2, ...)`
/// where each string is a multi-char case fold (e.g., ß→"ss"). In a lookbehind, this
/// causes O(N) separate lookbehind anchors to be created, each costing ~7 ops.
///
/// If the last codepoint of every multi-char fold string is already in the CClass,
/// the multi-char alternatives are redundant: the single-char CClass check already
/// rejects/accepts those positions. We can safely collapse back to just the CClass.
fn strip_redundant_casefold_alts_in_lookbehind(node: &mut Node, enc: OnigEncoding) {
    let body = if let NodeInner::Anchor(ref mut an) = node.inner {
        if let Some(ref mut body) = an.body {
            body
        } else {
            return;
        }
    } else {
        return;
    };

    // Check if body is Alt(CClass, ...) — the pattern generated by case-fold expansion
    let cc_ptr: *const CClassNode = if let NodeInner::Alt(ref cons) = body.inner {
        if let NodeInner::CClass(ref cc) = cons.car.inner {
            cc as *const CClassNode
        } else {
            return;
        }
    } else {
        return;
    };

    // Walk the cdr chain and check each string alternative
    let all_covered = {
        // SAFETY: `cc_ptr` was taken just above from the CClass in the first Alt
        // branch of `body`; the walk below only reads the chain and never mutates
        // `body`, so the pointee stays live while `cc` is in use.
        let cc = unsafe { &*cc_ptr };
        let mut cur: &Node = body;
        let mut has_alts = false;
        let mut covered = true;
        while let NodeInner::Alt(cons) = &cur.inner {
            let next = match cons.cdr.as_deref() {
                Some(node) => node,
                None => break,
            };

            // Each node in the cdr chain is either another Alt or the last branch
            let branch = if let NodeInner::Alt(ref cons2) = next.inner {
                &cons2.car
            } else {
                // Last branch is the node itself
                next
            };

            // Check if this branch is a String node (multi-char fold)
            if let NodeInner::String(ref sn) = branch.inner {
                if sn.s.is_empty() {
                    covered = false;
                    break;
                }
                has_alts = true;
                // Decode the last codepoint from the string
                let bytes = &sn.s;
                let last_code = decode_last_codepoint(bytes, enc);
                if !onig_is_code_in_cc(enc, last_code, cc) {
                    covered = false;
                    break;
                }
            } else {
                // Non-string alternative — don't optimize
                covered = false;
                break;
            }

            // Move to next in chain
            if let NodeInner::Alt(_) = next.inner {
                cur = next;
            } else {
                break;
            }
        }
        has_alts && covered
    };

    if all_covered {
        // Collapse: replace Alt(CClass, str1, str2, ...) with just the CClass node
        let old_inner = std::mem::replace(
            &mut body.inner,
            NodeInner::String(StrNode {
                s: Vec::new(),
                flag: 0,
            }),
        );
        if let NodeInner::Alt(cons) = old_inner {
            **body = *cons.car;
        }
    }
}

/// Decode the last codepoint from a UTF-8 byte slice.
fn decode_last_codepoint(bytes: &[u8], enc: OnigEncoding) -> OnigCodePoint {
    if bytes.is_empty() {
        return 0;
    }
    // Walk forward through the string to find the start of the last character
    let mut pos = 0;
    let mut last_pos = 0;
    while pos < bytes.len() {
        last_pos = pos;
        let clen = enc.mbc_enc_len(&bytes[pos..]);
        if clen == 0 {
            break;
        }
        pos += clen;
    }
    enc.mbc_to_code(&bytes[last_pos..], bytes.len())
}

/// Tune a lookbehind anchor: compute char lengths and split variable-length alternatives.
fn tune_look_behind(node: &mut Node, enc: OnigEncoding, syntax: &OnigSyntaxType) -> i32 {
    let (anchor_type, has_body) = if let NodeInner::Anchor(ref an) = node.inner {
        (an.anchor_type, an.body.is_some())
    } else {
        return 0;
    };

    if !has_body {
        return 0;
    }

    // Strip redundant multi-char case-fold alternatives from CClass in lookbehind.
    //
    // Under (?i), the parser expands a CClass like [-\w] into
    //   Alt(CClass[-\w...], "ss", "fi", "fl", ...)
    // because characters like ß case-fold to "ss". In a lookbehind, this causes
    // divide_look_behind_alt to create ~100 separate lookbehind anchors (one per
    // multi-char fold), each with its own Mark/Push/StepBack/body/PopToMark/Fail/Pop.
    //
    // These multi-char alternatives are redundant when the last character of each
    // fold sequence is already in the CClass. For [-\w], every multi-char fold of
    // a word character ends with a word character (e.g., ß→"ss", fi→"fi"), so the
    // single-char CClass check already covers all cases.
    strip_redundant_casefold_alts_in_lookbehind(node, enc);

    // Full validation of nodes inside lookbehind (C: check_node_in_look_behind)
    let mut lb_used = false;
    {
        let is_not = anchor_type == ANCR_LOOK_BEHIND_NOT;
        let body = if let NodeInner::Anchor(ref an) = node.inner {
            an.body.as_ref().unwrap()
        } else {
            return 0;
        };
        let r = check_node_in_look_behind(body, is_not, &mut lb_used, syntax);
        if r < 0 {
            return r;
        }
        if r > 0 {
            return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
        }
    }

    let body_char_len = {
        let body = if let NodeInner::Anchor(ref an) = node.inner {
            an.body.as_ref().unwrap()
        } else {
            return 0;
        };
        node_char_len(body, enc)
    };

    // Overflow check (C: #177)
    const LOOK_BEHIND_MAX_CHAR_LEN: OnigLen = 65535;
    let (cmin, cmax) = match body_char_len {
        CharLenResult::Fixed(n) => (n, n),
        CharLenResult::Variable(mn, mx) => (mn, mx),
    };
    if (cmax != INFINITE_LEN && cmax > LOOK_BEHIND_MAX_CHAR_LEN) || cmin > LOOK_BEHIND_MAX_CHAR_LEN
    {
        return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
    }

    match body_char_len {
        CharLenResult::Fixed(len) => {
            if let NodeInner::Anchor(ref mut an) = node.inner {
                an.char_min_len = len;
                an.char_max_len = len;
            }
            ONIG_NORMAL
        }
        CharLenResult::Variable(min, max) => {
            // Check if body is Alt with all branches individually fixed-length
            // (C's CHAR_LEN_TOP_ALT_FIXED case)
            let top_alt_fixed = if let NodeInner::Anchor(ref an) = node.inner {
                if let Some(ref body) = an.body {
                    is_alt_all_branches_fixed(body, enc)
                } else {
                    false
                }
            } else {
                false
            };

            if top_alt_fixed {
                // All alt branches are fixed-length, just different sizes
                if is_syntax_bv(syntax, ONIG_SYN_DIFFERENT_LEN_ALT_LOOK_BEHIND) {
                    let r = divide_look_behind_alt(node, anchor_type, enc);
                    if r == ONIG_NORMAL {
                        return r;
                    }
                    // Should not fail here since we checked all branches are fixed
                }
                // Fall through to variable-length path
                if is_syntax_bv(syntax, ONIG_SYN_VARIABLE_LEN_LOOK_BEHIND) {
                    if min == INFINITE_LEN {
                        return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
                    }
                    if let NodeInner::Anchor(ref mut an) = node.inner {
                        an.char_min_len = min;
                        an.char_max_len = max;
                    }
                    ONIG_NORMAL
                } else {
                    ONIGERR_INVALID_LOOK_BEHIND_PATTERN
                }
            } else {
                // Either non-alt body, or alt with variable-length branches
                if !is_syntax_bv(syntax, ONIG_SYN_VARIABLE_LEN_LOOK_BEHIND) {
                    return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
                }
                if min == INFINITE_LEN {
                    return ONIGERR_INVALID_LOOK_BEHIND_PATTERN;
                }
                if let NodeInner::Anchor(ref mut an) = node.inner {
                    an.char_min_len = min;
                    an.char_max_len = max;
                }
                ONIG_NORMAL
            }
        }
    }
}

/// Resolve all \g<name>/\g<num> call references in the tree.
/// Sets called_gnum on Call nodes and marks target groups as CALLED.
fn resolve_call_references(node: &mut Node, reg: &mut RegexType, env: &mut ParseEnv) -> i32 {
    match &mut node.inner {
        NodeInner::Call(call) => {
            // Resolve the call target
            let mem_node_ptr;
            if call.by_number {
                let gnum = call.called_gnum;
                if gnum > env.num_mem || gnum < 0 {
                    return ONIGERR_UNDEFINED_GROUP_REFERENCE;
                }
                mem_node_ptr = env.mem_env(gnum as usize).mem_node;
            } else {
                // Named call - look up name
                let name = call.name.clone();
                if let Some(ref nt) = reg.name_table {
                    if let Some(nums) = nt.name_to_group_numbers(&name) {
                        if nums.len() != 1 {
                            return ONIGERR_MULTIPLEX_DEFINITION_NAME_CALL;
                        }
                        call.called_gnum = nums[0];
                        mem_node_ptr = env.mem_env(nums[0] as usize).mem_node;
                    } else {
                        return ONIGERR_UNDEFINED_NAME_REFERENCE;
                    }
                } else {
                    return ONIGERR_UNDEFINED_NAME_REFERENCE;
                }
            }
            // Link the call node to its target (so recursive_call_check can follow calls)
            // Note: we store the raw pointer as a non-owning reference (the target node
            // is owned by the tree, not by this call). We wrap it in Box without ownership.
            if !mem_node_ptr.is_null() {
                // Store target pointer for recursion detection (not owning)
                call.target_node = mem_node_ptr;
            }
            0
        }
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            let r = resolve_call_references(&mut cons.car, reg, env);
            if r != 0 {
                return r;
            }
            if let Some(ref mut cdr) = cons.cdr {
                resolve_call_references(cdr, reg, env)
            } else {
                0
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(ref mut body) = qn.body {
                resolve_call_references(body, reg, env)
            } else {
                0
            }
        }
        NodeInner::Bag(bn) => {
            if let Some(ref mut body) = bn.body {
                let r = resolve_call_references(body, reg, env);
                if r != 0 {
                    return r;
                }
            }
            if let BagData::IfElse {
                ref mut then_node,
                ref mut else_node,
            } = bn.bag_data
            {
                if let Some(ref mut then_n) = then_node {
                    let r = resolve_call_references(then_n, reg, env);
                    if r != 0 {
                        return r;
                    }
                }
                if let Some(ref mut else_n) = else_node {
                    let r = resolve_call_references(else_n, reg, env);
                    if r != 0 {
                        return r;
                    }
                }
            }
            0
        }
        NodeInner::Anchor(an) => {
            if let Some(ref mut body) = an.body {
                resolve_call_references(body, reg, env)
            } else {
                0
            }
        }
        _ => 0,
    }
}

fn collect_called_groups(node: &Node, groups: &mut Vec<i32>) {
    match &node.inner {
        NodeInner::Call(call) => groups.push(call.called_gnum),
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            collect_called_groups(&cons.car, groups);
            if let Some(cdr) = &cons.cdr {
                collect_called_groups(cdr, groups);
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(body) = &qn.body {
                collect_called_groups(body, groups);
            }
        }
        NodeInner::Bag(bn) => {
            if let Some(body) = &bn.body {
                collect_called_groups(body, groups);
            }
            if let BagData::IfElse {
                then_node,
                else_node,
            } = &bn.bag_data
            {
                if let Some(then_node) = then_node {
                    collect_called_groups(then_node, groups);
                }
                if let Some(else_node) = else_node {
                    collect_called_groups(else_node, groups);
                }
            }
        }
        NodeInner::Anchor(an) => {
            if let Some(body) = &an.body {
                collect_called_groups(body, groups);
            }
        }
        _ => {}
    }
}

fn mark_called_groups(node: &mut Node, groups: &[i32]) {
    if let NodeInner::Bag(bn) = &node.inner {
        if bn.bag_type == BagType::Memory && groups.contains(&bn.regnum()) {
            node.status_add(ND_ST_CALLED);
        }
    }

    match &mut node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            mark_called_groups(&mut cons.car, groups);
            if let Some(cdr) = &mut cons.cdr {
                mark_called_groups(cdr, groups);
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(body) = &mut qn.body {
                mark_called_groups(body, groups);
            }
        }
        NodeInner::Bag(bn) => {
            if let Some(body) = &mut bn.body {
                mark_called_groups(body, groups);
            }
            if let BagData::IfElse {
                then_node,
                else_node,
            } = &mut bn.bag_data
            {
                if let Some(then_node) = then_node {
                    mark_called_groups(then_node, groups);
                }
                if let Some(else_node) = else_node {
                    mark_called_groups(else_node, groups);
                }
            }
        }
        NodeInner::Anchor(an) => {
            if let Some(body) = &mut an.body {
                mark_called_groups(body, groups);
            }
        }
        _ => {}
    }
}

fn mark_called_groups_as_multi_entry(node: &mut Node) {
    let is_called = node.has_status(ND_ST_CALLED);
    match &mut node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            mark_called_groups_as_multi_entry(&mut cons.car);
            if let Some(cdr) = &mut cons.cdr {
                mark_called_groups_as_multi_entry(cdr);
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(body) = &mut qn.body {
                mark_called_groups_as_multi_entry(body);
            }
        }
        NodeInner::Bag(bn) => {
            if bn.bag_type == BagType::Memory && is_called {
                if let BagData::Memory { entry_count, .. } = &mut bn.bag_data {
                    // A call graph can enter a group through recursive paths that
                    // are not representable as a single tree borrow. Treating every
                    // called group as multi-entry is conservative: it only disables
                    // single-entry optimizations while keeping traversal alias-free.
                    *entry_count = (*entry_count).max(2);
                }
            }
            if let Some(body) = &mut bn.body {
                mark_called_groups_as_multi_entry(body);
            }
            if let BagData::IfElse {
                then_node,
                else_node,
            } = &mut bn.bag_data
            {
                if let Some(then_node) = then_node {
                    mark_called_groups_as_multi_entry(then_node);
                }
                if let Some(else_node) = else_node {
                    mark_called_groups_as_multi_entry(else_node);
                }
            }
        }
        NodeInner::Anchor(an) => {
            if let Some(body) = &mut an.body {
                mark_called_groups_as_multi_entry(body);
            }
        }
        _ => {}
    }
}

fn collect_call_edges(node: &Node, current_groups: &mut Vec<usize>, edges: &mut [Vec<usize>]) {
    match &node.inner {
        NodeInner::Call(call) => {
            let target = call.called_gnum as usize;
            if target < edges.len() {
                for &group in current_groups.iter() {
                    edges[group].push(target);
                }
            }
        }
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            collect_call_edges(&cons.car, current_groups, edges);
            if let Some(cdr) = &cons.cdr {
                collect_call_edges(cdr, current_groups, edges);
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(body) = &qn.body {
                collect_call_edges(body, current_groups, edges);
            }
        }
        NodeInner::Bag(bn) => {
            let is_memory = bn.bag_type == BagType::Memory;
            if is_memory {
                let group = bn.regnum() as usize;
                for &parent in current_groups.iter() {
                    if parent != group {
                        edges[parent].push(group);
                    }
                }
                current_groups.push(group);
            }
            if let Some(body) = &bn.body {
                collect_call_edges(body, current_groups, edges);
            }
            if let BagData::IfElse {
                then_node,
                else_node,
            } = &bn.bag_data
            {
                if let Some(then_node) = then_node {
                    collect_call_edges(then_node, current_groups, edges);
                }
                if let Some(else_node) = else_node {
                    collect_call_edges(else_node, current_groups, edges);
                }
            }
            if is_memory {
                current_groups.pop();
            }
        }
        NodeInner::Anchor(an) => {
            if let Some(body) = &an.body {
                collect_call_edges(body, current_groups, edges);
            }
        }
        _ => {}
    }
}

fn reaches_group(edges: &[Vec<usize>], from: usize, target: usize, seen: &mut [bool]) -> bool {
    if from == target {
        return true;
    }
    if seen[from] {
        return false;
    }
    seen[from] = true;
    edges[from]
        .iter()
        .copied()
        .any(|next| reaches_group(edges, next, target, seen))
}

fn node_contains_called_group(node: &Node) -> bool {
    if node.has_status(ND_ST_CALLED) {
        return true;
    }

    match &node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            node_contains_called_group(&cons.car)
                || cons.cdr.as_deref().is_some_and(node_contains_called_group)
        }
        NodeInner::Quant(qn) => qn.body.as_deref().is_some_and(node_contains_called_group),
        NodeInner::Bag(bn) => {
            bn.body.as_deref().is_some_and(node_contains_called_group)
                || match &bn.bag_data {
                    BagData::IfElse {
                        then_node,
                        else_node,
                    } => {
                        then_node.as_deref().is_some_and(node_contains_called_group)
                            || else_node.as_deref().is_some_and(node_contains_called_group)
                    }
                    _ => false,
                }
        }
        NodeInner::Anchor(an) => an.body.as_deref().is_some_and(node_contains_called_group),
        _ => false,
    }
}

fn apply_call_graph_state(
    node: &mut Node,
    current_groups: &mut Vec<usize>,
    edges: &[Vec<usize>],
    recursive: &[bool],
    env: &mut ParseEnv,
) {
    let mut recursive_group = None;
    match &mut node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            apply_call_graph_state(&mut cons.car, current_groups, edges, recursive, env);
            if let Some(cdr) = &mut cons.cdr {
                apply_call_graph_state(cdr, current_groups, edges, recursive, env);
            }
        }
        NodeInner::Quant(qn) => {
            if qn.upper == 0 && qn.body.as_deref().is_some_and(node_contains_called_group) {
                qn.include_referred = 1;
            }
            if let Some(body) = &mut qn.body {
                apply_call_graph_state(body, current_groups, edges, recursive, env);
            }
        }
        NodeInner::Bag(bn) => {
            let is_memory = bn.bag_type == BagType::Memory;
            if is_memory {
                let regnum = bn.regnum() as usize;
                if recursive.get(regnum).copied().unwrap_or(false) {
                    recursive_group = Some(regnum);
                }
                current_groups.push(regnum);
            }
            if let Some(body) = &mut bn.body {
                apply_call_graph_state(body, current_groups, edges, recursive, env);
            }
            if let BagData::IfElse {
                then_node,
                else_node,
            } = &mut bn.bag_data
            {
                if let Some(then_node) = then_node {
                    apply_call_graph_state(then_node, current_groups, edges, recursive, env);
                }
                if let Some(else_node) = else_node {
                    apply_call_graph_state(else_node, current_groups, edges, recursive, env);
                }
            }
            if is_memory {
                current_groups.pop();
            }
        }
        NodeInner::Anchor(an) => {
            if let Some(body) = &mut an.body {
                apply_call_graph_state(body, current_groups, edges, recursive, env);
            }
        }
        NodeInner::Call(call) => {
            let target = call.called_gnum as usize;
            if target < edges.len()
                && current_groups.iter().copied().any(|group| {
                    let mut seen = vec![false; edges.len()];
                    reaches_group(edges, target, group, &mut seen)
                })
            {
                node.status_add(ND_ST_RECURSION);
            }
        }
        _ => {}
    }
    if let Some(regnum) = recursive_group {
        node.status_add(ND_ST_RECURSION);
        env.backtrack_mem |= 1u32 << regnum;
    }
}

fn analyze_call_graph(root: &mut Node, env: &mut ParseEnv) -> Vec<bool> {
    let mut edges = vec![Vec::new(); env.num_mem.max(0) as usize + 1];
    let mut current_groups = vec![0];
    collect_call_edges(root, &mut current_groups, &mut edges);
    let recursive = (0..edges.len())
        .map(|group| {
            edges[group].iter().copied().any(|next| {
                let mut seen = vec![false; edges.len()];
                reaches_group(&edges, next, group, &mut seen)
            })
        })
        .collect::<Vec<_>>();
    apply_call_graph_state(root, &mut current_groups, &edges, &recursive, env);
    recursive
}

fn must_recurse_without_consuming(node: &Node, must_recurse: &[bool], env: &ParseEnv) -> bool {
    match &node.inner {
        NodeInner::List(cons) => {
            let mut cur = node;
            while let NodeInner::List(cons) = &cur.inner {
                if must_recurse_without_consuming(&cons.car, must_recurse, env) {
                    return true;
                }
                if node_min_byte_len(&cons.car, env) != 0 {
                    return false;
                }
                match &cons.cdr {
                    Some(cdr) => cur = cdr,
                    None => break,
                }
            }
            false
        }
        NodeInner::Alt(cons) => {
            let mut cur = node;
            while let NodeInner::Alt(cons) = &cur.inner {
                if !must_recurse_without_consuming(&cons.car, must_recurse, env) {
                    return false;
                }
                match &cons.cdr {
                    Some(cdr) => cur = cdr,
                    None => break,
                }
            }
            true
        }
        NodeInner::Quant(qn) => {
            qn.lower != 0
                && qn
                    .body
                    .as_deref()
                    .is_some_and(|body| must_recurse_without_consuming(body, must_recurse, env))
        }
        NodeInner::Bag(bn) => {
            if let Some(body) = &bn.body {
                if must_recurse_without_consuming(body, must_recurse, env) {
                    return true;
                }
                if node_min_byte_len(body, env) != 0 {
                    return false;
                }
            }
            match &bn.bag_data {
                BagData::IfElse {
                    then_node,
                    else_node,
                } => {
                    then_node.as_deref().is_some_and(|then_node| {
                        must_recurse_without_consuming(then_node, must_recurse, env)
                    }) && else_node.as_deref().map_or(true, |else_node| {
                        must_recurse_without_consuming(else_node, must_recurse, env)
                    })
                }
                _ => false,
            }
        }
        NodeInner::Anchor(an) => an
            .body
            .as_deref()
            .is_some_and(|body| must_recurse_without_consuming(body, must_recurse, env)),
        NodeInner::Call(call) => must_recurse
            .get(call.called_gnum as usize)
            .copied()
            .unwrap_or(false),
        _ => false,
    }
}

fn update_must_recurse_groups(
    node: &Node,
    recursive: &[bool],
    current: &[bool],
    next: &mut [bool],
    env: &ParseEnv,
) {
    match &node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            update_must_recurse_groups(&cons.car, recursive, current, next, env);
            if let Some(cdr) = &cons.cdr {
                update_must_recurse_groups(cdr, recursive, current, next, env);
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(body) = &qn.body {
                update_must_recurse_groups(body, recursive, current, next, env);
            }
        }
        NodeInner::Bag(bn) => {
            if bn.bag_type == BagType::Memory {
                let regnum = bn.regnum() as usize;
                if recursive.get(regnum).copied().unwrap_or(false) {
                    next[regnum] = bn
                        .body
                        .as_deref()
                        .is_some_and(|body| must_recurse_without_consuming(body, current, env));
                }
            }
            if let Some(body) = &bn.body {
                update_must_recurse_groups(body, recursive, current, next, env);
            }
            if let BagData::IfElse {
                then_node,
                else_node,
            } = &bn.bag_data
            {
                if let Some(then_node) = then_node {
                    update_must_recurse_groups(then_node, recursive, current, next, env);
                }
                if let Some(else_node) = else_node {
                    update_must_recurse_groups(else_node, recursive, current, next, env);
                }
            }
        }
        NodeInner::Anchor(an) => {
            if let Some(body) = &an.body {
                update_must_recurse_groups(body, recursive, current, next, env);
            }
        }
        _ => {}
    }
}

fn analyze_must_recurse_groups(root: &Node, recursive: &[bool], env: &ParseEnv) -> Vec<bool> {
    let mut current = recursive.to_vec();
    loop {
        let mut next = current.clone();
        update_must_recurse_groups(root, recursive, &current, &mut next, env);
        if next == current {
            return current;
        }
        current = next;
    }
}

fn has_never_ending_recursion(node: &Node, recursive: &[bool], must_recurse: &[bool]) -> bool {
    match &node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            has_never_ending_recursion(&cons.car, recursive, must_recurse)
                || cons
                    .cdr
                    .as_deref()
                    .is_some_and(|cdr| has_never_ending_recursion(cdr, recursive, must_recurse))
        }
        NodeInner::Quant(qn) => qn
            .body
            .as_deref()
            .is_some_and(|body| has_never_ending_recursion(body, recursive, must_recurse)),
        NodeInner::Bag(bn) => {
            let regnum = bn.regnum() as usize;
            let recursive_memory = bn.bag_type == BagType::Memory
                && recursive.get(regnum).copied().unwrap_or(false)
                && node.has_status(ND_ST_CALLED)
                && must_recurse.get(regnum).copied().unwrap_or(false);
            recursive_memory
                || bn
                    .body
                    .as_deref()
                    .is_some_and(|body| has_never_ending_recursion(body, recursive, must_recurse))
                || match &bn.bag_data {
                    BagData::IfElse {
                        then_node,
                        else_node,
                    } => {
                        then_node.as_deref().is_some_and(|node| {
                            has_never_ending_recursion(node, recursive, must_recurse)
                        }) || else_node.as_deref().is_some_and(|node| {
                            has_never_ending_recursion(node, recursive, must_recurse)
                        })
                    }
                    _ => false,
                }
        }
        NodeInner::Anchor(an) => an
            .body
            .as_deref()
            .is_some_and(|body| has_never_ending_recursion(body, recursive, must_recurse)),
        _ => false,
    }
}

// ============================================================================
// disable_noname_group_capture — CAPTURE_ONLY_NAMED_GROUP support
// When syntax has this flag and named groups exist, unnamed groups become
// non-capturing and group numbers are renumbered to only include named groups.
// ============================================================================

/// Traverse tree: assign new sequential numbers to named groups, remove unnamed BAG_MEMORY.
/// Returns 1 when node was replaced (parent may need to reduce nested quantifiers).
fn make_named_capture_number_map(
    node: &mut Node,
    map: &mut [GroupNumMap],
    counter: &mut i32,
) -> i32 {
    let node_type = node.node_type();
    match node_type {
        NodeType::List | NodeType::Alt => {
            let cur = node as *mut Node;
            // SAFETY: `p` starts as the exclusive `&mut node` argument and only
            // advances to the boxed cdr, so every deref is of a live node; `car`
            // and `cdr` are disjoint fields, so recursing into car while holding
            // the cdr pointer creates no overlapping &mut (this pass follows no
            // call targets).
            unsafe {
                let mut p = cur;
                while let NodeInner::List(ref mut cons) | NodeInner::Alt(ref mut cons) = (*p).inner
                {
                    let car_ptr = &mut *cons.car as *mut Node;
                    let cdr_opt = cons.cdr.as_mut().map(|c| &mut **c as *mut Node);
                    let r = make_named_capture_number_map(&mut *car_ptr, map, counter);
                    if r < 0 {
                        return r;
                    }
                    match cdr_opt {
                        Some(next) => p = next,
                        None => break,
                    }
                }
            }
            0
        }
        NodeType::Quant => {
            let body_ptr: Option<*mut Node> = if let NodeInner::Quant(ref mut qn) = node.inner {
                qn.body.as_mut().map(|b| &mut **b as *mut Node)
            } else {
                None
            };
            if let Some(bp) = body_ptr {
                // SAFETY: `bp` points to the quantifier's boxed body, extracted above
                // to end the borrow of `node.inner`; no other reference to the body
                // exists during the call.
                let r = unsafe { make_named_capture_number_map(&mut *bp, map, counter) };
                if r < 0 {
                    return r;
                }
                // If node was replaced and became a quantifier, could reduce nested quantifiers
                // (rare case, skip for now like C's onig_reduce_nested_quantifier)
            }
            0
        }
        NodeType::Bag => {
            let is_memory =
                matches!(&node.inner, NodeInner::Bag(ref bn) if bn.bag_type == BagType::Memory);
            let is_named = node.has_status(ND_ST_NAMED_GROUP);

            if is_memory && !is_named {
                // Unnamed group — remove bag wrapper, replace node with its body
                let body = if let NodeInner::Bag(ref mut bn) = node.inner {
                    bn.body.take()
                } else {
                    None
                };
                if let Some(body) = body {
                    let body = *body;
                    node.inner = body.inner;
                    node.status = body.status;
                } else {
                    node.inner = NodeInner::String(StrNode {
                        s: Vec::new(),
                        flag: 0,
                    });
                }
                let r = make_named_capture_number_map(node, map, counter);
                if r < 0 {
                    return r;
                }
                return 1;
            }

            if is_memory && is_named {
                if let NodeInner::Bag(ref mut bn) = node.inner {
                    *counter += 1;
                    if let BagData::Memory { ref mut regnum, .. } = bn.bag_data {
                        map[*regnum as usize].new_val = *counter;
                        *regnum = *counter;
                    }
                    if let Some(ref mut body) = bn.body {
                        let r = make_named_capture_number_map(body, map, counter);
                        if r < 0 {
                            return r;
                        }
                    }
                }
                return 0;
            }

            // IfElse or other bag types
            // SAFETY: `node_ptr` is the exclusive `&mut node` argument; plain
            // reborrow used to recurse into the bag's children.
            unsafe {
                let node_ptr = node as *mut Node;
                if let NodeInner::Bag(ref mut bn) = (*node_ptr).inner {
                    if bn.bag_type == BagType::IfElse {
                        if let Some(ref mut body) = bn.body {
                            let r = make_named_capture_number_map(body, map, counter);
                            if r < 0 {
                                return r;
                            }
                        }
                        if let BagData::IfElse {
                            ref mut then_node,
                            ref mut else_node,
                        } = bn.bag_data
                        {
                            if let Some(ref mut tn) = then_node {
                                let r = make_named_capture_number_map(tn, map, counter);
                                if r < 0 {
                                    return r;
                                }
                            }
                            if let Some(ref mut en) = else_node {
                                let r = make_named_capture_number_map(en, map, counter);
                                if r < 0 {
                                    return r;
                                }
                            }
                        }
                    } else {
                        if let Some(ref mut body) = bn.body {
                            let r = make_named_capture_number_map(body, map, counter);
                            if r < 0 {
                                return r;
                            }
                        }
                    }
                }
            }
            0
        }
        NodeType::Anchor => {
            if let NodeInner::Anchor(ref mut a) = node.inner {
                if let Some(ref mut body) = a.body {
                    let r = make_named_capture_number_map(body, map, counter);
                    if r < 0 {
                        return r;
                    }
                }
            }
            0
        }
        _ => 0,
    }
}

/// Renumber backrefs in a single backref node using the group number map.
fn renumber_backref_node(node: &mut Node, map: &[GroupNumMap]) -> i32 {
    if !node.has_status(ND_ST_BY_NAME) {
        return ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED;
    }
    if let NodeInner::BackRef(ref mut br) = node.inner {
        let old_num = br.back_num as usize;
        let mut pos = 0usize;
        if let Some(ref mut dyn_refs) = br.back_dynamic {
            for i in 0..old_num {
                let n = map[dyn_refs[i] as usize].new_val;
                if n > 0 {
                    dyn_refs[pos] = n;
                    pos += 1;
                }
            }
        } else {
            for i in 0..old_num {
                let n = map[br.back_static[i] as usize].new_val;
                if n > 0 {
                    br.back_static[pos] = n;
                    pos += 1;
                }
            }
        }
        br.back_num = pos as i32;
    }
    0
}

/// Traverse tree to renumber all backrefs using the group number map.
fn renumber_backref_traverse(node: &mut Node, map: &[GroupNumMap]) -> i32 {
    match node.node_type() {
        NodeType::List | NodeType::Alt => {
            let cur = node as *mut Node;
            // SAFETY: `p` starts as the exclusive `&mut node` argument and only
            // advances to the boxed cdr, so every deref is of a live node; `car`
            // and `cdr` are disjoint fields, so recursing into car while holding
            // the cdr pointer creates no overlapping &mut (this pass follows no
            // call targets).
            unsafe {
                let mut p = cur;
                while let NodeInner::List(ref mut cons) | NodeInner::Alt(ref mut cons) =
                    &mut (*p).inner
                {
                    let car_ptr = &mut *cons.car as *mut Node;
                    let cdr_opt = cons.cdr.as_mut().map(|c| &mut **c as *mut Node);
                    let r = renumber_backref_traverse(&mut *car_ptr, map);
                    if r != 0 {
                        return r;
                    }
                    match cdr_opt {
                        Some(next) => {
                            p = next;
                        }
                        None => break,
                    }
                }
            }
            0
        }
        NodeType::Quant => {
            if let NodeInner::Quant(ref mut qn) = node.inner {
                if let Some(ref mut body) = qn.body {
                    return renumber_backref_traverse(body, map);
                }
            }
            0
        }
        NodeType::Bag => {
            // SAFETY: `node_ptr` is the exclusive `&mut node` argument; plain
            // reborrow used to recurse into the bag's children.
            unsafe {
                let node_ptr = node as *mut Node;
                if let NodeInner::Bag(ref mut bn) = (*node_ptr).inner {
                    if let Some(ref mut body) = bn.body {
                        let r = renumber_backref_traverse(body, map);
                        if r != 0 {
                            return r;
                        }
                    }
                    if bn.bag_type == BagType::IfElse {
                        if let BagData::IfElse {
                            ref mut then_node,
                            ref mut else_node,
                        } = bn.bag_data
                        {
                            if let Some(ref mut tn) = then_node {
                                let r = renumber_backref_traverse(tn, map);
                                if r != 0 {
                                    return r;
                                }
                            }
                            if let Some(ref mut en) = else_node {
                                let r = renumber_backref_traverse(en, map);
                                if r != 0 {
                                    return r;
                                }
                            }
                        }
                    }
                }
            }
            0
        }
        NodeType::BackRef => renumber_backref_node(node, map),
        NodeType::Anchor => {
            if let NodeInner::Anchor(ref mut a) = node.inner {
                if let Some(ref mut body) = a.body {
                    return renumber_backref_traverse(body, map);
                }
            }
            0
        }
        _ => 0,
    }
}

/// Check that no numbered (non-named) backrefs exist in the tree.
/// Called when all captures are named (num_named == num_mem).
fn numbered_ref_check(node: &Node) -> i32 {
    match &node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            let r = numbered_ref_check(&cons.car);
            if r != 0 {
                return r;
            }
            if let Some(ref next) = cons.cdr {
                return numbered_ref_check(next);
            }
            0
        }
        NodeInner::Quant(ref qn) => {
            if let Some(ref body) = qn.body {
                numbered_ref_check(body)
            } else {
                0
            }
        }
        NodeInner::Anchor(ref a) => {
            if let Some(ref body) = a.body {
                numbered_ref_check(body)
            } else {
                0
            }
        }
        NodeInner::Bag(ref bn) => {
            if let Some(ref body) = bn.body {
                let r = numbered_ref_check(body);
                if r != 0 {
                    return r;
                }
            }
            if bn.bag_type == BagType::IfElse {
                if let BagData::IfElse {
                    ref then_node,
                    ref else_node,
                } = bn.bag_data
                {
                    if let Some(ref tn) = then_node {
                        let r = numbered_ref_check(tn);
                        if r != 0 {
                            return r;
                        }
                    }
                    if let Some(ref en) = else_node {
                        let r = numbered_ref_check(en);
                        if r != 0 {
                            return r;
                        }
                    }
                }
            }
            0
        }
        NodeInner::BackRef(_) => {
            if !node.has_status(ND_ST_BY_NAME) {
                ONIGERR_NUMBERED_BACKREF_OR_CALL_NOT_ALLOWED
            } else {
                0
            }
        }
        _ => 0,
    }
}

/// When CAPTURE_ONLY_NAMED_GROUP is active and both named and unnamed groups
/// exist, remove unnamed captures and renumber everything to only use named groups.
fn disable_noname_group_capture(root: &mut Node, reg: &mut RegexType, env: &mut ParseEnv) -> i32 {
    let num_mem = env.num_mem as usize;
    let mut map: Vec<GroupNumMap> = (0..=num_mem).map(|_| GroupNumMap { new_val: 0 }).collect();
    let mut counter: i32 = 0;

    let r = make_named_capture_number_map(root, &mut map, &mut counter);
    if r < 0 {
        return r;
    }

    let r = renumber_backref_traverse(root, &map);
    if r != 0 {
        return r;
    }

    // Compact mem_env: shift named entries down to fill gaps left by removed unnamed groups
    let mut pos: usize = 1;
    for (i, map_entry) in map.iter().enumerate().skip(1).take(num_mem) {
        if map_entry.new_val > 0 {
            if pos != i {
                let src_node = env.mem_env(i).mem_node;
                let src_empty = env.mem_env(i).empty_repeat_node;
                let dst = env.mem_env_mut(pos);
                dst.mem_node = src_node;
                dst.empty_repeat_node = src_empty;
            }
            pos += 1;
        }
    }

    // Update cap_history bitmap with renumbered groups
    let loc = env.cap_history;
    env.cap_history = 0;
    for (i, map_entry) in map
        .iter()
        .enumerate()
        .skip(1)
        .take(std::cmp::min(num_mem, 31))
    {
        if (loc & (1u32 << i)) != 0 {
            let new_val = map_entry.new_val;
            if new_val > 0 && new_val <= 31 {
                env.cap_history |= 1u32 << (new_val as u32);
            }
        }
    }

    env.num_mem = env.num_named;
    reg.num_mem = env.num_named;

    // Renumber name table entries
    if let Some(ref mut nt) = reg.name_table {
        for entry in nt.entries.values_mut() {
            for back_ref in entry.back_refs.iter_mut() {
                let idx = *back_ref as usize;
                if idx < map.len() {
                    *back_ref = map[idx].new_val;
                }
            }
        }
    }

    0
}

// ============================================================================
// Call-node tuning: tune_call + tune_called_state
// ============================================================================

/// C: tune_call — mark zero-repeat contexts and adjust entry counts.
/// Call reference resolution is already handled by resolve_call_references.
fn tune_call(node: &mut Node, state: i32) {
    let np = node as *mut Node;
    // SAFETY: `np` is the exclusive `&mut node` argument; all derefs are
    // reborrows of it or of boxed cdr nodes reached from it, and the raw
    // pointer only serves to update `status` around borrows of `inner`
    // (disjoint fields). This pass follows no call targets.
    unsafe {
        match &mut (*np).inner {
            NodeInner::List(_) | NodeInner::Alt(_) => {
                let mut cur = np;
                while let NodeInner::List(c) | NodeInner::Alt(c) = &mut (*cur).inner {
                    tune_call(&mut c.car, state);
                    match &mut c.cdr {
                        Some(ref mut next) => cur = next.as_mut() as *mut Node,
                        None => break,
                    }
                }
            }
            NodeInner::Quant(qn) => {
                let s = if qn.upper == 0 {
                    state | IN_ZERO_REPEAT
                } else {
                    state
                };
                if let Some(ref mut body) = qn.body {
                    tune_call(body, s);
                }
            }
            NodeInner::Anchor(an) => {
                if let Some(ref mut body) = an.body {
                    tune_call(body, state);
                }
            }
            NodeInner::Bag(bn) => {
                let bt = bn.bag_type;
                if bt == BagType::Memory {
                    if (state & IN_ZERO_REPEAT) != 0 {
                        (*np).status_add(ND_ST_IN_ZERO_REPEAT);
                        if let NodeInner::Bag(ref mut bn) = (*np).inner {
                            if let BagData::Memory {
                                ref mut entry_count,
                                ..
                            } = bn.bag_data
                            {
                                *entry_count -= 1;
                            }
                            if let Some(ref mut body) = bn.body {
                                tune_call(body, state);
                            }
                        }
                    } else if let Some(ref mut body) = bn.body {
                        tune_call(body, state);
                    }
                } else if bt == BagType::IfElse {
                    if let Some(ref mut body) = bn.body {
                        tune_call(body, state);
                    }
                    if let BagData::IfElse {
                        ref mut then_node,
                        ref mut else_node,
                    } = bn.bag_data
                    {
                        if let Some(ref mut t) = then_node {
                            tune_call(t, state);
                        }
                        if let Some(ref mut e) = else_node {
                            tune_call(e, state);
                        }
                    }
                } else if let Some(ref mut body) = bn.body {
                    tune_call(body, state);
                }
            }
            NodeInner::Call(cn) => {
                if (state & IN_ZERO_REPEAT) != 0 {
                    (*np).status_add(ND_ST_IN_ZERO_REPEAT);
                    cn.entry_count -= 1;
                }
            }
            _ => {}
        }
    }
}

/// C: tune_called_state_call — propagate state flags through called nodes.
///
/// Internal compiler pass that propagates state bits (IN_ALT, IN_PEEK,
/// IN_REAL_REPEAT, etc.) through the call graph of subroutine-call nodes.
/// Only reachable when the pattern uses `\g<name>` or `(?R)` in specific
/// contexts. Tested indirectly through compat_utf8 suite.
#[cfg_attr(coverage_nightly, coverage(off))]
fn tune_called_state_call(node: &mut Node, state: i32) {
    let np = node as *mut Node;
    // SAFETY: `np` is the exclusive `&mut node` argument; derefs are reborrows
    // of it or of boxed cdr nodes, and the raw pointer only updates `status`
    // around borrows of `inner` (disjoint fields). Re-entry through call
    // cycles is cut by the MARK1 guard on Bag Memory nodes.
    unsafe {
        match &mut (*np).inner {
            NodeInner::Alt(_) => {
                let s = state | IN_ALT;
                let mut cur = np;
                while let NodeInner::Alt(c) | NodeInner::List(c) = &mut (*cur).inner {
                    tune_called_state_call(&mut c.car, s);
                    match &mut c.cdr {
                        Some(ref mut next) => cur = next.as_mut() as *mut Node,
                        None => break,
                    }
                }
            }
            NodeInner::List(_) => {
                let mut cur = np;
                while let NodeInner::List(c) | NodeInner::Alt(c) = &mut (*cur).inner {
                    tune_called_state_call(&mut c.car, state);
                    match &mut c.cdr {
                        Some(ref mut next) => cur = next.as_mut() as *mut Node,
                        None => break,
                    }
                }
            }
            NodeInner::Quant(qn) => {
                let mut s = state;
                if is_infinite_repeat(qn.upper) || qn.upper >= 2 {
                    s |= IN_REAL_REPEAT;
                }
                if qn.lower != qn.upper {
                    s |= IN_VAR_REPEAT;
                }
                if (state & IN_PEEK) != 0 {
                    (*np).status_add(ND_ST_INPEEK);
                }
                if let Some(ref mut body) = qn.body {
                    tune_called_state_call(body, s);
                }
            }
            NodeInner::Anchor(an) => match an.anchor_type {
                ANCR_PREC_READ_NOT | ANCR_LOOK_BEHIND_NOT => {
                    if let Some(ref mut body) = an.body {
                        tune_called_state_call(body, state | IN_NOT | IN_PEEK);
                    }
                }
                ANCR_PREC_READ | ANCR_LOOK_BEHIND => {
                    if let Some(ref mut body) = an.body {
                        tune_called_state_call(body, state | IN_PEEK);
                    }
                }
                _ => {}
            },
            NodeInner::Bag(bn) => {
                let bt = bn.bag_type;
                if bt == BagType::Memory {
                    if (*np).has_status(ND_ST_MARK1) {
                        if let NodeInner::Bag(ref mut bn) = (*np).inner {
                            if let BagData::Memory {
                                ref mut called_state,
                                ..
                            } = bn.bag_data
                            {
                                if (!*called_state & state) != 0 {
                                    *called_state |= state;
                                    if let Some(ref mut body) = bn.body {
                                        tune_called_state_call(body, state);
                                    }
                                }
                            }
                        }
                    } else {
                        (*np).status_add(ND_ST_MARK1);
                        if let NodeInner::Bag(ref mut bn) = (*np).inner {
                            if let BagData::Memory {
                                ref mut called_state,
                                ..
                            } = bn.bag_data
                            {
                                *called_state |= state;
                            }
                            if let Some(ref mut body) = bn.body {
                                tune_called_state_call(body, state);
                            }
                        }
                        (*np).status_remove(ND_ST_MARK1);
                    }
                } else if bt == BagType::IfElse {
                    let s = state | IN_ALT;
                    if let Some(ref mut body) = bn.body {
                        tune_called_state_call(body, s);
                    }
                    if let BagData::IfElse {
                        ref mut then_node,
                        ref mut else_node,
                    } = bn.bag_data
                    {
                        if let Some(ref mut t) = then_node {
                            tune_called_state_call(t, s);
                        }
                        if let Some(ref mut e) = else_node {
                            tune_called_state_call(e, s);
                        }
                    }
                } else if let Some(ref mut body) = bn.body {
                    tune_called_state_call(body, state);
                }
            }
            NodeInner::Call(cn) => {
                if (state & IN_PEEK) != 0 {
                    (*np).status_add(ND_ST_INPEEK);
                }
                if (state & IN_REAL_REPEAT) != 0 {
                    (*np).status_add(ND_ST_IN_REAL_REPEAT);
                }
                if let Some(ref mut body) = cn.body {
                    tune_called_state_call(body, state);
                }
            }
            _ => {}
        }
    }
}

/// C: tune_called_state — propagate state flags down the tree, entering called groups.
fn tune_called_state(node: &mut Node, state: i32) {
    let np = node as *mut Node;
    // SAFETY: `np` is the exclusive `&mut node` argument; all derefs are
    // reborrows of it or of boxed cdr nodes reached from it. Called groups are
    // entered only through tune_called_state_call, which guards call cycles
    // with MARK1.
    unsafe {
        match &mut (*np).inner {
            NodeInner::Alt(_) => {
                let s = state | IN_ALT;
                let mut cur = np;
                while let NodeInner::Alt(c) | NodeInner::List(c) = &mut (*cur).inner {
                    tune_called_state(&mut c.car, s);
                    match &mut c.cdr {
                        Some(ref mut next) => cur = next.as_mut() as *mut Node,
                        None => break,
                    }
                }
            }
            NodeInner::List(_) => {
                let mut cur = np;
                while let NodeInner::List(c) | NodeInner::Alt(c) = &mut (*cur).inner {
                    tune_called_state(&mut c.car, state);
                    match &mut c.cdr {
                        Some(ref mut next) => cur = next.as_mut() as *mut Node,
                        None => break,
                    }
                }
            }
            NodeInner::Call(_) => {
                if (state & IN_PEEK) != 0 {
                    (*np).status_add(ND_ST_INPEEK);
                }
                if (state & IN_REAL_REPEAT) != 0 {
                    (*np).status_add(ND_ST_IN_REAL_REPEAT);
                }
                tune_called_state_call(&mut *np, state);
            }
            NodeInner::Bag(bn) => {
                let bt = bn.bag_type;
                match bt {
                    BagType::Memory => {
                        let mut s = state;
                        if let BagData::Memory {
                            entry_count,
                            ref mut called_state,
                            ..
                        } = bn.bag_data
                        {
                            if entry_count > 1 {
                                s |= IN_MULTI_ENTRY;
                            }
                            *called_state |= s;
                        }
                        if let Some(ref mut body) = bn.body {
                            tune_called_state(body, s);
                        }
                    }
                    BagType::Option | BagType::StopBacktrack => {
                        if let Some(ref mut body) = bn.body {
                            tune_called_state(body, state);
                        }
                    }
                    BagType::IfElse => {
                        let s = state | IN_ALT;
                        if let Some(ref mut body) = bn.body {
                            tune_called_state(body, s);
                        }
                        if let BagData::IfElse {
                            ref mut then_node,
                            ref mut else_node,
                        } = bn.bag_data
                        {
                            if let Some(ref mut t) = then_node {
                                tune_called_state(t, s);
                            }
                            if let Some(ref mut e) = else_node {
                                tune_called_state(e, s);
                            }
                        }
                    }
                }
            }
            NodeInner::Quant(qn) => {
                let mut s = state;
                if is_infinite_repeat(qn.upper) || qn.upper >= 2 {
                    s |= IN_REAL_REPEAT;
                }
                if qn.lower != qn.upper {
                    s |= IN_VAR_REPEAT;
                }
                if (state & IN_PEEK) != 0 {
                    (*np).status_add(ND_ST_INPEEK);
                }
                if let Some(ref mut body) = qn.body {
                    tune_called_state(body, s);
                }
            }
            NodeInner::Anchor(an) => match an.anchor_type {
                ANCR_PREC_READ_NOT | ANCR_LOOK_BEHIND_NOT => {
                    if let Some(ref mut body) = an.body {
                        tune_called_state(body, state | IN_NOT | IN_PEEK);
                    }
                }
                ANCR_PREC_READ | ANCR_LOOK_BEHIND => {
                    if let Some(ref mut body) = an.body {
                        tune_called_state(body, state | IN_PEEK);
                    }
                }
                _ => {}
            },
            _ => {}
        }
    }
}

// ============================================================================
// Literal alternation detection — replaces pure literal Alt trees with trie
// ============================================================================

/// Minimum number of literal alternatives to trigger trie optimization.
const LITERAL_ALT_THRESHOLD: usize = 4;

/// Maximum number of extracted paths from nested alternation structures.
/// Prevents exponential blowup from deeply nested optionals.
const MAX_NESTED_TRIE_PATHS: usize = 8192;

/// Info about one branch in an Alt cons-chain.
struct AltBranchInfo {
    /// Index of this branch in the Alt cons-chain (0-based).
    index: usize,
    /// Whether this branch is a literal (plain string or nested structure
    /// that was successfully extracted into literal paths).
    is_literal: bool,
    /// The literal byte sequences extracted from this branch.
    /// A plain string branch has exactly one entry; a nested structure
    /// may have multiple.  Empty if `is_literal` is false.
    literals: Vec<Vec<u8>>,
}

/// Walk the AST and detect semantically safe literal alternations. When found,
/// build a `LiteralTrie` and replace the complete alternation with one trie
/// node. Partial rewrites are intentionally excluded: moving literal branches
/// ahead of non-literal ones changes ordered-alternation semantics.
///
/// **Must be called before `tune_tree`** so that case-fold expansion has not
/// yet rewritten the string nodes.
pub fn detect_literal_alternations(
    node: &mut Node,
    reg: &mut RegexType,
    backrefed_mem: MemStatusType,
) {
    detect_literal_alternations_inner(node, reg, false, backrefed_mem);
}

/// Recurse into the children of a node for literal alternation detection.
fn recurse_into_children(
    node: &mut Node,
    reg: &mut RegexType,
    in_anchor: bool,
    backrefed_mem: MemStatusType,
) {
    match &mut node.inner {
        NodeInner::List(_) | NodeInner::Alt(_) => {
            let mut cur: *mut Node = node;
            // SAFETY: `cur` starts as the exclusive `&mut node` argument and only
            // advances to the boxed cdr; `car` and `cdr` are disjoint fields, so
            // recursing into car (which may rewrite that subtree in place) never
            // aliases the cdr chain still being walked.
            unsafe {
                while let NodeInner::List(ref mut cons) | NodeInner::Alt(ref mut cons) =
                    (*cur).inner
                {
                    let car = &mut *cons.car as *mut Node;
                    let cdr = &mut cons.cdr;
                    detect_literal_alternations_inner(&mut *car, reg, in_anchor, backrefed_mem);
                    match cdr {
                        Some(ref mut next) => cur = &mut **next,
                        None => break,
                    };
                }
            }
        }
        NodeInner::Quant(ref mut qn) => {
            if let Some(ref mut body) = qn.body {
                detect_literal_alternations_inner(body, reg, in_anchor, backrefed_mem);
            }
        }
        NodeInner::Bag(ref mut bn) => {
            if let Some(ref mut body) = bn.body {
                detect_literal_alternations_inner(body, reg, in_anchor, backrefed_mem);
            }
        }
        NodeInner::Anchor(ref mut an) => {
            if let Some(ref mut body) = an.body {
                detect_literal_alternations_inner(body, reg, true, backrefed_mem);
            }
        }
        _ => {}
    }
}

/// Try to trie-optimize an Alt node using nested extraction.  Returns true
/// if optimization was applied (full or partial).
fn try_trie_optimize_alt(
    node: &mut Node,
    reg: &mut RegexType,
    backrefed_mem: MemStatusType,
) -> bool {
    // Collect info about each branch.
    let mut branches: Vec<AltBranchInfo> = Vec::new();
    let mut case_insensitive = false;
    let mut literal_count = 0usize;
    let mut all_plain_strings = true;

    {
        let mut cur: *const Node = node;
        let mut idx = 0usize;
        // SAFETY: `cur` starts as the exclusive `&mut node` argument (demoted to
        // shared) and only advances to boxed cdr nodes, so every deref is of a
        // live node; this walk and classify_branch perform reads only.
        unsafe {
            loop {
                let (car, cdr) = match &(*cur).inner {
                    NodeInner::Alt(ref cons) => (&*cons.car as *const Node, &cons.cdr),
                    _ => {
                        all_plain_strings &=
                            matches!(&(*cur).inner, NodeInner::String(sn) if !sn.is_crude());
                        let info = classify_branch(&*cur, backrefed_mem);
                        if info.is_literal && (*cur).has_status(ND_ST_IGNORECASE) {
                            case_insensitive = true;
                        }
                        if info.is_literal {
                            literal_count += info.literals.len();
                        }
                        branches.push(AltBranchInfo { index: idx, ..info });
                        break;
                    }
                };
                all_plain_strings &=
                    matches!(&(*car).inner, NodeInner::String(sn) if !sn.is_crude());
                let info = classify_branch(&*car, backrefed_mem);
                if info.is_literal && (*car).has_status(ND_ST_IGNORECASE) {
                    case_insensitive = true;
                }
                if info.is_literal {
                    literal_count += info.literals.len();
                }
                branches.push(AltBranchInfo { index: idx, ..info });
                idx += 1;
                match cdr {
                    Some(ref next) => cur = &**next,
                    None => break,
                }
            }
        }
    }

    let all_literal = branches.iter().all(|b| b.is_literal);
    if literal_count < LITERAL_ALT_THRESHOLD
        || !all_literal
        || !all_plain_strings
        || case_insensitive
        || reg.options.intersects(ONIG_OPTION_IGNORECASE)
    {
        return false;
    }

    // The trie returns the longest terminal. That is equivalent to ordered
    // alternation only when no two literals have a prefix relationship.
    let mut literals: Vec<Vec<u8>> = branches
        .iter()
        .flat_map(|b| b.literals.iter().cloned())
        .collect();
    // A lexicographic ordering places every possible extension immediately
    // after its prefix. Checking adjacent pairs avoids a quadratic scan for
    // large, generated literal alternations.
    literals.sort_unstable();
    if literals
        .windows(2)
        .any(|pair| pair[1].starts_with(pair[0].as_slice()))
    {
        return false;
    }

    let literal_refs: Vec<&[u8]> = literals.iter().map(|v| v.as_slice()).collect();
    let trie = crate::literal_trie::LiteralTrie::build(&literal_refs, false);
    let trie_idx = reg.literal_tries.len() as u32;
    reg.literal_tries.push(trie);

    node.inner = NodeInner::String(StrNode {
        s: trie_idx.to_le_bytes().to_vec(),
        flag: 0,
    });
    node.status_add(ND_ST_LITERAL_ALT);

    true
}

fn detect_literal_alternations_inner(
    node: &mut Node,
    reg: &mut RegexType,
    in_anchor: bool,
    backrefed_mem: MemStatusType,
) {
    // Try top-down: if this node is an Alt (not in anchor), try nested
    // extraction BEFORE recursing into children.  This prevents inner Alts
    // from being trie-optimized first (which makes them opaque to outer
    // extraction).
    if matches!(node.inner, NodeInner::Alt(_))
        && !in_anchor
        && try_trie_optimize_alt(node, reg, backrefed_mem)
    {
        // Successfully trie-optimized this complete literal alternation.
        recurse_into_children(node, reg, in_anchor, backrefed_mem);
        return;
    }

    // Recurse into children, then retry flat-check on this Alt.
    recurse_into_children(node, reg, in_anchor, backrefed_mem);

    // After recursion, retry on this Alt.  Inner Alts may now be trie
    // nodes; classify_branch handles that via check_literal_branch.
    if matches!(node.inner, NodeInner::Alt(_)) && !in_anchor {
        try_trie_optimize_alt(node, reg, backrefed_mem);
    }
}

/// Recursively extract all possible literal byte sequences from a nested AST
/// branch.  Handles String, List (sequence), Alt (fork), Bag (non-capturing or
/// non-backreferenced capturing groups), and Quant(0,1) (optional `?`).
///
/// Returns `None` if any sub-expression is non-literal (CClass, CType, complex
/// Quant, Anchor, BackRef, etc.).  The `limit` prevents exponential blowup.
fn extract_literal_paths(
    node: *const Node,
    current_prefixes: Vec<Vec<u8>>,
    limit: usize,
    backrefed_mem: MemStatusType,
) -> Option<Vec<Vec<u8>>> {
    if current_prefixes.len() > limit {
        return None;
    }
    // SAFETY: callers pass `node` pointing at a live node of the tree currently
    // borrowed by try_trie_optimize_alt (classify_branch derives it from a
    // reference; recursive calls pass children of the dereferenced node), and
    // only shared reads are performed.
    unsafe {
        match &(*node).inner {
            NodeInner::String(ref sn) => {
                if sn.is_crude() || (*node).has_status(ND_ST_LITERAL_ALT) {
                    return None;
                }
                // Append this string's bytes to each prefix
                let result: Vec<Vec<u8>> = current_prefixes
                    .into_iter()
                    .map(|mut prefix| {
                        prefix.extend_from_slice(&sn.s);
                        prefix
                    })
                    .collect();
                Some(result)
            }
            NodeInner::List(ref cons) => {
                // Sequence: walk car then cdr, threading prefixes through
                let car: *const Node = &*cons.car;
                let after_car = extract_literal_paths(car, current_prefixes, limit, backrefed_mem)?;
                if after_car.len() > limit {
                    return None;
                }
                match &cons.cdr {
                    Some(ref next) => {
                        let cdr: *const Node = &**next;
                        extract_literal_paths(cdr, after_car, limit, backrefed_mem)
                    }
                    None => Some(after_car),
                }
            }
            NodeInner::Alt(ref cons) => {
                // Fork: recurse into each branch, collect all resulting paths
                let mut all_paths: Vec<Vec<u8>> = Vec::new();
                let mut cur: *const Node = node;
                loop {
                    let (car, cdr) = match &(*cur).inner {
                        NodeInner::Alt(ref cons) => (&*cons.car as *const Node, &cons.cdr),
                        _ => {
                            // Last node in the chain (not wrapped in Alt)
                            let branch_paths = extract_literal_paths(
                                cur,
                                current_prefixes.clone(),
                                limit,
                                backrefed_mem,
                            )?;
                            all_paths.extend(branch_paths);
                            if all_paths.len() > limit {
                                return None;
                            }
                            break;
                        }
                    };
                    let branch_paths =
                        extract_literal_paths(car, current_prefixes.clone(), limit, backrefed_mem)?;
                    all_paths.extend(branch_paths);
                    if all_paths.len() > limit {
                        return None;
                    }
                    match cdr {
                        Some(ref next) => cur = &**next,
                        None => break,
                    }
                }
                Some(all_paths)
            }
            NodeInner::Bag(ref bn) => {
                match bn.bag_type {
                    BagType::Memory => {
                        // Capturing group: only safe if not backreferenced
                        if mem_status_at(backrefed_mem, bn.regnum() as usize) {
                            return None;
                        }
                        match &bn.body {
                            Some(ref body) => {
                                let body_ptr: *const Node = &**body;
                                extract_literal_paths(
                                    body_ptr,
                                    current_prefixes,
                                    limit,
                                    backrefed_mem,
                                )
                            }
                            None => Some(current_prefixes),
                        }
                    }
                    BagType::Option => {
                        // Non-capturing group (?:...) or option group
                        match &bn.body {
                            Some(ref body) => {
                                let body_ptr: *const Node = &**body;
                                extract_literal_paths(
                                    body_ptr,
                                    current_prefixes,
                                    limit,
                                    backrefed_mem,
                                )
                            }
                            None => Some(current_prefixes),
                        }
                    }
                    _ => None, // StopBacktrack, IfElse — not literal
                }
            }
            NodeInner::Quant(ref qn) => {
                if qn.lower == 0 && qn.upper == 1 {
                    // Optional `?`: fork into "with" and "without" paths
                    match &qn.body {
                        Some(ref body) => {
                            let body_ptr: *const Node = &**body;
                            let with_paths = extract_literal_paths(
                                body_ptr,
                                current_prefixes.clone(),
                                limit,
                                backrefed_mem,
                            )?;
                            let mut all = current_prefixes; // "without" paths
                            all.extend(with_paths);
                            if all.len() > limit {
                                return None;
                            }
                            Some(all)
                        }
                        None => Some(current_prefixes),
                    }
                } else {
                    None // Complex quantifier — not literal
                }
            }
            // CClass, CType, BackRef, Anchor, Call, Gimmick — not literal
            _ => None,
        }
    }
}

/// Classify a branch as literal or non-literal.  Tries the fast path
/// (`check_literal_branch`) first, then falls back to `extract_literal_paths`
/// for nested structures.
fn classify_branch(node: *const Node, backrefed_mem: MemStatusType) -> AltBranchInfo {
    let (is_lit, lit) = check_literal_branch(node);
    if is_lit {
        return AltBranchInfo {
            index: 0, // caller will override
            is_literal: true,
            literals: vec![lit],
        };
    }
    // Try nested extraction
    if let Some(paths) =
        extract_literal_paths(node, vec![Vec::new()], MAX_NESTED_TRIE_PATHS, backrefed_mem)
    {
        if !paths.is_empty() && paths.iter().all(|p| !p.is_empty()) {
            return AltBranchInfo {
                index: 0,
                is_literal: true,
                literals: paths,
            };
        }
    }
    AltBranchInfo {
        index: 0,
        is_literal: false,
        literals: Vec::new(),
    }
}

/// Check if a node is a plain literal string (non-crude, no ND_ST_LITERAL_ALT).
fn check_literal_branch(node: *const Node) -> (bool, Vec<u8>) {
    // SAFETY: callers pass `node` pointing at a live node of the currently
    // borrowed tree (derived from references in try_trie_optimize_alt and
    // classify_branch); only shared reads are performed.
    unsafe {
        if (*node).has_status(ND_ST_LITERAL_ALT) {
            return (false, Vec::new());
        }
        if let NodeInner::String(ref sn) = (*node).inner {
            if !sn.is_crude() {
                return (true, sn.s.clone());
            }
        }
        (false, Vec::new())
    }
}

/// Extract specific branches (by index) from an Alt cons-chain.
/// Returns the extracted nodes in the order of their indices.
fn extract_alt_branches(alt_node: &mut Node, indices: &[usize], out: &mut Vec<Node>) {
    // Walk the Alt cons-chain and collect the nodes at the given indices.
    let mut idx = 0usize;
    let mut cur: *mut Node = alt_node;
    // SAFETY: `cur` starts as the exclusive `&mut alt_node` argument and only
    // advances to boxed cdr nodes, so every deref is of a live, exclusively
    // borrowed node; the mem::replace calls swap out whole cars (or the tail
    // node) without touching the chain links still to be walked.
    unsafe {
        loop {
            match &mut (*cur).inner {
                NodeInner::Alt(ref mut cons) => {
                    if indices.contains(&idx) {
                        // Take the car node
                        let taken = std::mem::replace(
                            &mut cons.car,
                            Box::new(Node {
                                status: 0,
                                parent: std::ptr::null_mut(),
                                inner: NodeInner::String(StrNode {
                                    s: Vec::new(),
                                    flag: 0,
                                }),
                            }),
                        );
                        out.push(*taken);
                    }
                    idx += 1;
                    match cons.cdr {
                        Some(ref mut next) => cur = &mut **next,
                        None => break,
                    }
                }
                _ => {
                    // Last node (tail) — check if it's in the indices
                    if indices.contains(&idx) {
                        let placeholder = Node {
                            status: 0,
                            parent: std::ptr::null_mut(),
                            inner: NodeInner::String(StrNode {
                                s: Vec::new(),
                                flag: 0,
                            }),
                        };
                        let taken = std::mem::replace(&mut *cur, placeholder);
                        out.push(taken);
                    }
                    break;
                }
            }
        }
    }
}

/// Tree tuning pass - sets emptiness on quantifier nodes and propagates state.
/// Mirrors C's tune_tree() from regcomp.c.
pub fn tune_tree(node: &mut Node, reg: &mut RegexType, state: i32, env: &mut ParseEnv) -> i32 {
    // Skip nodes already optimized as literal alternation tries.
    if node.has_status(ND_ST_LITERAL_ALT) {
        return 0;
    }

    // Case-fold expansion: before the main match to get full &mut Node access
    if let NodeInner::String(ref sn) = node.inner {
        if node.has_status(ND_ST_IGNORECASE) && !sn.is_crude() {
            let r = unravel_case_fold_string(node, reg, state);
            if r != 0 {
                return r;
            }
            // After expansion, the node may have changed type (CClass, List, etc.)
            // Recurse to tune the expanded tree
            return tune_tree(node, reg, state, env);
        }
    }

    match &mut node.inner {
        NodeInner::List(_) => {
            // Walk the list: tune each element, then call tune_next for sequential pairs
            let mut cur: *mut Node = node;
            let mut prev: *mut Node = std::ptr::null_mut();
            // SAFETY: `cur` starts as the exclusive `&mut node` argument and only
            // advances to boxed cdr nodes. `prev` points at the previous
            // element's car — a node distinct from the current `cons.car` — so
            // the `&mut *prev` passed to tune_next does not alias the `&cons.car`
            // passed alongside it; tune_tree rewrites cars in place and never
            // moves or frees their boxed allocations.
            unsafe {
                while let NodeInner::List(ref mut cons) = (*cur).inner {
                    let r = tune_tree(&mut cons.car, reg, state, env);
                    if r != 0 {
                        return r;
                    }
                    // Call tune_next on previous node with current as next
                    if !prev.is_null() {
                        let r = tune_next(&mut *prev, &cons.car, reg);
                        if r != 0 {
                            return r;
                        }
                    }
                    prev = &mut *cons.car;
                    match cons.cdr {
                        Some(ref mut next) => cur = &mut **next,
                        None => break,
                    }
                }
            }
            0
        }

        NodeInner::Alt(_) => {
            let mut cur: *mut Node = node;
            // SAFETY: `cur` starts as the exclusive `&mut node` argument and only
            // advances to boxed cdr nodes, so every deref is of a live,
            // exclusively borrowed node.
            unsafe {
                while let NodeInner::Alt(ref mut cons) = (*cur).inner {
                    let r = tune_tree(&mut cons.car, reg, state | IN_ALT, env);
                    if r != 0 {
                        return r;
                    }
                    match cons.cdr {
                        Some(ref mut next) => cur = &mut **next,
                        None => break,
                    }
                }
            }
            0
        }

        NodeInner::Quant(ref mut qn) => {
            // Propagate repeat status flags
            if (state & IN_REAL_REPEAT) != 0 {
                node.status |= ND_ST_IN_REAL_REPEAT;
            }
            if (state & IN_MULTI_ENTRY) != 0 {
                node.status |= ND_ST_IN_MULTI_ENTRY;
            }

            // Check if body can match empty
            if is_infinite_repeat(qn.upper) || qn.upper >= 1 {
                if let Some(ref body) = qn.body {
                    let d = node_min_byte_len(body, env);
                    if d == 0 {
                        // Use quantifiers_memory_node_info to detect captures in body
                        qn.emptiness = quantifiers_memory_node_info(body);
                    }
                }
            }

            // Update state for recursive call
            let mut new_state = state;
            if is_infinite_repeat(qn.upper) || qn.upper >= 2 {
                new_state |= IN_REAL_REPEAT;
            }
            if qn.lower != qn.upper {
                new_state |= IN_VAR_REPEAT;
            }

            // Recurse into body
            if let Some(ref mut body) = qn.body {
                let r = tune_tree(body, reg, new_state, env);
                if r != 0 {
                    return r;
                }
            }

            // Expand string: "abc"{3} => "abcabcabc"
            const EXPAND_STRING_MAX_LENGTH: i32 = 100;
            if let Some(ref body) = qn.body {
                if let NodeInner::String(ref sn) = body.inner {
                    if !is_infinite_repeat(qn.lower)
                        && qn.lower == qn.upper
                        && qn.lower > 1
                        && qn.lower <= EXPAND_STRING_MAX_LENGTH
                    {
                        let len = sn.s.len() as i32;
                        if len * qn.lower <= EXPAND_STRING_MAX_LENGTH {
                            let n = qn.lower as usize;
                            let orig_bytes = sn.s.clone();
                            let flag = sn.flag;
                            // Build expanded string
                            let mut expanded = Vec::with_capacity(orig_bytes.len() * n);
                            for _ in 0..n {
                                expanded.extend_from_slice(&orig_bytes);
                            }
                            // Replace quantifier node with string node
                            let mut str_node = node_new_str(&expanded);
                            if let NodeInner::String(ref mut esn) = str_node.inner {
                                esn.flag = flag;
                            }
                            str_node.status = node.status;
                            *node = *str_node;
                            return 0;
                        }
                    }
                }
            }

            // Set head_exact: extract leading literal byte from body
            if qn.greedy && qn.emptiness == BodyEmptyType::NotEmpty {
                if let Some(ref body) = qn.body {
                    if let NodeInner::Quant(ref tqn) = body.inner {
                        // Propagate head_exact from nested quantifier
                        if tqn.head_exact.is_some() {
                            qn.head_exact = tqn.head_exact;
                        }
                    } else {
                        qn.head_exact = get_head_literal_byte(body, true, reg);
                    }
                }
            }

            0
        }

        NodeInner::Bag(ref mut bn) => {
            match bn.bag_type {
                BagType::Option => {
                    let saved_options = reg.options;
                    if let BagData::Option { options } = bn.bag_data {
                        reg.options = options;
                    }
                    let r = if let Some(ref mut body) = bn.body {
                        tune_tree(body, reg, state, env)
                    } else {
                        0
                    };
                    reg.options = saved_options;
                    r
                }
                BagType::Memory => {
                    // Propagate called_state into state (C: state |= en->m.called_state)
                    let mut state = state;
                    if let BagData::Memory { called_state, .. } = bn.bag_data {
                        state |= called_state;
                    }
                    if (state & (IN_ALT | IN_NOT | IN_VAR_REPEAT | IN_MULTI_ENTRY)) != 0
                        || (node.status & ND_ST_RECURSION) != 0
                    {
                        // Backtrack mem needed for captures in alternation/variable repeat/recursion
                        if let BagData::Memory { regnum, .. } = bn.bag_data {
                            mem_status_on(&mut env.backtrack_mem, regnum as usize);
                        }
                    }
                    if let Some(ref mut body) = bn.body {
                        tune_tree(body, reg, state, env)
                    } else {
                        0
                    }
                }
                BagType::StopBacktrack => {
                    if let Some(ref mut body) = bn.body {
                        tune_tree(body, reg, state, env)
                    } else {
                        0
                    }
                }
                BagType::IfElse => {
                    if let Some(ref mut body) = bn.body {
                        let r = tune_tree(body, reg, state | IN_ALT, env);
                        if r != 0 {
                            return r;
                        }
                    }
                    if let BagData::IfElse {
                        ref mut then_node,
                        ref mut else_node,
                    } = bn.bag_data
                    {
                        if let Some(ref mut then_n) = then_node {
                            let r = tune_tree(then_n, reg, state | IN_ALT, env);
                            if r != 0 {
                                return r;
                            }
                        }
                        if let Some(ref mut else_n) = else_node {
                            let r = tune_tree(else_n, reg, state | IN_ALT, env);
                            if r != 0 {
                                return r;
                            }
                        }
                    }
                    0
                }
            }
        }

        NodeInner::Anchor(ref mut an) => {
            let at = an.anchor_type;
            // For lookbehind anchors, compute char lengths (may transform node into Alt)
            if at == ANCR_LOOK_BEHIND || at == ANCR_LOOK_BEHIND_NOT {
                let enc = env.enc;
                let r = tune_look_behind(node, enc, &env.syntax);
                if r != 0 {
                    return r;
                }
                // tune_look_behind may have transformed node into an Alt;
                // if so, recurse on the new node structure
                if !matches!(node.inner, NodeInner::Anchor(_)) {
                    return tune_tree(node, reg, state, env);
                }
            }
            // Now recurse into the body
            if let NodeInner::Anchor(ref mut an) = node.inner {
                let anchor_type = an.anchor_type;
                if let Some(ref mut body) = an.body {
                    let new_state = if anchor_type == ANCR_PREC_READ {
                        state | IN_PREC_READ
                    } else if anchor_type == ANCR_PREC_READ_NOT {
                        state | IN_PREC_READ | IN_NOT
                    } else if anchor_type == ANCR_LOOK_BEHIND_NOT {
                        state | IN_NOT | IN_LOOK_BEHIND
                    } else if anchor_type == ANCR_LOOK_BEHIND {
                        state | IN_LOOK_BEHIND
                    } else {
                        state
                    };
                    let r = tune_tree(body, reg, new_state, env);
                    if r != 0 {
                        return r;
                    }

                    // Reduce quantifiers in lookbehind (upper = lower)
                    if anchor_type == ANCR_LOOK_BEHIND || anchor_type == ANCR_LOOK_BEHIND_NOT {
                        alt_reduce_in_look_behind(body);
                    }
                    0
                } else {
                    0
                }
            } else {
                0
            }
        }

        NodeInner::BackRef(ref br) => {
            // Set backrefed_mem for each referenced group
            for &back in br.back_refs() {
                if back > 0 {
                    mem_status_on(&mut env.backrefed_mem, back as usize);
                }
            }
            0
        }

        // Terminal nodes - nothing to tune
        NodeInner::String(_)
        | NodeInner::CType(_)
        | NodeInner::CClass(_)
        | NodeInner::Call(_)
        | NodeInner::Gimmick(_) => 0,
    }
}

// ============================================================================
// setup_empty_status_mem: compute qn.empty_status_mem for quantifiers
// ============================================================================

/// Pass 1: For each quantifier with emptiness >= MayBeEmptyMem, set
/// empty_repeat_node on all captures in its body.
fn mark_empty_repeat_node(node: &mut Node, env: &mut ParseEnv) {
    let node_ptr = node as *mut Node;
    match &mut node.inner {
        NodeInner::Quant(ref mut qn) => {
            let is_empty = qn.emptiness == BodyEmptyType::MayBeEmptyMem
                || qn.emptiness == BodyEmptyType::MayBeEmptyRec;
            if is_empty {
                if let Some(ref body) = qn.body {
                    set_empty_repeat_node_in_body(body, node_ptr as *const Node, env);
                }
            }
            if let Some(ref mut body) = qn.body {
                mark_empty_repeat_node(body, env);
            }
        }
        NodeInner::List(_) | NodeInner::Alt(_) => {
            let mut cur: *mut Node = node;
            // SAFETY: `cur` starts as the exclusive `&mut node` argument and only
            // advances to boxed cdr nodes, so every deref is of a live,
            // exclusively borrowed node; the recursion into car borrows a field
            // disjoint from the cdr link.
            unsafe {
                while let NodeInner::List(ref mut cons) | NodeInner::Alt(ref mut cons) =
                    (*cur).inner
                {
                    mark_empty_repeat_node(cons.car.as_mut(), env);
                    match cons.cdr {
                        Some(ref mut next) => cur = &mut **next,
                        None => break,
                    }
                }
            }
        }
        NodeInner::Bag(ref mut bn) => {
            if let Some(ref mut body) = bn.body {
                mark_empty_repeat_node(body, env);
            }
            if let BagData::IfElse {
                ref mut then_node,
                ref mut else_node,
            } = bn.bag_data
            {
                if let Some(ref mut t) = then_node {
                    mark_empty_repeat_node(t, env);
                }
                if let Some(ref mut e) = else_node {
                    mark_empty_repeat_node(e, env);
                }
            }
        }
        NodeInner::Anchor(ref mut an) => {
            if let Some(ref mut body) = an.body {
                mark_empty_repeat_node(body, env);
            }
        }
        _ => {}
    }
}

/// Helper: set empty_repeat_node for all BAG_MEMORY nodes in `node`.
fn set_empty_repeat_node_in_body(node: &Node, quant_ptr: *const Node, env: &mut ParseEnv) {
    match &node.inner {
        NodeInner::Bag(bn) => {
            if bn.bag_type == BagType::Memory {
                if let BagData::Memory { regnum, .. } = bn.bag_data {
                    let regnum = regnum as usize;
                    let entry = env.mem_env_mut(regnum);
                    entry.empty_repeat_node = quant_ptr as *mut Node;
                }
            }
            if let Some(ref body) = bn.body {
                set_empty_repeat_node_in_body(body, quant_ptr, env);
            }
            if let BagData::IfElse {
                ref then_node,
                ref else_node,
            } = bn.bag_data
            {
                if let Some(ref t) = then_node {
                    set_empty_repeat_node_in_body(t, quant_ptr, env);
                }
                if let Some(ref e) = else_node {
                    set_empty_repeat_node_in_body(e, quant_ptr, env);
                }
            }
        }
        NodeInner::List(_) | NodeInner::Alt(_) => {
            let mut cur: &Node = node;
            while let NodeInner::List(cons) | NodeInner::Alt(cons) = &cur.inner {
                set_empty_repeat_node_in_body(&cons.car, quant_ptr, env);
                match &cons.cdr {
                    Some(ref next) => cur = next,
                    None => break,
                }
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(ref body) = qn.body {
                set_empty_repeat_node_in_body(body, quant_ptr, env);
            }
        }
        NodeInner::Anchor(an) => {
            if let Some(ref body) = an.body {
                set_empty_repeat_node_in_body(body, quant_ptr, env);
            }
        }
        _ => {}
    }
}

/// Pass 2: Walk tree with a stack of enclosing empty-quantifier pointers.
/// When a backref is found, check if its target's empty_repeat_node is NOT
/// in the enclosing stack → set empty_status_mem on that quantifier.
fn resolve_empty_status_backrefs(
    node: &mut Node,
    enclosing_quants: &mut Vec<*const Node>,
    env: &ParseEnv,
) {
    let node_ptr = node as *const Node;
    match &mut node.inner {
        NodeInner::Quant(ref mut qn) => {
            let is_empty_quant = qn.emptiness == BodyEmptyType::MayBeEmptyMem
                || qn.emptiness == BodyEmptyType::MayBeEmptyRec;
            if is_empty_quant {
                enclosing_quants.push(node_ptr);
            }
            if let Some(ref mut body) = qn.body {
                resolve_empty_status_backrefs(body, enclosing_quants, env);
            }
            if is_empty_quant {
                enclosing_quants.pop();
            }
        }
        NodeInner::BackRef(ref br) => {
            for &back in br.back_refs() {
                if back <= 0 {
                    continue;
                }
                let back = back as usize;
                let entry = env.mem_env(back);
                let er_node = entry.empty_repeat_node;
                if !er_node.is_null() {
                    // Check if the backref is inside the quantifier
                    if !enclosing_quants.contains(&(er_node as *const Node)) {
                        // Backref is OUTSIDE the quantifier → set empty_status_mem
                        // SAFETY: `er_node` was set by mark_empty_repeat_node (pass 1)
                        // to a Quant node in this same tree, which has not been
                        // restructured since, so it is live. Every empty quantifier
                        // on the current traversal path is in `enclosing_quants`, so
                        // the contains() check above guarantees `er_node` is not a
                        // node this traversal currently borrows.
                        unsafe {
                            if let NodeInner::Quant(ref mut qn) = (*er_node).inner {
                                qn.empty_status_mem |= 1u32 << back;
                                (*er_node).status |= ND_ST_EMPTY_STATUS_CHECK;
                            }
                        }
                    }
                }
            }
        }
        NodeInner::List(_) | NodeInner::Alt(_) => {
            let mut cur: *mut Node = node;
            // SAFETY: `cur` starts as the exclusive `&mut node` argument and only
            // advances to boxed cdr nodes, so every deref is of a live,
            // exclusively borrowed node; the recursion into car borrows a field
            // disjoint from the cdr link.
            unsafe {
                while let NodeInner::List(ref mut cons) | NodeInner::Alt(ref mut cons) =
                    (*cur).inner
                {
                    resolve_empty_status_backrefs(cons.car.as_mut(), enclosing_quants, env);
                    match cons.cdr {
                        Some(ref mut next) => cur = &mut **next,
                        None => break,
                    }
                }
            }
        }
        NodeInner::Bag(ref mut bn) => {
            if let Some(ref mut body) = bn.body {
                resolve_empty_status_backrefs(body, enclosing_quants, env);
            }
            if let BagData::IfElse {
                ref mut then_node,
                ref mut else_node,
            } = bn.bag_data
            {
                if let Some(ref mut t) = then_node {
                    resolve_empty_status_backrefs(t, enclosing_quants, env);
                }
                if let Some(ref mut e) = else_node {
                    resolve_empty_status_backrefs(e, enclosing_quants, env);
                }
            }
        }
        NodeInner::Anchor(ref mut an) => {
            if let Some(ref mut body) = an.body {
                resolve_empty_status_backrefs(body, enclosing_quants, env);
            }
        }
        _ => {}
    }
}

/// Compute qn.empty_status_mem for all quantifiers in the tree.
fn setup_empty_status_mem(root: &mut Node, env: &mut ParseEnv) {
    // Pass 1: mark empty_repeat_node on captures inside empty quantifiers
    mark_empty_repeat_node(root, env);
    // Pass 2: resolve backrefs to set empty_status_mem
    let mut enclosing = Vec::new();
    resolve_empty_status_backrefs(root, &mut enclosing, env);
}

fn refresh_capture_nodes(node: &mut Node, env: &mut ParseEnv) {
    let node_ptr = node as *mut Node;
    match &mut node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            refresh_capture_nodes(cons.car.as_mut(), env);
            if let Some(cdr) = cons.cdr.as_mut() {
                refresh_capture_nodes(cdr.as_mut(), env);
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(body) = qn.body.as_mut() {
                refresh_capture_nodes(body.as_mut(), env);
            }
        }
        NodeInner::Bag(bn) => {
            if bn.bag_type == BagType::Memory {
                let regnum = bn.regnum() as usize;
                if regnum <= env.num_mem as usize {
                    env.mem_env_mut(regnum).mem_node = node_ptr;
                }
            }
            if let Some(body) = bn.body.as_mut() {
                refresh_capture_nodes(body.as_mut(), env);
            }
            if let BagData::IfElse {
                then_node,
                else_node,
            } = &mut bn.bag_data
            {
                if let Some(then_n) = then_node.as_mut() {
                    refresh_capture_nodes(then_n.as_mut(), env);
                }
                if let Some(else_n) = else_node.as_mut() {
                    refresh_capture_nodes(else_n.as_mut(), env);
                }
            }
        }
        NodeInner::Anchor(an) => {
            if let Some(body) = an.body.as_mut() {
                refresh_capture_nodes(body.as_mut(), env);
            }
            if let Some(lead) = an.lead_node.as_mut() {
                refresh_capture_nodes(lead.as_mut(), env);
            }
        }
        NodeInner::Call(cn) => {
            if let Some(body) = cn.body.as_mut() {
                refresh_capture_nodes(body.as_mut(), env);
            }
        }
        _ => {}
    }
}

fn refresh_call_targets(node: &mut Node, env: &ParseEnv) {
    match &mut node.inner {
        NodeInner::List(cons) | NodeInner::Alt(cons) => {
            refresh_call_targets(cons.car.as_mut(), env);
            if let Some(cdr) = cons.cdr.as_mut() {
                refresh_call_targets(cdr.as_mut(), env);
            }
        }
        NodeInner::Quant(qn) => {
            if let Some(body) = qn.body.as_mut() {
                refresh_call_targets(body.as_mut(), env);
            }
        }
        NodeInner::Bag(bn) => {
            if let Some(body) = bn.body.as_mut() {
                refresh_call_targets(body.as_mut(), env);
            }
            if let BagData::IfElse {
                then_node,
                else_node,
            } = &mut bn.bag_data
            {
                if let Some(then_n) = then_node.as_mut() {
                    refresh_call_targets(then_n.as_mut(), env);
                }
                if let Some(else_n) = else_node.as_mut() {
                    refresh_call_targets(else_n.as_mut(), env);
                }
            }
        }
        NodeInner::Anchor(an) => {
            if let Some(body) = an.body.as_mut() {
                refresh_call_targets(body.as_mut(), env);
            }
            if let Some(lead) = an.lead_node.as_mut() {
                refresh_call_targets(lead.as_mut(), env);
            }
        }
        NodeInner::Call(cn) => {
            cn.target_node = if cn.called_gnum > 0 && cn.called_gnum <= env.num_mem {
                env.mem_env(cn.called_gnum as usize).mem_node
            } else {
                std::ptr::null_mut()
            };
            if let Some(body) = cn.body.as_mut() {
                refresh_call_targets(body.as_mut(), env);
            }
        }
        _ => {}
    }
}

fn refresh_node_references(root: &mut Node, env: &mut ParseEnv) {
    if env.num_mem <= 0 && env.num_call <= 0 {
        return;
    }

    for i in 1..=env.num_mem as usize {
        env.mem_env_mut(i).mem_node = std::ptr::null_mut();
    }
    refresh_capture_nodes(root, env);

    if env.num_call > 0 {
        refresh_call_targets(root, env);
    }
}

/// Flatten a List node into a Vec of car elements.
fn flatten_list(mut node: Node) -> Vec<Node> {
    let mut items = Vec::new();
    loop {
        match node.inner {
            NodeInner::List(cons) => {
                items.push(*cons.car);
                match cons.cdr {
                    Some(next) => node = *next,
                    None => break,
                }
            }
            _ => {
                // Shouldn't happen - the last cdr should be None
                items.push(node);
                break;
            }
        }
    }
    items
}

/// Rebuild a List node from a Vec of car elements.
fn rebuild_list(items: Vec<Node>) -> Box<Node> {
    let mut items = items;
    assert!(!items.is_empty());
    let mut result = Box::new(Node {
        status: 0,
        parent: std::ptr::null_mut(),
        inner: NodeInner::List(ConsAltNode {
            car: Box::new(items.pop().unwrap()),
            cdr: None,
        }),
    });
    while let Some(item) = items.pop() {
        result = Box::new(Node {
            status: 0,
            parent: std::ptr::null_mut(),
            inner: NodeInner::List(ConsAltNode {
                car: Box::new(item),
                cdr: Some(result),
            }),
        });
    }
    result
}

/// Consolidate adjacent string nodes in the parse tree.
/// Mirrors C's reduce_string_list() from regcomp.c.
pub fn reduce_string_list(node: &mut Node, _enc: OnigEncoding) -> i32 {
    match &mut node.inner {
        NodeInner::List(_) => {
            // Take ownership of the list, flatten, merge, rebuild
            let placeholder = NodeInner::String(StrNode {
                s: Vec::new(),
                flag: 0,
            });
            let old_inner = std::mem::replace(&mut node.inner, placeholder);
            let list_node = Box::new(Node {
                status: 0,
                parent: std::ptr::null_mut(),
                inner: old_inner,
            });
            let mut items = flatten_list(*list_node);

            // First recurse into non-string children
            for item in items.iter_mut() {
                if item.node_type() != NodeType::String {
                    let r = reduce_string_list(item, _enc);
                    if r != 0 {
                        // Rebuild and put back before returning error
                        node.inner = rebuild_list(items).inner;
                        return r;
                    }
                }
            }

            // Merge adjacent string nodes with same flags and status
            let mut merged: Vec<Node> = Vec::new();
            for item in items {
                if item.node_type() == NodeType::String {
                    let can_merge = if let Some(last) = merged.last() {
                        if last.node_type() == NodeType::String {
                            let last_str = last.as_str().unwrap();
                            let curr_str = item.as_str().unwrap();
                            last_str.flag == curr_str.flag && last.status == item.status
                        } else {
                            false
                        }
                    } else {
                        false
                    };

                    if can_merge {
                        let curr_bytes = item.as_str().unwrap().s.clone();
                        let last = merged.last_mut().unwrap();
                        last.as_str_mut().unwrap().s.extend_from_slice(&curr_bytes);
                    } else {
                        merged.push(item);
                    }
                } else {
                    merged.push(item);
                }
            }

            // Rebuild the list
            if merged.len() == 1 {
                // Single node: unwrap from list
                let single = merged.into_iter().next().unwrap();
                *node = single;
            } else {
                node.inner = rebuild_list(merged).inner;
            }

            0
        }

        NodeInner::Alt(_) => {
            // Recurse into each alternative
            let saved_status = node.status; // preserve flags like ND_ST_SUPER
            let placeholder = NodeInner::String(StrNode {
                s: Vec::new(),
                flag: 0,
            });
            let old_inner = std::mem::replace(&mut node.inner, placeholder);
            let alt_node = Box::new(Node {
                status: 0,
                parent: std::ptr::null_mut(),
                inner: old_inner,
            });

            // Flatten the alt chain
            let mut items = Vec::new();
            let mut current: Option<Box<Node>> = Some(alt_node);
            while let Some(n) = current {
                match n.inner {
                    NodeInner::Alt(cons) => {
                        items.push(cons.car);
                        current = cons.cdr;
                    }
                    _ => {
                        items.push(n);
                        current = None;
                    }
                }
            }

            // Recurse into each alternative
            for item in items.iter_mut() {
                let r = reduce_string_list(item, _enc);
                if r != 0 {
                    // Rebuild alt chain and put back
                    let mut result = Node {
                        status: 0,
                        parent: std::ptr::null_mut(),
                        inner: NodeInner::Alt(ConsAltNode {
                            car: items.pop().unwrap(),
                            cdr: None,
                        }),
                    };
                    while let Some(item) = items.pop() {
                        result = Node {
                            status: 0,
                            parent: std::ptr::null_mut(),
                            inner: NodeInner::Alt(ConsAltNode {
                                car: item,
                                cdr: Some(Box::new(result)),
                            }),
                        };
                    }
                    *node = result;
                    return r;
                }
            }

            // Rebuild alt chain, preserving the original root status (e.g. ND_ST_SUPER)
            let mut items_rev: Vec<Box<Node>> = items;
            let last = items_rev.pop().unwrap();
            let mut result = Node {
                status: 0,
                parent: std::ptr::null_mut(),
                inner: NodeInner::Alt(ConsAltNode {
                    car: last,
                    cdr: None,
                }),
            };
            while let Some(item) = items_rev.pop() {
                result = Node {
                    status: 0,
                    parent: std::ptr::null_mut(),
                    inner: NodeInner::Alt(ConsAltNode {
                        car: item,
                        cdr: Some(Box::new(result)),
                    }),
                };
            }
            result.status = saved_status;
            *node = result;
            0
        }

        NodeInner::Quant(ref mut q) => {
            if let Some(ref mut body) = q.body {
                reduce_string_list(body, _enc)
            } else {
                0
            }
        }

        NodeInner::Anchor(ref mut a) => {
            if let Some(ref mut body) = a.body {
                let r = reduce_string_list(body, _enc);
                if r != 0 {
                    return r;
                }
            }
            0
        }

        NodeInner::Bag(ref mut b) => {
            if let Some(ref mut body) = b.body {
                let r = reduce_string_list(body, _enc);
                if r != 0 {
                    return r;
                }
            }
            if let BagData::IfElse {
                ref mut then_node,
                ref mut else_node,
            } = b.bag_data
            {
                if let Some(ref mut then_n) = then_node {
                    let r = reduce_string_list(then_n, _enc);
                    if r != 0 {
                        return r;
                    }
                }
                if let Some(ref mut else_n) = else_node {
                    let r = reduce_string_list(else_n, _enc);
                    if r != 0 {
                        return r;
                    }
                }
            }
            0
        }

        _ => 0,
    }
}

/// Simple compilation from a pre-parsed AST tree.
/// Used internally and by tests that parse separately.
#[cfg_attr(coverage_nightly, coverage(off))]
pub fn compile_from_tree(root: &Node, reg: &mut RegexType, env: &ParseEnv) -> i32 {
    // Clear previous bytecode
    reg.ops.clear();

    // Compile the tree to bytecode
    let r = compile_tree(root, reg, env);
    if r != 0 {
        return r;
    }

    // Add OP_END
    add_op(reg, OpCode::End, OperationPayload::None);
    refresh_capture_tracking_requirement(reg);

    0
}

fn opcode_requires_capture_tracking(opcode: OpCode) -> bool {
    matches!(
        opcode,
        OpCode::BackRef1
            | OpCode::BackRef2
            | OpCode::BackRefN
            | OpCode::BackRefNIc
            | OpCode::BackRefMulti
            | OpCode::BackRefMultiIc
            | OpCode::BackRefWithLevel
            | OpCode::BackRefWithLevelIc
            | OpCode::BackRefCheck
            | OpCode::BackRefCheckWithLevel
            | OpCode::MemStartPush
            | OpCode::MemEndPush
            | OpCode::MemEndPushRec
            | OpCode::MemEndRec
            | OpCode::EmptyCheckEndMemst
            | OpCode::EmptyCheckEndMemstPush
            | OpCode::Call
    )
}

fn refresh_capture_tracking_requirement(reg: &mut RegexType) {
    reg.needs_capture_tracking = reg
        .ops
        .iter()
        .any(|op| opcode_requires_capture_tracking(op.opcode));
}

// ============================================================================
// Optimization subsystem — mirrors C's regcomp.c lines 5881-7064
// ============================================================================

const MAX_ND_OPT_INFO_REF_COUNT: i32 = 5;

fn map_position_value(enc: OnigEncoding, i: usize) -> i32 {
    static VALS: [i16; 128] = [
        5, 1, 1, 1, 1, 1, 1, 1, 1, 10, 10, 1, 1, 10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 12, 4, 7, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5,
        5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
        6, 6, 5, 6, 5, 5, 5, 5, 6, 6, 6, 6, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
        6, 6, 6, 6, 5, 5, 5, 5, 1,
    ];
    if i < VALS.len() {
        if i == 0 && enc.min_enc_len() > 1 {
            20
        } else {
            VALS[i] as i32
        }
    } else {
        4
    }
}

fn distance_value(mm: &MinMaxLen) -> i32 {
    static DIST_VALS: [i16; 100] = [
        1000, 500, 333, 250, 200, 167, 143, 125, 111, 100, 91, 83, 77, 71, 67, 63, 59, 56, 53, 50,
        48, 45, 43, 42, 40, 38, 37, 36, 34, 33, 32, 31, 30, 29, 29, 28, 27, 26, 26, 25, 24, 24, 23,
        23, 22, 22, 21, 21, 20, 20, 20, 19, 19, 19, 18, 18, 18, 17, 17, 17, 16, 16, 16, 16, 15, 15,
        15, 15, 14, 14, 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, 12, 12, 12, 12, 12, 12, 11, 11, 11,
        11, 11, 11, 11, 11, 11, 10, 10, 10, 10, 10,
    ];
    if mm.max == INFINITE_LEN {
        return 0;
    }
    let d = (mm.max - mm.min) as usize;
    if d < DIST_VALS.len() {
        DIST_VALS[d] as i32
    } else {
        1
    }
}

fn comp_distance_value(d1: &MinMaxLen, d2: &MinMaxLen, v1: i32, v2: i32) -> i32 {
    if v2 <= 0 {
        return -1;
    }
    if v1 <= 0 {
        return 1;
    }
    let v1 = v1 * distance_value(d1);
    let v2 = v2 * distance_value(d2);
    if v2 > v1 {
        return 1;
    }
    if v2 < v1 {
        return -1;
    }
    if d2.min < d1.min {
        return 1;
    }
    if d2.min > d1.min {
        return -1;
    }
    0
}

fn concat_opt_anc_info(
    to: &mut OptAnc,
    left: &OptAnc,
    right: &OptAnc,
    left_len: OnigLen,
    right_len: OnigLen,
) {
    to.clear();
    to.left = left.left;
    if left_len == 0 {
        to.left |= right.left;
    }
    to.right = right.right;
    if right_len == 0 {
        to.right |= left.right;
    } else {
        to.right |= left.right & ANCR_PREC_READ_NOT;
    }
}

fn is_left_anchor(a: i32) -> bool {
    !(a == ANCR_END_BUF
        || a == ANCR_SEMI_END_BUF
        || a == ANCR_END_LINE
        || a == ANCR_PREC_READ
        || a == ANCR_PREC_READ_NOT)
}

fn is_set_opt_anc_info(to: &OptAnc, anc: i32) -> bool {
    (to.left & anc) != 0 || (to.right & anc) != 0
}

fn add_opt_anc_info(to: &mut OptAnc, anc: i32) {
    if is_left_anchor(anc) {
        to.left |= anc;
    } else {
        to.right |= anc;
    }
}

fn remove_opt_anc_info(to: &mut OptAnc, anc: i32) {
    if is_left_anchor(anc) {
        to.left &= !anc;
    } else {
        to.right &= !anc;
    }
}

fn alt_merge_opt_anc_info(to: &mut OptAnc, add: &OptAnc) {
    to.left &= add.left;
    to.right &= add.right;
}

fn concat_opt_exact(to: &mut OptStr, add: &OptStr, enc: OnigEncoding) -> i32 {
    let mut r = 0;
    let mut i = to.len;
    let mut p = 0usize; // index into add.s
    let end = add.len;
    while p < end {
        let len = enclen(enc, &add.s[p..], p);
        if i + len > OPT_EXACT_MAXLEN {
            r = 1;
            break;
        }
        for j in 0..len {
            if p >= end {
                break;
            }
            to.s[i] = add.s[p];
            i += 1;
            p += 1;
            let _ = j;
        }
    }
    to.len = i;
    to.reach_end = if p == end { add.reach_end } else { 0 };
    let mut tanc = OptAnc::new();
    concat_opt_anc_info(&mut tanc, &to.anc, &add.anc, 1, 1);
    if to.reach_end == 0 {
        tanc.right = 0;
    }
    to.anc = tanc;
    r
}

fn concat_opt_exact_str(to: &mut OptStr, s: &[u8], enc: OnigEncoding) {
    let mut i = to.len;
    let mut p = 0usize;
    while p < s.len() && i < OPT_EXACT_MAXLEN {
        let len = enclen(enc, &s[p..], p);
        if i + len > OPT_EXACT_MAXLEN {
            break;
        }
        for _ in 0..len {
            if p >= s.len() {
                break;
            }
            to.s[i] = s[p];
            i += 1;
            p += 1;
        }
    }
    to.len = i;
    if p >= s.len() {
        to.reach_end = 1;
    }
}

fn alt_merge_opt_exact(to: &mut OptStr, add: &OptStr, env_enc: OnigEncoding) {
    if add.len == 0 || to.len == 0 {
        to.clear();
        return;
    }
    if !to.mm.is_equal(&add.mm) {
        to.clear();
        return;
    }
    let mut i = 0;
    while i < to.len && i < add.len {
        if to.s[i] != add.s[i] {
            break;
        }
        let len = enclen(env_enc, &to.s[i..], i);
        let mut ok = true;
        for j in 1..len {
            if i + j >= to.len || i + j >= add.len || to.s[i + j] != add.s[i + j] {
                ok = false;
                break;
            }
        }
        if !ok {
            break;
        }
        i += len;
    }
    if add.reach_end == 0 || i < add.len || i < to.len {
        to.reach_end = 0;
    }
    to.len = i;
    alt_merge_opt_anc_info(&mut to.anc, &add.anc);
    if to.reach_end == 0 {
        to.anc.right = 0;
    }
}

fn select_opt_exact(enc: OnigEncoding, now: &mut OptStr, alt: &OptStr) {
    let mut vn = now.len as i32;
    let mut va = alt.len as i32;

    if va == 0 {
        return;
    }
    if vn == 0 {
        *now = *alt;
        return;
    }
    if vn <= 2 && va <= 2 {
        va = map_position_value(enc, now.s[0] as usize);
        vn = map_position_value(enc, alt.s[0] as usize);
        if now.len > 1 {
            vn += 5;
        }
        if alt.len > 1 {
            va += 5;
        }
    }
    vn *= 2;
    va *= 2;
    if comp_distance_value(&now.mm, &alt.mm, vn, va) > 0 {
        *now = *alt;
    }
}

fn add_char_opt_map(m: &mut OptMap, c: u8, enc: OnigEncoding) {
    if m.map[c as usize] == 0 {
        m.map[c as usize] = 1;
        m.value += map_position_value(enc, c as usize);
    }
}

fn select_opt_map(now: &mut OptMap, alt: &OptMap) {
    let z: i32 = 1 << 15;
    if alt.value == 0 {
        return;
    }
    if now.value == 0 {
        *now = *alt;
        return;
    }
    let vn = z / now.value;
    let va = z / alt.value;
    if comp_distance_value(&now.mm, &alt.mm, vn, va) > 0 {
        *now = *alt;
    }
}

fn comp_opt_exact_or_map(e: &OptStr, m: &OptMap) -> i32 {
    const COMP_EM_BASE: i32 = 20;
    if m.value <= 0 {
        return -1;
    }
    let case_value = 3;
    let ae = COMP_EM_BASE * e.len as i32 * case_value;
    let am = COMP_EM_BASE * 5 * 2 / m.value;
    comp_distance_value(&e.mm, &m.mm, ae, am)
}

fn alt_merge_opt_map(enc: OnigEncoding, to: &mut OptMap, add: &OptMap) {
    if to.value == 0 {
        return;
    }
    if add.value == 0 || to.mm.max < add.mm.min {
        to.clear();
        return;
    }
    to.mm.alt_merge(&add.mm);
    let mut val = 0;
    for i in 0..CHAR_MAP_SIZE {
        if add.map[i] != 0 {
            to.map[i] = 1;
        }
        if to.map[i] != 0 {
            val += map_position_value(enc, i);
        }
    }
    to.value = val;
    alt_merge_opt_anc_info(&mut to.anc, &add.anc);
}

fn set_bound_node_opt_info(opt: &mut OptNode, plen: &MinMaxLen) {
    opt.sb.mm = *plen;
    opt.spr.mm = *plen;
    opt.map.mm = *plen;
}

fn concat_left_node_opt_info(enc: OnigEncoding, to: &mut OptNode, add: &mut OptNode) {
    let mut tanc = OptAnc::new();
    concat_opt_anc_info(&mut tanc, &to.anc, &add.anc, to.len.max, add.len.max);
    to.anc = tanc;

    if add.sb.len > 0 && to.len.max == 0 {
        let mut tanc2 = OptAnc::new();
        concat_opt_anc_info(&mut tanc2, &to.anc, &add.sb.anc, to.len.max, add.len.max);
        add.sb.anc = tanc2;
    }

    if add.map.value > 0 && to.len.max == 0 && add.map.mm.max == 0 {
        add.map.anc.left |= to.anc.left;
    }

    let sb_reach = to.sb.reach_end;
    let sm_reach = to.sm.reach_end;

    if add.len.max != 0 {
        to.sb.reach_end = 0;
        to.sm.reach_end = 0;
    }

    if add.sb.len > 0 {
        if sb_reach != 0 {
            concat_opt_exact(&mut to.sb, &add.sb, enc);
            add.sb.clear();
        } else if sm_reach != 0 {
            concat_opt_exact(&mut to.sm, &add.sb, enc);
            add.sb.clear();
        }
    }
    select_opt_exact(enc, &mut to.sm, &add.sb);
    select_opt_exact(enc, &mut to.sm, &add.sm);

    if to.spr.len > 0 {
        if add.len.max > 0 {
            if to.spr.mm.max == 0 {
                select_opt_exact(enc, &mut to.sb, &to.spr.clone());
            } else {
                select_opt_exact(enc, &mut to.sm, &to.spr.clone());
            }
        }
    } else if add.spr.len > 0 {
        to.spr = add.spr;
    }

    select_opt_map(&mut to.map, &add.map);
    to.len.add(&add.len);
}

fn alt_merge_node_opt_info(to: &mut OptNode, add: &OptNode, env_enc: OnigEncoding) {
    alt_merge_opt_anc_info(&mut to.anc, &add.anc);
    alt_merge_opt_exact(&mut to.sb, &add.sb, env_enc);
    alt_merge_opt_exact(&mut to.sm, &add.sm, env_enc);
    alt_merge_opt_exact(&mut to.spr, &add.spr, env_enc);
    alt_merge_opt_map(env_enc, &mut to.map, &add.map);
    to.len.alt_merge(&add.len);
}

fn node_max_byte_len(node: &Node, env: &ParseEnv) -> OnigLen {
    match &node.inner {
        NodeInner::List(_) => {
            let mut len: OnigLen = 0;
            let mut cur = node;
            while let NodeInner::List(cons) = &cur.inner {
                let tmax = node_max_byte_len(&cons.car, env);
                len = distance_add(len, tmax);
                match &cons.cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
            len
        }
        NodeInner::Alt(_) => {
            let mut len: OnigLen = 0;
            let mut cur = node;
            while let NodeInner::Alt(cons) = &cur.inner {
                let tmax = node_max_byte_len(&cons.car, env);
                if len < tmax {
                    len = tmax;
                }
                match &cons.cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
            len
        }
        NodeInner::String(sn) => sn.s.len() as OnigLen,
        NodeInner::CType(_) | NodeInner::CClass(_) => env.enc.max_enc_len() as OnigLen,
        NodeInner::BackRef(_) => {
            if node.has_status(ND_ST_CHECKER) {
                0
            } else {
                // Following a backreference would leave the ownership tree through
                // a raw capture pointer. An unbounded maximum is conservative and
                // only disables optimizations that require a finite upper bound.
                INFINITE_LEN
            }
        }
        // Calls are self-referential AST edges. Staying inside the ownership tree
        // avoids aliasing their raw targets; an infinite maximum is conservative.
        NodeInner::Call(_) => INFINITE_LEN,
        NodeInner::Quant(qn) => {
            if qn.upper == 0 {
                0
            } else if let Some(ref body) = qn.body {
                let len = node_max_byte_len(body, env);
                if len != 0 {
                    if !is_infinite_repeat(qn.upper) {
                        distance_multiply(len, qn.upper)
                    } else {
                        INFINITE_LEN
                    }
                } else {
                    0
                }
            } else {
                0
            }
        }
        NodeInner::Bag(bn) => match bn.bag_type {
            BagType::Memory => {
                // Calls and backreferences above are conservative leaves, so this
                // traversal cannot cycle and needs no mutation-based cache.
                if let Some(ref body) = bn.body {
                    node_max_byte_len(body, env)
                } else {
                    0
                }
            }
            BagType::Option | BagType::StopBacktrack => {
                if let Some(ref body) = bn.body {
                    node_max_byte_len(body, env)
                } else {
                    0
                }
            }
            BagType::IfElse => {
                if let BagData::IfElse {
                    ref then_node,
                    ref else_node,
                } = bn.bag_data
                {
                    let mut len = if let Some(ref body) = bn.body {
                        node_max_byte_len(body, env)
                    } else {
                        0
                    };
                    if let Some(ref then_n) = then_node {
                        let tlen = node_max_byte_len(then_n, env);
                        len = distance_add(len, tlen);
                    }
                    let elen = if let Some(ref else_n) = else_node {
                        node_max_byte_len(else_n, env)
                    } else {
                        0
                    };
                    if elen > len {
                        elen
                    } else {
                        len
                    }
                } else {
                    0
                }
            }
        },
        NodeInner::Anchor(_) | NodeInner::Gimmick(_) => 0,
    }
}

fn optimize_nodes(
    node: &Node,
    opt: &mut OptNode,
    env_enc: OnigEncoding,
    env_mm: &mut MinMaxLen,
    scan_env: &ParseEnv,
) -> i32 {
    let enc = env_enc;
    opt.clear();
    set_bound_node_opt_info(opt, env_mm);

    // Literal alternation trie: we don't know the exact match length
    // (it's variable), so just set min=1, max=large and skip detailed opts.
    if node.has_status(ND_ST_LITERAL_ALT) {
        opt.len.set(1, INFINITE_LEN);
        return 0;
    }

    match &node.inner {
        NodeInner::List(_) => {
            let mut nenv_mm = *env_mm;
            let mut cur = node;
            while let NodeInner::List(cons) = &cur.inner {
                let mut xo = OptNode::new();
                let r = optimize_nodes(&cons.car, &mut xo, enc, &mut nenv_mm, scan_env);
                if r != 0 {
                    return r;
                }
                nenv_mm.add(&xo.len);
                concat_left_node_opt_info(enc, opt, &mut xo);
                match &cons.cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
        }
        NodeInner::Alt(_) => {
            let mut first = true;
            let mut cur = node;
            while let NodeInner::Alt(cons) = &cur.inner {
                let mut xo = OptNode::new();
                let r = optimize_nodes(&cons.car, &mut xo, enc, env_mm, scan_env);
                if r != 0 {
                    return r;
                }
                if first {
                    *opt = xo;
                    first = false;
                } else {
                    alt_merge_node_opt_info(opt, &xo, enc);
                }
                match &cons.cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
        }
        NodeInner::String(sn) => {
            let slen = sn.s.len();
            concat_opt_exact_str(&mut opt.sb, &sn.s, enc);
            if slen > 0 {
                add_char_opt_map(&mut opt.map, sn.s[0], enc);
            }
            opt.len.set(slen as OnigLen, slen as OnigLen);
        }
        NodeInner::CClass(cc) => {
            if cc.mbuf.is_some() || cc.is_not() {
                let min = enc.min_enc_len() as OnigLen;
                let max = enc.max_enc_len() as OnigLen;
                // Even with multi-byte ranges or negation, compute the ASCII
                // part of the map from the bitset. For non-ASCII lead bytes
                // (0x80-0xFF), mark them all as possible since any multi-byte
                // sequence could start there.
                for i in 0..SINGLE_BYTE_SIZE {
                    let z = bitset_at(&cc.bs, i);
                    if (z && !cc.is_not()) || (!z && cc.is_not()) {
                        add_char_opt_map(&mut opt.map, i as u8, enc);
                    }
                }
                // This branch is entered when cc.mbuf.is_some() || cc.is_not().
                // In both cases, multi-byte characters may match, so mark all
                // lead bytes >= 0x80 as possible.
                for i in 0x80..SINGLE_BYTE_SIZE {
                    add_char_opt_map(&mut opt.map, i as u8, enc);
                }
                opt.len.set(min, max);
            } else {
                for i in 0..SINGLE_BYTE_SIZE {
                    let z = bitset_at(&cc.bs, i);
                    if (z && !cc.is_not()) || (!z && cc.is_not()) {
                        add_char_opt_map(&mut opt.map, i as u8, enc);
                    }
                }
                opt.len.set(1, 1);
            }
        }
        NodeInner::CType(ct) => {
            let max = enc.max_enc_len() as OnigLen;
            let min = if max == 1 {
                1
            } else {
                enc.min_enc_len() as OnigLen
            };
            // Compute first-byte map for word, space, and digit types.
            // For multi-byte encodings (UTF-8), limit positive matches to ASCII
            // range (0-127) since those are the only single-byte characters.
            match ct.ctype {
                CTYPE_ANYCHAR => { /* nothing to add to map */ }
                _ if ct.ctype == crate::oniguruma::ONIGENC_CTYPE_WORD as i32
                    || ct.ctype == crate::oniguruma::ONIGENC_CTYPE_SPACE as i32
                    || ct.ctype == crate::oniguruma::ONIGENC_CTYPE_DIGIT as i32 =>
                {
                    let ctype_u32 = ct.ctype as u32;
                    let range = if ct.ascii_mode || max > 1 {
                        128
                    } else {
                        SINGLE_BYTE_SIZE
                    };
                    if ct.not {
                        for i in 0..range {
                            if !enc.is_code_ctype(i as u32, ctype_u32) {
                                add_char_opt_map(&mut opt.map, i as u8, enc);
                            }
                        }
                        for i in range..SINGLE_BYTE_SIZE {
                            add_char_opt_map(&mut opt.map, i as u8, enc);
                        }
                    } else {
                        for i in 0..range {
                            if enc.is_code_ctype(i as u32, ctype_u32) {
                                add_char_opt_map(&mut opt.map, i as u8, enc);
                            }
                        }
                        if max > 1 && !ct.ascii_mode {
                            // Non-ASCII-mode: Unicode spaces/words/digits may
                            // start with lead bytes >= 0x80
                            for i in 0x80..SINGLE_BYTE_SIZE {
                                add_char_opt_map(&mut opt.map, i as u8, enc);
                            }
                        }
                    }
                }
                _ => {}
            }
            opt.len.set(min, max);
        }
        NodeInner::Anchor(an) => {
            match an.anchor_type {
                ANCR_BEGIN_BUF | ANCR_BEGIN_POSITION | ANCR_BEGIN_LINE | ANCR_END_BUF
                | ANCR_SEMI_END_BUF | ANCR_END_LINE | ANCR_PREC_READ_NOT | ANCR_LOOK_BEHIND => {
                    add_opt_anc_info(&mut opt.anc, an.anchor_type);
                }
                ANCR_PREC_READ => {
                    if let Some(ref body) = an.body {
                        let mut xo = OptNode::new();
                        let r = optimize_nodes(body, &mut xo, enc, env_mm, scan_env);
                        if r == 0 {
                            if xo.sb.len > 0 {
                                opt.spr = xo.sb;
                            } else if xo.sm.len > 0 {
                                opt.spr = xo.sm;
                            }
                            opt.spr.reach_end = 0;
                            if xo.map.value > 0 {
                                opt.map = xo.map;
                            }
                        }
                    }
                }
                _ => { /* ANCR_LOOK_BEHIND_NOT etc. */ }
            }
        }
        NodeInner::BackRef(_br) => {
            if !node.has_status(ND_ST_CHECKER) {
                let min = node_min_byte_len(node, scan_env);
                let max = node_max_byte_len(node, scan_env);
                opt.len.set(min, max);
            }
        }
        // Calls are self-referential AST edges. Use conservative optimization
        // bounds instead of following their raw target pointers.
        NodeInner::Call(_) => opt.len.set(0, INFINITE_LEN),
        NodeInner::Quant(qn) => {
            if qn.upper == 0 {
                opt.len.set(0, 0);
            } else if let Some(ref body) = qn.body {
                let mut xo = OptNode::new();
                let r = optimize_nodes(body, &mut xo, enc, env_mm, scan_env);
                if r != 0 {
                    return r;
                }

                if qn.lower > 0 {
                    *opt = xo.clone();
                    if xo.sb.len > 0 && xo.sb.reach_end != 0 {
                        let mut i = 2;
                        while i <= qn.lower && !opt.sb.is_full() {
                            let rc = concat_opt_exact(&mut opt.sb, &xo.sb, enc);
                            if rc > 0 {
                                break;
                            }
                            i += 1;
                        }
                        if i < qn.lower {
                            opt.sb.reach_end = 0;
                        }
                    }
                    if qn.lower != qn.upper {
                        opt.sb.reach_end = 0;
                        opt.sm.reach_end = 0;
                    }
                    if qn.lower > 1 {
                        opt.sm.reach_end = 0;
                    }
                }

                let max = if is_infinite_repeat(qn.upper) {
                    if env_mm.max == 0 && body.is_anychar() && qn.greedy {
                        if body.has_status(ND_ST_MULTILINE) {
                            add_opt_anc_info(&mut opt.anc, ANCR_ANYCHAR_INF_ML);
                        } else {
                            add_opt_anc_info(&mut opt.anc, ANCR_ANYCHAR_INF);
                        }
                    }
                    if xo.len.max > 0 {
                        INFINITE_LEN
                    } else {
                        0
                    }
                } else {
                    distance_multiply(xo.len.max, qn.upper)
                };
                let min = distance_multiply(xo.len.min, qn.lower);
                opt.len.set(min, max);
            }
        }
        NodeInner::Bag(bn) => match bn.bag_type {
            BagType::StopBacktrack | BagType::Option => {
                if let Some(ref body) = bn.body {
                    let r = optimize_nodes(body, opt, enc, env_mm, scan_env);
                    if r != 0 {
                        return r;
                    }
                }
            }
            BagType::Memory => {
                if let Some(ref body) = bn.body {
                    let r = optimize_nodes(body, opt, enc, env_mm, scan_env);
                    if r != 0 {
                        return r;
                    }
                    if is_set_opt_anc_info(&opt.anc, ANCR_ANYCHAR_INF_MASK)
                        && mem_status_at(scan_env.backrefed_mem, bn.regnum() as usize)
                    {
                        remove_opt_anc_info(&mut opt.anc, ANCR_ANYCHAR_INF_MASK);
                    }
                }
            }
            BagType::IfElse => {
                if let BagData::IfElse {
                    ref then_node,
                    ref else_node,
                } = bn.bag_data
                {
                    if else_node.is_some() {
                        let mut nenv_mm = *env_mm;
                        if let Some(ref body) = bn.body {
                            let mut xo = OptNode::new();
                            let r = optimize_nodes(body, &mut xo, enc, &mut nenv_mm, scan_env);
                            if r != 0 {
                                return r;
                            }
                            nenv_mm.add(&xo.len);
                            concat_left_node_opt_info(enc, opt, &mut xo);
                        }
                        if let Some(ref then_n) = then_node {
                            let mut xo = OptNode::new();
                            let r = optimize_nodes(then_n, &mut xo, enc, &mut nenv_mm, scan_env);
                            if r != 0 {
                                return r;
                            }
                            concat_left_node_opt_info(enc, opt, &mut xo);
                        }
                        if let Some(ref else_n) = else_node {
                            let mut xo = OptNode::new();
                            let r = optimize_nodes(else_n, &mut xo, enc, env_mm, scan_env);
                            if r != 0 {
                                return r;
                            }
                            alt_merge_node_opt_info(opt, &xo, enc);
                        }
                    }
                }
            }
        },
        NodeInner::Gimmick(_) => {}
    }
    0
}

/// Build Sunday quick search / BMH skip table for exact string matching.
/// Mirrors C's set_sunday_quick_search_or_bmh_skip_table.
fn set_sunday_quick_search_or_bmh_skip_table(
    enc: OnigEncoding,
    s: &[u8],
    skip: &mut [u8; CHAR_MAP_SIZE],
    roffset: &mut i32,
) -> i32 {
    let mut offset = crate::regenc::enc_get_skip_offset(enc) as i32;
    if offset == 7 {
        // ENC_SKIP_OFFSET_1_OR_0
        let mut p = 0;
        loop {
            let len = enclen(enc, &s[p..], p);
            if p + len >= s.len() {
                offset = if len == 1 { 1 } else { 0 };
                break;
            }
            p += len;
        }
    }

    let slen = s.len() as i32;
    if slen + offset >= 255 {
        return ONIGERR_PARSER_BUG;
    }

    *roffset = offset;

    skip.fill((slen + offset) as u8);

    let mut p = 0;
    while p < s.len() {
        let clen = {
            let l = enclen(enc, &s[p..], p);
            if p + l > s.len() {
                s.len() - p
            } else {
                l
            }
        };
        let remaining = (s.len() - p) as i32;
        for j in 0..clen {
            let z = remaining - j as i32 + (offset - 1);
            if z <= 0 {
                break;
            }
            skip[s[p + j] as usize] = z as u8;
        }
        p += clen;
    }
    0
}

fn set_optimize_exact(reg: &mut RegexType, e: &OptStr) -> i32 {
    if e.len == 0 {
        return 0;
    }
    reg.exact = e.s[..e.len].to_vec();

    let allow_reverse = reg.enc.is_allowed_reverse_match(&reg.exact);

    if e.len >= 2 || (e.len >= 1 && allow_reverse) {
        let exact_copy = reg.exact.clone();
        let r = set_sunday_quick_search_or_bmh_skip_table(
            reg.enc,
            &exact_copy,
            &mut reg.map,
            &mut reg.map_offset,
        );
        if r != 0 {
            return r;
        }
        reg.optimize = if allow_reverse {
            OptimizeType::StrFast
        } else {
            OptimizeType::StrFastStepForward
        };
    } else {
        reg.optimize = OptimizeType::Str;
    }

    reg.dist_min = e.mm.min;
    reg.dist_max = e.mm.max;

    if reg.dist_min != INFINITE_LEN {
        reg.threshold_len = (reg.dist_min as i32) + (reg.exact.len() as i32);
    }
    0
}

fn set_optimize_map(reg: &mut RegexType, m: &OptMap) {
    reg.map = m.map;
    reg.optimize = OptimizeType::Map;
    reg.dist_min = m.mm.min;
    reg.dist_max = m.mm.max;
    if reg.dist_min != INFINITE_LEN {
        reg.threshold_len = (reg.dist_min as i32) + (reg.enc.min_enc_len() as i32);
    }

    // Precompute distinct set bytes for SIMD-accelerated map_search.
    // Only accelerate when all set bytes are ASCII (< 0x80) to avoid
    // false positives from UTF-8 continuation bytes.
    let mut bytes = [0u8; 3];
    let mut count: u8 = 0;
    for i in 0..CHAR_MAP_SIZE {
        if m.map[i] != 0 {
            if count >= 3 || i >= 0x80 {
                count = 0;
                break;
            }
            bytes[count as usize] = i as u8;
            count += 1;
        }
    }
    reg.map_bytes = bytes;
    reg.map_byte_count = count;
}

fn set_sub_anchor(reg: &mut RegexType, anc: &OptAnc) {
    reg.sub_anchor |= anc.left & ANCR_BEGIN_LINE;
    reg.sub_anchor |= anc.right & ANCR_END_LINE;
}

fn set_optimize_info_from_tree(root: &Node, reg: &mut RegexType, scan_env: &ParseEnv) -> i32 {
    let mut env_mm = MinMaxLen::new();
    let mut opt = OptNode::new();
    let r = optimize_nodes(root, &mut opt, reg.enc, &mut env_mm, scan_env);
    if r != 0 {
        return r;
    }

    reg.anchor = opt.anc.left
        & (ANCR_BEGIN_BUF
            | ANCR_BEGIN_POSITION
            | ANCR_ANYCHAR_INF
            | ANCR_ANYCHAR_INF_ML
            | ANCR_LOOK_BEHIND);

    if (opt.anc.left & (ANCR_LOOK_BEHIND | ANCR_PREC_READ_NOT)) != 0 {
        reg.anchor &= !ANCR_ANYCHAR_INF_ML;
    }

    reg.anchor |= opt.anc.right & (ANCR_END_BUF | ANCR_SEMI_END_BUF | ANCR_PREC_READ_NOT);

    if (reg.anchor & (ANCR_END_BUF | ANCR_SEMI_END_BUF)) != 0 {
        reg.anc_dist_min = opt.len.min;
        reg.anc_dist_max = opt.len.max;
    }

    // Save first-byte map for regset dispatch before the main optimization
    // choice potentially overwrites reg.map with BMH skip table data.
    if opt.map.value > 0 && opt.map.mm.min == 0 {
        reg.first_byte_map = opt.map.map;
        reg.has_first_byte_map = true;
    }

    if opt.sb.len > 0 || opt.sm.len > 0 {
        select_opt_exact(reg.enc, &mut opt.sb, &opt.sm);
        if opt.map.value > 0 && comp_opt_exact_or_map(&opt.sb, &opt.map) > 0 {
            set_optimize_map(reg, &opt.map);
            set_sub_anchor(reg, &opt.map.anc);
        } else {
            let r = set_optimize_exact(reg, &opt.sb);
            if r != 0 {
                return r;
            }
            set_sub_anchor(reg, &opt.sb.anc);
        }
    } else if opt.map.value > 0 {
        set_optimize_map(reg, &opt.map);
        set_sub_anchor(reg, &opt.map.anc);
    } else {
        reg.sub_anchor |= opt.anc.left & ANCR_BEGIN_LINE;
        if opt.len.max == 0 {
            reg.sub_anchor |= opt.anc.right & ANCR_END_LINE;
        }
    }

    0
}

/// Full compilation entry point - mirrors C's onig_compile().
/// Parses pattern, compiles to bytecode, sets up mem status and stack_pop_level.
pub fn onig_compile(reg: &mut RegexType, pattern: &[u8]) -> i32 {
    // Clear previous bytecode
    reg.ops.clear();

    // Parse the pattern into AST
    let mut env = ParseEnv {
        options: reg.options,
        case_fold_flag: reg.case_fold_flag,
        enc: reg.enc,
        syntax: reg.syntax.clone(),
        cap_history: 0,
        backtrack_mem: 0,
        backrefed_mem: 0,
        pattern: std::ptr::null(),
        pattern_end: std::ptr::null(),
        error: std::ptr::null(),
        error_end: std::ptr::null(),
        reg: reg as *mut RegexType,
        num_call: 0,
        num_mem: 0,
        num_named: 0,
        mem_alloc: 0,
        mem_env_static: Default::default(),
        mem_env_dynamic: None,
        backref_num: 0,
        keep_num: 0,
        id_num: 0,
        save_alloc_num: 0,
        saves: None,
        unset_addr_list: None,
        parse_depth: 0,
        ast_node_count: 0,
        flags: 0,
    };

    let mut root = match crate::regparse::onig_parse_tree(pattern, reg, &mut env) {
        Ok(node) => node,
        Err(e) => return e,
    };

    // CAPTURE_ONLY_NAMED_GROUP: when named groups exist, disable unnamed captures
    if env.num_named > 0
        && is_syntax_bv(&env.syntax, ONIG_SYN_CAPTURE_ONLY_NAMED_GROUP)
        && !opton_capture_group(reg.options)
    {
        let r = if env.num_named != env.num_mem {
            disable_noname_group_capture(&mut root, reg, &mut env)
        } else {
            numbered_ref_check(&root)
        };
        if r != 0 {
            return r;
        }
    }

    // Optimize: consolidate adjacent string nodes (mirrors C's reduce_string_list)
    let r = reduce_string_list(&mut root, reg.enc);
    if r != 0 {
        return r;
    }
    refresh_node_references(&mut root, &mut env);

    // Resolve subroutine call references before tune_tree
    if env.num_call > 0 {
        let r = resolve_call_references(&mut root, reg, &mut env);
        if r != 0 {
            return r;
        }
        let mut called_groups = Vec::new();
        collect_called_groups(&root, &mut called_groups);
        mark_called_groups(&mut root, &called_groups);
        // Mark zero-repeat contexts and adjust entry counts
        tune_call(&mut root, 0);
        // Conservatively avoid single-entry optimizations for called groups.
        // The historical transitive traversal followed self-referential raw
        // pointers and was not alias-safe under Miri.
        mark_called_groups_as_multi_entry(&mut root);
        // Analyze subroutine-call cycles without re-entering the AST through
        // self-referential raw pointers.
        let recursive_groups = analyze_call_graph(&mut root, &mut env);
        // A zero-length recursive group cannot make progress and would recurse
        // forever. This graph check avoids re-entering the AST through raw
        // self-references while preserving the compiler's rejection behavior.
        let must_recurse_groups = analyze_must_recurse_groups(&root, &recursive_groups, &env);
        if has_never_ending_recursion(&root, &recursive_groups, &must_recurse_groups) {
            return ONIGERR_NEVER_ENDING_RECURSION;
        }
        // Propagate state flags (IN_ALT, IN_REAL_REPEAT, etc.) through called groups
        tune_called_state(&mut root, 0);
    }

    // Detect literal alternations and replace with trie (before tune_tree
    // so case-fold expansion hasn't rewritten the string nodes yet).
    detect_literal_alternations(&mut root, reg, env.backrefed_mem);
    refresh_node_references(&mut root, &mut env);

    // Tune tree: detect empty loops, propagate state (mirrors C's tune_tree)
    let r = tune_tree(&mut root, reg, 0, &mut env);
    if r != 0 {
        return r;
    }
    refresh_node_references(&mut root, &mut env);

    // Compute empty_status_mem for quantifiers (determines EmptyCheckEnd vs EmptyCheckEndMemst)
    setup_empty_status_mem(&mut root, &mut env);

    // Set capture/mem tracking from parse env (mirrors C's onig_compile post-parse setup)
    reg.capture_history = env.cap_history;
    reg.push_mem_start = env.backtrack_mem | env.cap_history;
    reg.num_mem = env.num_mem;

    // Set push_mem_end
    if mem_status_is_all_on(reg.push_mem_start) {
        reg.push_mem_end = env.backrefed_mem | env.cap_history;
    } else {
        reg.push_mem_end = reg.push_mem_start & (env.backrefed_mem | env.cap_history);
    }

    // Initialize mark/save ID counter from parse env to avoid collisions
    // (C uses ID_ENTRY(env, id) which shares env->id_num between parser and compiler)
    reg.num_call = env.id_num;

    // Compile the tree to bytecode
    let r = compile_tree(&root, reg, &env);
    if r != 0 {
        return r;
    }

    // Patch unresolved subroutine call addresses
    if !reg.unset_call_addrs.is_empty() {
        for &(op_idx, gnum) in &reg.unset_call_addrs.clone() {
            let gnum = gnum as usize;
            if gnum < reg.called_addrs.len() && reg.called_addrs[gnum] >= 0 {
                let addr = reg.called_addrs[gnum];
                reg.ops[op_idx].payload = OperationPayload::Call { addr };
            }
        }
    }

    // Emit UPDATE_VAR(KeepFromStackLast) before OP_END if \K was used
    if env.keep_num > 0 {
        add_op(
            reg,
            OpCode::UpdateVar,
            OperationPayload::UpdateVar {
                var_type: UpdateVarType::KeepFromStackLast,
                id: 0,
                clear: false,
            },
        );
    }

    // Add OP_END
    add_op(reg, OpCode::End, OperationPayload::None);

    // If callouts exist, set push_mem_end (C: callout_num != 0 → push_mem_end = push_mem_start)
    if let Some(ref ext) = reg.extp {
        if ext.callout_num != 0 {
            reg.push_mem_end = reg.push_mem_start;
        }
    }

    // Set stack pop level based on what captures/features are used
    let has_callouts = reg.extp.as_ref().is_some_and(|e| e.callout_num != 0);
    if reg.push_mem_end != 0
        || reg.num_repeat != 0
        || reg.num_empty_check != 0
        || reg.num_call > 0
        || has_callouts
    {
        reg.stack_pop_level = StackPopLevel::All;
    } else if reg.push_mem_start != 0 {
        reg.stack_pop_level = StackPopLevel::MemStart;
    } else {
        reg.stack_pop_level = StackPopLevel::Free;
    }

    // Set optimization info (exact string, char map, anchors) from parse tree
    let r = set_optimize_info_from_tree(&root, reg, &env);
    if r != 0 {
        return r;
    }

    // Build Aho-Corasick automaton for literal alternation patterns.
    // This enables a single-pass scan instead of position-by-position matching.
    // Supports both bare `alpha|beta` and captured `(alpha|beta)`.
    if let Some((trie_idx, has_capture)) = detect_ac_eligible(reg) {
        let trie = &reg.literal_tries[trie_idx];
        let ac = aho_corasick::AhoCorasick::builder()
            .match_kind(aho_corasick::MatchKind::LeftmostFirst)
            .ascii_case_insensitive(trie.is_case_insensitive())
            .build(trie.literals());
        if let Ok(ac) = ac {
            reg.ac_alt = Some(ac);
            reg.ac_alt_has_capture = has_capture;
        }
    }

    refresh_capture_tracking_requirement(reg);

    0
}

/// Detect if a compiled regex is eligible for Aho-Corasick fast path.
/// Returns `(trie_idx, has_capture)` if eligible.
///
/// Accepted patterns (no anchors):
/// - `AltLiterals, End` (bare alternation, no capture)
/// - `MemStart, AltLiterals, MemEnd, End` (single capture group)
/// - `MemStartPush, AltLiterals, MemEndPush, End` (single capture group, push variant)
fn detect_ac_eligible(reg: &RegexType) -> Option<(usize, bool)> {
    if reg.anchor != 0 || reg.sub_anchor != 0 {
        return None;
    }

    let ops = &reg.ops;
    let opcodes: Vec<OpCode> = ops.iter().map(|op| op.opcode).collect();

    let (alt_idx, has_capture) = match opcodes.as_slice() {
        [OpCode::AltLiterals, OpCode::End] if reg.num_mem == 0 => (0, false),
        [OpCode::MemStart, OpCode::AltLiterals, OpCode::MemEnd, OpCode::End]
            if reg.num_mem == 1 =>
        {
            (1, true)
        }
        [OpCode::MemStartPush, OpCode::AltLiterals, OpCode::MemEndPush, OpCode::End]
            if reg.num_mem == 1 =>
        {
            (1, true)
        }
        _ => return None,
    };

    if let OperationPayload::AltLiterals { trie_idx } = ops[alt_idx].payload {
        Some((trie_idx as usize, has_capture))
    } else {
        None
    }
}

/// Create and compile a new regex - mirrors C's onig_new().
/// This is the main public API entry point.
pub fn onig_new(
    pattern: &[u8],
    option: OnigOptionType,
    enc: OnigEncoding,
    syntax: &OnigSyntaxType,
) -> Result<RegexType, crate::error::RegexError> {
    // Validate options
    if option.intersects(ONIG_OPTION_DONT_CAPTURE_GROUP)
        && option.intersects(ONIG_OPTION_CAPTURE_GROUP)
    {
        return Err(ONIGERR_INVALID_COMBINATION_OF_OPTIONS.into());
    }

    // Apply syntax default options (mirrors onig_reg_init)
    let mut effective_option = option;
    let syn = syntax;
    if option.intersects(ONIG_OPTION_NEGATE_SINGLELINE) {
        effective_option |= syn.options;
        effective_option &= !ONIG_OPTION_SINGLELINE;
    } else {
        effective_option |= syn.options;
    }

    // Case fold flag setup
    let mut case_fold_flag = ONIGENC_CASE_FOLD_MIN;
    if effective_option.intersects(ONIG_OPTION_IGNORECASE_IS_ASCII) {
        case_fold_flag &=
            !(INTERNAL_ONIGENC_CASE_FOLD_MULTI_CHAR | ONIGENC_CASE_FOLD_TURKISH_AZERI);
        case_fold_flag |= ONIGENC_CASE_FOLD_ASCII_ONLY;
    }

    let mut reg = RegexType {
        ops: Vec::new(),
        string_pool: Vec::new(),
        num_mem: 0,
        num_repeat: 0,
        num_empty_check: 0,
        num_call: 0,
        capture_history: 0,
        push_mem_start: 0,
        push_mem_end: 0,
        stack_pop_level: StackPopLevel::Free,
        repeat_range: Vec::new(),
        enc,
        options: effective_option,
        syntax: syntax.clone(),
        case_fold_flag,
        name_table: None,
        optimize: OptimizeType::None,
        threshold_len: 0,
        anchor: 0,
        anc_dist_min: 0,
        anc_dist_max: 0,
        sub_anchor: 0,
        exact: Vec::new(),
        map: [0u8; CHAR_MAP_SIZE],
        map_offset: 0,
        map_bytes: [0u8; 3],
        map_byte_count: 0,
        dist_min: 0,
        dist_max: 0,
        needs_capture_tracking: false,
        first_byte_map: [0u8; CHAR_MAP_SIZE],
        has_first_byte_map: false,
        called_addrs: vec![],
        unset_call_addrs: vec![],
        extp: None,
        literal_tries: Vec::new(),
        ac_alt: None,
        ac_alt_has_capture: false,
    };

    let r = onig_compile(&mut reg, pattern);
    if r != 0 {
        return Err(r.into());
    }

    Ok(reg)
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::regparse;
    use crate::regsyntax::OnigSyntaxOniguruma;

    fn make_test_context() -> (RegexType, ParseEnv) {
        let reg = RegexType {
            ops: Vec::new(),
            string_pool: Vec::new(),
            num_mem: 0,
            num_repeat: 0,
            num_empty_check: 0,
            num_call: 0,
            capture_history: 0,
            push_mem_start: 0,
            push_mem_end: 0,
            stack_pop_level: StackPopLevel::Free,
            repeat_range: Vec::new(),
            enc: &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            options: ONIG_OPTION_NONE,
            syntax: OnigSyntaxOniguruma.clone(),
            case_fold_flag: ONIGENC_CASE_FOLD_MIN,
            name_table: None,
            optimize: OptimizeType::None,
            threshold_len: 0,
            anchor: 0,
            anc_dist_min: 0,
            anc_dist_max: 0,
            sub_anchor: 0,
            exact: Vec::new(),
            map: [0u8; CHAR_MAP_SIZE],
            map_offset: 0,
            map_bytes: [0u8; 3],
            map_byte_count: 0,
            dist_min: 0,
            dist_max: 0,
            needs_capture_tracking: false,
            first_byte_map: [0u8; CHAR_MAP_SIZE],
            has_first_byte_map: false,
            called_addrs: vec![],
            unset_call_addrs: vec![],
            extp: None,
            literal_tries: Vec::new(),
            ac_alt: None,
            ac_alt_has_capture: false,
        };
        let env = ParseEnv {
            options: OnigOptionType::empty(),
            case_fold_flag: 0,
            enc: &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            syntax: OnigSyntaxOniguruma.clone(),
            cap_history: 0,
            backtrack_mem: 0,
            backrefed_mem: 0,
            pattern: std::ptr::null(),
            pattern_end: std::ptr::null(),
            error: std::ptr::null(),
            error_end: std::ptr::null(),
            reg: std::ptr::null_mut(),
            num_call: 0,
            num_mem: 0,
            num_named: 0,
            mem_alloc: 0,
            mem_env_static: Default::default(),
            mem_env_dynamic: None,
            backref_num: 0,
            keep_num: 0,
            id_num: 0,
            save_alloc_num: 0,
            saves: None,
            unset_addr_list: None,
            parse_depth: 0,
            ast_node_count: 0,
            flags: 0,
        };
        (reg, env)
    }

    fn parse_and_compile(pattern: &[u8]) -> Result<RegexType, i32> {
        let (mut reg, mut env) = make_test_context();
        let root = regparse::onig_parse_tree(pattern, &mut reg, &mut env)?;
        let r = compile_from_tree(&root, &mut reg, &env);
        if r != 0 {
            return Err(r);
        }
        Ok(reg)
    }

    #[test]
    fn compiled_regex_owns_caller_supplied_syntax() {
        let mut reg = {
            let mut syntax = OnigSyntaxOniguruma.clone();
            syntax.op = 0;
            onig_new(
                b"literal",
                ONIG_OPTION_NONE,
                &crate::encodings::utf8::ONIG_ENCODING_UTF8,
                &syntax,
            )
            .unwrap()
        };

        assert_eq!(reg.syntax.op, 0);
        assert_eq!(onig_compile(&mut reg, b"literal"), 0);
    }

    #[test]
    fn compile_literal_string() {
        let reg = parse_and_compile(b"abc").unwrap();
        assert!(!reg.ops.is_empty());
        // Should have string op + END
        let last = reg.ops.last().unwrap();
        assert_eq!(last.opcode, OpCode::End);
    }

    #[test]
    fn compile_alternation() {
        let reg = parse_and_compile(b"a|b").unwrap();
        // Should have PUSH + "a" + JUMP + "b" + END
        assert!(reg.ops.len() >= 4);
        assert_eq!(reg.ops[0].opcode, OpCode::Push);
        assert_eq!(reg.ops.last().unwrap().opcode, OpCode::End);
    }

    #[test]
    fn compile_star_quantifier() {
        let reg = parse_and_compile(b"a*").unwrap();
        // Should have PUSH + Str1 + JUMP + END
        assert!(reg.ops.len() >= 3);
        assert_eq!(reg.ops.last().unwrap().opcode, OpCode::End);
        // Check that a PUSH and JUMP are present
        let has_push = reg.ops.iter().any(|op| op.opcode == OpCode::Push);
        let has_jump = reg.ops.iter().any(|op| op.opcode == OpCode::Jump);
        assert!(has_push, "expected PUSH for a*");
        assert!(has_jump, "expected JUMP for a*");
    }

    #[test]
    fn compile_plus_quantifier() {
        let reg = parse_and_compile(b"a+").unwrap();
        // a+ = body + PUSH + body + JUMP
        assert!(reg.ops.len() >= 3);
        assert_eq!(reg.ops.last().unwrap().opcode, OpCode::End);
    }

    #[test]
    fn compile_capture_group() {
        let reg = parse_and_compile(b"(a)").unwrap();
        let has_mem_start = reg
            .ops
            .iter()
            .any(|op| op.opcode == OpCode::MemStart || op.opcode == OpCode::MemStartPush);
        let has_mem_end = reg
            .ops
            .iter()
            .any(|op| op.opcode == OpCode::MemEnd || op.opcode == OpCode::MemEndPush);
        assert!(has_mem_start, "expected MemStart for (a)");
        assert!(has_mem_end, "expected MemEnd for (a)");
    }

    #[test]
    fn compile_char_class() {
        let reg = parse_and_compile(b"[abc]").unwrap();
        let has_cclass = reg.ops.iter().any(|op| op.opcode == OpCode::CClass);
        assert!(has_cclass, "expected CClass for [abc]");
    }

    #[test]
    fn compile_anchor_begin() {
        let reg = parse_and_compile(b"^a").unwrap();
        assert_eq!(reg.ops[0].opcode, OpCode::BeginLine);
    }

    #[test]
    fn compile_word_type() {
        let reg = parse_and_compile(b"\\w").unwrap();
        let has_word = reg
            .ops
            .iter()
            .any(|op| op.opcode == OpCode::Word || op.opcode == OpCode::WordAscii);
        assert!(has_word, "expected Word for \\w");
    }

    #[test]
    fn compile_interval_quantifier() {
        // a{2,5} is compiled via greedy expansion: body*2 + 3*(PUSH+body)
        let reg = parse_and_compile(b"a{2,5}").unwrap();
        let has_push = reg.ops.iter().any(|op| op.opcode == OpCode::Push);
        assert!(has_push, "expected Push for a{{2,5}} greedy expansion");
        assert!(
            !reg.ops.iter().any(|op| op.opcode == OpCode::Repeat),
            "small interval should remain expanded"
        );
    }

    #[test]
    fn compile_over_limit_interval_quantifier_uses_repeat_bytecode() {
        // This is intentionally small enough to stay safe on the vulnerable
        // compiler path, while exceeding the upstream 10-op expansion budget.
        let reg = parse_and_compile(b"a{6,7}").unwrap();
        assert!(
            reg.ops.iter().any(|op| op.opcode == OpCode::Repeat),
            "over-limit interval should use bounded repeat bytecode"
        );
        assert_eq!(reg.repeat_range.len(), 1);
        assert_eq!(reg.repeat_range[0].lower, 6);
        assert_eq!(reg.repeat_range[0].upper, 7);

        let re = crate::api::Regex::new("a{6,7}").unwrap();
        assert!(re.is_match("aaaaaa"));
        assert!(re.is_match("aaaaaaa"));
        assert!(!re.is_match("aaaaa"));
    }

    #[test]
    fn compile_over_limit_interval_with_unrelated_call_uses_repeat_bytecode() {
        let mut reg = make_test_context().0;
        assert_eq!(onig_compile(&mut reg, b"(?<digit>\\d)\\g<digit>a{6,7}"), 0);

        assert!(
            reg.ops.iter().any(|op| op.opcode == OpCode::Repeat),
            "an unrelated subexpression call must not bypass the expansion limit"
        );
        assert_eq!(reg.repeat_range.len(), 1);
        assert_eq!(reg.repeat_range[0].lower, 6);
        assert_eq!(reg.repeat_range[0].upper, 7);

        let re = crate::api::Regex::new(r"(?<digit>\d)\g<digit>a{6,7}").unwrap();
        assert!(re.is_match("11aaaaaa"));
        assert!(re.is_match("11aaaaaaa"));
        assert!(!re.is_match("11aaaaa"));
    }

    #[test]
    fn compile_complex_pattern() {
        let reg = parse_and_compile(b"^[a-z]+\\d{2,4}$").unwrap();
        assert_eq!(reg.ops.last().unwrap().opcode, OpCode::End);
        // Just verify it compiles without error
    }

    #[test]
    fn compile_empty_pattern() {
        let reg = parse_and_compile(b"").unwrap();
        assert_eq!(reg.ops.len(), 1); // Just END
        assert_eq!(reg.ops[0].opcode, OpCode::End);
    }

    #[test]
    fn compile_non_capturing_group() {
        let reg = parse_and_compile(b"(?:abc)").unwrap();
        // Non-capturing group should not emit MemStart/MemEnd
        let has_mem_start = reg
            .ops
            .iter()
            .any(|op| op.opcode == OpCode::MemStart || op.opcode == OpCode::MemStartPush);
        assert!(
            !has_mem_start,
            "non-capturing group should not have MemStart"
        );
        assert_eq!(reg.ops.last().unwrap().opcode, OpCode::End);
    }

    #[test]
    fn compile_lookahead() {
        let reg = parse_and_compile(b"(?=abc)").unwrap();
        let has_mark = reg.ops.iter().any(|op| op.opcode == OpCode::Mark);
        let has_cut = reg.ops.iter().any(|op| op.opcode == OpCode::CutToMark);
        assert!(has_mark, "expected Mark for lookahead");
        assert!(has_cut, "expected CutToMark for lookahead");
    }

    #[test]
    fn compile_negative_lookahead() {
        let reg = parse_and_compile(b"(?!abc)").unwrap();
        let has_fail = reg.ops.iter().any(|op| op.opcode == OpCode::Fail);
        assert!(has_fail, "expected Fail for negative lookahead");
    }

    // ---- onig_new API tests ----

    #[test]
    fn onig_new_basic() {
        let reg = onig_new(
            b"abc",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
        )
        .unwrap();
        assert!(!reg.ops.is_empty());
        assert_eq!(reg.ops.last().unwrap().opcode, OpCode::End);
    }

    #[test]
    fn onig_new_with_captures() {
        let reg = onig_new(
            b"(a)(b)",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
        )
        .unwrap();
        assert_eq!(reg.num_mem, 2);
    }

    #[test]
    fn onig_new_stack_pop_level_free() {
        // Simple pattern with no captures => StackPopLevel::Free
        let reg = onig_new(
            b"abc",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
        )
        .unwrap();
        assert_eq!(reg.stack_pop_level, StackPopLevel::Free);
    }

    #[test]
    fn onig_new_invalid_pattern() {
        let result = onig_new(
            b"(",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
        );
        assert!(result.is_err());
    }

    #[test]
    fn reduce_string_list_merges() {
        // Parse "abc" - parser produces 3 single-char string nodes in a list
        // reduce_string_list should merge them into one "abc" node
        let (mut reg, mut env) = make_test_context();
        let mut root = regparse::onig_parse_tree(b"abc", &mut reg, &mut env).unwrap();

        // Before reduction, count the tree structure
        let before_type = root.node_type();

        // Apply reduction
        let r = reduce_string_list(&mut root, env.enc);
        assert_eq!(r, 0);

        // After reduction, "abc" should be a single string node (not a list)
        assert_eq!(root.node_type(), NodeType::String);
        let s = root.as_str().unwrap();
        assert_eq!(s.s, b"abc");
    }

    #[test]
    fn reduce_string_list_preserves_non_strings() {
        // "a.b" has string-dot-string, so strings cannot merge across the dot
        let (mut reg, mut env) = make_test_context();
        let mut root = regparse::onig_parse_tree(b"a.b", &mut reg, &mut env).unwrap();
        let r = reduce_string_list(&mut root, env.enc);
        assert_eq!(r, 0);
        // Should still be a list with 3 elements
        assert_eq!(root.node_type(), NodeType::List);
    }

    #[test]
    fn test_never_ending_recursion_direct() {
        let mut reg = make_test_context().0;
        let r = onig_compile(&mut reg, b"(?<abc>\\g<abc>)");
        assert_eq!(r, ONIGERR_NEVER_ENDING_RECURSION);
    }

    #[test]
    fn test_never_ending_recursion_conditional() {
        let mut reg = make_test_context().0;
        let r = onig_compile(&mut reg, b"(()(?(2)\\g<1>))");
        assert_eq!(r, ONIGERR_NEVER_ENDING_RECURSION);
    }

    #[test]
    fn nullable_terminating_recursive_alternative_is_valid() {
        let mut reg = make_test_context().0;
        let r = onig_compile(&mut reg, b"(?<n>|a\\g<n>)+");
        assert_eq!(r, ONIG_NORMAL);
    }

    #[test]
    fn mutually_recursive_group_with_nullable_exit_is_valid() {
        let mut reg = make_test_context().0;
        let r = onig_compile(&mut reg, b"\\A(?<n>|a\\g<m>)\\z|\\zEND (?<m>\\g<n>)");
        assert_eq!(r, ONIG_NORMAL);
    }

    #[test]
    fn zero_repeat_called_group_keeps_callable_bytecode() {
        let reg = onig_new(
            b"(?P<name>abc){0}(?P>name)",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxPython,
        )
        .unwrap();

        assert!(
            reg.called_addrs.get(1).is_some_and(|addr| *addr > 0),
            "a group referenced outside a zero repeat must still be emitted"
        );
    }

    #[test]
    fn casefold_lookbehind_cclass_no_bloat() {
        // Regression test: (?i) with [-\w] in a lookbehind must not generate
        // hundreds of redundant multi-char case-fold lookbehind blocks.
        // Without the optimization, (?i)(?<![-\w])x generates ~846 ops;
        // with it, it should be ~9 ops (same as without (?i)).
        let reg_ic = onig_new(
            br"(?<![-\w])x",
            ONIG_OPTION_IGNORECASE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
        )
        .unwrap();
        let reg_no_ic = onig_new(
            br"(?<![-\w])x",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
        )
        .unwrap();
        // With optimization, both should produce the same number of ops
        assert_eq!(
            reg_ic.ops.len(),
            reg_no_ic.ops.len(),
            "(?i)(?<![-\\w])x should not bloat: got {} ops vs {} without (?i)",
            reg_ic.ops.len(),
            reg_no_ic.ops.len()
        );
    }

    #[test]
    fn literal_alt_trie_triggers() {
        // 10 pure literal alternations — above threshold of 8
        // Use onig_new (full pipeline) to include detect_literal_alternations
        let reg = onig_new(
            b"alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxOniguruma,
        )
        .unwrap();
        assert_eq!(
            reg.literal_tries.len(),
            1,
            "expected 1 literal trie, got {}",
            reg.literal_tries.len()
        );
        let has_alt_literals = reg.ops.iter().any(|op| op.opcode == OpCode::AltLiterals);
        assert!(has_alt_literals, "expected AltLiterals opcode in bytecode");
        // Should NOT have Push/Jump from normal Alt compilation
        let has_push = reg.ops.iter().any(|op| op.opcode == OpCode::Push);
        assert!(
            !has_push,
            "should not have Push opcode for trie-optimized alt"
        );
    }

    #[test]
    fn literal_alt_trie_rejects_out_of_order_prefixes() {
        // The prefix pair is intentionally non-adjacent in source order. The
        // eligibility check must still leave this alternation on the ordered
        // backtracking path.
        let reg = onig_new(
            b"foobarbaz|a1|a2|a3|a4|a5|a6|a7|a8|foo",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxOniguruma,
        )
        .unwrap();
        assert!(reg.literal_tries.is_empty());
    }

    #[test]
    fn literal_alt_trie_below_threshold() {
        // 3 alternations — below threshold, should NOT trigger
        let reg = onig_new(
            b"a|bb|ccc",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxOniguruma,
        )
        .unwrap();
        assert_eq!(reg.literal_tries.len(), 0);
        let has_alt_literals = reg.ops.iter().any(|op| op.opcode == OpCode::AltLiterals);
        assert!(!has_alt_literals);
    }

    #[test]
    fn literal_alt_trie_match_works() {
        use crate::api::Regex;
        let re = Regex::new("alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa").unwrap();
        // Match "eta" in "the eta value"
        let m = re.find("the eta value").unwrap();
        assert_eq!(m.start(), 4);
        assert_eq!(m.end(), 7);
    }

    #[test]
    fn literal_alt_trie_no_match() {
        use crate::api::Regex;
        let re = Regex::new("alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa").unwrap();
        let result = re.find("no match here");
        assert!(result.is_none());
    }

    #[test]
    fn literal_alt_trie_mixed_non_literal_no_trigger() {
        // Partial trie rewrites would reorder literal and non-literal branches.
        let reg = onig_new(
            b"a|bb|ccc|dd|eee|ff|ggg|hh|\\d+",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxOniguruma,
        )
        .unwrap();
        assert!(reg.literal_tries.is_empty());
        let has_push = reg.ops.iter().any(|op| op.opcode == OpCode::Push);
        assert!(
            has_push,
            "partial trie should still have Push for non-literal branch"
        );
    }

    #[test]
    fn literal_alt_trie_partial_match() {
        // Mixed alternatives retain their original ordered branches.
        use crate::api::Regex;
        let re = Regex::new("alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|[xy]z").unwrap();
        assert!(re.as_raw().literal_tries.is_empty());
        // Match a literal branch
        let m = re.find("the eta value").unwrap();
        assert_eq!(m.as_str(), "eta");
        // Match the non-literal branch
        let m2 = re.find("the xz value").unwrap();
        assert_eq!(m2.as_str(), "xz");
    }

    #[test]
    fn literal_alt_trie_too_few_literals_with_non_literal() {
        // Only 2 literal + 1 non-literal = below threshold
        let reg = onig_new(
            b"a|bb|\\d+",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxOniguruma,
        )
        .unwrap();
        assert_eq!(reg.literal_tries.len(), 0);
    }

    #[test]
    fn literal_alt_trie_inside_group() {
        // CSS-like pattern: alternation inside non-capturing group with lookbehind/lookahead
        let reg = onig_new(
            b"(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa)",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxOniguruma,
        )
        .unwrap();
        assert_eq!(
            reg.literal_tries.len(),
            1,
            "should detect alt inside non-capturing group, got {}",
            reg.literal_tries.len()
        );
    }

    #[test]
    fn literal_alt_trie_case_insensitive() {
        // Case-insensitive alternatives stay on the general case-folding path.
        let reg = onig_new(
            b"(?i)(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa)",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxOniguruma,
        )
        .unwrap();
        assert!(reg.literal_tries.is_empty());
        // Verify case-insensitive matching
        use crate::api::Regex;
        let re =
            Regex::new("(?i)(?:alpha|beta|gamma|delta|epsilon|zeta|eta|theta|iota|kappa)").unwrap();
        let m = re.find("DELTA value").unwrap();
        assert_eq!(m.as_str(), "DELTA");
    }

    #[test]
    fn literal_alt_trie_css_like_pattern() {
        // Mimics CSS property-names: (?i)(?<![-\w])(?:prop1|prop2|...)(?![-\w])
        use crate::api::Regex;
        let re = Regex::new(
            r"(?i)(?<![-\w])(?:color|content|cursor|display|direction|float|font|height|left|margin|padding|position|right|top|width|z-index)(?![-\w])",
        )
        .unwrap();
        assert!(re.as_raw().literal_tries.is_empty());
        let has_alt_literals = re
            .as_raw()
            .ops
            .iter()
            .any(|op| op.opcode == OpCode::AltLiterals);
        assert!(!has_alt_literals);
        let m = re.find("  display: none").unwrap();
        assert_eq!(m.as_str(), "display");
        // Case insensitive
        let m2 = re.find("  DISPLAY: none").unwrap();
        assert_eq!(m2.as_str(), "DISPLAY");
        // Should not match partial words
        assert!(re.find("displaying").is_none());
    }

    // --- Nested alternation trie tests ---

    #[test]
    fn nested_alt_trie_simple() {
        // a(b|c)d → should extract ["abd", "acd"] and trigger trie
        // Need enough branches to exceed threshold, so use multiple nested alts
        use crate::api::Regex;
        let re = Regex::new("a(b|c|d|e|f)g").unwrap();
        assert!(
            !re.as_raw().literal_tries.is_empty(),
            "nested alternation a(b|c|d|e|f)g should trigger trie"
        );
        let m = re.find("xaegx").unwrap();
        assert_eq!(m.as_str(), "aeg");
        let m2 = re.find("xacgx").unwrap();
        assert_eq!(m2.as_str(), "acg");
    }

    #[test]
    fn nested_alt_trie_optional() {
        // Optional paths stay on the general Alt path to retain branch order.
        use crate::api::Regex;
        let re = Regex::new("ab(cd)?ef|abgh|abij|abkl|abmn").unwrap();
        assert!(re.as_raw().literal_tries.is_empty());
        // With optional present
        let m = re.find("xabcdefx").unwrap();
        assert_eq!(m.as_str(), "abcdef");
        // Without optional
        let m2 = re.find("xabefx").unwrap();
        assert_eq!(m2.as_str(), "abef");
        // Plain branch
        let m3 = re.find("xabghx").unwrap();
        assert_eq!(m3.as_str(), "abgh");
    }

    #[test]
    fn nested_alt_trie_partial_with_cclass() {
        // Mixed: nested structure with one CClass branch → partial optimization
        use crate::api::Regex;
        let re = Regex::new(r"a(b|c|d|e|f)g|[xy]z").unwrap();
        assert!(
            !re.as_raw().literal_tries.is_empty(),
            "nested alt with partial non-literal should trigger partial trie"
        );
        // Match literal branch
        let m = re.find("xabgx").unwrap();
        assert_eq!(m.as_str(), "abg");
        // Match non-literal branch
        let m2 = re.find("xxzx").unwrap();
        assert_eq!(m2.as_str(), "xz");
    }

    #[test]
    fn nested_alt_trie_entity_like() {
        // Mimics HTML entity pattern structure: nested trie encoded as regex
        use crate::api::Regex;
        let re = Regex::new(
            "a(s(ymp(eq)?|cr|t)|n(d(slope|and)?|g(le|st|msd)?|e))|b(a(ck(sim(eq)?|prime|cong|epsilon)|r(vee|wed))|o(x(times|plus|minus|dl|dr|ul|ur|v[lrhHV]|h[dDuU])|t)|u(ll(et)?|mp(e(q)?)?)|l(ock|k[34])|e(caus(e)?|rnou|tween|mptyv)|ig(c(ap|up|irc)|o(dot|plus|times)|tri(angle(down|up|left|right)|angle)|s(qcup|tar)|vee|wedge)|n(ot|e(quiv)?)|r(eve|vbar)|s(cr|ol(b|hsub)?|im(e)?)|(?:N|b)rk|f(r|isht)|karow|pf|scr)",
        )
        .unwrap();
        assert!(
            !re.as_raw().literal_tries.is_empty(),
            "entity-like nested pattern should trigger trie"
        );
        // Match some entity names
        let m = re.find("xasymp;").unwrap();
        assert_eq!(m.as_str(), "asymp");
        let m2 = re.find("xasympeq;").unwrap();
        assert_eq!(m2.as_str(), "asympeq");
        let m3 = re.find("xandslope;").unwrap();
        assert_eq!(m3.as_str(), "andslope");
        let m4 = re.find("xboxplus;").unwrap();
        assert_eq!(m4.as_str(), "boxplus");
    }

    #[test]
    fn nested_alt_trie_backreferenced_capture_skipped() {
        // Backreferenced capture group should NOT be optimized
        use crate::api::Regex;
        let re = Regex::new(r"(a|b|c|d|e)\1").unwrap();
        // This should NOT trigger trie because the capture is backreferenced
        // The alt itself has 5 branches but each is simple, so it might trigger
        // for the inner alt. The key test is that it still works correctly.
        let m = re.find("xaax").unwrap();
        assert_eq!(m.as_str(), "aa");
        assert!(re.find("xabx").is_none());
    }

    #[test]
    fn nested_alt_trie_non_capturing_group() {
        // Non-capturing group should be transparent
        use crate::api::Regex;
        let re = Regex::new("(?:a(?:b|c|d|e|f)g)").unwrap();
        assert!(
            !re.as_raw().literal_tries.is_empty(),
            "nested alt in non-capturing groups should trigger trie"
        );
        let m = re.find("xadgx").unwrap();
        assert_eq!(m.as_str(), "adg");
    }

    #[test]
    fn nested_alt_trie_entity_diagnostic() {
        // Compile the full HTML entity pattern to verify nested extraction
        let reg = onig_new(
            b"a(s(ymp(eq)?|cr|t)|n(d(slope|and)?|g(s(t|ph)|zarr|e|le|rt(vb(d)?)?|msd(aa)?)?|e)|c(y|irc|d|ute)?|tilde|o(pf|gon)|uml|p(id|os|prox(eq)?|acir)?|elig|f(r)?|l(pha|e(ph|fsym))|acute|ring|grave|m(p|a(cr|lg))|breve)|b(s(cr|im(e)?|ol(hsub|b)?|emi)|c(y|ong)|ig(s(tar|qcup)|c(irc|up|ap)|triangle(down|up)|o(times|dot|plus)|uplus|vee|wedge)|o(t(tom)?|pf|wtie)|u(ll(et)?|mp(e(q)?)?)|prime|e(caus(e)?|t(h|ween|a)|psi|rnou|mptyv)|karow|fr|l(ock|a(nk|ck(square|triangle(down|left|right)?|lozenge)))|a(ck(sim(eq)?|cong|prime|epsilon)|r(vee|wed(ge)?))|r(eve|vbar)|brk(tbrk)?)|c(s(cr|u(p(e)?|b(e)?))|h(cy|i|eck(mark)?)|ylcty|c(irc|ups(sm)?|edil|a(ps|ron))|tdot|ir(scir|c(eq|le(d(circ|dash|ast)))?|e|fnint|mid)?|o(n(int|g(dot)?)|p(y(sr)?|f|rod)|lon(e(q)?)?|m(p(fn|le(xes|ment))?|ma(t)?))|dot|u(darr(l|r)|p(s|c(up|ap)|or|dot|brcap)?|e(sc|pr)|vee|wed|larr(p)?|r(vearrow(left|right)|ly(eq(succ|prec)|vee|wedge)|arr(m)?|ren))|e(nt(erdot)?|dil|mptyv)|fr|lubs(uit)?|a(cute|p(s|c(up|ap)|dot|and|brcup)?|r(on|et))|r(oss|arr))|d(s(cr|trok|ol)|c(y|aron)|t(dot|ri(f)?)|i(sin|e|v(ide(ontimes)?|onx)?|am(s|ond(suit)?)?|gamma)|o(t(square|plus|eq(dot)?|minus)?|ublebarwedge|pf|wn(harpoon(left|right)|downarrows|arrow)|llar)|d(otseq|a(rr|gger))?|u(har|arr)|jcy|e(lta|g|mptyv)|f(isht|r)|lc(orn|rop)|a(sh(v)?|leth|rr|gger)|r(c(orn|rop)|bkarow)|bkarow|blac)",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxOniguruma,
        )
        .unwrap();
        eprintln!(
            "Entity subset: {} literal tries, {} ops",
            reg.literal_tries.len(),
            reg.ops.len()
        );
        let alt_lit_count = reg
            .ops
            .iter()
            .filter(|op| op.opcode == OpCode::AltLiterals)
            .count();
        let push_count = reg
            .ops
            .iter()
            .filter(|op| op.opcode == OpCode::Push)
            .count();
        assert!(
            !reg.literal_tries.is_empty(),
            "entity pattern should produce at least 1 trie"
        );
        // Nested branches keep their normal ordered backtracking operations.
        assert!(push_count > 0, "expected ordered Alt operations");
    }

    #[test]
    fn dump_named_capture_bytecode() {
        let pat = b"(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})";
        let reg = onig_new(
            pat,
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxOniguruma,
        )
        .unwrap();
        eprintln!("Bytecode ({} ops):", reg.ops.len());
        for (i, op) in reg.ops.iter().enumerate() {
            eprintln!("  [{:3}] {:?}", i, op.opcode);
        }
        eprintln!("push_mem_start: {}", reg.push_mem_start);
        eprintln!("push_mem_end: {}", reg.push_mem_end);
    }

    #[test]
    fn option_only_group_mid_pattern_keeps_ignorecase_semantics() {
        let reg = onig_new(
            b"a(?i)b|c",
            ONIG_OPTION_NONE,
            &crate::encodings::utf8::ONIG_ENCODING_UTF8,
            &crate::regsyntax::OnigSyntaxOniguruma,
        )
        .unwrap();
        assert!(
            reg.ops.iter().any(|op| op.opcode == OpCode::CClass),
            "expected case-folded branch bytecode"
        );
        let input_b = b"aB";
        let input_c = b"aC";
        let (result_b, _) = crate::regexec::onig_match(
            &reg,
            input_b,
            input_b.len(),
            0,
            Some(OnigRegion::new()),
            ONIG_OPTION_NONE,
        );
        let (result_c, _) = crate::regexec::onig_match(
            &reg,
            input_c,
            input_c.len(),
            0,
            Some(OnigRegion::new()),
            ONIG_OPTION_NONE,
        );
        assert_eq!(result_b, 2, "expected aB to match");
        assert_eq!(result_c, 2, "expected aC to match");
    }

    #[test]
    fn repeated_compile_absent_expr_backref_does_not_overflow() {
        for _ in 0..2 {
            let reg = onig_new(
                br"(a)(?~|b|\1)",
                ONIG_OPTION_NONE,
                &crate::encodings::utf8::ONIG_ENCODING_UTF8,
                &crate::regsyntax::OnigSyntaxOniguruma,
            )
            .unwrap();
            std::mem::forget(reg);
        }
    }
}