regexrs 0.1.6

A pure-Rust rich regular expression engine with portable matching and optional native acceleration
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
// Copyright 2026 The Fancy Regex Authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#![doc = include_str!("../docs/main.md")]
#![doc = include_str!("../docs/features.md")]
#![doc = include_str!("../docs/syntax.md")]
#![doc = include_str!("../docs/subroutines/1_intro.md")]
#![doc = include_str!("../docs/subroutines/2_flags.md")]
#![doc = include_str!("../docs/subroutines/3_left_recursion.md")]
#![doc = include_str!("../docs/subroutines/4_recursion.md")]
#![doc = include_str!("../docs/absent.md")]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec;
use alloc::vec::Vec;

use core::convert::TryFrom;
use core::fmt;
use core::fmt::{Debug, Formatter};
use core::ops::{Index, Range};
use core::str::FromStr;
use regex_automata::Anchored as RaAnchored;
use regex_automata::Input as RaInput;
use regex_automata::meta::Regex as RaRegex;
use regex_automata::util::captures::Captures as RaCaptures;
use regex_automata::util::primitives::NonMaxUsize;
use regex_automata::util::syntax::Config as SyntaxConfig;

mod analyze;
mod bytes;
mod compile;
mod error;
mod expand;
mod input;
#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]
mod native;
mod optimize;
mod parse;
mod parse_flags;
mod plan;
mod regexset;
mod regular;
mod regular_route;
mod replacer;
mod searcher;
mod seek;
mod start;
mod to_hir;
mod vm;

use crate::analyze::can_compile_as_anchored;
use crate::analyze::{AnalyzeContext, analyze};
use crate::compile::{CompileOptions, compile};
use crate::optimize::optimize;
use crate::parse::{ExprTree, NamedGroups, Parser};
use crate::parse_flags::*;
use crate::plan::{NFA_UNIT_BUDGET, Plan, PlanInput};
use crate::regular_route::{Automata, RegularRoute, RouteEngine};
use crate::start::StartFilter;
use crate::vm::{OPTION_FIND_NOT_EMPTY, OPTION_NOT_CONTINUED_FROM_PREVIOUS_MATCH, Prog};

pub use crate::bytes::MatchBytes;
pub use crate::error::{CompileError, Error, ParseError, Result, RuntimeError};
pub use crate::expand::Expander;
pub use crate::input::{Input, RegexInput};
pub use crate::regexset::{RegexSet, RegexSetMatch, RegexSetOptions};
pub use crate::regular::{RegularCaptureMatches, RegularMatches, RegularRegex};
pub use crate::replacer::{NoExpand, Replacer, ReplacerRef};
pub use crate::searcher::Searcher;
pub use crate::seek::seek_pattern_is_useful;

/// Controls how the regex engine handles input encoding.
///
/// This enum represents the three valid combinations of the `utf8` and `unicode`
/// flags in the underlying regex engine. Each variant has different trade-offs
/// between input flexibility and character class semantics.
///
/// The default is [`BytesMode::Unicode`].
///
/// # Variants
///
/// ## `BytesMode::Unicode` (default)
///
/// - Input is expected to be valid UTF-8
/// - `.` matches any Unicode scalar value (except `\n` unless `dot_matches_new_line` is set)
/// - `\w`, `\d`, `\s` match Unicode characters
/// - Unicode properties like `\p{Letter}` are available
/// - Word boundaries (`\b`) are Unicode-aware
///
/// ## `BytesMode::Ascii`
///
/// - Input can be arbitrary bytes (no UTF-8 requirement)
/// - `.` matches any single **byte** (except `\n` unless `dot_matches_new_line` is set)
/// - `\w` matches `[a-zA-Z0-9_]` only (ASCII)
/// - `\d` matches `[0-9]` only (ASCII)
/// - `\s` matches ASCII whitespace only
/// - Unicode properties are **not available**
/// - Word boundaries (`\b`, `\B`, `\<`, `\>`, the half boundaries, and
///   `(?-u:\b)` too) are **not** ASCII-only. As in the other modes, a valid
///   UTF-8 encoding of a Unicode word character counts as a word character, and
///   any other byte that is not an ASCII word character does not. So in `café x`
///   there is no boundary between `caf` and `é`, and `\b\w+\b` finds only `x`,
///   although `\w` alone matches `caf`.
///
/// Use this mode when matching raw binary data or filenames that may contain
/// non-UTF-8 bytes and you don't need Unicode character classes.
///
/// ## `BytesMode::UnicodeBytes`
///
/// - Input can be arbitrary bytes (no UTF-8 requirement)
/// - `.` matches Unicode scalar values (sequences of valid UTF-8 bytes)
/// - `\w`, `\d`, `\s` match Unicode characters
/// - Unicode properties like `\p{Letter}` are available
///
/// Use this mode when the input may contain non-UTF-8 bytes but you still want
/// Unicode-aware character classes. Note that `.` will **not** match individual
/// non-UTF-8 bytes — it only matches valid UTF-8 codepoint sequences.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum BytesMode {
    /// Unicode mode: input must be valid UTF-8, full Unicode support.
    /// (utf8=true, unicode=true)
    #[default]
    Unicode,
    /// ASCII bytes mode: `.` matches any byte, character classes are ASCII-only,
    /// word boundaries still use Unicode word characters.
    /// (utf8=false, unicode=false)
    Ascii,
    /// Unicode-aware bytes mode: input can be non-UTF-8, character classes
    /// remain Unicode-aware. `.` matches Unicode scalar values only.
    /// (utf8=false, unicode=true)
    UnicodeBytes,
}

const MAX_RECURSION: usize = 64;

// the public API

/// A builder for a `Regex` to allow configuring options.
#[derive(Debug)]
pub struct RegexBuilder {
    pattern: String,
    options: RegexOptionsBuilder,
}

/// A builder for a `Regex` to allow configuring options.
#[derive(Debug)]
pub struct RegexOptionsBuilder {
    options: RegexOptions,
}

/// A compiled regular expression.
#[derive(Clone)]
pub struct Regex {
    inner: RegexImpl,
    named_groups: Arc<NamedGroups>,
    #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]
    native: Option<Arc<native::LazyNative>>,
}

// Separate enum because we don't want to expose any of this
#[derive(Clone)]
enum RegexImpl {
    // Do we want to box this? It's pretty big...
    Wrap {
        engine: WrapEngine,
        /// The original pattern which the regex was constructed from
        pattern: String,
        /// Some optimizations avoid the VM, but need to use an extra capture group to represent the match boundaries
        explicit_capture_group_0: bool,
        /// The actual pattern passed to regex-automata for delegation
        delegated_pattern: String,
    },
    Fancy {
        prog: Arc<Prog>,
        n_groups: usize,
        /// The original pattern which the regex was constructed from
        pattern: String,
        /// The parse flags the pattern was compiled with, to derive its seek
        /// approximation again when the program does not carry one.
        flags: u32,
        options: HardRegexRuntimeOptions,
        /// For a pattern that needs the VM only for word boundaries, the same
        /// pattern as automata, used where `Regex::regular_route` shows the
        /// results cannot differ from the VM's.
        regular: Option<Arc<RegularRoute>>,
    },
}

/// How a pattern without rich constructs is searched.
#[derive(Clone)]
pub(crate) enum WrapEngine {
    /// regex-automata's meta engine.
    Meta(RaRegex),
    /// A pattern whose matches follow one deterministic path: its plan
    /// gives the meta engine's results, so that engine is not kept.
    Plan(Arc<Plan>),
}

impl WrapEngine {
    /// The plan for `hir` where it has one, else the meta engine
    /// `build` returns. The meta engine is still built, and dropped, wherever
    /// explicit size limits or the size of the pattern could make building it
    /// fail, so compiling reports exactly the errors it did.
    pub(crate) fn new(
        hir: Option<&regex_syntax::hir::Hir>,
        options: &CompileOptions,
        usage: compile::DelegateUsage,
        build: impl FnOnce() -> Result<RaRegex>,
    ) -> Result<WrapEngine> {
        let Some(plan) = hir.and_then(|hir| Plan::new(hir, usage.prefilter())) else {
            return build().map(WrapEngine::Meta);
        };
        let default_limits =
            options.delegate_size_limit.is_none() && options.delegate_dfa_size_limit.is_none();
        if !default_limits || plan.nfa_units() > NFA_UNIT_BUDGET {
            build()?;
        }
        Ok(WrapEngine::Plan(Arc::new(plan)))
    }

    fn captures_len(&self) -> usize {
        match self {
            WrapEngine::Meta(inner) => inner.captures_len(),
            WrapEngine::Plan(plan) => plan.captures_len(),
        }
    }

    fn create_captures(&self) -> RaCaptures {
        match self {
            WrapEngine::Meta(inner) => inner.create_captures(),
            WrapEngine::Plan(plan) => plan.create_captures(),
        }
    }
}

/// A single match of a regex or group in an input text
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Match<'t> {
    text: &'t str,
    start: usize,
    end: usize,
}

/// An iterator over all non-overlapping matches for a particular input.
///
/// The iterator yields a `Result<S::Match>`. The iterator stops when no more
/// matches can be found.
///
/// `'r` is the lifetime of the compiled regular expression and `'t` is the
/// lifetime of the matched input.
#[derive(Debug)]
pub struct Matches<'r, 't, S: input::Input + ?Sized> {
    re: &'r Regex,
    state: IterState<'t, S>,
    /// A [`Searcher`]'s exclusive scratch, when iterating through one.
    cache: Option<&'r mut searcher::Cache>,
}

impl<'r, 't, S: input::Input + ?Sized> Matches<'r, 't, S> {
    fn new(
        re: &'r Regex,
        input: RegexInput<'t, S>,
        cache: Option<&'r mut searcher::Cache>,
    ) -> Self {
        Matches {
            re,
            state: IterState::new(input),
            cache,
        }
    }

    /// Return the underlying regex.
    pub fn regex(&self) -> &'r Regex {
        self.re
    }

    /// Return the text being searched.
    pub fn text(&self) -> &'t S {
        self.state.input.haystack()
    }

    /// Return the current search input configuration.
    pub fn input(&self) -> &RegexInput<'t, S> {
        &self.state.input
    }
}

/// The position and empty-match bookkeeping shared by every match iterator.
#[derive(Debug)]
struct IterState<'t, S: input::Input + ?Sized> {
    input: RegexInput<'t, S>,
    last_match: Option<usize>,
    last_skipped_empty: bool,
}

impl<'t, S: input::Input + ?Sized> IterState<'t, S> {
    fn new(input: RegexInput<'t, S>) -> Self {
        IterState {
            input,
            last_match: None,
            last_skipped_empty: false,
        }
    }

    /// Adapted from the `regex` crate. Calls `search` repeatedly, ignoring empty
    /// matches immediately after a match. Also passes a flag when skipping an
    /// empty match, so that \G wouldn't match at the new start position.
    /// After an error, the iterator is exhausted.
    fn next_with<F, R, E>(&mut self, mut search: F) -> Option<core::result::Result<R, E>>
    where
        F: FnMut(&RegexInput<'t, S>, u32) -> core::result::Result<Option<(R, (usize, usize))>, E>,
    {
        if self.input.is_done() {
            return None;
        }

        let option_flags = if self.last_skipped_empty {
            OPTION_NOT_CONTINUED_FROM_PREVIOUS_MATCH
        } else {
            0
        };

        let pos = self.input.effective_start();
        let (result, (match_start, match_end)) = match search(&self.input, option_flags) {
            Err(error) => {
                // Stop on first error: If an error is encountered, return it, and set the "last match position"
                // to the string length, so that the next next() call will return None, to prevent an infinite loop.
                self.input
                    .set_start(self.input.get_range().end.saturating_add(1));
                return Some(Err(error));
            }
            Ok(None) => return None,
            Ok(Some(pair)) => pair,
        };

        if match_start == match_end {
            // This is an empty match. To ensure we make progress, start
            // the next search at the smallest possible starting position
            // of the next match following this one.
            self.input
                .set_start(self.input.haystack().advance_position(match_end));
            // Only set OPTION_NOT_CONTINUED_FROM_PREVIOUS_MATCH on the next call if this was a
            // truly zero-length match (the VM consumed no bytes from `pos`).
            // This means that \K won't prevent \G from matching.
            self.last_skipped_empty = match_end == pos;
            // Don't accept empty matches immediately following a match.
            // Just move on to the next match.
            if Some(match_end) == self.last_match {
                return self.next_with(search);
            }
        } else {
            self.input.set_start(match_end);
            self.last_skipped_empty = false;
        }

        self.last_match = Some(match_end);

        Some(Ok(result))
    }
}

impl<'r, 't, S: input::Input + ?Sized> Iterator for Matches<'r, 't, S> {
    type Item = Result<S::Match<'t>>;

    fn next(&mut self) -> Option<Self::Item> {
        let Matches { re, state, cache } = self;
        let text = state.input.haystack();
        state.next_with(|input, flags| {
            re.find_input_raw_cached(input, flags, cache.as_deref_mut())
                .map(|opt| opt.map(|(s, e)| (text.make_match(s, e), (s, e))))
        })
    }
}

/// An iterator that yields all non-overlapping capture groups matching a
/// particular regular expression.
///
/// The iterator stops when no more matches can be found.
///
/// `'r` is the lifetime of the compiled regular expression and `'t` is the
/// lifetime of the matched string.
#[derive(Debug)]
pub struct CaptureMatches<'r, 't, S: input::Input + ?Sized>(Matches<'r, 't, S>);

impl<'r, 't, S: input::Input + ?Sized> CaptureMatches<'r, 't, S> {
    /// Return the text being searched.
    pub fn text(&self) -> &'t S {
        self.0.text()
    }

    /// Return the underlying regex.
    pub fn regex(&self) -> &'r Regex {
        self.0.re
    }
}

impl<'r, 't, S: input::Input + ?Sized> Iterator for CaptureMatches<'r, 't, S> {
    type Item = Result<Captures<'t, S>>;

    fn next(&mut self) -> Option<Self::Item> {
        let Matches { re, state, cache } = &mut self.0;
        state.next_with(|input, flags| {
            let captures = re.captures_input_cached(input, flags, cache.as_deref_mut())?;
            Ok(captures.map(|c| {
                let (start, end) = c
                    .inner
                    .get_span(0)
                    .expect("`Captures` is expected to have entire match at 0th position");
                (c, (start, end))
            }))
        })
    }
}

/// A set of capture groups found for a regex.
///
/// `S` is the input type, `str` by default, so a replacement closure can be
/// written `|caps: &Captures| ...`. Byte haystacks produce `Captures<'_, [u8]>`.
#[derive(Debug)]
pub struct Captures<'t, S: input::Input + ?Sized = str> {
    inner: CapturesImpl,
    named_groups: Arc<NamedGroups>,
    input: &'t S,
}

#[derive(Clone, Debug)]
enum CapturesImpl {
    Wrap {
        locations: RaCaptures,
        /// Some optimizations avoid the VM but need an extra capture group to represent the match boundaries.
        /// Therefore what is actually capture group 1 should be treated as capture group 0, and all other
        /// capture groups should have their index reduced by one as well to line up with what the pattern specifies.
        explicit_capture_group_0: bool,
    },
    Fancy {
        saves: Vec<usize>,
    },
}

impl CapturesImpl {
    fn get_span(&self, i: usize) -> Option<(usize, usize)> {
        match self {
            CapturesImpl::Wrap {
                locations,
                explicit_capture_group_0,
            } => locations
                .get_group(i + if *explicit_capture_group_0 { 1 } else { 0 })
                .map(|span| (span.start, span.end)),
            CapturesImpl::Fancy { saves } => {
                let slot = i * 2;
                if slot >= saves.len() {
                    return None;
                }
                let lo = saves[slot];
                if lo == usize::MAX {
                    return None;
                }
                let hi = saves[slot + 1];
                Some((lo, hi))
            }
        }
    }

    fn len(&self) -> usize {
        match self {
            CapturesImpl::Wrap {
                locations,
                explicit_capture_group_0,
            } => locations.group_len() - if *explicit_capture_group_0 { 1 } else { 0 },
            CapturesImpl::Fancy { saves } => saves.len() / 2,
        }
    }
}

/// Iterator for captured groups in order in which they appear in the regex.
#[derive(Debug)]
pub struct SubCaptureMatches<'c, 't, S: input::Input + ?Sized> {
    data: &'c Captures<'t, S>,
    i: usize,
}

/// Caller-owned storage for the capture spans of one search, filled by
/// [`Searcher::captures_read`] without allocating a [`Captures`] snapshot.
///
/// Create it with [`Regex::capture_locations`]. A search overwrites the
/// previous contents: after a match every group's span is available, and after
/// a miss or an error every group reads as `None`. Spans are byte offsets into
/// the haystack of the most recent search; the locations do not borrow it.
#[derive(Clone, Debug)]
pub struct CaptureLocations {
    slots: CapturesImpl,
    groups: usize,
    /// Shared with the creating regex and its clones; identifies compatible slots.
    named_groups: Arc<NamedGroups>,
}

#[allow(clippy::len_without_is_empty)] // follow regex's API; there is always group 0
impl CaptureLocations {
    /// The start and end byte offsets of group `i` in the last search, or
    /// `None` if that search did not match, the group did not participate or
    /// `i` is not a group. Group 0 is the overall match.
    pub fn get(&self, i: usize) -> Option<(usize, usize)> {
        if i < self.groups {
            self.slots.get_span(i)
        } else {
            None
        }
    }

    /// The span of the group named `name`; see [`CaptureLocations::get`].
    pub fn name(&self, name: &str) -> Option<(usize, usize)> {
        self.named_groups.get(name).and_then(|&i| self.get(i))
    }

    /// The number of groups, including group 0, whether or not the last search
    /// matched.
    pub fn len(&self) -> usize {
        self.groups
    }

    fn clear(&mut self) {
        match &mut self.slots {
            CapturesImpl::Wrap { locations, .. } => locations.set_pattern(None),
            CapturesImpl::Fancy { saves } => saves.clear(),
        }
    }
}

/// An iterator over all substrings delimited by a regex.
///
/// This iterator yields `Result<&'h str>`, where each item is a substring of the
/// target string that is delimited by matches of the regular expression. It stops when there
/// are no more substrings to yield.
///
/// `'r` is the lifetime of the compiled regular expression, and `'h` is the
/// lifetime of the target string being split.
///
/// This iterator can be created by the [`Regex::split`] method.
#[derive(Debug)]
pub struct Split<'r, 'h> {
    matches: Matches<'r, 'h, str>,
    next_start: usize,
    target: &'h str,
}

impl<'r, 'h> Iterator for Split<'r, 'h> {
    type Item = Result<&'h str>;

    /// Returns the next substring that results from splitting the target string by the regex.
    ///
    /// If no more matches are found, returns the remaining part of the string,
    /// or `None` if all substrings have been yielded.
    fn next(&mut self) -> Option<Result<&'h str>> {
        match self.matches.next() {
            None => {
                let len = self.target.len();
                if self.next_start > len {
                    // No more substrings to return
                    None
                } else {
                    // Return the last part of the target string
                    // Next call will return None
                    let part = &self.target[self.next_start..len];
                    self.next_start = len + 1;
                    Some(Ok(part))
                }
            }
            // Return the next substring
            Some(Ok(m)) => {
                let part = &self.target[self.next_start..m.start()];
                self.next_start = m.end();
                Some(Ok(part))
            }
            Some(Err(e)) => Some(Err(e)),
        }
    }
}

impl<'r, 'h> core::iter::FusedIterator for Split<'r, 'h> {}

/// An iterator over at most `N` substrings delimited by a regex.
///
/// This iterator yields `Result<&'h str>`, where each item is a substring of the
/// target that is delimited by matches of the regular expression. It stops either when
/// there are no more substrings to yield, or after `N` substrings have been yielded.
///
/// The `N`th substring is the remaining part of the target.
///
/// `'r` is the lifetime of the compiled regular expression, and `'h` is the
/// lifetime of the target string being split.
///
/// This iterator can be created by the [`Regex::splitn`] method.
#[derive(Debug)]
pub struct SplitN<'r, 'h> {
    splits: Split<'r, 'h>,
    limit: usize,
}

impl<'r, 'h> Iterator for SplitN<'r, 'h> {
    type Item = Result<&'h str>;

    /// Returns the next substring resulting from splitting the target by the regex,
    /// limited to `N` splits.
    ///
    /// Returns `None` if no more matches are found or if the limit is reached after yielding
    /// the remaining part of the target.
    fn next(&mut self) -> Option<Result<&'h str>> {
        if self.limit == 0 {
            // Limit reached. No more substrings available.
            return None;
        }

        // Decrement the limit for each split.
        self.limit -= 1;
        if self.limit > 0 {
            return self.splits.next();
        }

        // Nth split
        let len = self.splits.target.len();
        if self.splits.next_start > len {
            // No more substrings available.
            None
        } else {
            // Return the remaining part of the target
            let start = self.splits.next_start;
            self.splits.next_start = len + 1;
            Some(Ok(&self.splits.target[start..len]))
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, Some(self.limit))
    }
}

impl<'r, 'h> core::iter::FusedIterator for SplitN<'r, 'h> {}

#[derive(Clone)]
struct RegexOptions {
    syntaxc: SyntaxConfig,
    delegate_size_limit: Option<usize>,
    delegate_dfa_size_limit: Option<usize>,
    oniguruma_mode: bool,
    ignore_numbered_groups_when_named_groups_exist: bool,
    hard_regex_runtime_options: HardRegexRuntimeOptions,
    bytes_mode: BytesMode,
    seek_filter: Option<fn(&str) -> bool>,
    /// Whether the top-level engine of an easy (`Wrap`) pattern should build a
    /// prefilter. `RegexSet` turns this off for its internally-built members:
    /// the set only ever searches them anchored at candidate positions, where
    /// a prefilter is never consulted, so building one wastes time and memory.
    delegate_prefilter: bool,
    #[cfg(feature = "native")]
    native_enabled: bool,
    /// Set by `backtrack_limit`: exact VM limit accounting was requested, so
    /// no route that changes it (native code, the regular automata) is used.
    explicit_backtrack_limit: bool,
}

impl fmt::Debug for RegexOptions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let seek_filter_desc = match self.seek_filter {
            None => "None",
            Some(f_ptr) if (f_ptr as *const ()) == (seek_pattern_is_useful as *const ()) => {
                "Some(seek_pattern_is_useful)"
            }
            Some(_) => "Some(<custom>)",
        };
        f.debug_struct("RegexOptions")
            .field("syntaxc", &self.syntaxc)
            .field("delegate_size_limit", &self.delegate_size_limit)
            .field("delegate_dfa_size_limit", &self.delegate_dfa_size_limit)
            .field("oniguruma_mode", &self.oniguruma_mode)
            .field(
                "ignore_numbered_groups_when_named_groups_exist",
                &self.ignore_numbered_groups_when_named_groups_exist,
            )
            .field(
                "hard_regex_runtime_options",
                &self.hard_regex_runtime_options,
            )
            .field("seek_filter", &seek_filter_desc)
            .field("delegate_prefilter", &self.delegate_prefilter)
            .finish()
    }
}

impl Default for RegexOptions {
    fn default() -> Self {
        RegexOptions {
            syntaxc: SyntaxConfig::new().unicode(true),
            delegate_size_limit: None,
            delegate_dfa_size_limit: None,
            oniguruma_mode: false,
            ignore_numbered_groups_when_named_groups_exist: false,
            hard_regex_runtime_options: HardRegexRuntimeOptions::default(),
            bytes_mode: BytesMode::default(),
            seek_filter: None, // when we are ready to enable seek by default, use: `Some(seek_pattern_is_useful)`
            delegate_prefilter: true,
            #[cfg(feature = "native")]
            native_enabled: true,
            explicit_backtrack_limit: false,
        }
    }
}

#[derive(Copy, Clone, Debug)]
struct HardRegexRuntimeOptions {
    backtrack_limit: usize,
    find_not_empty: bool,
    disallow_empty_match_at_eof_after_newline: bool,
    allow_input_assertion_overrides: bool,
}

impl RegexOptions {
    fn get_flag_value(flag_value: bool, enum_value: u32) -> u32 {
        if flag_value { enum_value } else { 0 }
    }

    fn compute_flags(&self) -> u32 {
        let insensitive = Self::get_flag_value(self.syntaxc.get_case_insensitive(), FLAG_CASEI);
        let multiline = Self::get_flag_value(self.syntaxc.get_multi_line(), FLAG_MULTI);
        let whitespace =
            Self::get_flag_value(self.syntaxc.get_ignore_whitespace(), FLAG_IGNORE_SPACE);
        let dotnl = Self::get_flag_value(self.syntaxc.get_dot_matches_new_line(), FLAG_DOTNL);
        let unicode = Self::get_flag_value(
            self.syntaxc.get_unicode() && !matches!(self.bytes_mode, BytesMode::Ascii),
            FLAG_UNICODE,
        );
        let oniguruma_mode = Self::get_flag_value(self.oniguruma_mode, FLAG_ONIGURUMA_MODE);
        let crlf = Self::get_flag_value(self.syntaxc.get_crlf(), FLAG_CRLF);
        let named_groups_only = Self::get_flag_value(
            self.ignore_numbered_groups_when_named_groups_exist,
            FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
        );

        insensitive
            | multiline
            | whitespace
            | dotnl
            | unicode
            | oniguruma_mode
            | crlf
            | named_groups_only
    }
}

impl Default for HardRegexRuntimeOptions {
    fn default() -> Self {
        HardRegexRuntimeOptions {
            backtrack_limit: 1_000_000,
            find_not_empty: false,
            disallow_empty_match_at_eof_after_newline: false,
            allow_input_assertion_overrides: false,
        }
    }
}

impl Default for RegexOptionsBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl RegexOptionsBuilder {
    /// Enable or disable native acceleration for supported whole-string
    /// boolean searches. It is enabled by default, but only takes effect with
    /// the `native` feature on a supported platform; other platforms and
    /// patterns retain the complete portable engine. Explicit execution limits
    /// always use the portable path, regardless of this setting.
    ///
    /// The method exists with or without the feature, so a library can request
    /// `native(false)` even when Cargo feature unification enables `native` on
    /// behalf of another dependency.
    pub fn native(&mut self, enabled: bool) -> &mut Self {
        #[cfg(feature = "native")]
        {
            self.options.native_enabled = enabled;
        }
        #[cfg(not(feature = "native"))]
        let _ = enabled;
        self
    }

    /// Create a new regex options builder.
    pub fn new() -> Self {
        RegexOptionsBuilder {
            options: RegexOptions::default(),
        }
    }

    /// Build a `Regex` from the given pattern.
    ///
    /// Returns an [`Error`](enum.Error.html) if the pattern could not be parsed.
    pub fn build(&self, pattern: String) -> Result<Regex> {
        Regex::new_options(pattern, &self.options)
    }

    /// Build a [`RegularRegex`] from the given pattern with these options.
    ///
    /// # Errors
    ///
    /// As [`RegularRegex::new`], and [`CompileError::NotRegular`] for an option
    /// that changes matching semantics only the backtracking engine
    /// implements.
    pub fn build_regular(&self, pattern: String) -> Result<RegularRegex> {
        RegularRegex::new_options(pattern, &self.options)
    }

    fn set_config(&mut self, func: impl Fn(SyntaxConfig) -> SyntaxConfig) -> &mut Self {
        self.options.syntaxc = func(self.options.syntaxc);
        self
    }

    /// Override default case insensitive
    /// this is to enable/disable casing via builder instead of a flag within
    /// the raw string pattern which will be parsed
    ///
    /// Default is false
    pub fn case_insensitive(&mut self, yes: bool) -> &mut Self {
        self.set_config(|x| x.case_insensitive(yes))
    }

    /// Enable multi-line regex
    pub fn multi_line(&mut self, yes: bool) -> &mut Self {
        self.set_config(|x| x.multi_line(yes))
    }

    /// Allow ignore whitespace
    pub fn ignore_whitespace(&mut self, yes: bool) -> &mut Self {
        self.set_config(|x| x.ignore_whitespace(yes))
    }

    /// Enable or disable the "dot matches any character" flag.
    /// When this is enabled, `.` will match any character. When it's disabled, then `.` will match any character
    /// except for a new line character.
    pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut Self {
        self.set_config(|x| x.dot_matches_new_line(yes))
    }

    /// Enable or disable the CRLF mode flag (`R`).
    ///
    /// When enabled, `\r\n` is treated as a single line ending for the purposes of
    /// `^` and `$` in multi-line mode, instead of treating `\r` and `\n` as separate
    /// line endings.
    ///
    /// By default, this is disabled. It may be selectively enabled in the regular
    /// expression by using the `R` flag, e.g. `(?mR)` or `(?Rm)`.
    pub fn crlf(&mut self, yes: bool) -> &mut Self {
        self.set_config(|x| x.crlf(yes))
    }

    /// Enable verbose mode in the regular expression.
    ///
    /// The same as ignore_whitespace
    ///
    /// When enabled, verbose mode permits insigificant whitespace in many
    /// places in the regular expression, as well as comments. Comments are
    /// started using `#` and continue until the end of the line.
    ///
    /// By default, this is disabled. It may be selectively enabled in the
    /// regular expression by using the `x` flag regardless of this setting.
    pub fn verbose_mode(&mut self, yes: bool) -> &mut Self {
        self.set_config(|x| x.ignore_whitespace(yes))
    }

    /// Enable or disable the Unicode flag (`u`) by default.
    ///
    /// By default this is **enabled**. The inline `u` flag inside a pattern
    /// is only accepted when it **matches** the current builder setting (e.g.
    /// `(?u)` when unicode is already enabled, or `(?-u)` when it is already
    /// disabled). Attempts to change the mode inline are rejected with a
    /// [`ParseError::ChangingUnicodeModeUnsupported`] error. Use this builder
    /// method to set the desired mode instead.
    ///
    /// ## Effect on `str` input (default)
    ///
    /// When matching against `&str` (the default), the underlying engine
    /// requires that all matches respect UTF-8 boundaries. Disabling Unicode
    /// therefore has the following effects:
    ///
    /// - **`\w`, `\d`, `\s`** become ASCII-only (`[a-zA-Z0-9_]`, `[0-9]`,
    ///   and ASCII whitespace respectively).
    /// - **`\W`, `\D`, `\S`**, bare **`.`**, and **`\p{...}`** Unicode
    ///   properties **fail to compile**, because they could match byte
    ///   sequences that violate UTF-8 boundaries.
    ///
    /// If you need those constructs with `unicode_mode(false)`, use the bytes
    /// API with [`BytesMode::Ascii`] instead.
    ///
    /// ## Effect on byte input
    ///
    /// When matching against `&[u8]` (via [`BytesMode::Ascii`]), all
    /// constructs work as expected in ASCII mode (`.` matches any byte,
    /// `\W`/`\D`/`\S` match non-ASCII byte values, etc.).
    ///
    /// **WARNING**: Unicode mode can greatly increase the size of the compiled
    /// DFA, which can noticeably impact both memory usage and compilation
    /// time. This is especially noticeable if your regex contains character
    /// classes like `\w` that are impacted by whether Unicode is enabled or
    /// not. If Unicode is not necessary, you are encouraged to disable it.
    pub fn unicode_mode(&mut self, yes: bool) -> &mut Self {
        self.set_config(|x| x.unicode(yes))
    }

    /// Limit for how many times backtracking should be attempted for fancy regexes (where
    /// backtracking is used). If this limit is exceeded, execution returns an error with
    /// [`Error::BacktrackLimitExceeded`](enum.Error.html#variant.BacktrackLimitExceeded).
    /// This is for preventing a regex with catastrophic backtracking to run for too long.
    ///
    /// Default is `1_000_000` (1 million).
    ///
    /// Setting a limit, even the default value, also keeps patterns that need
    /// the backtracking engine only for word boundaries on that engine, with
    /// its exact limit accounting. Without one, such patterns search with
    /// automata wherever the results are provably identical. Those searches
    /// never report a backtrack limit error: where the automata give up and the
    /// backtracking engine runs and exceeds the limit, the automata answer
    /// instead. Other errors, such as a backtrack stack overflow, are reported.
    pub fn backtrack_limit(&mut self, limit: usize) -> &mut Self {
        self.options.hard_regex_runtime_options.backtrack_limit = limit;
        self.options.explicit_backtrack_limit = true;
        self
    }

    /// Set the approximate size limit of the compiled regular expression.
    ///
    /// This option is forwarded from the wrapped `regex` crate. Note that depending on the used
    /// regex features there may be multiple delegated sub-regexes fed to the `regex` crate. As
    /// such the actual limit is closer to `<number of delegated regexes> * delegate_size_limit`.
    pub fn delegate_size_limit(&mut self, limit: usize) -> &mut Self {
        self.options.delegate_size_limit = Some(limit);
        self
    }

    /// Set the approximate size of the cache used by the DFA.
    ///
    /// This option is forwarded from the wrapped `regex` crate. Note that depending on the used
    /// regex features there may be multiple delegated sub-regexes fed to the `regex` crate. As
    /// such the actual limit is closer to `<number of delegated regexes> *
    /// delegate_dfa_size_limit`.
    pub fn delegate_dfa_size_limit(&mut self, limit: usize) -> &mut Self {
        self.options.delegate_dfa_size_limit = Some(limit);
        self
    }

    /// Require that matches are non-empty (i.e. match at least one character).
    ///
    /// When this is enabled, any match attempt that would result in a zero-length match is
    /// rejected.
    ///
    /// Default is `false`.
    ///
    /// N.B. When `find_not_empty` is set and analysis determines the pattern will only ever
    /// produce an empty match, compiling the regex will return
    /// `CompileError::PatternCanNeverMatch` instead of silently constructing a regex that can never
    /// return a result. This catches the user error at compile time rather than allowing the
    /// combination to execute pointlessly at runtime.
    pub fn find_not_empty(&mut self, yes: bool) -> &mut Self {
        self.options.hard_regex_runtime_options.find_not_empty = yes;
        self
    }

    /// Treat unnamed capture groups as non-capturing when named groups exist.
    /// Prevents accessing capture groups by number from within the pattern
    /// (backrefs, subroutine calls) when named groups are present.
    pub fn ignore_numbered_groups_when_named_groups_exist(&mut self, yes: bool) -> &mut Self {
        self.options.ignore_numbered_groups_when_named_groups_exist = yes;
        self
    }

    /// ⚠️ Experimental: This API may change, be removed without notice, or cause matches to be
    /// skipped. This requires more real-world testing to prove correctness and observe in which
    /// circumstances it brings performance benefits and in which it has the opposite effect.
    /// Feedback (and benchmarks on real-world patterns/haystacks) would be very welcome!
    ///
    /// Enable the Seek pre-filter optimization for hard (backtracking) patterns.
    ///
    /// When enabled, the compiler attempts to derive a regular approximation of the pattern
    /// which is used to skip to the earliest plausible match position in the haystack before
    /// invoking the backtracking VM. This can dramatically speed up searches in long haystacks
    /// when the pattern can only match at infrequent positions.
    ///
    /// The seek pattern is always a conservative over-approximation — it may report false-positive
    /// positions but will never skip a true match.
    ///
    /// A seek is combined with the start positions the pattern's leading tests allow. When the
    /// pattern starts with a lookbehind over literals, which the seek pattern drops, those
    /// literals propose the candidates and the seek pattern confirms them. With an explicit
    /// [`backtrack_limit`](Self::backtrack_limit) the seek always proposes them, so limit errors
    /// are exactly those of seeking alone.
    ///
    /// When `yes` is `true`, uses the default [`seek_pattern_is_useful`] filter to decide
    /// whether the derived pattern is worth using. When `false`, disables seek entirely.
    ///
    /// To supply a custom filter, use [`seek_filter`](Self::seek_filter) instead.
    pub fn seek(&mut self, yes: bool) -> &mut Self {
        self.options.seek_filter = if yes {
            Some(seek_pattern_is_useful)
        } else {
            None
        };
        self
    }

    /// Set a custom filter function that decides whether the derived seek pattern is useful.
    ///
    /// The function receives the seek pattern string and returns `true` if the pattern should
    /// be used as a pre-filter, or `false` to fall back to the standard unanchored search.
    ///
    /// Calling this method implicitly enables seek. Pass [`seek_pattern_is_useful`] to restore
    /// the default behavior.
    ///
    /// # Example
    ///
    /// ```rust
    /// use regexrs::{RegexOptionsBuilder, seek_pattern_is_useful};
    ///
    /// // Use the default filter (equivalent to seek(true))
    /// let mut builder = RegexOptionsBuilder::new();
    /// builder.seek_filter(seek_pattern_is_useful);
    ///
    /// // Use a custom filter that additionally requires the pattern to be longer than 3 bytes
    /// let mut builder = RegexOptionsBuilder::new();
    /// builder.seek_filter(|pat| pat.len() > 3 && seek_pattern_is_useful(pat));
    /// ```
    pub fn seek_filter(&mut self, filter: fn(&str) -> bool) -> &mut Self {
        self.options.seek_filter = Some(filter);
        self
    }

    /// Attempts to better match [Oniguruma](https://github.com/kkos/oniguruma)'s default parsing behavior
    ///
    /// Currently this amounts to changing behavior with:
    ///
    /// # Left and right word bounds
    ///
    /// `regexrs` follows the default of other regex engines such as the `regex` crate itself
    /// where `\<` and `\>` correspond to a _left_ and _right_ word-bound respectively. This
    /// differs from Oniguruma's defaults which treat them as matching the literals `<` and `>`.
    /// When this option is set using `\<` and `\>` in the pattern will match the literals
    /// `<` and `>` instead of word bounds.
    ///
    /// # Repetition/Quantifiers on empty groups
    ///
    /// `regexrs` would normally reject patterns like `(?:)+` because the `+` has nothing
    /// to target. In Oniguruma mode, the empty repeat is silently dropped at parse time.
    ///
    /// # Swapped order quantifiers
    ///
    /// `regexrs` would normally treat `x{0,3}` as a syntax error because the minimum is
    /// greater than the maximum. In Oniguruma mode, the limits are swapped (behaving as
    /// `x{3,0}`) and the resulting repeat is treated as atomic (possessive), matching
    /// Oniguruma's behavior.
    ///
    /// # Adjacent quantifiers
    ///
    /// `regexrs` would normally reject adjacent quantifiers like `a{3}{2}`, treating the
    /// second as having nothing to target. In Oniguruma mode, each quantifier wraps the
    /// previous result (e.g. `a{3}{2}` becomes `(?:a{3}){2}`).
    ///
    /// Outside Oniguruma mode, `+` after `{...}` is a possessive modifier (e.g. `x{2}+` is
    /// possessive). In Oniguruma mode, `+` after a user-specified `{...}` repeat is treated
    /// as another repeat modifier — `x{2}+` is equivalent to `(?:x{2})+`.
    ///
    /// # Start of line (`^`) in multiline mode
    ///
    /// In multiline mode (`(?m)`), `^` normally matches at the start of the input and after
    /// any newline. In Oniguruma mode, it additionally rejects a match at the absolute end of
    /// the input when it is preceded by a trailing newline.
    /// Inside lookarounds, `^` behaves as a plain line start without the end-of-input rejection.
    ///
    /// ## Example
    ///
    /// ```
    /// use regexrs::{Regex, RegexBuilder};
    ///
    /// let haystack = "turbo::<Fish>";
    /// let regex = r"\<\w*\>";
    ///
    /// // By default `\<` and `\>` will match the start and end of a word boundary
    /// let word_bounds_regex = Regex::new(regex).unwrap();
    /// let word_bounds = word_bounds_regex.find(haystack).unwrap().unwrap();
    /// assert_eq!(word_bounds.as_str(), "turbo");
    ///
    /// // With the option set they instead match the literal `<` and `>` characters
    /// let literals_regex = RegexBuilder::new(regex).oniguruma_mode(true).build().unwrap();
    /// let literals = literals_regex.find(haystack).unwrap().unwrap();
    /// assert_eq!(literals.as_str(), "<Fish>");
    /// ```
    pub fn oniguruma_mode(&mut self, yes: bool) -> &mut Self {
        self.options.oniguruma_mode = yes;
        self
    }

    /// Set the input encoding mode for the regex.
    ///
    /// Controls how the regex engine handles input encoding. See [`BytesMode`]
    /// for details on each variant.
    ///
    /// Default is [`BytesMode::Unicode`].
    ///
    /// # Example
    ///
    /// ```rust
    /// use regexrs::{BytesMode, RegexBuilder};
    ///
    /// // ASCII bytes mode: . matches any byte including non-UTF-8
    /// let re = RegexBuilder::new(r".+")
    ///     .bytes_mode(BytesMode::Ascii)
    ///     .build()
    ///     .unwrap();
    /// assert!(re.is_match(b"\x80\x81\x82").unwrap());
    ///
    /// // Default Unicode mode: . only matches valid UTF-8 codepoints
    /// let re = RegexBuilder::new(r".+")
    ///     .build()
    ///     .unwrap();
    /// assert!(!re.is_match(b"\x80\x81\x82").unwrap());
    /// ```
    pub fn bytes_mode(&mut self, mode: BytesMode) -> &mut Self {
        self.options.bytes_mode = mode;
        self
    }

    /// Sometimes you want to pass in a haystack containing a trailing newline,
    /// and have that last position ignored for the purposes of anchors like ^ and $
    /// and even for lookarounds, unless \z is specifically used to anchor to the end of the string.
    /// This is how Oniguruma works for example.
    pub fn disallow_empty_match_at_eof_after_newline(&mut self, yes: bool) -> &mut Self {
        self.options
            .hard_regex_runtime_options
            .disallow_empty_match_at_eof_after_newline = yes;
        self
    }

    /// Allow [`RegexInput`] assertion suppression overrides at runtime.
    ///
    /// When enabled, patterns containing `\A` and `\z` are treated as hard and compiled to the VM
    /// so that [`RegexInput::start_text`] and [`RegexInput::end_text`] can suppress those
    /// assertions.
    ///
    /// When disabled (the default), those runtime overrides are ignored.
    pub fn allow_input_assertion_overrides(&mut self, yes: bool) -> &mut Self {
        self.options
            .hard_regex_runtime_options
            .allow_input_assertion_overrides = yes;
        self
    }
}

impl RegexBuilder {
    /// See [`RegexOptionsBuilder::native`].
    pub fn native(&mut self, enabled: bool) -> &mut Self {
        self.options.native(enabled);
        self
    }

    /// Create a new regex builder.
    pub fn new(pattern: &str) -> Self {
        RegexBuilder {
            pattern: pattern.to_string(),
            options: RegexOptionsBuilder::new(),
        }
    }

    /// Build a `Regex` from the given pattern.
    ///
    /// Returns an [`Error`](enum.Error.html) if the pattern could not be parsed.
    pub fn build(&self) -> Result<Regex> {
        self.options.build(self.pattern.clone())
    }

    /// Build a [`RegularRegex`], which accepts only the regular subset of the
    /// syntax and never backtracks.
    ///
    /// # Errors
    ///
    /// As [`RegularRegex::new`], and [`CompileError::NotRegular`] for an option
    /// that changes matching semantics only the backtracking engine
    /// implements, such as [`RegexBuilder::find_not_empty`].
    ///
    /// ```
    /// use regexrs::RegexBuilder;
    /// let words = RegexBuilder::new(r"\bcolou?r\b").case_insensitive(true).build_regular()?;
    /// assert!(words.is_match("Colour"));
    /// assert!(RegexBuilder::new("a+").find_not_empty(true).build_regular().is_err());
    /// # Ok::<(), regexrs::Error>(())
    /// ```
    pub fn build_regular(&self) -> Result<RegularRegex> {
        self.options.build_regular(self.pattern.clone())
    }

    /// Change the pattern to build. Useful when building multiple regexes from
    /// many patterns.
    pub fn pattern(&mut self, pattern: String) -> &mut Self {
        self.pattern = pattern;
        self
    }

    /// See [`RegexOptionsBuilder::case_insensitive`]
    pub fn case_insensitive(&mut self, yes: bool) -> &mut Self {
        self.options.case_insensitive(yes);
        self
    }

    /// See [`RegexOptionsBuilder::multi_line`]
    pub fn multi_line(&mut self, yes: bool) -> &mut Self {
        self.options.multi_line(yes);
        self
    }

    /// See [`RegexOptionsBuilder::ignore_whitespace`]
    pub fn ignore_whitespace(&mut self, yes: bool) -> &mut Self {
        self.options.ignore_whitespace(yes);
        self
    }

    /// See [`RegexOptionsBuilder::dot_matches_new_line`]
    pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut Self {
        self.options.dot_matches_new_line(yes);
        self
    }

    /// See [`RegexOptionsBuilder::verbose_mode`]
    pub fn verbose_mode(&mut self, yes: bool) -> &mut Self {
        self.options.ignore_whitespace(yes);
        self
    }

    /// See [`RegexOptionsBuilder::unicode_mode`]
    pub fn unicode_mode(&mut self, yes: bool) -> &mut Self {
        self.options.unicode_mode(yes);
        self
    }

    /// See [`RegexOptionsBuilder::backtrack_limit`]
    pub fn backtrack_limit(&mut self, limit: usize) -> &mut Self {
        self.options.backtrack_limit(limit);
        self
    }

    /// See [`RegexOptionsBuilder::delegate_size_limit`]
    pub fn delegate_size_limit(&mut self, limit: usize) -> &mut Self {
        self.options.delegate_size_limit(limit);
        self
    }

    /// See [`RegexOptionsBuilder::delegate_dfa_size_limit`]
    pub fn delegate_dfa_size_limit(&mut self, limit: usize) -> &mut Self {
        self.options.delegate_dfa_size_limit(limit);
        self
    }

    /// See [`RegexOptionsBuilder::oniguruma_mode`]
    pub fn oniguruma_mode(&mut self, yes: bool) -> &mut Self {
        self.options.oniguruma_mode(yes);
        self
    }

    /// See [`RegexOptionsBuilder::bytes_mode`]
    pub fn bytes_mode(&mut self, mode: BytesMode) -> &mut Self {
        self.options.bytes_mode(mode);
        self
    }

    /// See [`RegexOptionsBuilder::crlf`]
    pub fn crlf(&mut self, yes: bool) -> &mut Self {
        self.options.crlf(yes);
        self
    }

    /// See [`RegexOptionsBuilder::find_not_empty`]
    pub fn find_not_empty(&mut self, yes: bool) -> &mut Self {
        self.options.find_not_empty(yes);
        self
    }

    /// See [`RegexOptionsBuilder::ignore_numbered_groups_when_named_groups_exist`]
    pub fn ignore_numbered_groups_when_named_groups_exist(&mut self, yes: bool) -> &mut Self {
        self.options
            .ignore_numbered_groups_when_named_groups_exist(yes);
        self
    }

    /// See [`RegexOptionsBuilder::seek`]
    pub fn seek(&mut self, yes: bool) -> &mut Self {
        self.options.seek(yes);
        self
    }

    /// See [`RegexOptionsBuilder::seek_filter`]
    pub fn seek_filter(&mut self, filter: fn(&str) -> bool) -> &mut Self {
        self.options.seek_filter(filter);
        self
    }

    /// See [`RegexOptionsBuilder::disallow_empty_match_at_eof_after_newline`]
    pub fn disallow_empty_match_at_eof_after_newline(&mut self, yes: bool) -> &mut Self {
        self.options.disallow_empty_match_at_eof_after_newline(yes);
        self
    }

    /// See [`RegexOptionsBuilder::allow_input_assertion_overrides`]
    pub fn allow_input_assertion_overrides(&mut self, yes: bool) -> &mut Self {
        self.options.allow_input_assertion_overrides(yes);
        self
    }
}

impl fmt::Debug for Regex {
    /// Shows the original regular expression.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl fmt::Display for Regex {
    /// Shows the original regular expression
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

impl FromStr for Regex {
    type Err = Error;

    /// Attempts to parse a string into a regular expression
    fn from_str(s: &str) -> Result<Regex> {
        Regex::new(s)
    }
}

impl Regex {
    /// Create reusable working memory for repeated searches with this regex.
    ///
    /// A searcher borrows the immutable regex and owns its scratch buffers. It
    /// does not cache answers or borrow the previous haystack. Use independent
    /// searchers on independent threads. Owned capture results remain snapshots.
    ///
    /// ```
    /// use regexrs::Regex;
    /// let regex = Regex::new(r"(\w+)\s+\1")?;
    /// let mut search = regex.searcher();
    /// assert!(search.is_match("word word")?);
    /// assert!(!search.is_match("word other")?);
    /// # Ok::<(), regexrs::Error>(())
    /// ```
    pub fn searcher(&self) -> Searcher<'_> {
        Searcher::new(self)
    }

    /// Parse and compile a regex with default options, see `RegexBuilder`.
    ///
    /// Returns an [`Error`](enum.Error.html) if the pattern could not be parsed.
    pub fn new(re: &str) -> Result<Regex> {
        Self::new_options(re.to_string(), &RegexOptions::default())
    }

    pub(crate) fn new_options(pattern: String, options: &RegexOptions) -> Result<Regex> {
        let flags = options.compute_flags();
        let mut tree = Expr::parse_tree_with_flags(&pattern, flags)?;
        // The pattern as written, before the optimizer rewrites a final
        // lookahead, for a route between edge lookarounds.
        let edged = edge_lookarounds(&tree.expr).then(|| tree.expr.clone());
        // Lower the already-parsed original tree before capture-boundary rewrites.
        // Emission happens only after the portable compiler validates everything.
        #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]
        let native_pattern = if options.native_enabled
            && options.delegate_prefilter
            && !options.explicit_backtrack_limit
            && options.syntaxc.get_unicode()
            && matches!(options.bytes_mode, BytesMode::Unicode)
            && !options.oniguruma_mode
            && !options.ignore_numbered_groups_when_named_groups_exist
            && !options.hard_regex_runtime_options.find_not_empty
            && !options
                .hard_regex_runtime_options
                .allow_input_assertion_overrides
            && !options
                .hard_regex_runtime_options
                .disallow_empty_match_at_eof_after_newline
            && pattern.len() <= 4096
        {
            native::Pattern::from_expr(&tree.expr).filter(|pattern| pattern.rich)
        } else {
            None
        };

        let runtime = &options.hard_regex_runtime_options;
        let find_not_empty = runtime.find_not_empty;
        let disallow_empty_match_at_eof_after_newline =
            runtime.disallow_empty_match_at_eof_after_newline;
        let (requires_capture_group_fixup, context) = prepare_tree(&mut tree, runtime);
        let info = analyze(&tree, context)?;

        if find_not_empty && info.const_size && info.min_size == 0 {
            return Err(CompileError::PatternCanNeverMatch.into());
        }

        if !info.hard {
            // easy case, wrap regex

            // we do our own to_str because escapes are different
            // The cooked form is the pattern plus some flag-group decoration. It is
            // kept even though the engine is normally built from an Hir below,
            // because it doubles as the seek pattern for RegexSet membership and
            // as debug output.
            let mut re_cooked = String::with_capacity(pattern.len() + pattern.len() / 2);
            tree.expr.to_str(&mut re_cooked, 0);
            let compile_options = CompileOptions {
                bytes_mode: options.bytes_mode,
                unicode: options.syntaxc.get_unicode()
                    && !matches!(options.bytes_mode, BytesMode::Ascii),
                delegate_size_limit: options.delegate_size_limit,
                delegate_dfa_size_limit: options.delegate_dfa_size_limit,
                // The remaining fields (anchored, contains_subroutines, seek_filter,
                // disallow_empty_match_at_eof_after_newline) are irrelevant for a plain
                // delegate compile in the easy path and their defaults are correct.
                ..CompileOptions::default()
            };
            // The whole pattern is delegated and searched unanchored, so it keeps
            // its prefilter and all capture groups (the user may request captures).
            // RegexSet members are the exception: they are only searched anchored,
            // so their prefilter build is skipped (see `delegate_prefilter`).
            let usage = if options.delegate_prefilter {
                compile::DelegateUsage::unanchored()
            } else {
                compile::DelegateUsage::unanchored_no_prefilter()
            };
            // Build the engine from an Hir translated directly from the tree, so
            // the engine doesn't re-parse the cooked pattern. Fall back to the
            // string path for anything the translator doesn't cover.
            let utf8 = matches!(compile_options.bytes_mode, BytesMode::Unicode);
            let mut hir_ctx = to_hir::HirCtx::new(compile_options.unicode, utf8);
            let hir = to_hir::expr_to_hir(&tree.expr, &mut hir_ctx);
            // A plan reports a rewritten capture group zero as group 1, within
            // fixed slot storage.
            let planned = hir.as_ref().filter(|hir| {
                !requires_capture_group_fixup
                    || 2 * (hir.properties().explicit_captures_len() + 1) <= FIXUP_SLOTS
            });
            let engine = WrapEngine::new(planned, &compile_options, usage, || match &hir {
                Some(hir) => compile::compile_inner_from_hir(hir, &compile_options, usage),
                None => compile::compile_inner(&re_cooked, &compile_options, usage),
            })?;
            return Ok(Regex {
                inner: RegexImpl::Wrap {
                    engine,
                    pattern,
                    explicit_capture_group_0: requires_capture_group_fixup,
                    delegated_pattern: re_cooked,
                },
                named_groups: Arc::new(tree.named_groups),
                #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]
                native: None,
            });
        }

        let prog = compile(
            &info,
            CompileOptions {
                anchored: can_compile_as_anchored(&tree.expr),
                contains_subroutines: tree.contains_subroutines,
                seek_filter: options.seek_filter,
                disallow_empty_match_at_eof_after_newline,
                bytes_mode: options.bytes_mode,
                unicode: options.syntaxc.get_unicode()
                    && !matches!(options.bytes_mode, BytesMode::Ascii),
                delegate_size_limit: options.delegate_size_limit,
                delegate_dfa_size_limit: options.delegate_dfa_size_limit,
                explicit_backtrack_limit: options.explicit_backtrack_limit,
            },
        )?;
        let n_groups = info.end_group();
        let regular = if options.explicit_backtrack_limit || prog.repeats_empty_matches() {
            None
        } else if requires_capture_group_fixup {
            edged
                .as_ref()
                .and_then(|expr| assertion_route(expr, &prog, options, n_groups))
                .map(Arc::new)
        } else {
            word_boundary_automata(&tree.expr, options, n_groups)
                .or_else(|| {
                    let expr = edged.as_ref()?;
                    assertion_route(expr, &prog, options, n_groups)
                })
                .map(Arc::new)
        };
        Ok(Regex {
            #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]
            native: native_pattern.map(|pattern| Arc::new(native::LazyNative::new(pattern))),
            inner: RegexImpl::Fancy {
                prog: Arc::new(prog),
                n_groups,
                options: options.hard_regex_runtime_options,
                pattern,
                flags,
                regular,
            },
            named_groups: Arc::new(tree.named_groups),
        })
    }

    /// Returns the original string of this regex.
    pub fn as_str(&self) -> &str {
        match &self.inner {
            RegexImpl::Wrap { pattern, .. } => pattern,
            RegexImpl::Fancy { pattern, .. } => pattern,
        }
    }

    /// Check if the regex matches the input.
    ///
    /// Accepts any type implementing [`Input`]: `&str`, `&String`, or `&[u8]`.
    ///
    /// # Example
    ///
    /// Test if some text contains the same word twice:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    ///
    /// let re = Regex::new(r"(\w+) \1").unwrap();
    /// assert!(re.is_match("mirror mirror on the wall").unwrap());
    /// ```
    ///
    /// Match against raw bytes:
    ///
    /// ```rust
    /// # use regexrs::{BytesMode, RegexBuilder};
    ///
    /// let re = RegexBuilder::new(r"\d+")
    ///     .bytes_mode(BytesMode::Ascii)
    ///     .build()
    ///     .unwrap();
    /// assert!(re.is_match(b"abc 123").unwrap());
    /// ```
    pub fn is_match<S: input::Input + ?Sized>(&self, input: &S) -> Result<bool> {
        match &self.inner {
            RegexImpl::Wrap { .. } => self.is_match_input(RegexInput::new(input)),
            RegexImpl::Fancy { .. } => self.fancy_is_match(&RegexInput::new(input), true, None),
        }
    }

    pub(crate) fn native_match<S: input::Input + ?Sized>(&self, input: &S) -> Option<bool> {
        #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]
        {
            let text = input.as_utf8()?;
            self.native.as_ref()?.get()?.is_match(text)
        }
        #[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]
        {
            let _ = input;
            None
        }
    }

    /// Whether native boolean-matching code exists for this expression. Code is
    /// emitted on the first boolean search or query. An expensive input can
    /// still defer to the portable matcher; this is not route telemetry.
    pub fn has_native_code(&self) -> bool {
        self.native_code_bytes() != 0
    }

    /// Native instruction-buffer size, or zero on a portable-only expression.
    /// Emits the code if no boolean search has done so yet.
    pub fn native_code_bytes(&self) -> usize {
        #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]
        {
            self.native
                .as_ref()
                .and_then(|native| native.get())
                .map_or(0, native::NativeRegex::code_bytes)
        }
        #[cfg(not(all(feature = "native", target_os = "linux", target_arch = "x86_64")))]
        {
            0
        }
    }

    /// Returns true if and only if this regex matches anywhere in the given
    /// search input.
    pub fn is_match_input<S: input::Input + ?Sized>(
        &self,
        input: RegexInput<'_, S>,
    ) -> Result<bool> {
        match &self.inner {
            RegexImpl::Wrap { engine, .. } => Ok(!input.is_done()
                && match engine {
                    WrapEngine::Plan(plan) => plan_is_match(plan, &input),
                    WrapEngine::Meta(inner) => inner.is_match(ra_input(&input)),
                }),
            RegexImpl::Fancy { .. } => self.fancy_is_match(&input, false, None),
        }
    }

    /// A boolean search on the VM's program: the regular route's lazy DFA
    /// where it applies, then native code for a whole-text search, then the
    /// VM.
    pub(crate) fn fancy_is_match<S: input::Input + ?Sized>(
        &self,
        input: &RegexInput<'_, S>,
        whole_text: bool,
        mut cache: Option<&mut searcher::Cache>,
    ) -> Result<bool> {
        if input.is_done() {
            return Ok(false);
        }
        if let Some(route) = self.regular_route(input) {
            if let Some(found) = route
                .plan()
                .and_then(|plan| plan.is_match(&plan_input(input)))
            {
                return Ok(found);
            }
            if let Some(automata) = route.automata()
                && let Ok(found) = automata.is_match(
                    &ra_input(input),
                    cache.as_deref_mut().and_then(|cache| cache.route(automata)),
                )
            {
                return Ok(found);
            }
        }
        if whole_text && let Some(found) = self.native_match(input.haystack()) {
            return Ok(found);
        }
        Ok(self.find_on_vm(input, 0, cache)?.is_some())
    }

    /// The route of a word-boundary pattern, when its automata report exactly
    /// what the VM would for `input`:
    ///
    /// - The range must end at the end of the haystack. The VM matches over
    ///   the whole haystack and rejects a match that ends past the range,
    ///   without trying a shorter match of a delegated sub-expression; the
    ///   automata stop at the range end and can report that shorter match.
    /// - In ASCII mode both step one byte at a time. Otherwise the haystack
    ///   must be text known to be valid UTF-8, searched from a character
    ///   boundary: elsewhere the VM advances over an invalid or partial
    ///   character by the length its first byte implies, visiting positions
    ///   the automata would not.
    ///
    /// The route's lazy DFAs can still give up on non-ASCII text, leaving the
    /// search to the VM; its plan, if any, answers only where they
    /// would not. The route's engine is decided and built here on first use.
    pub(crate) fn regular_route<S: input::Input + ?Sized>(
        &self,
        input: &RegexInput<'_, S>,
    ) -> Option<&RouteEngine> {
        let RegexImpl::Fancy {
            regular: Some(route),
            ..
        } = &self.inner
        else {
            return None;
        };
        let haystack = input.haystack();
        let eligible = input.get_range().end == haystack.len()
            && (route.ascii
                || haystack
                    .as_utf8()
                    .is_some_and(|text| text.is_char_boundary(input.effective_start())));
        eligible.then(|| route.engine())
    }

    /// Returns an iterator for each successive non-overlapping match in `text`.
    ///
    /// If you have capturing groups in your regex that you want to extract, use the [Regex::captures_iter()]
    /// method.
    ///
    /// # Example
    ///
    /// Find all words followed by an exclamation point:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    ///
    /// let re = Regex::new(r"\w+(?=!)").unwrap();
    /// let mut matches = re.find_iter("so fancy! even with! iterators!");
    /// assert_eq!(matches.next().unwrap().unwrap().as_str(), "fancy");
    /// assert_eq!(matches.next().unwrap().unwrap().as_str(), "with");
    /// assert_eq!(matches.next().unwrap().unwrap().as_str(), "iterators");
    /// assert!(matches.next().is_none());
    /// ```
    pub fn find_iter<'r, 't, S: input::Input + ?Sized>(
        &'r self,
        text: &'t S,
    ) -> Matches<'r, 't, S> {
        self.find_iter_input(RegexInput::new(text))
    }

    /// Returns an iterator for each successive non-overlapping match in the
    /// given search input.
    pub fn find_iter_input<'r, 't, S: input::Input + ?Sized>(
        &'r self,
        input: RegexInput<'t, S>,
    ) -> Matches<'r, 't, S> {
        Matches::new(self, input, None)
    }

    /// Find the first match in the input.
    ///
    /// Accepts any type implementing [`Input`]: `&str`, `&String`, or `&[u8]`.
    ///
    /// # Example
    ///
    /// Find a word that is followed by an exclamation point:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    ///
    /// let re = Regex::new(r"\w+(?=!)").unwrap();
    /// assert_eq!(re.find("so fancy!").unwrap().unwrap().as_str(), "fancy");
    /// ```
    pub fn find<'t, S: input::Input + ?Sized>(&self, input: &'t S) -> Result<Option<S::Match<'t>>> {
        self.find_input(RegexInput::new(input))
    }

    /// Find the first match in the given search input.
    pub fn find_input<'t, S: input::Input + ?Sized>(
        &self,
        input: RegexInput<'t, S>,
    ) -> Result<Option<S::Match<'t>>> {
        Ok(self
            .find_input_raw(&input, 0)?
            .map(|(s, e)| input.haystack().make_match(s, e)))
    }

    /// Returns the first match in `input`, starting from the specified byte position `pos`.
    ///
    /// # Examples
    ///
    /// Finding match starting at a position:
    ///
    /// ```
    /// # use regexrs::Regex;
    /// let re = Regex::new(r"(?m:^)(\d+)").unwrap();
    /// let text = "1 test 123\n2 foo";
    /// let mat = re.find_from_pos(text, 7).unwrap().unwrap();
    ///
    /// assert_eq!(mat.start(), 11);
    /// assert_eq!(mat.end(), 12);
    /// ```
    ///
    /// Note that in some cases this is not the same as using the `find`
    /// method and passing a slice of the string, see [Regex::captures_from_pos()]
    /// for details. To constrain matching to a byte range without slicing, use
    /// [Regex::find_input()] with [`RegexInput`].
    pub fn find_from_pos<'t, S: input::Input + ?Sized>(
        &self,
        input: &'t S,
        pos: usize,
    ) -> Result<Option<S::Match<'t>>> {
        self.find_input(RegexInput::new(input).from_pos(pos))
    }

    pub(crate) fn find_input_raw<S: input::Input + ?Sized>(
        &self,
        input: &RegexInput<'_, S>,
        option_flags: u32,
    ) -> Result<Option<(usize, usize)>> {
        self.find_input_raw_cached(input, option_flags, None)
    }

    pub(crate) fn find_input_raw_cached<S: input::Input + ?Sized>(
        &self,
        input: &RegexInput<'_, S>,
        option_flags: u32,
        mut cache: Option<&mut searcher::Cache>,
    ) -> Result<Option<(usize, usize)>> {
        if input.is_done() {
            return Ok(None);
        }
        if let Some(route) = self.regular_route(input) {
            if let Some(found) = route
                .plan()
                .and_then(|plan| plan.find::<[usize]>(&plan_input(input), None))
            {
                return Ok(found);
            }
            if let Some(automata) = route.automata()
                && let Ok(found) = automata.find(
                    &ra_input(input),
                    cache.as_deref_mut().and_then(|cache| cache.route(automata)),
                )
            {
                return Ok(found);
            }
        }
        self.find_on_vm(input, option_flags, cache)
    }

    /// `find_input_raw_cached` without the regular route's lazy DFAs.
    pub(crate) fn find_on_vm<S: input::Input + ?Sized>(
        &self,
        input: &RegexInput<'_, S>,
        option_flags: u32,
        mut cache: Option<&mut searcher::Cache>,
    ) -> Result<Option<(usize, usize)>> {
        match &self.inner {
            RegexImpl::Wrap {
                engine: WrapEngine::Plan(plan),
                explicit_capture_group_0,
                ..
            } => {
                if !*explicit_capture_group_0 {
                    return Ok(plan_find(plan, input, None));
                }
                Ok(plan_find_rewritten(plan, input))
            }
            RegexImpl::Wrap {
                engine: WrapEngine::Meta(inner),
                explicit_capture_group_0,
                ..
            } => {
                let delegated_input = ra_input(input);
                let result = if !*explicit_capture_group_0 {
                    regular_find(
                        inner,
                        &delegated_input,
                        cache.and_then(searcher::Cache::regular),
                    )
                } else {
                    // Only group 1's span is needed (the real match bounds of
                    // the rewritten pattern); a fixed 4-slot search avoids
                    // allocating full captures on every find.
                    let mut slots = [None; 4];
                    let result = match cache.and_then(searcher::Cache::regular) {
                        Some((cache, _)) => {
                            inner.search_slots_with(cache, &delegated_input, &mut slots)
                        }
                        None => inner.search_slots(&delegated_input, &mut slots),
                    };
                    if result.is_some() {
                        slots[2]
                            .zip(slots[3])
                            .map(|(start, end)| (start.get(), end.get()))
                    } else {
                        None
                    }
                };
                Ok(result)
            }
            RegexImpl::Fancy { prog, options, .. } => {
                let option_flags = option_flags
                    | if options.find_not_empty {
                        OPTION_FIND_NOT_EMPTY
                    } else {
                        0
                    };
                // Span-only VM entry: nothing is moved out of the pooled
                // scratch, so this path is allocation-free per call.
                let found = match cache.as_deref_mut().and_then(searcher::Cache::rich) {
                    Some(scratch) => {
                        vm::run_spans_cached(prog, input, option_flags, options, scratch)
                    }
                    None => vm::run_spans(prog, input, option_flags, options),
                };
                match found {
                    Err(error) => match limit_recovery(
                        self.regular_route(input).and_then(RouteEngine::automata),
                        &error,
                    ) {
                        Some((route, regex)) => Ok(regular_find(
                            regex,
                            &ra_input(input),
                            cache.and_then(|cache| cache.route_meta(route)),
                        )),
                        None => Err(error),
                    },
                    found => found,
                }
            }
        }
    }

    /// Build a `Captures` value containing only group 0 for the given span.
    ///
    /// This is used by `RegexSet` as a fast path for patterns without capture
    /// groups, where we only need to preserve the overall match range.
    ///
    /// The caller must pass a valid `start..end` match span for `input`.
    /// Behavior is otherwise undefined for APIs reading the resulting captures.
    pub(crate) fn captures_for_span<'t, S: input::Input + ?Sized>(
        &self,
        input: &'t S,
        start: usize,
        end: usize,
    ) -> Captures<'t, S> {
        Captures {
            inner: CapturesImpl::Fancy {
                saves: vec![start, end],
            },
            named_groups: self.named_groups.clone(),
            input,
        }
    }

    /// Returns an iterator over all the non-overlapping capture groups matched in `text`.
    ///
    /// # Examples
    ///
    /// Finding all matches and capturing parts of each:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    ///
    /// let re = Regex::new(r"(\d{4})-(\d{2})").unwrap();
    /// let text = "It was between 2018-04 and 2020-01";
    /// let mut all_captures = re.captures_iter(text);
    ///
    /// let first = all_captures.next().unwrap().unwrap();
    /// assert_eq!(first.get(1).unwrap().as_str(), "2018");
    /// assert_eq!(first.get(2).unwrap().as_str(), "04");
    /// assert_eq!(first.get(0).unwrap().as_str(), "2018-04");
    ///
    /// let second = all_captures.next().unwrap().unwrap();
    /// assert_eq!(second.get(1).unwrap().as_str(), "2020");
    /// assert_eq!(second.get(2).unwrap().as_str(), "01");
    /// assert_eq!(second.get(0).unwrap().as_str(), "2020-01");
    ///
    /// assert!(all_captures.next().is_none());
    /// ```
    pub fn captures_iter<'r, 't, S: input::Input + ?Sized>(
        &'r self,
        text: &'t S,
    ) -> CaptureMatches<'r, 't, S> {
        self.captures_iter_input(RegexInput::new(text))
    }

    /// Returns an iterator over all the non-overlapping capture groups matched
    /// in the given search input.
    pub fn captures_iter_input<'r, 't, S: input::Input + ?Sized>(
        &'r self,
        input: RegexInput<'t, S>,
    ) -> CaptureMatches<'r, 't, S> {
        CaptureMatches(self.find_iter_input(input))
    }

    /// Returns the capture groups for the first match in `text`.
    ///
    /// If no match is found, then `Ok(None)` is returned.
    ///
    /// # Examples
    ///
    /// Finding matches and capturing parts of the match:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    ///
    /// let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
    /// let text = "The date was 2018-04-07";
    /// let captures = re.captures(text).unwrap().unwrap();
    ///
    /// assert_eq!(captures.get(1).unwrap().as_str(), "2018");
    /// assert_eq!(captures.get(2).unwrap().as_str(), "04");
    /// assert_eq!(captures.get(3).unwrap().as_str(), "07");
    /// assert_eq!(captures.get(0).unwrap().as_str(), "2018-04-07");
    /// ```
    pub fn captures<'t, S: input::Input + ?Sized>(
        &self,
        text: &'t S,
    ) -> Result<Option<Captures<'t, S>>> {
        self.captures_input(RegexInput::new(text))
    }

    /// Returns the capture groups for the first match in the given search
    /// input.
    pub fn captures_input<'t, S: input::Input + ?Sized>(
        &self,
        input: RegexInput<'t, S>,
    ) -> Result<Option<Captures<'t, S>>> {
        self.captures_input_with_option_flags(&input, 0)
    }

    /// Returns the capture groups for the first match in `text`, starting from
    /// the specified byte position `pos`.
    ///
    /// # Examples
    ///
    /// Finding captures starting at a position:
    ///
    /// ```
    /// # use regexrs::Regex;
    /// let re = Regex::new(r"(?m:^)(\d+)").unwrap();
    /// let text = "1 test 123\n2 foo";
    /// let captures = re.captures_from_pos(text, 7).unwrap().unwrap();
    ///
    /// let group = captures.get(1).unwrap();
    /// assert_eq!(group.as_str(), "2");
    /// assert_eq!(group.start(), 11);
    /// assert_eq!(group.end(), 12);
    /// ```
    ///
    /// Note that in some cases this is not the same as using the `captures`
    /// method and passing a slice of the string, see the capture that we get
    /// when we do this:
    ///
    /// ```
    /// # use regexrs::Regex;
    /// let re = Regex::new(r"(?m:^)(\d+)").unwrap();
    /// let text = "1 test 123\n2 foo";
    /// let captures = re.captures(&text[7..]).unwrap().unwrap();
    /// assert_eq!(captures.get(1).unwrap().as_str(), "123");
    /// ```
    ///
    /// This matched the number "123" because it's at the beginning of the text
    /// of the string slice.
    ///
    /// To constrain matching to a byte range without slicing, use
    /// [Regex::captures_input()] with [`RegexInput`].
    ///
    pub fn captures_from_pos<'t, S: input::Input + ?Sized>(
        &self,
        text: &'t S,
        pos: usize,
    ) -> Result<Option<Captures<'t, S>>> {
        self.captures_input(RegexInput::new(text).from_pos(pos))
    }

    pub(crate) fn captures_input_with_option_flags<'t, S: input::Input + ?Sized>(
        &self,
        input: &RegexInput<'t, S>,
        option_flags: u32,
    ) -> Result<Option<Captures<'t, S>>> {
        self.captures_input_cached(input, option_flags, None)
    }

    pub(crate) fn captures_input_cached<'t, S: input::Input + ?Sized>(
        &self,
        input: &RegexInput<'t, S>,
        option_flags: u32,
        mut cache: Option<&mut searcher::Cache>,
    ) -> Result<Option<Captures<'t, S>>> {
        if input.is_done() {
            return Ok(None);
        }
        let named_groups = self.named_groups.clone();
        let haystack = input.haystack();
        let route = self.regular_route(input);
        let routed = |locations: Option<RaCaptures>| {
            locations.map(|locations| Captures {
                inner: CapturesImpl::Wrap {
                    locations,
                    explicit_capture_group_0: false,
                },
                named_groups: named_groups.clone(),
                input: haystack,
            })
        };
        if let Some(locations) = route
            .and_then(RouteEngine::plan)
            .and_then(|plan| plan.captures(&plan_input(input)))
        {
            return Ok(routed(locations));
        }
        let route = route.and_then(RouteEngine::automata);
        if let Some(route) = route
            && let Some(regex) = route.regex()
            && let Ok(found) = route.find(
                &ra_input(input),
                cache.as_deref_mut().and_then(|cache| cache.route(route)),
            )
        {
            let locations = found.and_then(|(start, end)| {
                let span = ra_input(input).span(start..end).anchored(RaAnchored::Yes);
                regular_captures(
                    regex,
                    &span,
                    cache.and_then(|cache| cache.route_meta(route)),
                )
            });
            return Ok(routed(locations));
        }
        match &self.inner {
            RegexImpl::Wrap {
                engine: WrapEngine::Plan(plan),
                explicit_capture_group_0,
                ..
            } => {
                let mut locations = plan.create_captures();
                plan_captures_into(plan, input, &mut locations);
                Ok(locations.is_match().then_some(Captures {
                    inner: CapturesImpl::Wrap {
                        locations,
                        explicit_capture_group_0: *explicit_capture_group_0,
                    },
                    named_groups,
                    input: haystack,
                }))
            }
            RegexImpl::Wrap {
                engine: WrapEngine::Meta(inner),
                explicit_capture_group_0,
                ..
            } => {
                // find_not_empty patterns are always compiled as Fancy, so find_not_empty is
                // always false here.
                let explicit = *explicit_capture_group_0;
                let locations = regular_captures(
                    inner,
                    &ra_input(input),
                    cache.and_then(searcher::Cache::regular),
                );
                Ok(locations.map(|locations| Captures {
                    inner: CapturesImpl::Wrap {
                        locations,
                        explicit_capture_group_0: explicit,
                    },
                    named_groups,
                    input: haystack,
                }))
            }
            RegexImpl::Fancy {
                prog,
                n_groups,
                options,
                ..
            } => {
                let option_flags = option_flags
                    | if options.find_not_empty {
                        OPTION_FIND_NOT_EMPTY
                    } else {
                        0
                    };
                let result = match cache.as_deref_mut().and_then(searcher::Cache::rich) {
                    Some(scratch) => vm::run_cached(prog, input, option_flags, options, scratch),
                    None => vm::run(prog, input, option_flags, options),
                };
                let result = match result {
                    Err(error) => match limit_recovery(route, &error) {
                        Some((route, regex)) => {
                            let meta = cache.and_then(|cache| cache.route_meta(route));
                            return Ok(routed(regular_captures(regex, &ra_input(input), meta)));
                        }
                        None => return Err(error),
                    },
                    Ok(result) => result,
                };
                Ok(result.map(|mut saves| {
                    saves.truncate(n_groups * 2);
                    Captures {
                        inner: CapturesImpl::Fancy { saves },
                        named_groups,
                        input: haystack,
                    }
                }))
            }
        }
    }

    /// A regular over-approximation of the pattern, as `RegexSet` membership
    /// tests use. A program only keeps the seek approximation it seeks with, so
    /// any other is derived again from the pattern, exactly as compiling did.
    pub(crate) fn seek_pattern(&self) -> Result<Cow<'_, str>> {
        match &self.inner {
            RegexImpl::Wrap {
                delegated_pattern, ..
            } => Ok(Cow::Borrowed(delegated_pattern)),
            RegexImpl::Fancy {
                prog,
                pattern,
                flags,
                options,
                ..
            } => match prog.seek_pattern() {
                Some(seek_pattern) => Ok(Cow::Borrowed(seek_pattern)),
                None => {
                    let mut tree = Expr::parse_tree_with_flags(pattern, *flags)?;
                    let (_, context) = prepare_tree(&mut tree, options);
                    let info = analyze(&tree, context)?;
                    Ok(Cow::Owned(compile::seek_pattern_of(&info)))
                }
            },
        }
    }

    /// Returns the number of captures, including the implicit capture of the entire expression.
    pub fn captures_len(&self) -> usize {
        match &self.inner {
            RegexImpl::Wrap {
                engine,
                explicit_capture_group_0,
                ..
            } => engine.captures_len() - if *explicit_capture_group_0 { 1 } else { 0 },
            RegexImpl::Fancy { n_groups, .. } => *n_groups,
        }
    }

    /// Create empty caller-owned capture storage for this regex, to be filled
    /// by [`Searcher::captures_read`].
    pub fn capture_locations(&self) -> CaptureLocations {
        let slots = match &self.inner {
            RegexImpl::Wrap {
                engine,
                explicit_capture_group_0,
                ..
            } => CapturesImpl::Wrap {
                locations: engine.create_captures(),
                explicit_capture_group_0: *explicit_capture_group_0,
            },
            RegexImpl::Fancy { n_groups, .. } => CapturesImpl::Fancy {
                saves: Vec::with_capacity(n_groups * 2),
            },
        };
        CaptureLocations {
            slots,
            groups: self.captures_len(),
            named_groups: Arc::clone(&self.named_groups),
        }
    }

    /// Fill `locations` from one search, returning whether it matched. Storage
    /// from another regex is replaced first; misses and errors clear it.
    pub(crate) fn captures_read_cached<S: input::Input + ?Sized>(
        &self,
        input: &RegexInput<'_, S>,
        locations: &mut CaptureLocations,
        cache: Option<&mut searcher::Cache>,
    ) -> Result<bool> {
        if !Arc::ptr_eq(&locations.named_groups, &self.named_groups) {
            *locations = self.capture_locations();
        }
        if input.is_done() {
            locations.clear();
            return Ok(false);
        }
        self.captures_into(input, 0, &mut locations.slots, cache)
    }

    /// Fill `slots`, storage from [`Regex::capture_locations`], from one
    /// search of `input`, which must not be done, returning whether it
    /// matched. `option_flags` are those of an iteration's later searches.
    fn captures_into<S: input::Input + ?Sized>(
        &self,
        input: &RegexInput<'_, S>,
        option_flags: u32,
        slots: &mut CapturesImpl,
        mut cache: Option<&mut searcher::Cache>,
    ) -> Result<bool> {
        let route = self.regular_route(input);
        if let (Some(plan), CapturesImpl::Fancy { saves }) =
            (route.and_then(RouteEngine::plan), &mut *slots)
        {
            saves.clear();
            saves.resize(plan.slot_len(), usize::MAX);
            match plan.find(&plan_input(input), Some(&mut saves[..])) {
                Some(Some(_)) => return Ok(true),
                Some(None) => {
                    saves.clear();
                    return Ok(false);
                }
                // The automata and the VM below refill `saves`.
                None => {}
            }
        }
        let route = route.and_then(RouteEngine::automata);
        if let (Some(route), CapturesImpl::Fancy { saves }) = (route, &mut *slots)
            && let Some(regex) = route.regex()
            && let Ok(found) = route.find(
                &ra_input(input),
                cache.as_deref_mut().and_then(|cache| cache.route(route)),
            )
        {
            let Some((start, end)) = found else {
                saves.clear();
                return Ok(false);
            };
            let span = ra_input(input).span(start..end).anchored(RaAnchored::Yes);
            let meta = cache.and_then(|cache| cache.route_meta(route));
            return Ok(regular_captures_into(regex, &span, meta, saves));
        }
        match (&self.inner, slots) {
            (
                RegexImpl::Wrap {
                    engine: WrapEngine::Plan(plan),
                    ..
                },
                CapturesImpl::Wrap { locations, .. },
            ) => {
                plan_captures_into(plan, input, locations);
                Ok(locations.is_match())
            }
            (
                RegexImpl::Wrap {
                    engine: WrapEngine::Meta(inner),
                    ..
                },
                CapturesImpl::Wrap { locations, .. },
            ) => {
                let delegated_input = ra_input(input);
                match cache.and_then(searcher::Cache::regular) {
                    Some((cache, _)) => {
                        inner.search_captures_with(cache, &delegated_input, locations)
                    }
                    None => inner.search_captures(&delegated_input, locations),
                }
                Ok(locations.is_match())
            }
            (
                RegexImpl::Fancy {
                    prog,
                    n_groups,
                    options,
                    ..
                },
                CapturesImpl::Fancy { saves },
            ) => {
                let option_flags = option_flags
                    | if options.find_not_empty {
                        OPTION_FIND_NOT_EMPTY
                    } else {
                        0
                    };
                let scratch = cache.as_deref_mut().and_then(searcher::Cache::rich);
                let found = vm::run_into(
                    prog,
                    input,
                    option_flags,
                    options,
                    scratch,
                    (n_groups * 2, saves),
                );
                // The VM cleared `saves` before it ran, so an error leaves
                // them empty and recovery refills them.
                match found {
                    Err(error) => match limit_recovery(route, &error) {
                        Some((route, regex)) => {
                            let meta = cache.and_then(|cache| cache.route_meta(route));
                            Ok(regular_captures_into(regex, &ra_input(input), meta, saves))
                        }
                        None => Err(error),
                    },
                    found => found,
                }
            }
            // Clones of one regex share its named groups, so their storage
            // always has the matching representation.
            _ => unreachable!("capture locations belong to this regex"),
        }
    }

    /// Returns an iterator over the capture names.
    pub fn capture_names(&self) -> CaptureNames<'_> {
        capture_names_of(&self.named_groups, self.captures_len())
    }

    /// Whether searches run on a plan: the whole pattern's, or the route's of
    /// a pattern that needs the VM only for word boundaries, for the searches
    /// the route takes. For tests and diagnostics, not part of the supported
    /// interface.
    #[doc(hidden)]
    pub fn planned(&self) -> bool {
        match &self.inner {
            RegexImpl::Wrap { engine, .. } => matches!(engine, WrapEngine::Plan(_)),
            RegexImpl::Fancy {
                regular: Some(route),
                ..
            } => route.engine().plan().is_some(),
            RegexImpl::Fancy { .. } => false,
        }
    }

    // for debugging only
    #[doc(hidden)]
    pub fn debug_print(&self, writer: &mut Formatter<'_>) -> fmt::Result {
        match &self.inner {
            RegexImpl::Wrap {
                delegated_pattern,
                explicit_capture_group_0,
                ..
            } => {
                write!(
                    writer,
                    "wrapped Regex {:?}, explicit_capture_group_0: {:}",
                    delegated_pattern, *explicit_capture_group_0
                )
            }
            RegexImpl::Fancy { prog, .. } => prog.debug_print(writer),
        }
    }

    /// Replaces the leftmost-first match with the replacement provided.
    /// The replacement can be a regular string (where `$N` and `$name` are
    /// expanded to match capture groups) or a function that takes the matches'
    /// `Captures` and returns the replaced string.
    ///
    /// If no match is found, then a copy of the string is returned unchanged.
    ///
    /// # Replacement string syntax
    ///
    /// All instances of `$name` in the replacement text is replaced with the
    /// corresponding capture group `name`.
    ///
    /// `name` may be an integer corresponding to the index of the
    /// capture group (counted by order of opening parenthesis where `0` is the
    /// entire match) or it can be a name (consisting of letters, digits or
    /// underscores) corresponding to a named capture group.
    ///
    /// If `name` isn't a valid capture group (whether the name doesn't exist
    /// or isn't a valid index), then it is replaced with the empty string.
    ///
    /// The longest possible name is used. e.g., `$1a` looks up the capture
    /// group named `1a` and not the capture group at index `1`. To exert more
    /// precise control over the name, use braces, e.g., `${1}a`.
    ///
    /// To write a literal `$` use `$$`.
    ///
    /// # Examples
    ///
    /// Note that this function is polymorphic with respect to the replacement.
    /// In typical usage, this can just be a normal string:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    /// let re = Regex::new("[^01]+").unwrap();
    /// assert_eq!(re.replace("1078910", ""), "1010");
    /// ```
    ///
    /// But anything satisfying the `Replacer` trait will work. For example,
    /// a closure of type `|&Captures| -> String` provides direct access to the
    /// captures corresponding to a match. This allows one to access
    /// capturing group matches easily:
    ///
    /// ```rust
    /// # use regexrs::{Regex, Captures};
    /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap();
    /// let result = re.replace("Springsteen, Bruce", |caps: &Captures<'_, str>| {
    ///     format!("{} {}", &caps[2], &caps[1])
    /// });
    /// assert_eq!(result, "Bruce Springsteen");
    /// ```
    ///
    /// But this is a bit cumbersome to use all the time. Instead, a simple
    /// syntax is supported that expands `$name` into the corresponding capture
    /// group. Here's the last example, but using this expansion technique
    /// with named capture groups:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap();
    /// let result = re.replace("Springsteen, Bruce", "$first $last");
    /// assert_eq!(result, "Bruce Springsteen");
    /// ```
    ///
    /// Note that using `$2` instead of `$first` or `$1` instead of `$last`
    /// would produce the same result. To write a literal `$` use `$$`.
    ///
    /// Sometimes the replacement string requires use of curly braces to
    /// delineate a capture group replacement and surrounding literal text.
    /// For example, if we wanted to join two words together with an
    /// underscore:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap();
    /// let result = re.replace("deep fried", "${first}_$second");
    /// assert_eq!(result, "deep_fried");
    /// ```
    ///
    /// Without the curly braces, the capture group name `first_` would be
    /// used, and since it doesn't exist, it would be replaced with the empty
    /// string.
    ///
    /// Finally, sometimes you just want to replace a literal string with no
    /// regard for capturing group expansion. This can be done by wrapping a
    /// byte string with `NoExpand`:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    /// use regexrs::NoExpand;
    ///
    /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap();
    /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last"));
    /// assert_eq!(result, "$2 $last");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if matching fails, for example with
    /// [`RuntimeError::BacktrackLimitExceeded`]. Use [`Regex::try_replace`] to
    /// handle the error instead.
    pub fn replace<'t, R: Replacer>(&self, text: &'t str, rep: R) -> Cow<'t, str> {
        self.replacen(text, 1, rep)
    }

    /// Replaces the leftmost-first match, returning an error instead of
    /// panicking if matching fails.
    ///
    /// The replacement syntax is that of [`Regex::replace`].
    ///
    /// # Errors
    ///
    /// Returns the first matching error, such as
    /// [`RuntimeError::BacktrackLimitExceeded`]; no partial result is returned.
    ///
    /// ```rust
    /// # use regexrs::{Captures, Regex};
    /// let re = Regex::new(r"(?<last>[^,\s]+),\s+(?<first>\S+)")?;
    /// let swapped = re.try_replace("Springsteen, Bruce", |caps: &Captures| {
    ///     format!("{} {}", &caps["first"], &caps["last"])
    /// })?;
    /// assert_eq!(swapped, "Bruce Springsteen");
    /// # Ok::<(), regexrs::Error>(())
    /// ```
    pub fn try_replace<'t, R: Replacer>(&self, text: &'t str, rep: R) -> Result<Cow<'t, str>> {
        self.try_replacen(text, 1, rep)
    }

    /// Replaces all non-overlapping matches in `text` with the replacement
    /// provided. This is the same as calling `replacen` with `limit` set to
    /// `0`.
    ///
    /// See the documentation for `replace` for details on how to access
    /// capturing group matches in the replacement string.
    ///
    /// # Panics
    ///
    /// Panics if matching fails; use [`Regex::try_replace_all`] to handle the
    /// error instead.
    pub fn replace_all<'t, R: Replacer>(&self, text: &'t str, rep: R) -> Cow<'t, str> {
        self.replacen(text, 0, rep)
    }

    /// Replaces all non-overlapping matches, returning an error instead of
    /// panicking if matching fails.
    ///
    /// # Errors
    ///
    /// Returns the first matching error, such as
    /// [`RuntimeError::BacktrackLimitExceeded`]; no partial result is returned.
    ///
    /// ```rust
    /// # use regexrs::{Error, RegexBuilder, RuntimeError};
    /// let re = RegexBuilder::new(r"(a+)+\1$").backtrack_limit(100).build()?;
    /// assert!(matches!(
    ///     re.try_replace_all("aaaaaaaaaaaaaaaaaaaa!", ""),
    ///     Err(Error::RuntimeError(RuntimeError::BacktrackLimitExceeded))
    /// ));
    /// # Ok::<(), regexrs::Error>(())
    /// ```
    pub fn try_replace_all<'t, R: Replacer>(&self, text: &'t str, rep: R) -> Result<Cow<'t, str>> {
        self.try_replacen(text, 0, rep)
    }

    /// Replaces at most `limit` non-overlapping matches in `text` with the
    /// replacement provided. If `limit` is 0, then all non-overlapping matches
    /// are replaced.
    ///
    /// # Panics
    ///
    /// Panics if matching fails. Use [`Regex::try_replacen`], which this
    /// function unwraps, to handle the error instead.
    ///
    /// See the documentation for `replace` for details on how to access
    /// capturing group matches in the replacement string.
    ///
    pub fn replacen<'t, R: Replacer>(&self, text: &'t str, limit: usize, rep: R) -> Cow<'t, str> {
        self.try_replacen(text, limit, rep).unwrap()
    }

    /// Replaces at most `limit` non-overlapping matches in `text` with the
    /// replacement provided. If `limit` is 0, then all non-overlapping matches
    /// are replaced.
    ///
    /// Propagates any errors encountered, such as `RuntimeError::BacktrackLimitExceeded`.
    ///
    /// See the documentation for `replace` for details on how to access
    /// capturing group matches in the replacement string.
    pub fn try_replacen<'t, R: Replacer>(
        &self,
        text: &'t str,
        limit: usize,
        rep: R,
    ) -> Result<Cow<'t, str>> {
        replacen_with(
            text,
            limit,
            rep,
            || self.find_iter(text),
            || Captures {
                inner: self.capture_locations().slots,
                named_groups: Arc::clone(&self.named_groups),
                input: text,
            },
            |input, flags, slots| self.captures_into(input, flags, slots, None),
        )
    }

    /// Splits the string by matches of the regex.
    ///
    /// Returns an iterator over the substrings of the target string
    ///  that *aren't* matched by the regex.
    ///
    /// # Example
    ///
    /// To split a string delimited by arbitrary amounts of spaces or tabs:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    /// let re = Regex::new(r"[ \t]+").unwrap();
    /// let target = "a b \t  c\td    e";
    /// let fields: Vec<&str> = re.split(target).map(|x| x.unwrap()).collect();
    /// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]);
    /// ```
    pub fn split<'r, 'h>(&'r self, target: &'h str) -> Split<'r, 'h> {
        Split {
            matches: self.find_iter(target),
            next_start: 0,
            target,
        }
    }

    /// Splits the string by matches of the regex at most `limit` times.
    ///
    /// Returns an iterator over the substrings of the target string
    /// that *aren't* matched by the regex.
    ///
    /// The `N`th substring is the remaining part of the target.
    ///
    /// # Example
    ///
    /// To split a string delimited by arbitrary amounts of spaces or tabs
    /// 3 times:
    ///
    /// ```rust
    /// # use regexrs::Regex;
    /// let re = Regex::new(r"[ \t]+").unwrap();
    /// let target = "a b \t  c\td    e";
    /// let fields: Vec<&str> = re.splitn(target, 3).map(|x| x.unwrap()).collect();
    /// assert_eq!(fields, vec!["a", "b", "c\td    e"]);
    /// ```
    pub fn splitn<'r, 'h>(&'r self, target: &'h str, limit: usize) -> SplitN<'r, 'h> {
        SplitN {
            splits: self.split(target),
            limit,
        }
    }
}

/// `Display` adapter that prints a [`Regex`]'s internal representation via
/// [`Regex::debug_print`]. Intended for debugging and test output only.
#[doc(hidden)]
#[derive(Debug)]
#[allow(dead_code)]
pub struct DebugRegex<'a>(pub &'a Regex);

impl fmt::Display for DebugRegex<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.0.debug_print(f)
    }
}

/// Optimize a parsed tree as compiling does and return whether capture group
/// zero needs fixing up, with the matching analysis context.
fn prepare_tree(tree: &mut ExprTree, runtime: &HardRegexRuntimeOptions) -> (bool, AnalyzeContext) {
    let requires_capture_group_fixup = if runtime.find_not_empty {
        // if the find_not_empty flag is set, we skip optimizations
        // partially because we have to go though the VM anyway
        // partially because having the last instruction of the expression not have
        // ix be at the end of capture group 0 ruins our empty match checking logic.
        false
    } else {
        // try to optimize the expression tree so that a hard pattern could become easy
        // with a fixup of the capture groups
        optimize(tree)
    };
    let context = AnalyzeContext {
        explicit_capture_group_0: requires_capture_group_fixup,
        find_not_empty: runtime.find_not_empty,
        disallow_empty_match_at_eof_after_newline: runtime
            .disallow_empty_match_at_eof_after_newline,
        allow_input_assertion_overrides: runtime.allow_input_assertion_overrides,
    };
    (requires_capture_group_fixup, context)
}

/// A route to automata for a pattern whose only constructs outside the
/// regular subset are word boundaries, or `None`. Word boundaries translate
/// to the Unicode look-around definitions the VM tests (see `to_hir`); any
/// construct, option or translation the regular engine cannot take keeps the
/// VM alone, as do automata that exceed the configured size limits.
fn word_boundary_automata(
    expr: &Expr,
    options: &RegexOptions,
    n_groups: usize,
) -> Option<RegularRoute> {
    if regular::rich_option(options).is_some() || regular::rich_construct(expr).is_some() {
        return None;
    }
    let unicode = options.syntaxc.get_unicode() && !matches!(options.bytes_mode, BytesMode::Ascii);
    let utf8 = matches!(options.bytes_mode, BytesMode::Unicode);
    let hir = to_hir::expr_to_hir(expr, &mut to_hir::HirCtx::new(unicode, utf8))
        .filter(|hir| hir.properties().explicit_captures_len() + 1 == n_groups)?;
    let compile_options = CompileOptions {
        bytes_mode: options.bytes_mode,
        unicode,
        delegate_size_limit: options.delegate_size_limit,
        delegate_dfa_size_limit: options.delegate_dfa_size_limit,
        ..CompileOptions::default()
    };
    let usage = if options.delegate_prefilter {
        compile::DelegateUsage::unanchored()
    } else {
        compile::DelegateUsage::unanchored_no_prefilter()
    };
    let ascii = matches!(options.bytes_mode, BytesMode::Ascii);
    Some(RegularRoute::new(hir, compile_options, usage, ascii, None))
}

/// Whether `expr` is a sequence with a lookaround at an edge, among the
/// assertions there: the shape [`assertion_route`] takes.
fn edge_lookarounds(expr: &Expr) -> bool {
    let Expr::Concat(children) = expr else {
        return false;
    };
    let edge = |child: &Expr| match child {
        Expr::LookAround(..) => Some(true),
        Expr::Assertion(_) => None,
        _ => Some(false),
    };
    children.iter().find_map(edge) == Some(true)
        || children.iter().rev().find_map(edge) == Some(true)
}

/// A route to a plan for a regular pattern between fixed-width lookbehinds
/// at its start and lookaheads at its end, or `None`. It is built from
/// `expr`, the pattern as written, before the optimizer turns a final
/// lookahead into a rewritten capture group zero, so its groups are those
/// `Regex` reports.
fn assertion_route(
    expr: &Expr,
    prog: &Prog,
    options: &RegexOptions,
    n_groups: usize,
) -> Option<RegularRoute> {
    if regular::rich_option(options).is_some() {
        return None;
    }
    let Expr::Concat(children) = expr else {
        return None;
    };
    // Assertions next to the lookarounds test the same position, so they
    // stay with the core, at its edges.
    let edge = |child: &&Expr, kinds: [LookAround; 2]| match child {
        Expr::LookAround(_, kind) => kinds.contains(kind),
        Expr::Assertion(_) => true,
        _ => false,
    };
    let front = children
        .iter()
        .take_while(|child| edge(child, [LookAround::LookBehind, LookAround::LookBehindNeg]))
        .count();
    let back = children[front..]
        .iter()
        .rev()
        .take_while(|child| edge(child, [LookAround::LookAhead, LookAround::LookAheadNeg]))
        .count();
    let is_lookaround = |child: &&Expr| matches!(child, Expr::LookAround(..));
    let (behind, ahead): (Vec<&Expr>, Vec<&Expr>) = (
        children[..front].iter().filter(is_lookaround).collect(),
        children[children.len() - back..]
            .iter()
            .filter(is_lookaround)
            .collect(),
    );
    if behind.len() + ahead.len() == 0 || front + back == children.len() {
        return None;
    }
    // Lookarounds anywhere between the edges stay in the core, which then
    // has a rich construct.
    let middle = &children[front..children.len() - back];
    let core = Expr::Concat(
        children[..front]
            .iter()
            .filter(|child| !is_lookaround(child))
            .chain(middle)
            .chain(
                children[children.len() - back..]
                    .iter()
                    .filter(|child| !is_lookaround(child)),
            )
            .cloned()
            .collect(),
    );
    if regular::rich_construct(&core).is_some() {
        return None;
    }
    let unicode = options.syntaxc.get_unicode() && !matches!(options.bytes_mode, BytesMode::Ascii);
    let utf8 = matches!(options.bytes_mode, BytesMode::Unicode);
    let hir = to_hir::expr_to_hir(&core, &mut to_hir::HirCtx::new(unicode, utf8))
        .filter(|hir| hir.properties().explicit_captures_len() + 1 == n_groups)?;
    let lookaround = |child: &Expr| {
        let Expr::LookAround(body, kind) = child else {
            return None;
        };
        let negated = matches!(kind, LookAround::LookAheadNeg | LookAround::LookBehindNeg);
        let body = to_hir::expr_to_hir(body, &mut to_hir::HirCtx::new(unicode, utf8))?;
        plan::Edge::new(&body, negated)
    };
    let edges = plan::Edges {
        behind: behind.into_iter().map(lookaround).collect::<Option<_>>()?,
        ahead: ahead.into_iter().map(lookaround).collect::<Option<_>>()?,
        prefilter: prog
            .start_filter()
            .and_then(StartFilter::behind_prefilter)
            .map(|(literals, prefilter)| (literals.to_vec(), prefilter.clone())),
    };
    let compile_options = CompileOptions {
        bytes_mode: options.bytes_mode,
        unicode,
        delegate_size_limit: options.delegate_size_limit,
        delegate_dfa_size_limit: options.delegate_dfa_size_limit,
        ..CompileOptions::default()
    };
    let usage = if options.delegate_prefilter {
        compile::DelegateUsage::unanchored()
    } else {
        compile::DelegateUsage::unanchored_no_prefilter()
    };
    let ascii = matches!(options.bytes_mode, BytesMode::Ascii);
    Some(RegularRoute::new(
        hir,
        compile_options,
        usage,
        ascii,
        Some(edges),
    ))
}

/// The route and meta engine that answer a routed search after the VM itself
/// ran and exceeded the default backtrack limit, or `None` for that search to
/// return `error`. Only that error is recovered: the automata cannot exceed a
/// backtrack limit, while a backtrack stack overflow or a delegate's own failure
/// is the VM's to report. Without a route, as with an explicit limit, nothing
/// is recovered.
fn limit_recovery<'r>(
    route: Option<&'r Automata>,
    error: &Error,
) -> Option<(&'r Automata, &'r RaRegex)> {
    if !matches!(
        error,
        Error::RuntimeError(RuntimeError::BacktrackLimitExceeded)
    ) {
        return None;
    }
    let route = route?;
    Some((route, route.regex()?))
}

/// A searcher's cache and capture storage for an ordinary engine.
type RegularCache<'c> = Option<(&'c mut regex_automata::meta::Cache, &'c mut RaCaptures)>;

/// The leftmost-first match span of an ordinary engine, through a searcher's
/// cache when there is one.
#[inline]
fn regular_find(
    regex: &RaRegex,
    input: &RaInput<'_>,
    cache: RegularCache<'_>,
) -> Option<(usize, usize)> {
    match cache {
        Some((cache, _)) => regex.search_with(cache, input),
        None => regex.search(input),
    }
    .map(|found| (found.start(), found.end()))
}

/// Fill VM-layout capture slots (start and end per group, `usize::MAX` for a
/// group that did not take part) from an ordinary engine's search, returning
/// whether it matched. `saves` is left empty on a miss.
fn regular_captures_into(
    regex: &RaRegex,
    input: &RaInput<'_>,
    cache: RegularCache<'_>,
    saves: &mut Vec<usize>,
) -> bool {
    let fill = |locations: &RaCaptures, saves: &mut Vec<usize>| {
        saves.clear();
        if locations.is_match() {
            for group in 0..locations.group_len() {
                let span = locations.get_group(group);
                saves.push(span.map_or(usize::MAX, |span| span.start));
                saves.push(span.map_or(usize::MAX, |span| span.end));
            }
        }
    };
    match cache {
        Some((cache, locations)) => {
            regex.search_captures_with(cache, input, locations);
            fill(locations, saves);
        }
        None => {
            let mut locations = regex.create_captures();
            regex.search_captures(input, &mut locations);
            fill(&locations, saves);
        }
    }
    !saves.is_empty()
}

/// An owned snapshot of an ordinary engine's captures, filled through a
/// searcher's cache and storage when there are some.
fn regular_captures(
    regex: &RaRegex,
    input: &RaInput<'_>,
    cache: RegularCache<'_>,
) -> Option<RaCaptures> {
    match cache {
        Some((cache, locations)) => {
            regex.search_captures_with(cache, input, locations);
            locations.is_match().then(|| locations.clone())
        }
        None => {
            let mut locations = regex.create_captures();
            regex.search_captures(input, &mut locations);
            locations.is_match().then_some(locations)
        }
    }
}

/// The names of `len` capture groups, `None` for unnamed groups.
fn capture_names_of(named_groups: &NamedGroups, len: usize) -> CaptureNames<'_> {
    let mut names = Vec::new();
    names.resize(len, None);
    for (name, &i) in named_groups.iter() {
        names[i] = Some(name.as_str());
    }
    CaptureNames(names.into_iter())
}

/// Shared body of the replacement methods. `matches` starts an iteration
/// over `text`. `fill` writes one search's captures into storage that
/// `captures` creates and every match reuses: a replacer only borrows each
/// match's captures, so it cannot keep one that a later search overwrites.
fn replacen_with<'t, R, E, M>(
    text: &'t str,
    limit: usize,
    mut rep: R,
    matches: impl FnOnce() -> M,
    captures: impl FnOnce() -> Captures<'t, str>,
    mut fill: impl FnMut(&RegexInput<'t, str>, u32, &mut CapturesImpl) -> core::result::Result<bool, E>,
) -> core::result::Result<Cow<'t, str>, E>
where
    R: Replacer,
    M: Iterator<Item = core::result::Result<Match<'t>, E>>,
{
    // If we know that the replacement doesn't have any capture expansions,
    // then we can fast path. The fast path can make a tremendous
    // difference:
    //
    //   1) We use `find_iter` instead of `captures_iter`. Not asking for
    //      captures generally makes the regex engines faster.
    //   2) We don't need to look up all of the capture groups and do
    //      replacements inside the replacement string. We just push it
    //      at each match and be done with it.
    if let Some(rep) = rep.no_expansion() {
        let mut it = matches().enumerate().peekable();
        if it.peek().is_none() {
            return Ok(Cow::Borrowed(text));
        }
        let mut new = String::with_capacity(text.len());
        let mut last_match = 0;
        for (i, m) in it {
            let m = m?;

            if limit > 0 && i >= limit {
                break;
            }
            new.push_str(&text[last_match..m.start()]);
            new.push_str(&rep);
            last_match = m.end();
        }
        new.push_str(&text[last_match..]);
        return Ok(Cow::Owned(new));
    }

    // The slower path, which we use if the replacement needs access to
    // capture groups.
    let mut captures = captures();
    let mut state = IterState::new(RegexInput::new(text));
    let mut new = None;
    let mut last_match = 0;
    for i in 0.. {
        let found = state.next_with(|input, flags| {
            let matched = fill(input, flags, &mut captures.inner)?;
            Ok(matched.then(|| {
                let span = captures.inner.get_span(0);
                let span = span.expect("captures only report matches");
                (span, span)
            }))
        });
        let Some(found) = found else {
            break;
        };
        let (start, end) = found?;

        if limit > 0 && i >= limit {
            break;
        }
        let new = new.get_or_insert_with(|| String::with_capacity(text.len()));
        new.push_str(&text[last_match..start]);
        rep.replace_append(&captures, new);
        last_match = end;
    }
    Ok(match new {
        Some(mut new) => {
            new.push_str(&text[last_match..]);
            Cow::Owned(new)
        }
        None => Cow::Borrowed(text),
    })
}

/// The `regex-automata` input for a search: same haystack, range, start and
/// anchoring, so every entry point of an ordinary pattern agrees.
#[inline]
fn ra_input<'a, S: input::Input + ?Sized>(input: &'a RegexInput<'a, S>) -> RaInput<'a> {
    let mut ra_input = RaInput::new(input.haystack().as_bytes()).range(input.get_range());
    ra_input.set_start(input.effective_start());
    if input.is_anchored() {
        ra_input.set_anchored(RaAnchored::Yes);
    }
    ra_input
}

/// The most capture slots a plan for a pattern with a rewritten capture
/// group zero may have, so that a search for its span needs no allocation.
const FIXUP_SLOTS: usize = 32;

/// Where a plan searches `input`, which must not be done: the same
/// span and anchoring as [`ra_input`].
fn plan_input<'h, S: input::Input + ?Sized>(input: &RegexInput<'h, S>) -> PlanInput<'h> {
    let haystack = input.haystack();
    PlanInput {
        haystack: haystack.as_bytes(),
        start: input.effective_start(),
        end: input.get_range().end,
        anchored: input.is_anchored(),
        utf8: haystack.as_utf8().is_some(),
    }
}

/// A plan's leftmost-first span in `input`, which must not be done.
fn plan_find<S: input::Input + ?Sized>(
    plan: &Plan,
    input: &RegexInput<'_, S>,
    slots: Option<&mut [Option<NonMaxUsize>]>,
) -> Option<(usize, usize)> {
    plan.find(&plan_input(input), slots)
}

/// The span of a plan for a pattern whose final lookahead the optimizer
/// consumed: group 1 holds the match. Kept out of line, so that the common
/// search keeps its small frame.
#[inline(never)]
fn plan_find_rewritten<S: input::Input + ?Sized>(
    plan: &Plan,
    input: &RegexInput<'_, S>,
) -> Option<(usize, usize)> {
    let mut slots = [usize::MAX; FIXUP_SLOTS];
    let found = plan.find(&plan_input(input), Some(&mut slots[..plan.slot_len()]));
    found.and((slots[2] != usize::MAX).then_some((slots[2], slots[3])))
}

/// Whether a plan matches in `input`, which must not be done.
fn plan_is_match<S: input::Input + ?Sized>(plan: &Plan, input: &RegexInput<'_, S>) -> bool {
    plan.is_match(&plan_input(input))
}

/// Fill regex-automata capture storage from a plan's search.
fn plan_captures_into<S: input::Input + ?Sized>(
    plan: &Plan,
    input: &RegexInput<'_, S>,
    locations: &mut RaCaptures,
) {
    let found = plan_find(plan, input, Some(locations.slots_mut())).is_some();
    locations.set_pattern(found.then_some(regex_automata::PatternID::ZERO));
}

impl TryFrom<&str> for Regex {
    type Error = Error;

    /// Attempts to parse a string into a regular expression
    fn try_from(s: &str) -> Result<Self> {
        Self::new(s)
    }
}

impl TryFrom<String> for Regex {
    type Error = Error;

    /// Attempts to parse a string into a regular expression
    fn try_from(s: String) -> Result<Self> {
        Self::new(&s)
    }
}

impl<'t> Match<'t> {
    /// Returns the starting byte offset of the match in the text.
    #[inline]
    pub fn start(&self) -> usize {
        self.start
    }

    /// Returns the ending byte offset of the match in the text.
    #[inline]
    pub fn end(&self) -> usize {
        self.end
    }

    /// Returns the range over the starting and ending byte offsets of the match in text.
    #[inline]
    pub fn range(&self) -> Range<usize> {
        self.start..self.end
    }

    /// Returns the matched text.
    #[inline]
    pub fn as_str(&self) -> &'t str {
        &self.text[self.start..self.end]
    }

    /// Creates a new match from the given text and byte offsets.
    pub(crate) fn new(text: &'t str, start: usize, end: usize) -> Match<'t> {
        Match { text, start, end }
    }
}

impl<'t> From<Match<'t>> for &'t str {
    fn from(m: Match<'t>) -> &'t str {
        m.as_str()
    }
}

impl<'t> From<Match<'t>> for Range<usize> {
    fn from(m: Match<'t>) -> Range<usize> {
        m.range()
    }
}

#[allow(clippy::len_without_is_empty)] // follow regex's API
impl<'t, S: input::Input + ?Sized> Captures<'t, S> {
    pub(crate) fn get_span(&self, i: usize) -> Option<(usize, usize)> {
        self.inner.get_span(i)
    }

    /// Get the capture group by its index in the regex.
    ///
    /// If there is no match for that group or the index does not correspond to a group, `None` is
    /// returned. The index 0 returns the whole match.
    pub fn get(&self, i: usize) -> Option<S::Match<'t>> {
        self.inner
            .get_span(i)
            .map(|(start, end)| self.input.make_match(start, end))
    }

    /// Returns the match for a named capture group.  Returns `None` the capture
    /// group did not match or if there is no group with the given name.
    pub fn name(&self, name: &str) -> Option<S::Match<'t>> {
        self.named_groups.get(name).and_then(|i| self.get(*i))
    }

    /// Iterate over the captured groups in order in which they appeared in the regex. The first
    /// capture corresponds to the whole match.
    pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 't, S> {
        SubCaptureMatches { data: self, i: 0 }
    }

    /// How many groups were captured. This is always at least 1 because group 0 returns the whole
    /// match.
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns the byte slice of the entire input that was searched.
    pub fn input_as_bytes(&self) -> &'t [u8] {
        self.input.as_bytes()
    }
}

// str-only methods
impl<'t> Captures<'t, str> {
    /// Expands all instances of `$group` in `replacement` to the corresponding
    /// capture group `name`, and writes them to the `dst` buffer given.
    ///
    /// `group` may be an integer corresponding to the index of the
    /// capture group (counted by order of opening parenthesis where `\0` is the
    /// entire match) or it can be a name (consisting of letters, digits or
    /// underscores) corresponding to a named capture group.
    ///
    /// If `group` isn't a valid capture group (whether the name doesn't exist
    /// or isn't a valid index), then it is replaced with the empty string.
    ///
    /// The longest possible name is used. e.g., `$1a` looks up the capture
    /// group named `1a` and not the capture group at index `1`. To exert more
    /// precise control over the name, use braces, e.g., `${1}a`.
    ///
    /// To write a literal `$`, use `$$`.
    ///
    /// For more control over expansion, see [`Expander`].
    ///
    /// [`Expander`]: expand/struct.Expander.html
    pub fn expand(&self, replacement: &str, dst: &mut String) {
        Expander::default().append_expansion(dst, replacement, self);
    }
}

/// Get a group by index.
///
/// `'t` is the lifetime of the matched text.
///
/// The text can't outlive the `Captures` object if this method is
/// used, because of how `Index` is defined (normally `a[i]` is part
/// of `a` and can't outlive it); to do that, use `get()` instead.
///
/// # Panics
///
/// If there is no group at the given index.
impl<'t> Index<usize> for Captures<'t, str> {
    type Output = str;

    fn index(&self, i: usize) -> &str {
        self.get(i)
            .map(|m| m.as_str())
            .unwrap_or_else(|| panic!("no group at index '{}'", i))
    }
}

/// Get a group by name.
///
/// `'t` is the lifetime of the matched text and `'i` is the lifetime
/// of the group name (the index).
///
/// The text can't outlive the `Captures` object if this method is
/// used, because of how `Index` is defined (normally `a[i]` is part
/// of `a` and can't outlive it); to do that, use `name` instead.
///
/// # Panics
///
/// If there is no group named by the given value.
impl<'t, 'i> Index<&'i str> for Captures<'t, str> {
    type Output = str;

    fn index<'a>(&'a self, name: &'i str) -> &'a str {
        self.name(name)
            .map(|m| m.as_str())
            .unwrap_or_else(|| panic!("no group named '{}'", name))
    }
}

impl<'c, 't, S: input::Input + ?Sized> Iterator for SubCaptureMatches<'c, 't, S> {
    type Item = Option<S::Match<'t>>;

    fn next(&mut self) -> Option<Option<S::Match<'t>>> {
        if self.i < self.data.len() {
            let result = self.data.get(self.i);
            self.i += 1;
            Some(result)
        } else {
            None
        }
    }
}

// TODO: might be nice to implement ExactSizeIterator etc for SubCaptures

/// Regular expression AST. This is public for now but may change.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Expr {
    /// An empty expression, e.g. the last branch in `(a|b|)`
    Empty,
    /// Any character, regex `.`
    Any {
        /// Whether it also matches newlines or not
        newline: bool,
        /// Whether CRLF mode is enabled (`\r` also counts as a newline, so dot
        /// excludes both `\r` and `\n`)
        crlf: bool,
    },
    /// An assertion
    Assertion(Assertion),
    /// General newline sequence, `\R`
    /// Matches `\r\n` or any single newline character (\n, \v, \f, \r)
    /// In Unicode mode, also matches U+0085, U+2028, U+2029
    GeneralNewline {
        /// Whether Unicode mode is enabled
        unicode: bool,
    },
    /// The string as a literal, e.g. `a`
    Literal {
        /// The string to match
        val: String,
        /// Whether match is case-insensitive or not
        casei: bool,
    },
    /// Concatenation of multiple expressions, must match in order, e.g. `a.` is a concatenation of
    /// the literal `a` and `.` for any character
    Concat(Vec<Expr>),
    /// Alternative of multiple expressions, one of them must match, e.g. `a|b` is an alternative
    /// where either the literal `a` or `b` must match
    Alt(Vec<Expr>),
    /// Capturing group of expression, e.g. `(a.)` matches `a` and any character and "captures"
    /// (remembers) the match
    Group(Arc<Expr>),
    /// Look-around (e.g. positive/negative look-ahead or look-behind) with an expression, e.g.
    /// `(?=a)` means the next character must be `a` (but the match is not consumed)
    LookAround(Box<Expr>, LookAround),
    /// Repeat of an expression, e.g. `a*` or `a+` or `a{1,3}`
    Repeat {
        /// The expression that is being repeated
        child: Box<Expr>,
        /// The minimum number of repetitions
        lo: usize,
        /// The maximum number of repetitions (or `usize::MAX`)
        hi: usize,
        /// Greedy means as much as possible is matched, e.g. `.*b` would match all of `abab`.
        /// Non-greedy means as little as possible, e.g. `.*?b` would match only `ab` in `abab`.
        greedy: bool,
    },
    /// Delegate a regex to the regex crate. This is used as a simplification so that we don't have
    /// to represent all the expressions in the AST, e.g. character classes.
    ///
    /// **Constraint**: All Delegate expressions must match exactly 1 character. This ensures
    /// consistent analysis and compilation behavior. For zero-width or multi-character patterns,
    /// use the appropriate Expr variants instead (e.g., Assertion, Repeat, Concat).
    Delegate {
        /// The regex
        inner: String,
        /// Whether the matching is case-insensitive or not
        casei: bool,
    },
    /// Back reference to a capture group, e.g. `\1` in `(abc|def)\1` references the captured group
    /// and the whole regex matches either `abcabc` or `defdef`.
    Backref {
        /// The capture group number being referenced
        group: usize,
        /// Whether the matching is case-insensitive or not
        casei: bool,
    },
    /// Back reference to a capture group at the given specified relative recursion level.
    BackrefWithRelativeRecursionLevel {
        /// The capture group number being referenced
        group: usize,
        /// Relative recursion level
        relative_level: isize,
        /// Whether the matching is case-insensitive or not
        casei: bool,
    },
    /// Atomic non-capturing group, e.g. `(?>ab|a)` in text that contains `ab` will match `ab` and
    /// never backtrack and try `a`, even if matching fails after the atomic group.
    AtomicGroup(Box<Expr>),
    /// Keep matched text so far out of overall match
    KeepOut,
    /// Anchor to match at the position where the previous match ended
    ContinueFromPreviousMatchEnd,
    /// Conditional expression based on whether the numbered capture group matched or not.
    /// The optional `relative_recursion_level` qualifies which recursion level's capture is
    /// tested (Oniguruma `(?(name+N)...)` syntax).
    BackrefExistsCondition {
        /// The resolved capture group number
        group: usize,
        /// Optional relative recursion level (e.g. `+0`, `-1`)
        relative_recursion_level: Option<isize>,
    },
    /// If/Then/Else Condition. If there is no Then/Else, these will just be empty expressions.
    Conditional {
        /// The conditional expression to evaluate
        condition: Box<Expr>,
        /// What to execute if the condition is true
        true_branch: Box<Expr>,
        /// What to execute if the condition is false
        false_branch: Box<Expr>,
    },
    /// Subroutine call to the specified group number
    SubroutineCall(usize),
    /// Backtracking control verb
    BacktrackingControlVerb(BacktrackingControlVerb),
    /// Match while the given expression is absent from the haystack
    Absent(Absent),
    /// DEFINE group - defines capture groups for subroutines without matching anything
    /// The expressions inside are parsed and assigned group numbers, but no VM instructions
    /// are generated for the DEFINE block itself.
    DefineGroup {
        /// The expressions/groups being defined
        definitions: Box<Expr>,
    },
    /// Abstract Syntax Tree node - will be resolved into an Expr before analysis.
    /// Contains the position in the pattern where the node was parsed from
    AstNode(AstNode, usize),
}

/// Target of a backreference or subroutine call
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum CaptureGroupTarget {
    /// Direct numbered reference
    ByNumber(usize),

    /// Named reference
    ByName(String),

    /// Relative reference (e.g., -1, -2, etc.)
    Relative(isize),
}

/// Abstract Syntax Tree node - will be resolved into an Expr before analysis
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum AstNode {
    /// Group with optional name - name is only present if explicitly specified in pattern
    AstGroup {
        /// Optional name of the capture group, present only when explicitly named in the pattern
        name: Option<String>,
        /// The inner expression of the group
        inner: Box<Expr>,
    },
    /// Backreference
    Backref {
        /// The target capture group being referenced
        target: CaptureGroupTarget,
        /// Whether the matching is case-insensitive or not
        // TODO: move out of Backref and prefer a Flags AstNode. The resolver can then track the flags and set casei on the resolved Expr accordingly
        casei: bool,
        /// Optional relative recursion level for the backreference
        relative_recursion_level: Option<isize>,
    },
    /// Subroutine Call
    SubroutineCall(CaptureGroupTarget),
    /// Backreference exists condition `(?(name)...)` or `(?(1)...)` - unresolved target.
    /// The optional `relative_recursion_level` corresponds to the Oniguruma `+N`/`-N` suffix
    /// (e.g. `(?(name+0)...)`) which qualifies which recursion level's capture is tested.
    BackrefExistsCondition {
        /// The target capture group being tested for existence
        target: CaptureGroupTarget,
        /// Optional relative recursion level qualifier (e.g. `+0`, `-1`)
        relative_recursion_level: Option<isize>,
    },
}

/// Type of look-around assertion as used for a look-around expression.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum LookAround {
    /// Look-ahead assertion, e.g. `(?=a)`
    LookAhead,
    /// Negative look-ahead assertion, e.g. `(?!a)`
    LookAheadNeg,
    /// Look-behind assertion, e.g. `(?<=a)`
    LookBehind,
    /// Negative look-behind assertion, e.g. `(?<!a)`
    LookBehindNeg,
}

/// Type of absent operator as used for Oniguruma's absent functionality.
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Absent {
    /// Absent repeater `(?~absent)` - works like `\O*` (match any character including newline, repeated)
    /// but is limited by the range that does not include the string match with `absent`.
    /// This is a written abbreviation of `(?~|absent|\O*)`.
    Repeater(Box<Expr>),
    /// Absent expression `(?~|absent|exp)` - works like `exp`, but is limited by the range
    /// that does not include the string match with `absent`.
    Expression {
        /// The expression to avoid matching
        absent: Box<Expr>,
        /// The expression to match
        exp: Box<Expr>,
    },
    /// Absent stopper `(?~|absent)` - after this operator, haystack range is limited
    /// up to the point where `absent` matches.
    Stopper(Box<Expr>),
    /// Range clear `(?~|)` - clears the effects caused by absent stoppers.
    Clear,
}

/// Type of backtracking control verb which affects how backtracking will behave.
/// See <https://www.regular-expressions.info/verb.html>
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum BacktrackingControlVerb {
    /// Fail this branch immediately
    Fail,
    /// Treat match so far as successful overall match
    Accept,
    /// Abort the entire match on failure
    Commit,
    /// Restart the entire match attempt at the current position
    Skip,
    /// Prune all backtracking states and restart the entire match attempt at the next position
    Prune,
}

/// An iterator over capture names in a [Regex].  The iterator
/// returns the name of each group, or [None] if the group has
/// no name.  Because capture group 0 cannot have a name, the
/// first item returned is always [None].
pub struct CaptureNames<'r>(vec::IntoIter<Option<&'r str>>);

impl Debug for CaptureNames<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("<CaptureNames>")
    }
}

impl<'r> Iterator for CaptureNames<'r> {
    type Item = Option<&'r str>;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

// silly to write my own, but this is super-fast for the common 1-digit
// case.
fn push_usize(s: &mut String, x: usize) {
    if x >= 10 {
        push_usize(s, x / 10);
        s.push((b'0' + (x % 10) as u8) as char);
    } else {
        s.push((b'0' + (x as u8)) as char);
    }
}

/// Emit a repeat quantifier `?`, `*`, `+`, or `{lo,hi}` (optionally non-greedy) into `buf`.
///
/// This is shared between [`Expr::to_str`] and `build_seek_pattern` in the compiler.
pub(crate) fn write_quantifier(buf: &mut String, lo: usize, hi: usize, greedy: bool) {
    match (lo, hi) {
        (0, 1) => buf.push('?'),
        (0, usize::MAX) => buf.push('*'),
        (1, usize::MAX) => buf.push('+'),
        (lo, hi) => {
            buf.push('{');
            push_usize(buf, lo);
            if lo != hi {
                buf.push(',');
                if hi != usize::MAX {
                    push_usize(buf, hi);
                }
            }
            buf.push('}');
        }
    }
    if !greedy {
        buf.push('?');
    }
}

fn is_special(c: char) -> bool {
    matches!(
        c,
        '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '|' | '[' | ']' | '{' | '}' | '^' | '$' | '#'
    )
}

pub(crate) fn push_quoted(buf: &mut String, s: &str) {
    if !s.bytes().any(|b| {
        b == b'\\'
            || b == b'\n'
            || b == b'\t'
            || b == b'\r'
            || matches!(
                b,
                b'.' | b'+'
                    | b'*'
                    | b'?'
                    | b'('
                    | b')'
                    | b'|'
                    | b'['
                    | b']'
                    | b'{'
                    | b'}'
                    | b'^'
                    | b'$'
                    | b'#'
            )
    }) {
        buf.push_str(s);
        return;
    }

    for c in s.chars() {
        match c {
            '\\' => buf.push_str("\\\\"),
            '\n' => buf.push_str("\\n"),
            '\t' => buf.push_str("\\t"),
            '\r' => buf.push_str("\\r"),
            _ => {
                if is_special(c) {
                    buf.push('\\');
                }
                buf.push(c);
            }
        }
    }
}

/// Escapes special characters in `text` with '\\'.  Returns a string which, when interpreted
/// as a regex, matches exactly `text`.
pub fn escape(text: &str) -> Cow<'_, str> {
    // Using bytes() is OK because all special characters are single bytes.
    match text.bytes().filter(|&b| is_special(b as char)).count() {
        0 => Cow::Borrowed(text),
        n => {
            // The capacity calculation is exact because '\\' is a single byte.
            let mut buf = String::with_capacity(text.len() + n);
            push_quoted(&mut buf, text);
            Cow::Owned(buf)
        }
    }
}

/// Type of assertions
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Assertion {
    /// Start of input text
    StartText,
    /// End of input text
    EndText,
    /// End of input text, or before any trailing newlines at the end (Oniguruma's `\Z`)
    EndTextIgnoreTrailingNewlines {
        /// Whether CRLF mode is enabled.
        /// If `true`, trailing `\r\n` pairs (in addition to bare `\n`) are also ignored.
        crlf: bool,
    },
    /// Start of a line
    StartLine {
        /// CRLF mode.
        /// If true, this assertion matches at the starting position of the input text, or at the position immediately
        /// following either a `\r` or `\n` character, but never after a `\r` when a `\n` follows.
        crlf: bool,
    },
    /// Start of a line in Oniguruma mode.
    /// Behaves like [`Assertion::StartLine`], but additionally rejects matches at the end of the input
    /// when it is preceded by a newline.
    StartLineOniguruma {
        /// CRLF mode.
        /// If true, this assertion matches at the starting position of the input text, or at the position immediately
        /// following either a `\r` or `\n` character, but never after a `\r` when a `\n` follows.
        crlf: bool,
    },
    /// End of a line
    EndLine {
        /// CRLF mode
        /// If true, this assertion matches at the ending position of the input text, or at the position immediately
        /// preceding either a `\r` or `\n` character, but never after a `\r` when a `\n` follows.
        crlf: bool,
    },
    /// Left word boundary
    LeftWordBoundary,
    /// Left word half boundary
    LeftWordHalfBoundary,
    /// Right word boundary
    RightWordBoundary,
    /// Right word half boundary
    RightWordHalfBoundary,
    /// Both word boundaries
    WordBoundary,
    /// Not word boundary
    NotWordBoundary,
}

impl Assertion {
    pub(crate) fn is_always_hard(&self) -> bool {
        use Assertion::*;
        matches!(
            self,
            // these will make regex-automata use PikeVM and are not compabible with certain regex-automata features we use
            LeftWordBoundary
                | LeftWordHalfBoundary
                | RightWordBoundary
                | RightWordHalfBoundary
                | WordBoundary
                | NotWordBoundary
                // `\Z` needs custom trailing-newline handling.
                | EndTextIgnoreTrailingNewlines { .. }
        )
    }
}

/// An iterator over the immediate children of an [`Expr`].
///
/// This iterator yields references to child expressions but does not recurse into them.
#[derive(Debug)]
pub enum ExprChildrenIter<'a> {
    /// No children (leaf node)
    Empty,
    /// A single child (Group, LookAround, AtomicGroup, Repeat)
    Single(Option<&'a Expr>),
    /// Multiple children in a Vec (Concat, Alt)
    Vec(alloc::slice::Iter<'a, Expr>),
    /// Three children (Conditional)
    Triple {
        /// First child
        first: Option<&'a Expr>,
        /// Second child
        second: Option<&'a Expr>,
        /// Third child
        third: Option<&'a Expr>,
    },
}

/// An iterator over the immediate children of an [`Expr`] for mutable access.
///
/// This iterator yields mutable references to child expressions but does not recurse into them.
#[derive(Debug)]
pub enum ExprChildrenIterMut<'a> {
    /// No children (leaf node)
    Empty,
    /// A single child (Group, LookAround, AtomicGroup, Repeat)
    Single(Option<&'a mut Expr>),
    /// Multiple children in a Vec (Concat, Alt)
    Vec(alloc::slice::IterMut<'a, Expr>),
    /// Three children (Conditional)
    Triple {
        /// First child
        first: Option<&'a mut Expr>,
        /// Second child
        second: Option<&'a mut Expr>,
        /// Third child
        third: Option<&'a mut Expr>,
    },
}

impl<'a> Iterator for ExprChildrenIter<'a> {
    type Item = &'a Expr;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            ExprChildrenIter::Empty => None,
            ExprChildrenIter::Single(child) => child.take(),
            ExprChildrenIter::Vec(iter) => iter.next(),
            ExprChildrenIter::Triple {
                first,
                second,
                third,
            } => first
                .take()
                .or_else(|| second.take())
                .or_else(|| third.take()),
        }
    }
}

impl<'a> Iterator for ExprChildrenIterMut<'a> {
    type Item = &'a mut Expr;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            ExprChildrenIterMut::Empty => None,
            ExprChildrenIterMut::Single(child) => child.take(),
            ExprChildrenIterMut::Vec(iter) => iter.next(),
            ExprChildrenIterMut::Triple {
                first,
                second,
                third,
            } => first
                .take()
                .or_else(|| second.take())
                .or_else(|| third.take()),
        }
    }
}

macro_rules! children_iter_match {
    ($self:expr, $iter:ident, $vec_method:ident, $single_method:ident, $group_method:ident) => {
        match $self {
            Expr::Concat(children) | Expr::Alt(children) => $iter::Vec(children.$vec_method()),
            Expr::Group(child) => $iter::Single(Some(Arc::$group_method(child))),
            Expr::Absent(Absent::Repeater(child))
            | Expr::Absent(Absent::Stopper(child))
            | Expr::LookAround(child, _)
            | Expr::AtomicGroup(child)
            | Expr::Repeat { child, .. } => $iter::Single(Some(child.$single_method())),
            Expr::Conditional {
                condition,
                true_branch,
                false_branch,
            } => $iter::Triple {
                first: Some(condition.$single_method()),
                second: Some(true_branch.$single_method()),
                third: Some(false_branch.$single_method()),
            },
            Expr::Absent(Absent::Expression { absent, exp }) => $iter::Triple {
                first: Some(absent.$single_method()),
                second: Some(exp.$single_method()),
                third: None,
            },
            Expr::DefineGroup { definitions } => $iter::Single(Some(definitions.$single_method())),
            _ if $self.is_leaf_node() => $iter::Empty,
            _ => unimplemented!(),
        }
    };
}
impl Expr {
    /// Parse the regex and return an expression (AST) and a bit set with the indexes of groups
    /// that are referenced by backrefs.
    pub fn parse_tree(re: &str) -> Result<ExprTree> {
        Expr::parse_tree_with_flags(re, RegexOptions::default().compute_flags())
    }

    /// Parse the regex and return an expression (AST)
    /// Flags should be bit based based on flags
    pub fn parse_tree_with_flags(re: &str, flags: u32) -> Result<ExprTree> {
        Parser::parse_with_flags(re, flags)
    }

    /// Returns `true` if this expression is a leaf node (has no children).
    ///
    /// Leaf nodes include literals, assertions, backreferences, and other atomic expressions.
    /// Non-leaf nodes include groups, concatenations, alternations, and repetitions.
    pub fn is_leaf_node(&self) -> bool {
        matches!(
            self,
            Expr::Empty
                | Expr::Any { .. }
                | Expr::Assertion(_)
                | Expr::GeneralNewline { .. }
                | Expr::Literal { .. }
                | Expr::Delegate { .. }
                | Expr::Backref { .. }
                | Expr::BackrefWithRelativeRecursionLevel { .. }
                | Expr::KeepOut
                | Expr::ContinueFromPreviousMatchEnd
                | Expr::BackrefExistsCondition { .. }
                | Expr::BacktrackingControlVerb(_)
                |             Expr::SubroutineCall(_)
                | Expr::Absent(Absent::Clear)
                // An unresolved AstNode has no separate child Expr to iterate; the resolver
                // should have replaced it before analysis, so treat it as a leaf so that
                // collection/iteration doesn't panic, and let the analyzer emit the error.
                | Expr::AstNode(..),
        )
    }

    /// Returns `true` if any descendant of this expression (not including itself)
    /// satisfies the given predicate.
    ///
    /// This performs an iterative depth-first search using [`children_iter`](Self::children_iter).
    pub fn has_descendant(&self, predicate: impl Fn(&Expr) -> bool) -> bool {
        let mut stack: Vec<&Expr> = self.children_iter().collect();
        while let Some(expr) = stack.pop() {
            if predicate(expr) {
                return true;
            }
            stack.extend(expr.children_iter());
        }
        false
    }

    /// Returns an iterator over the immediate children of this expression.
    ///
    /// For leaf nodes, this returns an empty iterator. For non-leaf nodes, it returns
    /// references to their immediate children (non-recursive).
    pub fn children_iter(&self) -> ExprChildrenIter<'_> {
        children_iter_match!(self, ExprChildrenIter, iter, as_ref, as_ref)
    }

    /// Returns an iterator over the immediate children of this expression for mutable access.
    ///
    /// For leaf nodes, this returns an empty iterator. For non-leaf nodes, it returns
    /// mutable references to their immediate children (non-recursive).
    pub fn children_iter_mut(&mut self) -> ExprChildrenIterMut<'_> {
        children_iter_match!(self, ExprChildrenIterMut, iter_mut, as_mut, make_mut)
    }

    /// Convert expression to a regex string in the regex crate's syntax.
    ///
    /// # Panics
    ///
    /// Panics for expressions that are hard, i.e. can not be handled by the regex crate.
    pub fn to_str(&self, buf: &mut String, precedence: u8) {
        match *self {
            Expr::Empty => (),
            Expr::Any { newline, crlf } => buf.push_str(match (newline, crlf) {
                (true, _) => "(?s:.)",
                (false, true) => "(?R-s:.)",
                (false, false) => ".",
            }),
            Expr::Literal { ref val, casei } => {
                if casei {
                    buf.push_str("(?i:");
                }
                push_quoted(buf, val);
                if casei {
                    buf.push(')');
                }
            }
            Expr::Assertion(Assertion::StartText) => buf.push('^'),
            Expr::Assertion(Assertion::EndText) => buf.push('$'),
            Expr::Assertion(
                Assertion::StartLine { crlf: false }
                | Assertion::StartLineOniguruma { crlf: false },
            ) => buf.push_str("(?m:^)"),
            Expr::Assertion(Assertion::EndLine { crlf: false }) => buf.push_str("(?m:$)"),
            Expr::Assertion(
                Assertion::StartLine { crlf: true } | Assertion::StartLineOniguruma { crlf: true },
            ) => buf.push_str("(?Rm:^)"),
            Expr::Assertion(Assertion::EndLine { crlf: true }) => buf.push_str("(?Rm:$)"),
            Expr::Concat(ref children) => {
                if precedence > 1 {
                    buf.push_str("(?:");
                }
                for child in children {
                    child.to_str(buf, 2);
                }
                if precedence > 1 {
                    buf.push(')')
                }
            }
            Expr::Alt(_) => {
                if precedence > 0 {
                    buf.push_str("(?:");
                }
                let mut children = self.children_iter();
                if let Some(first) = children.next() {
                    first.to_str(buf, 1);
                    for child in children {
                        buf.push('|');
                        child.to_str(buf, 1);
                    }
                }
                if precedence > 0 {
                    buf.push(')');
                }
            }
            Expr::Group(ref child) => {
                buf.push('(');
                child.to_str(buf, 0);
                buf.push(')');
            }
            Expr::Repeat {
                ref child,
                lo,
                hi,
                greedy,
            } => {
                if precedence > 2 {
                    buf.push_str("(?:");
                }
                child.to_str(buf, 3);
                write_quantifier(buf, lo, hi, greedy);
                if precedence > 2 {
                    buf.push(')');
                }
            }
            Expr::Delegate {
                ref inner, casei, ..
            } => {
                // at the moment, delegate nodes are just atoms
                if casei {
                    buf.push_str("(?i:");
                }
                buf.push_str(inner);
                if casei {
                    buf.push(')');
                }
            }
            Expr::DefineGroup { .. } => {
                // DEFINE groups match nothing - output empty string for delegation
            }
            _ => panic!("attempting to format hard expr {:?}", self),
        }
    }
}

// precondition: ix > 0
fn prev_codepoint_ix(s: &str, mut ix: usize) -> usize {
    let bytes = s.as_bytes();
    loop {
        ix -= 1;
        // fancy bit magic for ranges 0..0x80 + 0xc0..
        if (bytes[ix] as i8) >= -0x40 {
            break;
        }
    }
    ix
}

fn codepoint_len(b: u8) -> usize {
    match b {
        b if b < 0x80 => 1,
        b if b < 0xe0 => 2,
        b if b < 0xf0 => 3,
        _ => 4,
    }
}

// If this returns false, then there is no possible backref in the re

// Both potential implementations are turned off, because we currently
// always need to do a deeper analysis because of 1-character
// look-behind. If we could call a find_from_pos method of regex::Regex,
// it would make sense to bring this back.
/*
pub fn detect_possible_backref(re: &str) -> bool {
    let mut last = b'\x00';
    for b in re.as_bytes() {
        if b'0' <= *b && *b <= b'9' && last == b'\\' { return true; }
        last = *b;
    }
    false
}

pub fn detect_possible_backref(re: &str) -> bool {
    let mut bytes = re.as_bytes();
    loop {
        match memchr::memchr(b'\\', &bytes[..bytes.len() - 1]) {
            Some(i) => {
                bytes = &bytes[i + 1..];
                let c = bytes[0];
                if b'0' <= c && c <= b'9' { return true; }
            }
            None => return false
        }
    }
}
*/

/// The internal module only exists so that the toy example can access internals for debugging and
/// experimenting.
#[doc(hidden)]
pub mod internal {
    pub use crate::analyze::{AnalyzeContext, Info, analyze, can_compile_as_anchored};
    pub use crate::compile::{CompileOptions, compile};
    pub use crate::optimize::optimize;
    pub use crate::parse_flags::{
        FLAG_CASEI, FLAG_CRLF, FLAG_DOTNL, FLAG_IGNORE_NUMBERED_GROUPS_WHEN_NAMED_GROUPS_EXIST,
        FLAG_IGNORE_SPACE, FLAG_MULTI, FLAG_ONIGURUMA_MODE, FLAG_UNICODE,
    };
    pub use crate::vm::{Insn, Prog, Seek, run_default, run_trace};
}

#[cfg(test)]
mod tests {
    use alloc::borrow::Cow;
    use alloc::boxed::Box;
    use alloc::string::{String, ToString};
    use alloc::sync::Arc;
    use alloc::vec::Vec;
    use alloc::{format, vec};

    use crate::parse::{make_group, make_literal};
    use crate::{Absent, Expr, Regex, RegexBuilder, RegexImpl, RegexInput};

    //use detect_possible_backref;

    // tests for to_str

    fn to_str(e: Expr) -> String {
        let mut s = String::new();
        e.to_str(&mut s, 0);
        s
    }

    #[test]
    fn to_str_concat_alt() {
        let e = Expr::Concat(vec![
            Expr::Alt(vec![make_literal("a"), make_literal("b")]),
            make_literal("c"),
        ]);
        assert_eq!(to_str(e), "(?:a|b)c");
    }

    #[test]
    fn to_str_rep_concat() {
        let e = Expr::Repeat {
            child: Box::new(Expr::Concat(vec![make_literal("a"), make_literal("b")])),
            lo: 2,
            hi: 3,
            greedy: true,
        };
        assert_eq!(to_str(e), "(?:ab){2,3}");
    }

    #[test]
    fn to_str_group_alt() {
        let e = Expr::Group(Arc::new(Expr::Alt(vec![
            make_literal("a"),
            make_literal("b"),
        ])));
        assert_eq!(to_str(e), "(a|b)");
    }

    #[test]
    fn to_str_literal_special_chars() {
        assert_eq!(to_str(make_literal("\n")), "\\n");
        assert_eq!(to_str(make_literal("\t")), "\\t");
        assert_eq!(to_str(make_literal("\r")), "\\r");
        assert_eq!(to_str(make_literal("\\")), "\\\\");
        assert_eq!(to_str(make_literal(".")), "\\.");
    }

    #[test]
    fn as_str_debug() {
        let s = r"(a+)b\1";
        let regex = Regex::new(s).unwrap();
        assert_eq!(s, regex.as_str());
        assert_eq!(s, format!("{:?}", regex));
    }

    #[test]
    fn display() {
        let s = r"(a+)b\1";
        let regex = Regex::new(s).unwrap();
        assert_eq!(s, format!("{}", regex));
    }

    #[test]
    fn from_str() {
        let s = r"(a+)b\1";
        let regex = s.parse::<Regex>().unwrap();
        assert_eq!(regex.as_str(), s);
    }

    #[test]
    fn to_str_repeat() {
        fn repeat(lo: usize, hi: usize, greedy: bool) -> Expr {
            Expr::Repeat {
                child: Box::new(make_literal("a")),
                lo,
                hi,
                greedy,
            }
        }

        assert_eq!(to_str(repeat(2, 2, true)), "a{2}");
        assert_eq!(to_str(repeat(2, 2, false)), "a{2}?");
        assert_eq!(to_str(repeat(2, 3, true)), "a{2,3}");
        assert_eq!(to_str(repeat(2, 3, false)), "a{2,3}?");
        assert_eq!(to_str(repeat(2, usize::MAX, true)), "a{2,}");
        assert_eq!(to_str(repeat(2, usize::MAX, false)), "a{2,}?");
        assert_eq!(to_str(repeat(0, 1, true)), "a?");
        assert_eq!(to_str(repeat(0, 1, false)), "a??");
        assert_eq!(to_str(repeat(0, usize::MAX, true)), "a*");
        assert_eq!(to_str(repeat(0, usize::MAX, false)), "a*?");
        assert_eq!(to_str(repeat(1, usize::MAX, true)), "a+");
        assert_eq!(to_str(repeat(1, usize::MAX, false)), "a+?");
    }

    #[test]
    fn escape() {
        // Check that strings that need no quoting are borrowed, and that non-special punctuation
        // is not quoted.
        match crate::escape("@foo") {
            Cow::Borrowed(s) => assert_eq!(s, "@foo"),
            _ => panic!("Value should be borrowed."),
        }

        // Check typical usage.
        assert_eq!(crate::escape("fo*o").into_owned(), "fo\\*o");

        // Check that multibyte characters are handled correctly.
        assert_eq!(crate::escape("fø*ø").into_owned(), "fø\\*ø");
    }

    #[test]
    fn push_quoted_special_chars() {
        fn pq(s: &str) -> String {
            let mut buf = String::new();
            crate::push_quoted(&mut buf, s);
            buf
        }
        assert_eq!(pq("\n"), "\\n");
        assert_eq!(pq("\t"), "\\t");
        assert_eq!(pq("\r"), "\\r");
        assert_eq!(pq("\\"), "\\\\");
        assert_eq!(pq("."), "\\.");
        assert_eq!(pq("hello"), "hello");
        assert_eq!(pq("a.b"), "a\\.b");
        assert_eq!(pq("fø*ø"), "fø\\*ø");
    }

    #[test]
    fn trailing_positive_lookahead_wrap_capture_group_fixup() {
        let s = r"a+(?=c)";
        let regex = s.parse::<Regex>().unwrap();
        assert!(
            matches!(
                regex.inner,
                RegexImpl::Wrap {
                    explicit_capture_group_0: true,
                    ..
                }
            ),
            "trailing positive lookahead for an otherwise easy pattern should avoid going through the VM"
        );
        assert_eq!(s, regex.as_str());
        assert_eq!(s, format!("{:?}", regex));
    }

    #[test]
    fn easy_regex() {
        let s = r"(a+)b";
        let regex = s.parse::<Regex>().unwrap();
        assert!(
            matches!(
                regex.inner,
                RegexImpl::Wrap {
                    explicit_capture_group_0: false,
                    ..
                }
            ),
            "easy pattern should avoid going through the VM, and capture group 0 should be implicit"
        );

        assert_eq!(s, regex.as_str());
        assert_eq!(s, format!("{:?}", regex));
    }

    #[test]
    fn hard_regex() {
        let s = r"(a+)(?>c)";
        let regex = s.parse::<Regex>().unwrap();
        assert!(
            matches!(regex.inner, RegexImpl::Fancy { .. }),
            "hard regex should be compiled into a VM"
        );
        assert_eq!(s, regex.as_str());
        assert_eq!(s, format!("{:?}", regex));
    }

    #[test]
    fn start_end_text_assertions_can_stay_wrap_without_override_opt_in() {
        let regex = Regex::new(r"\Afoo\z").unwrap();
        assert!(
            matches!(regex.inner, RegexImpl::Wrap { .. }),
            r"\A...\z should stay on the wrap path unless input assertion overrides are enabled"
        );
    }

    #[test]
    fn start_end_text_assertions_become_fancy_with_override_opt_in() {
        let regex = RegexBuilder::new(r"\Afoo\z")
            .allow_input_assertion_overrides(true)
            .build()
            .unwrap();
        assert!(
            matches!(regex.inner, RegexImpl::Fancy { .. }),
            r"\A...\z should use the VM when input assertion overrides are enabled"
        );
    }

    fn has_regular_route(regex: &Regex) -> bool {
        match &regex.inner {
            RegexImpl::Fancy {
                regular: Some(route),
                ..
            } => route.engine().automata().is_some(),
            _ => false,
        }
    }

    fn fancy_prog(regex: &Regex) -> &crate::vm::Prog {
        match &regex.inner {
            RegexImpl::Fancy { prog, .. } => prog,
            RegexImpl::Wrap { .. } => unreachable!("expected a VM program"),
        }
    }

    /// A program only carries the seek approximation it seeks with. Any other
    /// is derived again on demand; both equal what 0.1.4 stored for every
    /// regex.
    #[test]
    fn seek_approximation_is_only_built_for_a_seek() {
        for (pattern, released) in [
            (r"(abc)\1", "(?:abc)(?:abc)"),
            (r"(?<=Mr\. |Dr\. )[A-Z]\w+", r"[A-Z]\w+"),
            (r"\g<1>-(a+)\1", "a+-a+a+"),
            (r"(?i)(?<n>a+)\k<n>(?=b)", "(?:(?i:a)+(?i:(?i:a)+))(?i:b)"),
            (r"(?m)(x)\1$", "xx(?m:$)"),
            (r"(a)?(?(1)b|c)\1", "a?(?:b|c)a"),
            (r"(?(DEFINE)(?<d>\d))\g<d>(\w)\1", r"\d\w\d"),
            (r"(?x) ( a ) \1 # comment", "aa"),
        ] {
            let plain = Regex::new(pattern).unwrap();
            let seeking = RegexBuilder::new(pattern)
                .seek_filter(|_| true)
                .build()
                .unwrap();
            assert_eq!(fancy_prog(&plain).seek_pattern(), None, "{pattern}");
            assert_eq!(
                fancy_prog(&seeking).seek_pattern(),
                Some(released),
                "{pattern}"
            );
            assert_eq!(plain.seek_pattern().unwrap(), released, "{pattern}");
            assert_eq!(seeking.seek_pattern().unwrap(), released, "{pattern}");
        }
        // An anchored program never seeks, nor one whose filter declines.
        let anchored = RegexBuilder::new(r"^(a)\1").seek(true).build().unwrap();
        assert_eq!(fancy_prog(&anchored).seek_pattern(), None);
        assert_eq!(anchored.seek_pattern().unwrap(), "^aa");
        let declined = RegexBuilder::new(r"(abc)\1")
            .seek_filter(|_| false)
            .build()
            .unwrap();
        assert_eq!(fancy_prog(&declined).seek_pattern(), None);
        assert_eq!(declined.seek_pattern().unwrap(), "(?:abc)(?:abc)");
    }

    /// A start filter from a leading lookbehind leads a seek preamble, except
    /// under an explicit limit; other start filters only reject the seek's
    /// candidates.
    #[test]
    fn lookbehind_literals_lead_seek_without_an_explicit_limit() {
        let plan = |builder: &mut RegexBuilder| {
            let regex = builder.build().unwrap();
            let prog = fancy_prog(&regex);
            (
                prog.seek_pattern().is_some(),
                prog.start_filter().is_some(),
                prog.filter_leads_seek(),
            )
        };
        let titled = r"(?<=Mr\. )[A-Z]\w+";
        assert_eq!(
            plan(RegexBuilder::new(titled).seek(true)),
            (true, true, true)
        );
        assert_eq!(
            plan(RegexBuilder::new(titled).seek(true).backtrack_limit(1000)),
            (true, true, false)
        );
        assert_eq!(plan(&mut RegexBuilder::new(titled)), (false, true, false));
        assert_eq!(
            plan(RegexBuilder::new(r"#(\d)\1").seek(true)),
            (true, true, false)
        );
    }

    #[test]
    fn word_boundary_patterns_get_a_regular_route() {
        for pattern in [
            r"\bfn\b",
            r"\B\w+",
            r"(?i)\<k(\w)\>",
            r"\b\d+\b|\w",
            r"\b{start-half}a",
            r"\b(a|){2,3}",
            r"\b(?:a|){0,4}b*",
        ] {
            let regex = Regex::new(pattern).unwrap();
            assert!(has_regular_route(&regex), "{pattern}");
        }
        // Constructs the automata cannot run, group-zero rewrites, and
        // unbounded repetitions of expressions that can match empty, where
        // backtracking differs.
        for pattern in [
            r"(a|)*\bb",
            r"(?:\b|a)+b",
            r"(\b\w*)*",
            r"\b(\w+) \1\b",
            r"\b(?=a)",
            r"\bfoo\Kbar\b",
            r"\bfoo(?=bar)",
            r"(?>\b\w)",
            r"\b\w++",
            r"\Gab\b",
        ] {
            let regex = Regex::new(pattern).unwrap();
            assert!(matches!(regex.inner, RegexImpl::Fancy { .. }), "{pattern}");
            assert!(!has_regular_route(&regex), "{pattern}");
        }
        // Options that change VM semantics or ask for its limit accounting.
        let configured = |configure: fn(&mut RegexBuilder) -> &mut RegexBuilder| {
            let mut builder = RegexBuilder::new(r"\bab\b");
            configure(&mut builder);
            has_regular_route(&builder.build().unwrap())
        };
        assert!(configured(|b| b.case_insensitive(true)));
        assert!(configured(|b| b.bytes_mode(crate::BytesMode::Ascii)));
        assert!(!configured(|b| b.backtrack_limit(1_000_000)));
        assert!(!configured(|b| b.find_not_empty(true)));
        assert!(!configured(|b| b.allow_input_assertion_overrides(true)));
    }

    /// Native code stays for whole-text booleans the lazy DFA gives up on.
    #[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]
    #[test]
    fn native_code_backs_the_regular_route_on_non_ascii_text() {
        let regex = Regex::new(r"\b(?:fn|let|é)\b").unwrap();
        assert!(has_regular_route(&regex));
        assert!(regex.native.is_some());
        assert!(regex.is_match("let x").unwrap());
        assert!(!regex.is_match("fnord").unwrap());
        assert!(regex.is_match("é x").unwrap());
        assert!(!regex.is_match("éfn").unwrap());
    }

    #[test]
    fn regular_route_dfa_gives_up_on_non_ascii_text() {
        let regex = Regex::new(r"\b(?:a|a)+\b!").unwrap();
        let find = |text: &str| {
            let input = RegexInput::new(text);
            let route = regex.regular_route(&input).unwrap().automata().unwrap();
            (
                route.find(&crate::ra_input(&input), None).is_err(),
                route.is_match(&crate::ra_input(&input), None).is_err(),
            )
        };
        assert_eq!(find("aaaa a!"), (false, false));
        assert_eq!(find("aaaaé"), (true, true));
    }

    /// A route's plan answers every search on valid UTF-8, where its Unicode
    /// word boundaries are the VM's, including text where the automata would
    /// give up. In ASCII mode it answers only the searches the automata would:
    /// those reading only ASCII bytes, without alternatives or groups, which
    /// can read past the match.
    #[test]
    fn regular_route_plan_answers_on_utf8_and_defers_in_ascii_mode() {
        let answered = |pattern: &str, text: &str| {
            let regex = Regex::new(pattern).unwrap();
            let input = RegexInput::new(text);
            let plan = regex.regular_route(&input).unwrap().plan().unwrap();
            plan.find::<[usize]>(&crate::plan_input(&input), None)
        };
        assert_eq!(answered(r"\b\w+\b", "ab cd"), Some(Some((0, 2))));
        assert_eq!(answered(r"\b\w+\b", "ab é"), Some(Some((0, 2))));
        assert_eq!(answered(r"\b\w+\b", "ab\u{e9}"), Some(Some((0, 4))));
        assert_eq!(answered(r"\b\w+\b", "\u{e9}\u{e9} x"), Some(Some((0, 4))));
        assert_eq!(answered(r"\b\w+!", "\u{e9}\u{e9}"), Some(None));
        assert_eq!(answered(r"\b(?:fn|let)\b", "é let"), Some(Some((3, 6))));
        // Word boundaries stay Unicode's in ASCII mode, where the VM steps
        // one byte at a time.
        let ascii = |pattern: &str, text: &[u8]| {
            let regex = RegexBuilder::new(pattern)
                .bytes_mode(crate::BytesMode::Ascii)
                .build()
                .unwrap();
            let input = RegexInput::new(text);
            let plan = regex.regular_route(&input).unwrap().plan().unwrap();
            plan.find::<[usize]>(&crate::plan_input(&input), None)
        };
        // The automata may read one byte past the match; that byte is checked too.
        assert_eq!(ascii(r"\bfn\b", b"x fn  \xFF"), Some(Some((2, 4))));
        assert_eq!(ascii(r"\bfn\b", b"x fn \xFF"), None);
        assert_eq!(ascii(r"\bfn\b", b"\xFF fn"), None);
        assert_eq!(ascii(r"\b(?:fn|let)\b", b"x fn  "), None);
    }

    #[test]
    fn regular_route_is_chosen_per_search() {
        let regex = Regex::new(r"\b\w+\b").unwrap();
        let text = "é ab";
        let routed = |input: RegexInput<'_, str>| regex.regular_route(&input).is_some();
        assert!(routed(RegexInput::new(text)));
        assert!(routed(RegexInput::new(text).from_pos(2)));
        assert!(routed(RegexInput::new(text).range(3..5).anchored(true)));
        // Inside a character, or a range ending before the haystack does.
        assert!(!routed(RegexInput::new(text).from_pos(1)));
        assert!(!routed(RegexInput::new(text).range(0..4)));
        // Bytes outside ASCII mode keep the VM, which steps over invalid
        // UTF-8 differently.
        assert!(
            regex
                .regular_route(&RegexInput::new(text.as_bytes()))
                .is_none()
        );

        let ascii = RegexBuilder::new(r"\b\w+\b")
            .bytes_mode(crate::BytesMode::Ascii)
            .build()
            .unwrap();
        let bytes: &[u8] = b"\xFF ab";
        assert!(
            ascii
                .regular_route(&RegexInput::new(bytes).from_pos(1))
                .is_some()
        );
        assert!(
            ascii
                .regular_route(&RegexInput::new(bytes).range(0..3))
                .is_none()
        );
    }

    /*
    #[test]
    fn detect_backref() {
        assert_eq!(detect_possible_backref("a0a1a2"), false);
        assert_eq!(detect_possible_backref("a0a1\\a2"), false);
        assert_eq!(detect_possible_backref("a0a\\1a2"), true);
        assert_eq!(detect_possible_backref("a0a1a2\\"), false);
    }
    */

    #[test]
    fn test_is_leaf_node_leaf_nodes() {
        // Test all leaf node variants
        assert!(Expr::Empty.is_leaf_node());
        assert!(
            Expr::Any {
                newline: false,
                crlf: false
            }
            .is_leaf_node()
        );
        assert!(
            Expr::Any {
                newline: true,
                crlf: false
            }
            .is_leaf_node()
        );
        assert!(Expr::Assertion(crate::Assertion::StartText).is_leaf_node());
        assert!(
            Expr::Literal {
                val: "test".to_string(),
                casei: false
            }
            .is_leaf_node()
        );
        assert!(
            Expr::Delegate {
                inner: "[0-9]".to_string(),
                casei: false,
            }
            .is_leaf_node()
        );
        assert!(
            Expr::Backref {
                group: 1,
                casei: false
            }
            .is_leaf_node()
        );
        assert!(
            Expr::BackrefWithRelativeRecursionLevel {
                group: 1,
                relative_level: -1,
                casei: false
            }
            .is_leaf_node()
        );
        assert!(Expr::KeepOut.is_leaf_node());
        assert!(Expr::ContinueFromPreviousMatchEnd.is_leaf_node());
        assert!(
            Expr::BackrefExistsCondition {
                group: 1,
                relative_recursion_level: None
            }
            .is_leaf_node()
        );
        assert!(Expr::BacktrackingControlVerb(crate::BacktrackingControlVerb::Fail).is_leaf_node());
        assert!(Expr::SubroutineCall(1).is_leaf_node());

        assert!(Expr::Absent(Absent::Clear).is_leaf_node());
    }

    #[test]
    fn test_is_leaf_node_non_leaf_nodes() {
        // Test all non-leaf node variants
        assert!(!Expr::Concat(vec![make_literal("a")]).is_leaf_node());
        assert!(!Expr::Alt(vec![make_literal("a"), make_literal("b")]).is_leaf_node());
        assert!(!make_group(make_literal("a")).is_leaf_node());
        assert!(
            !Expr::LookAround(Box::new(make_literal("a")), crate::LookAround::LookAhead)
                .is_leaf_node()
        );
        assert!(
            !Expr::Repeat {
                child: Box::new(make_literal("a")),
                lo: 0,
                hi: 1,
                greedy: true
            }
            .is_leaf_node()
        );
        assert!(!Expr::AtomicGroup(Box::new(make_literal("a"))).is_leaf_node());
        assert!(
            !Expr::Conditional {
                condition: Box::new(Expr::BackrefExistsCondition {
                    group: 1,
                    relative_recursion_level: None
                }),
                true_branch: Box::new(make_literal("a")),
                false_branch: Box::new(Expr::Empty)
            }
            .is_leaf_node()
        );

        assert!(!Expr::Absent(Absent::Repeater(Box::new(make_literal("a")))).is_leaf_node());
        assert!(
            !Expr::Absent(Absent::Expression {
                absent: Box::new(make_literal("/*")),
                exp: Box::new(Expr::Repeat {
                    child: Box::new(Expr::Any {
                        newline: true,
                        crlf: false
                    }),
                    lo: 0,
                    hi: usize::MAX,
                    greedy: true
                })
            })
            .is_leaf_node()
        );
        assert!(!Expr::Absent(Absent::Stopper(Box::new(make_literal("/*")))).is_leaf_node());
    }

    #[test]
    fn test_children_iter_empty() {
        // Leaf nodes should return empty iterator
        let expr = Expr::Empty;
        let mut iter = expr.children_iter();
        assert!(iter.next().is_none());

        let expr = make_literal("test");
        let mut iter = expr.children_iter();
        assert!(iter.next().is_none());
    }

    #[test]
    fn test_children_iter_single() {
        // Group, LookAround, AtomicGroup, Repeat should return single child
        let child = make_literal("a");
        let expr = make_group(child.clone());
        let children: Vec<_> = expr.children_iter().collect();
        assert_eq!(children.len(), 1);

        let expr = Expr::Repeat {
            child: Box::new(child.clone()),
            lo: 0,
            hi: 1,
            greedy: true,
        };
        let children: Vec<_> = expr.children_iter().collect();
        assert_eq!(children.len(), 1);
    }

    #[test]
    fn test_children_iter_vec() {
        // Concat and Alt should return all children
        let children_vec = vec![make_literal("a"), make_literal("b"), make_literal("c")];
        let expr = Expr::Concat(children_vec.clone());
        let children: Vec<_> = expr.children_iter().collect();
        assert_eq!(children.len(), 3);

        let expr = Expr::Alt(children_vec);
        let children: Vec<_> = expr.children_iter().collect();
        assert_eq!(children.len(), 3);
    }

    #[test]
    fn test_children_iter_triple() {
        // Conditional should return three children
        let expr = Expr::Conditional {
            condition: Box::new(Expr::BackrefExistsCondition {
                group: 1,
                relative_recursion_level: None,
            }),
            true_branch: Box::new(make_literal("a")),
            false_branch: Box::new(make_literal("b")),
        };
        let children: Vec<_> = expr.children_iter().collect();
        assert_eq!(children.len(), 3);

        // Absent expression should return two children
        let expr = Expr::Absent(Absent::Expression {
            absent: Box::new(make_literal("/*")),
            exp: Box::new(Expr::Repeat {
                child: Box::new(Expr::Any {
                    newline: true,
                    crlf: false,
                }),
                lo: 0,
                hi: usize::MAX,
                greedy: true,
            }),
        });
        let children: Vec<_> = expr.children_iter().collect();
        assert_eq!(children.len(), 2);
    }

    #[test]
    fn find_input_raw_honors_anchored_flag_for_wrapped_regex() {
        let regex = Regex::new("abc").unwrap();

        // Unanchored search finds match at position 1
        let input = RegexInput::new("zabc");
        assert_eq!(
            Some((1, 4)),
            regex
                .find_input(input)
                .unwrap()
                .map(|m| (m.start(), m.end()))
        );

        // Anchored at position 0 returns None (abc doesn't match at pos 0)
        let anchored_at_start = RegexInput::new("zabc").anchored(true);
        assert!(regex.find_input(anchored_at_start).unwrap().is_none());

        // Anchored at position 1 finds match
        let anchored_at_match = RegexInput::new("zabc").from_pos(1).anchored(true);
        assert_eq!(
            regex
                .find_input(anchored_at_match)
                .unwrap()
                .map(|m| (m.start(), m.end())),
            Some((1, 4))
        );
    }
}