ferroni 2.7.0

Oniguruma regex in pure Rust, with a TextMate scanner, portable prepared Eager archives, and no C toolchain
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
//! Rust-only (ADR-008): a multi-pattern DFA pre-filter for the scanner's
//! RegSet search, after fancy-regex's `RegexSet`.
//!
//! A TextMate scanner asks its set for the earliest match of any pattern,
//! and most attempts the position-lead search makes fail. The pre-filter
//! decides, before any attempt, which entries can match where.
//!
//! [`derive`] reads a pattern's tuned parse tree and writes an
//! over-approximation of it as regex-automata's HIR, its *seek*: wherever
//! the pattern can match, the seek matches too (it may match in more
//! places, never fewer). Literals, classes, concatenation, alternation and
//! repetition are exact; groups are transparent; look-behind, negative
//! look-ahead, `\G`, `\K` and text-segment boundaries become empty, except
//! that a negative look at a class holding every ASCII word character
//! becomes the ASCII half boundary it is contained in; back references and
//! calls become `(?s:.)*`; a positive look-ahead keeps its body where
//! nothing consuming follows it and is dropped otherwise. Classes are
//! byte-based: the ASCII members are exact and any non-ASCII member stands
//! for one UTF-8 sequence, which keeps the automata small; any character is
//! an ASCII byte or such a sequence. A seek that matches at every position
//! narrows nothing; its entry is searched on its own (`Seek::Everywhere`).
//! The regex does not carry its seek: the scanner hands it to its set, and
//! a pattern cache keeps one per distinct pattern, in a compact encoding
//! ([`SeekCode`]) that is decoded when the automata are built.
//!
//! [`Automata`] compiles the seeks of one pattern list into a forward and a
//! reverse lazy DFA, which find the earliest position where any seek matches
//! (the strategy of regex-automata's meta regex), and a lazy DFA over all
//! seeks, which says which of them match at that position. They are built on
//! a set's first pre-filtered
//! search, not when the set is constructed, and every set built from one
//! pattern cache over the same pattern list shares them ([`AutomataCell`]);
//! [`SetPrefilter`] is a set's own part: the lazy DFA caches and the
//! search's scratch state. The RegSet (`regset_search_body_prefilter`)
//! attempts only the entries the automata name, anchored at that position,
//! in index order; the first event decides, and without one the search
//! goes on one character later. A pattern list whose automata would exceed
//! [`MAX_NFA_STATES`] builds none and its sets keep the position-lead
//! search as it was.
//!
//! The `dfa-prefilter` feature compiles this module, and
//! `ScannerConfig::prefilter` switches it per scanner. A search under a
//! limit of the caller's own keeps C's attempts (see `prefilter_decides` in
//! `regset.rs`).

mod accept;

pub(crate) use accept::{AcceptCode, derive_accept};

use crate::oniguruma::{
    ONIG_OPTION_FIND_NOT_EMPTY, ONIG_OPTION_NOTBOL, ONIG_OPTION_NOTEOL, ONIGENC_CTYPE_WORD,
};
use crate::regcomp::literal_alt_trie_index;
use crate::regenc::OnigEncoding;
use crate::regint::*;
use crate::regparse_types::*;
use regex_automata::hybrid::LazyStateID;
use regex_automata::hybrid::dfa as hybrid;
use regex_automata::hybrid::regex as hybrid_regex;
use regex_automata::nfa::thompson;
use regex_automata::util::pool::Pool;

use regex_automata::{Anchored, Input, MatchKind, PatternID};
use regex_syntax::hir::{
    Class, ClassBytes, ClassBytesRange, ClassUnicode, ClassUnicodeRange, Hir, HirKind, Look,
    Repetition,
};
use regex_syntax::utf8::Utf8Sequences;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock};

#[cfg(feature = "scanner-group-nfa-prototype")]
pub(crate) mod group_archive;
#[cfg(feature = "precompiled-eager")]
mod portable;

const MIB: usize = 1 << 20;
/// Lazy DFA cache of the search DFAs (fancy-regex: 64 MiB).
const SEARCH_CACHE_CAPACITY: usize = 2 * MIB;
/// The search DFAs' efficiency check: regex-automata's meta regex gives its
/// own lazy DFAs the same clear count (`MIN_CACHE_CLEARS`) and this.
const SEARCH_MIN_BYTES_PER_STATE: usize = 10;
/// Lazy DFA cache of the overlapping DFA (fancy-regex: 64 MiB).
const OVERLAPPING_CACHE_CAPACITY: usize = MIB;
/// Hard bound on the NFA size per set, for both automata.
const NFA_SIZE_LIMIT: usize = 16 * MIB;
/// The overlapping DFA gives up once its cache has been cleared this many
/// times and it searched fewer than `MIN_BYTES_PER_STATE` bytes per state
/// it holds: it is creating states faster than it can reuse them (every
/// state of a set over a hundred case-insensitive keyword lists holds
/// thousands of NFA states, so a 1 MiB cache holds a few hundred of them,
/// and a walk at every position of a long identifier rebuilt them all
/// every few searches: 100 µs a search against 0.4 without the pre-filter
/// on the flat CSS grammar set). The set then drops its pre-filter for
/// good (`retire_prefilter` in `regset.rs`). regex-automata's meta regex
/// gives its own lazy DFAs the same clear count.
const MIN_CACHE_CLEARS: usize = 3;
/// See `MIN_CACHE_CLEARS`.
const MIN_BYTES_PER_STATE: usize = 20;
/// Counted repetitions above this bound become unbounded ones.
const MAX_COUNTED_REPEAT: u32 = 64;
/// Bytes the anchored candidate scan reads past a position before it
/// declares every covered entry a candidate there. A seek such as `\w+`
/// stays alive to the end of a word run, and the scan would otherwise read
/// it again from every position of the run.
pub(crate) const CANDIDATE_SCAN_BYTES: usize = 256;

/// A seek whose matches are at most this long settles within that many
/// bytes of a candidate walk: it has matched or its states are dead. The
/// longer and the unbounded seeks (`\w+:`) are the ones that can keep a
/// walk alive past that, and a walk asks which of their entries the
/// search admits at the position: an entry the search would not attempt
/// never decides there, so a walk that has recorded every admissible one
/// stops. Asking costs about as much as a long walk, so a walk asks right
/// after the bounded seeks settled only while the set's walks keep
/// running to the bound or ending by such an ask (`ask_early`: every
/// position of a word run a seek like `\w+:` sits in while its entry is
/// ruled out), and otherwise only after `LONG_WALK_BYTES` (see ADR-008).
pub(crate) const LONG_SEEK_BYTES: usize = 16;

/// Bytes after which a walk asks about the long seeks in any case.
pub(crate) const LONG_WALK_BYTES: usize = 64;

/// Sets whose NFA has more states than this get no pre-filter: a bound on
/// what one set costs to build and keep, not a break-even. The largest set
/// of the captured replays (PHP, 37,437 states, 4.2 MiB of automata, built
/// in about 60 ms) takes 2% of its time with the pre-filter, and size does
/// not tell which sets lose: C++ sets of 25,000 states take a quarter of
/// their time, the hot SCSS set at 17,000 states 13% more (see ADR-008).
pub(crate) const MAX_NFA_STATES: usize = 65_536;

/// Cheap HIR estimate gate before the measured 64-state bitset/assertion guard.
const MAX_SINGLE_DENSE_ESTIMATED_NFA_STATES: usize = 512;
const MAX_SINGLE_BITSET_NFA_STATES: usize = u64::BITS as usize;

/// Both the final table and auxiliary determinization workspace have
/// independent hard caps. If either cap is reached, the hybrid DFA remains
/// available instead. This small policy retains at most 64 KiB per dense DFA
/// and bounds each determinization workspace to 32 KiB.
const SINGLE_DENSE_DFA_SIZE_LIMIT: usize = 64 * 1024;
const SINGLE_DENSE_DETERMINIZE_SIZE_LIMIT: usize = 32 * 1024;

/// Sets whose automata would cover at most this many entries with at most
/// `TINY_SET_NFA_STATES` NFA states get no pre-filter unless the scanner
/// asks for it from the first search (`ScannerConfig::prefilter_warmup`
/// of 0): such patterns are literals and small classes, whose attempts
/// the first-byte table dispatches and the first-instruction tests reject
/// as cheaply as a walk of the automata would, so the pre-filter has
/// nothing to save there and costs its walks and search DFA searches on
/// every call (the six sets of the JSON grammar, 3 to 11 patterns over 24
/// to 104 states, took 1.5 to 2.5 times their time with it, and no set of
/// the captured replays within these bounds gains; see ADR-008).
pub(crate) const TINY_SET_ENTRIES: usize = 12;
/// See `TINY_SET_ENTRIES`.
pub(crate) const TINY_SET_NFA_STATES: usize = 128;

#[cfg(test)]
thread_local! {
    /// Searches of a set's search DFAs on this thread, for tests that bound
    /// the pre-filter's work (`search_in`).
    pub(crate) static EARLIEST_CALLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    /// Bytes the candidate scans read on this thread.
    pub(crate) static SCAN_STEPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    /// Bytes the search DFAs read on this thread.
    pub(crate) static META_BYTES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
    /// The overlapping DFA's cache capacity for the automata built on this
    /// thread, when a test sets one (`overlapping_config`).
    pub(crate) static OVERLAPPING_CACHE_BYTES: std::cell::Cell<Option<usize>> =
        const { std::cell::Cell::new(None) };
}

/// The configuration of the overlapping DFA. A test sets a cache capacity
/// for its thread (`OVERLAPPING_CACHE_BYTES`): the lazy DFA then clears its
/// cache as often as a walk needs, without the give-up that would retire the
/// pre-filter before the walk reached the case under test.
fn overlapping_config() -> hybrid::Config {
    let config = hybrid::Config::new()
        .match_kind(MatchKind::All)
        .skip_cache_capacity_check(true);
    #[cfg(test)]
    if let Some(bytes) = OVERLAPPING_CACHE_BYTES.with(|bytes| bytes.get()) {
        return config
            .cache_capacity(bytes)
            .minimum_cache_clear_count(None)
            .minimum_bytes_per_state(None);
    }
    config
        .cache_capacity(OVERLAPPING_CACHE_CAPACITY)
        .minimum_cache_clear_count(Some(MIN_CACHE_CLEARS))
        .minimum_bytes_per_state(Some(MIN_BYTES_PER_STATE))
}

/// The seek approximation of one compiled pattern. A scanner passes it to
/// its set, which builds the automata from it, and its pattern cache keeps
/// it per distinct pattern (ADR-006); the regex itself does not carry it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Seek {
    /// The approximation matches at every position, so it cannot narrow
    /// anything: the entry is searched on its own.
    Everywhere,
    /// The approximation, for the automata.
    Pattern(SeekCode),
}

/// The seek approximation of `reg`, whose tuned parse tree is `root`.
/// `None` for an entry the pre-filter must not decide for: callouts observe
/// every attempt, and the seek reads UTF-8.
pub(crate) fn derive(root: &Node, reg: &RegexType, precise: bool) -> Option<Seek> {
    if reg.extp.as_ref().is_some_and(|ext| ext.callout_num != 0) {
        return None;
    }
    // Trait-object pointers may differ in their vtable between codegen
    // units, so the encoding is identified by name.
    let utf8: OnigEncoding = &crate::encodings::utf8::ONIG_ENCODING_UTF8;
    if reg.enc.name() != utf8.name() || reg.enc.max_enc_len() != utf8.max_enc_len() {
        return None;
    }
    walk_seek(root, reg, precise)
}

/// The walk of `derive`. A precise seek whose automaton would be too large
/// falls back to the scanner's seek, which is smaller.
fn walk_seek(root: &Node, reg: &RegexType, precise: bool) -> Option<Seek> {
    // The tail rewrite of `\Z` is exact, and the scanner's seeks keep their
    // approximation of it (`$`), so only a single regex's seek takes it.
    let mut tails = Vec::new();
    if precise {
        collect_tails(root, &mut tails);
    }
    let mut walk = Walk {
        reg,
        lookaheads_kept: 0,
        inexact: false,
        tails,
        precise,
    };
    let hir = walk.item(root, true);
    if matches_everywhere(&hir) {
        return Some(Seek::Everywhere);
    }
    if precise && nfa_states_estimate(&hir) > MAX_NFA_STATES {
        return walk_seek(root, reg, false);
    }
    // Exact when the seek matches exactly where the pattern does, so that a
    // match of the seek is a match of the pattern (`SeekCode::exact`). The
    // line anchors and the options that change what a line start or end
    // is, or what counts as a match, make the seek inexact.
    let exact = !walk.inexact
        && line_starts_exact(&hir)
        && !reg
            .options
            .intersects(ONIG_OPTION_NOTBOL | ONIG_OPTION_NOTEOL | ONIG_OPTION_FIND_NOT_EMPTY);
    // A node the encoding has no tag for leaves the entry on its own, which
    // is always right; the walk writes none.
    let code = SeekCode::encode(&hir, exact)?;
    debug_assert_eq!(code.decode(), hir, "the seek code round-trips");
    Some(Seek::Pattern(code))
}

/// A seek's HIR in a compact encoding, kept per distinct pattern until the
/// automata are built: a flag byte (whether the seek is exact, see
/// [`SeekCode::exact`]), then the tree in pre-order, each node a tag byte and
/// its data. An HIR node carries a boxed property block and its own
/// allocations, some 20–30 KiB per seek over the captured grammars; the
/// code is a few hundred bytes. Decoding rebuilds the tree through the
/// smart constructors that built it (`Hir::concat`, `Hir::alternation`,
/// `Hir::class`, ...), whose simplifications are stable on their own
/// output, so the decoded HIR equals the original (`derive` asserts it in
/// debug builds, and a test checks it over every seek of the captured
/// grammars).
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct SeekCode(Box<[u8]>);

/// The node tags of a `SeekCode`.
mod tag {
    pub(super) const EMPTY: u8 = 0;
    /// Length, then the bytes.
    pub(super) const LITERAL: u8 = 1;
    /// Range count, then each range as two bytes.
    pub(super) const BYTES: u8 = 2;
    /// Range count, then each range as two code points.
    pub(super) const UNICODE: u8 = 3;
    /// `Look::as_repr`.
    pub(super) const LOOK: u8 = 4;
    /// Minimum, maximum plus one (0 for unbounded), greediness, the body.
    pub(super) const REPETITION: u8 = 5;
    /// Count, then the parts.
    pub(super) const CONCAT: u8 = 6;
    /// Count, then the branches.
    pub(super) const ALTERNATION: u8 = 7;
}

impl SeekCode {
    #[cfg(feature = "precompiled")]
    pub(crate) fn precompiled_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Check the complete seek before the infallible internal decoder sees it.
    /// Depth and node budgets also bound the HIR constructors and destruction.
    #[cfg(feature = "precompiled")]
    pub(crate) fn from_precompiled(bytes: Vec<u8>) -> Option<Self> {
        struct Check<'a> {
            bytes: &'a [u8],
            nodes: usize,
        }
        impl Check<'_> {
            fn byte(&mut self) -> Option<u8> {
                let (&first, rest) = self.bytes.split_first()?;
                self.bytes = rest;
                Some(first)
            }
            fn number(&mut self) -> Option<usize> {
                let mut value = 0u64;
                for shift in (0..35).step_by(7) {
                    let b = self.byte()?;
                    value |= u64::from(b & 0x7f) << shift;
                    if b & 0x80 == 0 {
                        return usize::try_from(value)
                            .ok()
                            .filter(|v| *v <= u32::MAX as usize);
                    }
                }
                None
            }
            fn node(&mut self, depth: usize) -> Option<()> {
                self.nodes = self.nodes.checked_sub(1)?;
                if depth > 256 {
                    return None;
                }
                match self.byte()? {
                    tag::EMPTY => {}
                    tag::LITERAL => {
                        let len = self.number()?;
                        self.bytes = self.bytes.get(len..)?;
                    }
                    kind @ (tag::BYTES | tag::UNICODE) => {
                        let count = self.number()?;
                        if count > self.bytes.len() / 2 {
                            return None;
                        }
                        let mut previous = None;
                        for _ in 0..count {
                            let (lo, hi) = if kind == tag::BYTES {
                                (u32::from(self.byte()?), u32::from(self.byte()?))
                            } else {
                                let lo = self.number()? as u32;
                                let hi = self.number()? as u32;
                                char::from_u32(lo)?;
                                char::from_u32(hi)?;
                                (lo, hi)
                            };
                            if lo > hi || previous.is_some_and(|p| p >= lo) {
                                return None;
                            }
                            previous = Some(hi);
                        }
                    }
                    tag::LOOK => {
                        Look::from_repr(self.number()? as u32)?;
                    }
                    tag::REPETITION => {
                        let min = self.number()?;
                        let max = self.number()?;
                        if (max != 0 && max - 1 < min) || self.byte()? > 1 {
                            return None;
                        }
                        self.node(depth + 1)?;
                    }
                    tag::CONCAT | tag::ALTERNATION => {
                        let count = self.number()?;
                        if count > self.nodes {
                            return None;
                        }
                        for _ in 0..count {
                            self.node(depth + 1)?;
                        }
                    }
                    _ => return None,
                }
                Some(())
            }
        }
        let mut check = Check {
            bytes: &bytes,
            nodes: 65_536,
        };
        if check.byte()? > 1 {
            return None;
        }
        check.node(0)?;
        if !check.bytes.is_empty() {
            return None;
        }
        Some(Self(bytes.into_boxed_slice()))
    }

    /// `hir` encoded, or `None` for a node kind the walk never writes
    /// (a capture).
    fn encode(hir: &Hir, exact: bool) -> Option<SeekCode> {
        let mut out = vec![u8::from(exact)];
        Self::write(hir, &mut out)?;
        Some(SeekCode(out.into_boxed_slice()))
    }

    /// Whether the seek matches exactly where the pattern does, for the
    /// purposes of existence: no construct was approximated, no line start
    /// the matcher would not see is admitted, and no option changes a match
    /// the seek describes. A match of an exact seek is a match of the
    /// pattern, which is what a standard `is_match` may answer from it. The
    /// matcher finds that match with no limit; under a limit it may stop
    /// instead, and the answer is then the one without the limit (ADR-017).
    pub(crate) fn exact(&self) -> bool {
        self.0[0] != 0
    }

    fn write(hir: &Hir, out: &mut Vec<u8>) -> Option<()> {
        match hir.kind() {
            HirKind::Empty => out.push(tag::EMPTY),
            HirKind::Literal(literal) => {
                out.push(tag::LITERAL);
                Self::varint(literal.0.len(), out);
                out.extend_from_slice(&literal.0);
            }
            HirKind::Class(Class::Bytes(class)) => {
                out.push(tag::BYTES);
                Self::varint(class.ranges().len(), out);
                for range in class.ranges() {
                    out.push(range.start());
                    out.push(range.end());
                }
            }
            HirKind::Class(Class::Unicode(class)) => {
                out.push(tag::UNICODE);
                Self::varint(class.ranges().len(), out);
                for range in class.ranges() {
                    Self::varint(range.start() as usize, out);
                    Self::varint(range.end() as usize, out);
                }
            }
            HirKind::Look(look) => {
                out.push(tag::LOOK);
                Self::varint(look.as_repr() as usize, out);
            }
            HirKind::Repetition(rep) => {
                out.push(tag::REPETITION);
                Self::varint(rep.min as usize, out);
                Self::varint(rep.max.map_or(0, |max| max as usize + 1), out);
                out.push(u8::from(rep.greedy));
                Self::write(&rep.sub, out)?;
            }
            HirKind::Concat(parts) => {
                out.push(tag::CONCAT);
                Self::varint(parts.len(), out);
                for part in parts {
                    Self::write(part, out)?;
                }
            }
            HirKind::Alternation(branches) => {
                out.push(tag::ALTERNATION);
                Self::varint(branches.len(), out);
                for branch in branches {
                    Self::write(branch, out)?;
                }
            }
            HirKind::Capture(_) => return None,
        }
        Some(())
    }

    /// LEB128.
    fn varint(mut value: usize, out: &mut Vec<u8>) {
        while value >= 0x80 {
            out.push((value as u8) | 0x80);
            value >>= 7;
        }
        out.push(value as u8);
    }

    /// The HIR the code was made from.
    pub(crate) fn decode(&self) -> Hir {
        let mut reader = SeekReader {
            code: &self.0,
            at: 1,
        };
        let hir = reader.hir();
        debug_assert_eq!(reader.at, self.0.len(), "the seek code is read whole");
        hir
    }

    /// Bytes of the code.
    #[cfg(test)]
    pub(crate) fn len(&self) -> usize {
        self.0.len()
    }
}

/// A cursor over a `SeekCode`, decoding it.
struct SeekReader<'a> {
    code: &'a [u8],
    at: usize,
}

impl SeekReader<'_> {
    fn byte(&mut self) -> u8 {
        let b = self.code[self.at];
        self.at += 1;
        b
    }

    fn varint(&mut self) -> usize {
        let mut value = 0usize;
        let mut shift = 0;
        loop {
            let b = self.byte();
            value |= usize::from(b & 0x7F) << shift;
            if b & 0x80 == 0 {
                return value;
            }
            shift += 7;
        }
    }

    fn hir(&mut self) -> Hir {
        match self.byte() {
            tag::EMPTY => Hir::empty(),
            tag::LITERAL => {
                let len = self.varint();
                let bytes = &self.code[self.at..self.at + len];
                self.at += len;
                Hir::literal(bytes)
            }
            tag::BYTES => {
                let count = self.varint();
                let ranges: Vec<ClassBytesRange> = (0..count)
                    .map(|_| {
                        let lo = self.byte();
                        let hi = self.byte();
                        ClassBytesRange::new(lo, hi)
                    })
                    .collect();
                Hir::class(Class::Bytes(ClassBytes::new(ranges)))
            }
            tag::UNICODE => {
                let count = self.varint();
                let ranges: Vec<ClassUnicodeRange> = (0..count)
                    .map(|_| {
                        let lo = char::from_u32(self.varint() as u32).expect("a code point");
                        let hi = char::from_u32(self.varint() as u32).expect("a code point");
                        ClassUnicodeRange::new(lo, hi)
                    })
                    .collect();
                Hir::class(Class::Unicode(ClassUnicode::new(ranges)))
            }
            tag::LOOK => Hir::look(Look::from_repr(self.varint() as u32).expect("a look")),
            tag::REPETITION => {
                let min = self.varint() as u32;
                let max = match self.varint() {
                    0 => None,
                    max => Some(max as u32 - 1),
                };
                let greedy = self.byte() != 0;
                let sub = Box::new(self.hir());
                Hir::repetition(Repetition {
                    min,
                    max,
                    greedy,
                    sub,
                })
            }
            tag::CONCAT => {
                let count = self.varint();
                Hir::concat((0..count).map(|_| self.hir()).collect())
            }
            tag::ALTERNATION => {
                let count = self.varint();
                Hir::alternation((0..count).map(|_| self.hir()).collect())
            }
            _ => unreachable!("a seek code tag"),
        }
    }
}

/// The decoded seek in regex syntax.
impl std::fmt::Debug for SeekCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("SeekCode")
            .field(&self.decode().to_string())
            .finish()
    }
}

/// Any character, newline included: an ASCII byte or one UTF-8 sequence.
/// One byte would not do: `.x` matches `éx` at the `é`, two bytes before
/// the `x`.
fn any_char() -> Hir {
    byte_class(u128::MAX, true)
}

/// Any character but a newline.
fn any_char_except_newline() -> Hir {
    byte_class(!(1u128 << b'\n'), true)
}

/// `(?s:.)*`, for a node the seek cannot express.
fn placeholder() -> Hir {
    Hir::repetition(Repetition {
        min: 0,
        max: None,
        greedy: true,
        sub: Box::new(any_char()),
    })
}

fn is_placeholder(hir: &Hir) -> bool {
    match hir.kind() {
        HirKind::Repetition(rep) => rep.min == 0 && rep.max.is_none() && *rep.sub == any_char(),
        _ => false,
    }
}

/// Any non-ASCII character as its UTF-8 bytes: a lead byte and one to
/// three continuation bytes, a superset of every valid sequence.
fn non_ascii_char() -> Hir {
    Hir::concat(vec![
        Hir::class(Class::Bytes(ClassBytes::new([ClassBytesRange::new(
            0xC2, 0xF4,
        )]))),
        Hir::repetition(Repetition {
            min: 1,
            max: Some(3),
            greedy: true,
            sub: Box::new(Hir::class(Class::Bytes(ClassBytes::new([
                ClassBytesRange::new(0x80, 0xBF),
            ])))),
        }),
    ])
}

/// Whether the HIR matches at every position: it is nullable without any
/// look assertion, or it starts with `(?s:.)*`.
fn matches_everywhere(hir: &Hir) -> bool {
    let properties = hir.properties();
    if properties.minimum_len() == Some(0) && properties.look_set().is_empty() {
        return true;
    }
    let first = match hir.kind() {
        HirKind::Concat(subs) => subs.first(),
        _ => Some(hir),
    };
    first.is_some_and(is_placeholder)
}

/// Whether a class over these code point ranges is exact in the seek: its
/// non-ASCII members are none, or every non-ASCII character, since `class_hir`
/// writes them as one UTF-8 sequence, which is exact only then. A negation
/// takes the complement of those, so the same condition covers it.
fn class_exact(ranges: &[(u32, u32)]) -> bool {
    ranges
        .iter()
        .all(|&(lo, hi)| lo > hi || hi < 0x80 || (lo.max(0x80) == 0x80 && hi >= 0x10FFFF))
}

/// The most non-ASCII members a class may list one by one (`explicit_class`).
const EXPLICIT_MEMBERS: usize = 16;

/// A positive class whose non-ASCII members are few, written exactly: its
/// ASCII members as bytes and each non-ASCII member as its UTF-8 sequence. A
/// case-insensitive class holds such members (the Kelvin sign for `k`, the
/// long s for `s`), and listing them keeps the class exact where
/// `class_hir` would approximate them. `None` when there are more than
/// `EXPLICIT_MEMBERS`, which `class_hir` writes instead.
fn explicit_class(ranges: &[(u32, u32)]) -> Option<Hir> {
    let mut ascii: u128 = 0;
    let mut members = Vec::new();
    for &(lo, hi) in ranges {
        if lo > hi {
            continue;
        }
        if lo <= 0x7F {
            ascii |= ascii_mask(lo as u8, hi.min(0x7F) as u8);
        }
        let lo = lo.max(0x80);
        if hi < lo {
            continue;
        }
        let count = (hi - lo) as usize + 1;
        if members.len() + count > EXPLICIT_MEMBERS {
            return None;
        }
        for code in lo..=hi {
            // A surrogate is no character, and the matcher never reads one.
            if let Some(c) = char::from_u32(code) {
                members.push(Hir::literal(c.to_string().into_bytes().into_boxed_slice()));
            }
        }
    }
    members.insert(0, byte_class(ascii, false));
    Some(alternation(members))
}

/// Whether every `^` (`Look::StartLF`) in the seek is one the matcher reads
/// alike. The matcher holds `^` at the start of the subject and after a
/// newline that is not the last byte, the seek after any newline; the two
/// differ only where nothing follows the `^`. So a `^` must be followed by
/// something that consumes a byte, in its own sequence or branch.
fn line_starts_exact(hir: &Hir) -> bool {
    if !hir.properties().look_set().contains(Look::StartLF) {
        return true;
    }
    match hir.kind() {
        HirKind::Concat(parts) => parts.iter().enumerate().all(|(k, part)| {
            if matches!(part.kind(), HirKind::Look(Look::StartLF)) {
                parts[k + 1..]
                    .iter()
                    .map(|rest| rest.properties().minimum_len().unwrap_or(0))
                    .sum::<usize>()
                    >= 1
            } else {
                line_starts_exact(part)
            }
        }),
        HirKind::Alternation(branches) => branches.iter().all(line_starts_exact),
        // A `^` under a repetition, a capture or alone is not judged here.
        _ => false,
    }
}

/// A class over code point ranges (inclusive), negated or not: the ASCII
/// members exactly, and one UTF-8 sequence for any non-ASCII member.
///
/// One pass over the ranges fills an ASCII bitset and notes whether the
/// class reaches past ASCII. A negated class reaches past ASCII unless one
/// range held every code point from 0x80 up; a negated class that covers
/// more of them than that keeps the sequence too, which admits more.
fn class_hir(ranges: impl IntoIterator<Item = (u32, u32)>, negate: bool) -> Hir {
    let mut ascii: u128 = 0;
    let mut non_ascii = false;
    let mut all_non_ascii = false;
    for (lo, hi) in ranges {
        if lo > hi {
            continue;
        }
        if lo <= 0x7F {
            ascii |= ascii_mask(lo as u8, hi.min(0x7F) as u8);
        }
        if hi >= 0x80 {
            non_ascii = true;
            all_non_ascii |= lo <= 0x80 && hi >= 0x10FFFF;
        }
    }
    if negate {
        ascii = !ascii;
        non_ascii = !all_non_ascii;
    }
    byte_class(ascii, non_ascii)
}

/// The bits `lo..=hi` of an ASCII bitset.
fn ascii_mask(lo: u8, hi: u8) -> u128 {
    debug_assert!(lo <= hi && hi <= 0x7F);
    let width = u32::from(hi - lo) + 1;
    let run = if width == 128 {
        u128::MAX
    } else {
        (1u128 << width) - 1
    };
    run << lo
}

/// The class of the ASCII bytes in `ascii`, and of any non-ASCII character
/// when `non_ascii`.
fn byte_class(ascii: u128, non_ascii: bool) -> Hir {
    let mut ranges = Vec::new();
    let mut byte = 0u32;
    while byte <= 0x7F {
        if ascii & (1u128 << byte) == 0 {
            byte += 1;
            continue;
        }
        let lo = byte;
        while byte < 0x7F && ascii & (1u128 << (byte + 1)) != 0 {
            byte += 1;
        }
        ranges.push(ClassBytesRange::new(lo as u8, byte as u8));
        byte += 1;
    }
    match (ranges.is_empty(), non_ascii) {
        (false, false) => Hir::class(Class::Bytes(ClassBytes::new(ranges))),
        (false, true) => alternation(vec![
            Hir::class(Class::Bytes(ClassBytes::new(ranges))),
            non_ascii_char(),
        ]),
        (true, true) => non_ascii_char(),
        (true, false) => Hir::fail(),
    }
}

/// Whether the HIR never matches (an empty class).
fn is_fail(hir: &Hir) -> bool {
    match hir.kind() {
        HirKind::Class(Class::Bytes(class)) => class.ranges().is_empty(),
        HirKind::Class(Class::Unicode(class)) => class.ranges().is_empty(),
        _ => false,
    }
}

/// `Hir::concat` without the parts a never-matching part makes
/// unreachable, which `Hir::concat` keeps.
fn concat(parts: Vec<Hir>) -> Hir {
    if parts.iter().any(is_fail) {
        Hir::fail()
    } else {
        Hir::concat(parts)
    }
}

/// `sub` repeated `min` to `max` times (`None`: unbounded), always greedy,
/// since the automata only ask where a seek matches.
///
/// A repetition of a repetition is flattened: `(X{a,b}){c,d}` reads between
/// `a·c` and `b·d` copies of `X`, so `X{a·c,b·d}` matches wherever it does
/// and compiles to fewer states. Counted bounds above `MAX_COUNTED_REPEAT`
/// become unbounded.
fn repetition(mut min: u32, mut max: Option<u32>, sub: Hir, inexact: &mut bool) -> Hir {
    let nested = match sub.kind() {
        HirKind::Repetition(inner) => Some((inner.min, inner.max, (*inner.sub).clone())),
        _ => None,
    };
    let sub = match nested {
        Some((inner_min, inner_max, inner)) => {
            min = min.saturating_mul(inner_min);
            max = match (max, inner_max) {
                (Some(outer), Some(inner)) => Some(outer.saturating_mul(inner)),
                _ => None,
            };
            inner
        }
        None => sub,
    };
    if min > MAX_COUNTED_REPEAT || max.is_some_and(|max| max > MAX_COUNTED_REPEAT) {
        // A bound above the limit widens the repetition.
        *inexact = true;
        min = min.min(MAX_COUNTED_REPEAT);
        max = None;
    }
    Hir::repetition(Repetition {
        min,
        max,
        greedy: true,
        sub: Box::new(sub),
    })
}

/// `Hir::alternation` without the branches that never match, which
/// `Hir::alternation` keeps.
fn alternation(mut branches: Vec<Hir>) -> Hir {
    branches.retain(|branch| !is_fail(branch));
    if branches.is_empty() {
        Hir::fail()
    } else {
        Hir::alternation(branches)
    }
}

/// The `(from, to)` pairs of a code range buffer (`data[0]` is the count).
fn code_ranges(bbuf: &BBuf) -> impl Iterator<Item = (u32, u32)> + '_ {
    let words = bbuf.data.as_chunks::<4>().0;
    let n = words.first().map_or(0, |chunk| u32::from_ne_bytes(*chunk)) as usize;
    words[1..]
        .as_chunks::<2>()
        .0
        .iter()
        .take(n)
        .map(|pair| (u32::from_ne_bytes(pair[0]), u32::from_ne_bytes(pair[1])))
}

/// The members of a class node, as the matcher reads them over UTF-8: the
/// bits below 0x80 decide a single-byte character and the code ranges from
/// 0x80 up a multibyte one, and nothing else is read. Nested negations
/// (`[^[^[^İ]\S]]`) leave the other side with entries the matcher never
/// consults: bits at 0x80 and up, and code ranges below 0x80.
fn class_members(cc: &CClassNode) -> impl Iterator<Item = (u32, u32)> + '_ {
    let bits = bitset_members(&cc.bs)
        .filter(|&member| member < 0x80)
        .map(|member| (member as u32, member as u32));
    let ranges = cc
        .mbuf
        .iter()
        .flat_map(code_ranges)
        .filter_map(|(lo, hi)| (hi >= 0x80).then_some((lo.max(0x80), hi)));
    bits.chain(ranges)
}

/// The ASCII half boundary a negative look stands for, where its body is
/// one class that holds every ASCII word character: `(?<!\w)` and
/// `(?<![-\w])` hold only where the previous character is not an ASCII word
/// character (`\b{start-half}`), `(?!\w)` and `(?![.:\w])` only where the
/// next one is not (`\b{end-half}`). Next to a non-ASCII character the
/// half boundary holds and the look may not, which admits more. Without
/// this, a keyword list behind `(?<![-\w])` would be a candidate inside
/// every identifier that contains a keyword.
fn word_class_look(an: &AnchorNode) -> Option<Look> {
    let look = match an.anchor_type {
        ANCR_LOOK_BEHIND_NOT => Look::WordStartHalfAscii,
        ANCR_PREC_READ_NOT => Look::WordEndHalfAscii,
        _ => return None,
    };
    let body = an.body.as_deref()?;
    let word_bytes = (b'0'..=b'9')
        .chain(b'A'..=b'Z')
        .chain(b'a'..=b'z')
        .chain(*b"_");
    let holds_every_word_byte = match &body.inner {
        NodeInner::CType(ct) => ct.ctype == ONIGENC_CTYPE_WORD as i32 && !ct.not,
        NodeInner::CClass(cc) => {
            let mut members = word_bytes.map(|byte| bitset_at(&cc.bs, byte as usize));
            if cc.is_not() {
                members.all(|member| !member)
            } else {
                members.all(|member| member)
            }
        }
        _ => false,
    };
    holds_every_word_byte.then_some(look)
}

/// A group-number condition (`(?(1)…)`, `(?(<name>)…)`): a back reference
/// that only checks whether the group captured.
fn is_capture_check(node: &Node) -> bool {
    matches!(node.inner, NodeInner::BackRef(_)) && node.has_status(ND_ST_CHECKER)
}

/// Whether a stop-backtrack bag is one `tune_next` made for automatic
/// possessification: a greedy repeat followed by an item that cannot start
/// where its body does is `(?>a*)` followed by that item (C: `tune_next`).
/// Only that pass sets `ND_ST_STRICT_REAL_REPEAT`, and it sets it on that
/// bag alone, so a user-written atomic group or possessive quantifier never
/// has it. The bag keeps the language of its repetition (the item cannot
/// match at any position the repeat could give back to), so the seek writes
/// the plain repetition and stays exact.
fn automatic_possessive(node: &Node) -> bool {
    node.has_status(ND_ST_STRICT_REAL_REPEAT)
}

/// A node that produces nothing in the seek and consumes nothing, so a
/// positive look-ahead before it may keep its body in place.
fn droppable(node: &Node) -> bool {
    match &node.inner {
        NodeInner::BackRef(_) => is_capture_check(node),
        NodeInner::Anchor(an) => match an.anchor_type {
            ANCR_PREC_READ_NOT | ANCR_LOOK_BEHIND_NOT => word_class_look(an).is_none(),
            ANCR_PREC_READ
            | ANCR_LOOK_BEHIND
            | ANCR_BEGIN_POSITION
            | ANCR_TEXT_SEGMENT_BOUNDARY
            | ANCR_NO_TEXT_SEGMENT_BOUNDARY => true,
            _ => false,
        },
        NodeInner::Gimmick(_) => true,
        NodeInner::String(sn) => sn.s.is_empty(),
        NodeInner::Quant(qn) => qn.upper == 0 || qn.body.as_deref().is_none_or(droppable),
        NodeInner::Bag(bn) => match &bn.bag_data {
            BagData::IfElse {
                then_node,
                else_node,
            } => {
                bn.body.as_deref().is_none_or(droppable)
                    && then_node.as_deref().is_none_or(droppable)
                    && else_node.as_deref().is_none_or(droppable)
            }
            _ => bn.body.as_deref().is_none_or(droppable),
        },
        NodeInner::List(_) | NodeInner::Alt(_) => cons_items(node).into_iter().all(droppable),
        _ => false,
    }
}

/// The code points of a node that is a class, a string, or a list,
/// alternation or group of those, added to `ranges`, with the fewest and
/// most characters it reads. `None` for any other node.
fn class_union(node: &Node, ranges: &mut Vec<(u32, u32)>) -> Option<(usize, usize)> {
    match &node.inner {
        NodeInner::CClass(cc) => {
            if cc.is_not() {
                return None;
            }
            ranges.extend(class_members(cc));
            Some((1, 1))
        }
        NodeInner::String(sn) => {
            if node.has_status(ND_ST_IGNORECASE) && !sn.is_crude() {
                return None;
            }
            let text = std::str::from_utf8(&sn.s).ok()?;
            let mut count = 0;
            for c in text.chars() {
                ranges.push((c as u32, c as u32));
                count += 1;
            }
            Some((count, count))
        }
        NodeInner::List(_) => {
            let mut lens = (0, 0);
            for item in cons_items(node) {
                let (lo, hi) = class_union(item, ranges)?;
                lens = (lens.0 + lo, lens.1 + hi);
            }
            Some(lens)
        }
        NodeInner::Alt(_) => {
            let mut lens = (usize::MAX, 0);
            for item in cons_items(node) {
                let (lo, hi) = class_union(item, ranges)?;
                lens = (lens.0.min(lo), lens.1.max(hi));
            }
            Some(lens)
        }
        NodeInner::Bag(bn) if !matches!(bn.bag_data, BagData::IfElse { .. }) => {
            class_union(bn.body.as_deref()?, ranges)
        }
        _ => None,
    }
}

/// The elements of a List or Alt chain.
fn cons_items(node: &Node) -> Vec<&Node> {
    let mut items = Vec::new();
    let mut cur = node;
    loop {
        match &cur.inner {
            NodeInner::List(cons) | NodeInner::Alt(cons) => {
                items.push(&*cons.car);
                match &cons.cdr {
                    Some(next) => cur = next,
                    None => break,
                }
            }
            _ => {
                items.push(cur);
                break;
            }
        }
    }
    items
}

/// Writes the `\Z` nodes that end the pattern: the last element of a list,
/// a branch of an alternation in that position, or the body of a group there.
/// Nothing follows such a node, so `\Z` holds exactly where the seek writes
/// `(?:\n)?\z`: before the end or before a final newline. Elsewhere `\Z` is
/// approximated by `$` (`Walk::anchor`). Addresses only, compared and never
/// read.
fn collect_tails(node: &Node, out: &mut Vec<*const Node>) {
    match &node.inner {
        NodeInner::List(_) => {
            if let Some(&last) = cons_items(node).last() {
                collect_tails(last, out);
            }
        }
        NodeInner::Alt(_) => {
            for branch in cons_items(node) {
                collect_tails(branch, out);
            }
        }
        NodeInner::Bag(bn) if !matches!(bn.bag_data, BagData::IfElse { .. }) => {
            if let Some(body) = bn.body.as_deref() {
                collect_tails(body, out);
            }
        }
        NodeInner::Anchor(an) if an.anchor_type == ANCR_SEMI_END_BUF => {
            out.push(node as *const Node);
        }
        _ => {}
    }
}

/// One walk over a tuned parse tree, writing the seek HIR.
struct Walk<'a> {
    reg: &'a RegexType,
    /// Positive look-aheads whose body was kept in place so far.
    lookaheads_kept: u32,
    /// A construct the seek approximates was written (`SeekCode::exact`).
    inexact: bool,
    /// The `\Z` nodes that end the pattern (`collect_tails`), by address.
    tails: Vec<*const Node>,
    /// The seek of a single `Regex` (`derive`'s `precise`): alternations
    /// are written branch by branch, where the scanner's seek shortcuts a
    /// class-led alternation as a repetition of its class.
    precise: bool,
}

impl Walk<'_> {
    /// `node` as an element whose following siblings are all droppable
    /// when `rest_droppable`: a positive look-ahead then keeps its body.
    fn item(&mut self, node: &Node, rest_droppable: bool) -> Hir {
        if let NodeInner::Anchor(an) = &node.inner {
            if an.anchor_type == ANCR_PREC_READ {
                return self.lookahead(an, rest_droppable);
            }
        }
        self.node(node, rest_droppable)
    }

    fn lookahead(&mut self, an: &AnchorNode, keep: bool) -> Hir {
        self.inexact = true;
        if keep {
            self.lookaheads_kept += 1;
            an.body
                .as_deref()
                .map_or_else(Hir::empty, |body| self.item(body, true))
        } else {
            Hir::empty()
        }
    }

    fn node(&mut self, node: &Node, rest_droppable: bool) -> Hir {
        if node.has_status(ND_ST_LITERAL_ALT) {
            return self.trie(node);
        }
        match &node.inner {
            NodeInner::String(sn) => {
                // The tuner unravels a case-insensitive string into exact
                // alternatives; one it left stands for anything.
                if node.has_status(ND_ST_IGNORECASE) {
                    self.inexact = true;
                    if !sn.is_crude() {
                        return placeholder();
                    }
                }
                if sn.s.is_empty() {
                    Hir::empty()
                } else {
                    Hir::literal(sn.s.clone().into_boxed_slice())
                }
            }
            NodeInner::CClass(cc) => self.cclass(cc),
            NodeInner::CType(ct) => self.ctype(node, ct),
            NodeInner::BackRef(_) | NodeInner::Call(_) => {
                self.inexact = true;
                placeholder()
            }
            NodeInner::Quant(qn) => {
                let Some(body) = qn.body.as_deref() else {
                    return Hir::empty();
                };
                // A look-ahead kept in a body that runs again would be read
                // before the next iteration's text, so only a body that runs
                // at most once keeps one.
                let body_rest = rest_droppable && (0..=1).contains(&qn.upper);
                let sub = self.item(body, body_rest);
                let min = u32::try_from(qn.lower.max(0)).unwrap_or(u32::MAX);
                let max = (qn.upper >= 0).then_some(qn.upper as u32);
                repetition(min, max, sub, &mut self.inexact)
            }
            NodeInner::Bag(bn) => match &bn.bag_data {
                // The condition runs first and, where it holds, the then
                // branch goes on after what the condition consumed; where
                // it fails, the else branch runs from the start. A
                // group-number condition (`(?(1)…)`) is a zero-width check.
                BagData::IfElse {
                    then_node,
                    else_node,
                } => {
                    self.inexact = true;
                    let condition = bn
                        .body
                        .as_deref()
                        .map_or_else(Hir::empty, |cond| self.condition(cond));
                    let then = then_node
                        .as_deref()
                        .map_or_else(Hir::empty, |n| self.item(n, rest_droppable));
                    let otherwise = else_node
                        .as_deref()
                        .map_or_else(Hir::empty, |n| self.item(n, rest_droppable));
                    alternation(vec![concat(vec![condition, then]), otherwise])
                }
                // An atomic group keeps only the first way its body matches,
                // which the seek, keeping every way, does not: `(?>abc|ab)c`
                // has no match in `abc`, its seek does. The bag `tune_next`
                // makes for automatic possessification is the repetition
                // itself, see `automatic_possessive`.
                BagData::StopBacktrack | BagData::TextSegment => {
                    if !(matches!(bn.bag_data, BagData::StopBacktrack)
                        && automatic_possessive(node))
                    {
                        self.inexact = true;
                    }
                    bn.body
                        .as_deref()
                        .map_or_else(Hir::empty, |body| self.item(body, rest_droppable))
                }
                _ => bn
                    .body
                    .as_deref()
                    .map_or_else(Hir::empty, |body| self.item(body, rest_droppable)),
            },
            NodeInner::Anchor(an) => {
                if self.tails.contains(&(node as *const Node)) {
                    let newline = repetition(0, Some(1), Hir::literal(*b"\n"), &mut self.inexact);
                    return concat(vec![newline, Hir::look(Look::End)]);
                }
                self.anchor(an)
            }
            NodeInner::List(_) => self.list(node, rest_droppable),
            NodeInner::Alt(_) => {
                let branches = cons_items(node);
                // `(?i)` turns a class with multi-character folds into
                // `Alt(class, "ss", "fi", …)`, and such classes repeat in a
                // pattern: the union of their characters, repeated as often
                // as the longest branch reads, stands for all of them.
                if !self.precise
                    && branches.len() >= 2
                    && matches!(branches[0].inner, NodeInner::CClass(_))
                {
                    let mut ranges = Vec::new();
                    let mut lens: Option<(usize, usize)> = Some((usize::MAX, 0));
                    for branch in &branches {
                        match class_union(branch, &mut ranges) {
                            Some((lo, hi)) => lens = lens.map(|(a, b)| (a.min(lo), b.max(hi))),
                            None => {
                                lens = None;
                                break;
                            }
                        }
                    }
                    if let Some((min, max)) = lens {
                        self.inexact = true;
                        return Hir::repetition(Repetition {
                            min: u32::try_from(min).unwrap_or(u32::MAX),
                            max: Some(u32::try_from(max).unwrap_or(u32::MAX)),
                            greedy: true,
                            sub: Box::new(class_hir(ranges, false)),
                        });
                    }
                }
                let branches = branches
                    .into_iter()
                    .map(|branch| self.item(branch, rest_droppable))
                    .collect();
                alternation(branches)
            }
            // `\K` and the absent operator's bookkeeping consume nothing;
            // the absent operator's own `Fail` never matches (`(*FAIL)` is
            // a callout, which leaves the pattern without a seek).
            NodeInner::Gimmick(gn) => {
                // `\K` is exact for existence. The range cutter of the absent
                // operator (a save and updates of the range, and a `Fail`)
                // is not, and the other gimmicks are left out.
                let keep = match gn.gimmick_type {
                    GimmickType::Save => gn.detail_type == SaveType::Keep as i32,
                    GimmickType::UpdateVar => {
                        gn.detail_type == UpdateVarType::KeepFromStackLast as i32
                    }
                    _ => false,
                };
                if !keep {
                    self.inexact = true;
                }
                match gn.gimmick_type {
                    GimmickType::Fail => Hir::fail(),
                    _ => Hir::empty(),
                }
            }
        }
    }

    /// The condition of a conditional: a group-number condition is a
    /// zero-width check of the group's capture; any other reads text as the
    /// expression it is.
    fn condition(&mut self, cond: &Node) -> Hir {
        if is_capture_check(cond) {
            Hir::empty()
        } else {
            self.item(cond, false)
        }
    }

    fn list(&mut self, node: &Node, rest_droppable: bool) -> Hir {
        let items = cons_items(node);
        let mut parts = Vec::with_capacity(items.len());
        let mut kept_before = false;
        for (k, item) in items.iter().enumerate() {
            // At most one look-ahead per list keeps its body: two of them
            // hold at the same position, and in the seek the second would
            // follow the first's text.
            let rest =
                rest_droppable && !kept_before && items[k + 1..].iter().all(|n| droppable(n));
            let kept = self.lookaheads_kept;
            parts.push(self.item(item, rest));
            if self.lookaheads_kept != kept {
                kept_before = true;
            }
        }
        concat(parts)
    }

    fn anchor(&mut self, an: &AnchorNode) -> Hir {
        // Only `\A`, `\z`, `$` and `^` read the text the way the seek does.
        if !matches!(
            an.anchor_type,
            ANCR_BEGIN_BUF | ANCR_END_BUF | ANCR_END_LINE | ANCR_BEGIN_LINE
        ) {
            self.inexact = true;
        }
        match an.anchor_type {
            // A look-ahead reaches here only where something consuming
            // follows it. Look-behinds read what is before the position.
            ANCR_PREC_READ | ANCR_LOOK_BEHIND => Hir::empty(),
            ANCR_PREC_READ_NOT | ANCR_LOOK_BEHIND_NOT => {
                word_class_look(an).map_or_else(Hir::empty, Hir::look)
            }
            ANCR_BEGIN_BUF => Hir::look(Look::Start),
            ANCR_END_BUF => Hir::look(Look::End),
            // `\Z` holds before a final newline; `(?m:$)` before any.
            ANCR_SEMI_END_BUF | ANCR_END_LINE => Hir::look(Look::EndLF),
            ANCR_BEGIN_LINE => Hir::look(Look::StartLF),
            // `\G` depends on the search start.
            ANCR_BEGIN_POSITION => Hir::empty(),
            ANCR_WORD_BOUNDARY | ANCR_NO_WORD_BOUNDARY | ANCR_WORD_BEGIN | ANCR_WORD_END
                if an.ascii_mode =>
            {
                // ASCII word boundaries need no quit bytes.
                Hir::look(match an.anchor_type {
                    ANCR_WORD_BOUNDARY => Look::WordAscii,
                    ANCR_NO_WORD_BOUNDARY => Look::WordAsciiNegate,
                    ANCR_WORD_BEGIN => Look::WordStartAscii,
                    _ => Look::WordEndAscii,
                })
            }
            ANCR_WORD_BOUNDARY | ANCR_NO_WORD_BOUNDARY | ANCR_WORD_BEGIN | ANCR_WORD_END => {
                // A Unicode word boundary makes a lazy DFA quit at non-ASCII
                // bytes, after which a search gives up on the DFA (see
                // `candidate_in`). Between two ASCII characters it is the ASCII
                // boundary; next to a non-ASCII character it may hold, and
                // the ASCII half boundaries (the previous or the next
                // character is not an ASCII word character) admit that.
                Hir::alternation(vec![
                    Hir::look(match an.anchor_type {
                        ANCR_WORD_BOUNDARY => Look::WordAscii,
                        ANCR_NO_WORD_BOUNDARY => Look::WordAsciiNegate,
                        ANCR_WORD_BEGIN => Look::WordStartAscii,
                        _ => Look::WordEndAscii,
                    }),
                    Hir::look(Look::WordStartHalfAscii),
                    Hir::look(Look::WordEndHalfAscii),
                ])
            }
            // Text segment boundaries (`\y`, `\Y`).
            _ => Hir::empty(),
        }
    }

    fn cclass(&mut self, cc: &CClassNode) -> Hir {
        let ranges: Vec<(u32, u32)> = class_members(cc).collect();
        if self.precise && !cc.is_not() {
            if let Some(hir) = explicit_class(&ranges) {
                return hir;
            }
        }
        if !class_exact(&ranges) {
            self.inexact = true;
        }
        class_hir(ranges, cc.is_not())
    }

    fn ctype(&mut self, node: &Node, ct: &CtypeNode) -> Hir {
        if ct.ctype == CTYPE_ANYCHAR {
            return if node.has_status(ND_ST_MULTILINE) {
                any_char()
            } else {
                any_char_except_newline()
            };
        }
        // The non-ASCII part of a Unicode `\w` or `\W` is every non-ASCII
        // character, which is exact only in ASCII mode (see below).
        if !(ct.ctype == ONIGENC_CTYPE_WORD as i32 && ct.ascii_mode) {
            self.inexact = true;
        }
        if ct.ctype == ONIGENC_CTYPE_WORD as i32 {
            // The ASCII word characters are the same in both modes; the
            // Unicode mode adds non-ASCII ones, which stand for any
            // non-ASCII character. `\W` is the complement of the exact ASCII
            // set plus any non-ASCII character: every one of them in ASCII
            // mode, all but the Unicode word characters otherwise.
            // Complementing the widened set would leave them all out.
            let word = ascii_mask(b'0', b'9')
                | ascii_mask(b'A', b'Z')
                | ascii_mask(b'_', b'_')
                | ascii_mask(b'a', b'z');
            return if ct.not {
                byte_class(!word, true)
            } else {
                byte_class(word, !ct.ascii_mode)
            };
        }
        // The parser turns the other ctypes into classes; a remaining one
        // stands for any character.
        any_char()
    }

    /// A literal trie: its literals, or for a folded trie what the engine
    /// accepts for them (ASCII case pairs, the non-ASCII members of each
    /// letter's class, and the strings of each multi-character segment).
    fn trie(&mut self, node: &Node) -> Hir {
        let reg = self.reg;
        let Some(trie) = literal_alt_trie_index(node).and_then(|idx| reg.literal_tries.get(idx))
        else {
            self.inexact = true;
            return placeholder();
        };
        let literals = trie.literals();
        if !trie.is_case_insensitive() {
            return alternation(
                literals
                    .iter()
                    .map(|literal| Hir::literal(literal.clone().into_boxed_slice()))
                    .collect(),
            );
        }
        self.inexact = true;
        let Some(folds) = trie.folds() else {
            return placeholder();
        };
        // Every literal as ASCII case classes: one byte class per letter.
        let mut branches: Vec<Hir> = literals
            .iter()
            .map(|literal| {
                concat(
                    literal
                        .iter()
                        .map(|&c| {
                            if c.is_ascii_alphabetic() {
                                Hir::class(Class::Bytes(ClassBytes::new([
                                    ClassBytesRange::new(
                                        c.to_ascii_lowercase(),
                                        c.to_ascii_lowercase(),
                                    ),
                                    ClassBytesRange::new(
                                        c.to_ascii_uppercase(),
                                        c.to_ascii_uppercase(),
                                    ),
                                ])))
                            } else {
                                Hir::literal([c])
                            }
                        })
                        .collect(),
                )
            })
            .collect();
        // A folded match that reads a non-ASCII character (a class member
        // such as the Kelvin sign for `k`, or a ligature such as `ß` for
        // `ss`) reads at most `longest - 1` ASCII characters before it and,
        // since every remaining literal character reads at least one text
        // character, at most `longest - 1` characters of any kind after it:
        // one escape alternative per trie admits those matches, and ends
        // where the literal can end, so what follows the trie is read from
        // there.
        let mut non_ascii: Vec<Hir> = folds
            .class_members
            .iter()
            .filter_map(|&(code, _)| char::from_u32(code))
            .map(|c| Hir::literal(c.to_string().into_bytes().into_boxed_slice()))
            .chain(
                folds
                    .ligatures
                    .iter()
                    .map(|(bytes, _)| Hir::literal(bytes.clone().into_boxed_slice())),
            )
            .collect();
        if !non_ascii.is_empty() {
            non_ascii.sort_by_key(|a| a.to_string());
            non_ascii.dedup_by(|a, b| a.to_string() == b.to_string());
            let longest = literals.iter().map(Vec::len).max().unwrap_or(1).max(1);
            let rest = u32::try_from(longest - 1).unwrap_or(u32::MAX);
            let ascii_prefix = repetition(
                0,
                Some(rest),
                Hir::class(Class::Bytes(ClassBytes::new([ClassBytesRange::new(
                    0x00, 0x7F,
                )]))),
                &mut self.inexact,
            );
            let suffix = repetition(0, Some(rest), any_char(), &mut self.inexact);
            branches.push(concat(vec![ascii_prefix, alternation(non_ascii), suffix]));
        }
        alternation(branches)
    }
}

/// The automata of one pattern list: forward and reverse lazy DFAs over the
/// covered seeks for the earliest candidate position, and an overlapping
/// lazy DFA for the entries whose seek matches there. Both are read-only
/// once built (their lazy DFA caches are the set's, in `SetPrefilter`), so
/// every set over the same pattern list can hold the same `Automata`.
pub(crate) struct Automata {
    search: Arc<hybrid_regex::Regex>,
    dfa: hybrid::DFA,
    /// The entry index each pattern ID stands for, ascending.
    entries: Vec<u16>,
    /// Entries searched on their own, in index order.
    own: Vec<u16>,
    /// The pattern IDs of the seeks that can keep a walk alive past
    /// `settle`: unbounded or longer than `LONG_SEEK_BYTES`.
    long: Vec<u16>,
    /// Bytes after which every other seek has settled.
    settle: usize,
    #[cfg(feature = "scanner-group-prototype")]
    frozen: Option<Arc<group_archive::Frozen>>,
    #[cfg(feature = "precompiled-eager")]
    portable: Option<Arc<portable::Portable>>,
}

/// A set's handle on its automata: built by the first set that searches
/// with the pre-filter, and shared with every set built from one pattern
/// cache over the same pattern list (ADR-006). Holds `None` once a build
/// found nothing to cover, an entry with callouts, or too much
/// (`MAX_NFA_STATES`): those sets keep the position-lead search.
#[derive(Clone, Default)]
pub(crate) struct AutomataCell(Arc<OnceLock<Option<Arc<Automata>>>>);

impl AutomataCell {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    /// The automata, built by `build` unless a set has built them already.
    pub(crate) fn get_or_build(
        &self,
        build: impl FnOnce() -> Option<Automata>,
    ) -> Option<Arc<Automata>> {
        self.0.get_or_init(|| build().map(Arc::new)).clone()
    }
}

/// A set's part of the pre-filter: its lazy DFA caches over the shared
/// [`Automata`], and the scratch state of its searches.
pub(crate) struct SetPrefilter {
    /// The automata of the set's pattern list: clones of the shared
    /// [`Automata`]'s, which keep their NFAs and transition tables behind
    /// `Arc`s, so a search reads them as the set's own, without an
    /// indirection, and the heavy parts are held once.
    search: Arc<hybrid_regex::Regex>,
    search_cache: hybrid_regex::Cache,
    dfa: hybrid::DFA,
    dfa_cache: hybrid::Cache,
    patset: PatternBits,
    /// The entry index each pattern ID stands for, ascending.
    entries: Vec<u16>,
    /// Entries searched on their own, in index order.
    own: Vec<u16>,
    /// The pattern IDs of the seeks that can keep a walk alive past
    /// `settle`: unbounded or longer than `LONG_SEEK_BYTES`.
    long: Vec<u16>,
    /// Bytes after which every other seek has settled.
    settle: usize,
    /// The last walk ran to the bound or ended by asking: the next one
    /// asks as soon as the bounded seeks have settled.
    ask_early: bool,
    /// The overlapping DFA or a search DFA gave up on its cache
    /// (`MIN_CACHE_CLEARS`): the set retires the pre-filter after the search.
    gave_up: bool,
    /// Bytes the walks of the current search read, which the DFA cache's
    /// efficiency check counts: one progress span per search, updated
    /// after each walk (a span per walk cost the captured C replay 8% of
    /// its instructions).
    walked: usize,
    /// Per pattern ID, the bytes the set's first-byte table dispatches its
    /// entry on (every byte for a fallback entry).
    dispatch: Vec<[u64; 4]>,
    /// The bytes any long seek's entry is dispatched on, and any entry's.
    long_dispatch: [u64; 4],
    any_dispatch: [u64; 4],
    /// Per pattern ID, the `stamp` of the last walk that found its entry
    /// admissible at the position.
    admissible: Vec<u32>,
    stamp: u32,
    /// Scratch for `candidates_at`, and the position it holds the
    /// candidates of in the current search.
    candidates: Vec<u16>,
    walked_at: Option<usize>,
    /// The last search result for a subject (`earliest_memo`).
    search_memo: Option<SearchMemo>,
    /// The walks of a subject searched again.
    candidate_memo: CandidateMemo,
    #[cfg(feature = "scanner-group-prototype")]
    frozen: Option<Arc<group_archive::Frozen>>,
    #[cfg(feature = "precompiled-eager")]
    portable: Option<(Arc<portable::Portable>, portable::Caches)>,
}

/// What the walks of a subject found (`candidates_at`), per position, for
/// the searches of that subject after its first: a walk reads the subject
/// from its position and asks admission there, both of which depend on the
/// subject only (see `SearchMemo`), so a later search reuses it where it
/// walks a position again, the way the position-lead search reuses its
/// fallback memo. A line tokenized again (an editor re-tokenizing it, a
/// benchmark) walks every position again; a tokenizing pass walks a
/// position the previous search's window walked. The memo holds at most
/// `CANDIDATE_MEMO_POSITIONS` positions, kept sorted (the loop walks
/// forwards), and is cleared when the subject changes. Recording starts
/// once a search of the subject starts at or before the previous one's
/// start, which a tokenizing pass never does (every call starts at the
/// last match's end), so a line tokenized once pays nothing: recording
/// every walk cost the captured C replay 10% of its instructions.
#[derive(Default)]
struct CandidateMemo {
    subject: Option<(crate::regset::FallbackMemoIdentity, usize)>,
    /// The subject was searched again from no later than before: record
    /// and reuse.
    active: bool,
    /// Where the last search of the subject started.
    last_start: usize,
    /// The positions walked, ascending, each with its candidates' span in
    /// `store` and whether a seek matched there (`Some` from
    /// `candidates_at`).
    at: Vec<u32>,
    spans: Vec<(u32, u16, bool)>,
    store: Vec<u16>,
}

/// Records the patterns of the match state `sid`. Out of line on purpose:
/// inlined into the byte walk, the bitset's fields kept the walk's state ID
/// on the stack in Ferriki's arm64 addon, and a walk reaches a match state
/// far less often than it reads a byte. Rust-only (ADR-008).
#[inline(never)]
fn record_match(
    dfa: &hybrid::DFA,
    cache: &hybrid::Cache,
    patset: &mut PatternBits,
    sid: LazyStateID,
) {
    for k in 0..dfa.match_len(cache, sid) {
        patset.insert(dfa.match_pattern(cache, sid, k));
    }
}

/// `record_match`, counting the newly recorded patterns stamped `stamp`.
#[inline(never)]
fn record_needed(
    dfa: &hybrid::DFA,
    cache: &hybrid::Cache,
    patset: &mut PatternBits,
    sid: LazyStateID,
    stamps: &[u32],
    stamp: u32,
) -> usize {
    let mut found = 0;
    for k in 0..dfa.match_len(cache, sid) {
        let pid = dfa.match_pattern(cache, sid, k);
        if patset.insert(pid) && stamps[pid.as_usize()] == stamp {
            found += 1;
        }
    }
    found
}

/// The covered entries a walk recorded, as a bitset over their pattern IDs.
/// `regex_automata::PatternSet` keeps one bool per pattern, which a walk
/// pays for in every `clear` and every ascending scan of the set;
/// membership and insertion here are one word access, and `iter` yields the
/// IDs ascending by `trailing_zeros`, so the candidates keep their order.
/// Rust-only (ADR-008): the same set of IDs, in the same order.
struct PatternBits {
    words: Box<[u64]>,
    /// The bits set.
    len: usize,
    capacity: usize,
}

impl PatternBits {
    fn new(capacity: usize) -> Self {
        PatternBits {
            words: vec![0; capacity.div_ceil(64)].into_boxed_slice(),
            len: 0,
            capacity,
        }
    }

    /// Empties the set; a set that holds nothing is left as it is.
    #[inline]
    fn clear(&mut self) {
        if self.len > 0 {
            self.words.fill(0);
            self.len = 0;
        }
    }

    #[inline]
    fn contains(&self, pid: PatternID) -> bool {
        let i = pid.as_usize();
        i < self.capacity && (self.words[i / 64] >> (i % 64)) & 1 == 1
    }

    /// Adds `pid`, and reports whether it was not in the set.
    #[inline]
    fn insert(&mut self, pid: PatternID) -> bool {
        let i = pid.as_usize();
        assert!(i < self.capacity, "pattern ID {i} outside the set");
        let word = &mut self.words[i / 64];
        let bit = 1u64 << (i % 64);
        if *word & bit != 0 {
            return false;
        }
        *word |= bit;
        self.len += 1;
        true
    }

    #[inline]
    fn is_empty(&self) -> bool {
        self.len == 0
    }

    #[inline]
    fn is_full(&self) -> bool {
        self.len == self.capacity
    }

    /// The pattern IDs in the set, ascending.
    #[inline]
    fn iter(&self) -> impl Iterator<Item = usize> + '_ {
        self.words.iter().enumerate().flat_map(|(w, &word)| {
            let mut bits = word;
            std::iter::from_fn(move || {
                (bits != 0).then(|| {
                    let b = bits.trailing_zeros() as usize;
                    bits &= bits - 1;
                    w * 64 + b
                })
            })
        })
    }
}

/// Positions a `CandidateMemo` holds at most.
const CANDIDATE_MEMO_POSITIONS: usize = 4096;

impl CandidateMemo {
    /// The memo's state for a search of `subject` from `start`: the
    /// previous subject's walks are dropped, and recording starts once a
    /// search of the subject starts no later than the previous one.
    #[inline]
    fn begin(
        &mut self,
        subject: Option<(crate::regset::FallbackMemoIdentity, usize)>,
        start: usize,
    ) {
        if subject.is_some() && subject == self.subject {
            if start <= self.last_start {
                self.active = true;
            }
            self.last_start = start;
            return;
        }
        self.subject = subject;
        self.active = false;
        self.last_start = start;
        self.at.clear();
        self.spans.clear();
        self.store.clear();
    }

    /// The candidates a walk at `at` found, and whether a seek matched.
    fn get(&self, at: usize) -> Option<(&[u16], bool)> {
        let at = u32::try_from(at).ok()?;
        let i = self.at.binary_search(&at).ok()?;
        let (start, len, some) = self.spans[i];
        Some((
            &self.store[start as usize..start as usize + len as usize],
            some,
        ))
    }

    /// Records a walk at `at`.
    fn insert(&mut self, at: usize, candidates: &[u16], some: bool) {
        if self.at.len() >= CANDIDATE_MEMO_POSITIONS {
            return;
        }
        let (Ok(at), Ok(len)) = (u32::try_from(at), u16::try_from(candidates.len())) else {
            return;
        };
        let start = self.store.len() as u32;
        self.store.extend_from_slice(candidates);
        let i = match self.at.binary_search(&at) {
            Ok(_) => return,
            Err(i) => i,
        };
        self.at.insert(i, at);
        self.spans.insert(i, (start, len, some));
    }
}

/// What the covered searches of a subject found, reusable by every later
/// search of it from a position at or after `from`: no covered entry can
/// decide in `[from, at)` and one can at `at`, or, with `at` `None`, none
/// in `[from, until)` (to the end of the subject once the windows reached
/// it). The facts are start-independent: the loop head looks at a search's
/// first position itself, and admission elsewhere depends on the subject
/// and the position only (the gate cache serves later starts alike).
#[derive(Clone, Copy)]
struct SearchMemo {
    subject: (crate::regset::FallbackMemoIdentity, usize),
    from: usize,
    until: usize,
    at: Option<usize>,
}

/// How a candidate walk ended.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ScanEnd {
    /// The DFA died or the haystack ended: every seek match is recorded.
    Finished,
    /// Stopped early: every entry that can decide at the position is
    /// recorded.
    Settled,
    /// The bound, or the DFA quit: the DFA is still alive.
    Bound,
    /// The DFA gave up on its cache: as `Bound`, and the set retires the
    /// pre-filter after the search.
    GaveUp,
}

impl std::fmt::Debug for SetPrefilter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SetPrefilter")
            .field("entries", &self.entries.len())
            .field("own", &self.own.len())
            .field("nfa_states", &self.nfa_states())
            .finish_non_exhaustive()
    }
}

impl Automata {
    /// The automata over the seeks of the entries (in entry order, each with
    /// its regex), or `None` when no entry can be pre-filtered, an entry has
    /// callouts, the automata would be too large (`MAX_NFA_STATES`) or do
    /// not build, or, with `skip_tiny`, too small to pay (`TINY_SET_ENTRIES`).
    pub(crate) fn build<'a>(
        entries: impl Iterator<Item = (Option<&'a Seek>, &'a RegexType)>,
        skip_tiny: bool,
    ) -> Option<Self> {
        #[cfg(feature = "scanner-load-profile")]
        let _phase =
            crate::scanner::load_profile::scope(crate::scanner::load_profile::Phase::GroupBuild);
        let mut hirs: Vec<Hir> = Vec::new();
        let mut covered = Vec::new();
        let mut own = Vec::new();
        for (index, (seek, reg)) in entries.enumerate() {
            let index = u16::try_from(index).ok()?;
            match seek {
                Some(Seek::Pattern(code)) => {
                    hirs.push(code.decode());
                    covered.push(index);
                }
                Some(Seek::Everywhere) => own.push(index),
                // Callouts observe every attempt; nothing in the set may
                // skip one. Patterns compiled without a seek are searched on
                // their own.
                None if reg.extp.as_ref().is_some_and(|ext| ext.callout_num != 0) => return None,
                None => own.push(index),
            }
        }
        if covered.is_empty() {
            return None;
        }
        let entries = covered;
        let nfa = thompson::Compiler::new()
            .configure(
                thompson::Config::new()
                    .utf8(false)
                    .which_captures(thompson::WhichCaptures::None)
                    .nfa_size_limit(Some(NFA_SIZE_LIMIT)),
            )
            .build_many_from_hir(&hirs)
            .ok()?;
        if nfa.states().len() > MAX_NFA_STATES {
            return None;
        }
        if skip_tiny
            && entries.len() <= TINY_SET_ENTRIES
            && nfa.states().len() <= TINY_SET_NFA_STATES
        {
            return None;
        }
        // The earliest match start is found as regex-automata's meta regex
        // finds it (its lazy DFA strategy): a leftmost-first forward search
        // for the end, then a reverse search from there for the start. The
        // searches report no captures, so both DFAs run over NFAs without
        // capture states. The forward NFA is the one the overlapping DFA
        // runs on, shared rather than compiled again (Rust-only, ADR-008).
        let nfarev = thompson::Compiler::new()
            .configure(
                thompson::Config::new()
                    .utf8(false)
                    .reverse(true)
                    .which_captures(thompson::WhichCaptures::None)
                    .nfa_size_limit(Some(NFA_SIZE_LIMIT)),
            )
            .build_many_from_hir(&hirs)
            .ok()?;
        let forward = search_dfa(nfa.clone(), MatchKind::LeftmostFirst)?;
        let reverse = search_dfa(nfarev, MatchKind::All)?;
        let search = Arc::new(hybrid_regex::Builder::new().build_from_dfas(forward, reverse));
        // The seeks use ASCII look-arounds only, so the DFA never quits.
        let dfa = hybrid::Builder::new()
            .configure(overlapping_config())
            .build_from_nfa(nfa)
            .ok()?;
        let mut long = Vec::new();
        let mut settle = 0;
        for (pid, hir) in hirs.iter().enumerate() {
            match hir.properties().maximum_len() {
                // A match state is entered by the byte after the match.
                Some(len) if len < LONG_SEEK_BYTES => settle = settle.max(len + 1),
                _ => long.push(pid as u16),
            }
        }
        Some(Automata {
            search,
            dfa,
            entries,
            own,
            long,
            settle,
            #[cfg(feature = "scanner-group-prototype")]
            frozen: None,
            #[cfg(feature = "precompiled-eager")]
            portable: None,
        })
    }

    /// NFA states of the overlapping DFA (the search DFAs hold about twice
    /// as many: a forward and a reverse NFA).
    pub(crate) fn nfa_states(&self) -> usize {
        #[cfg(feature = "scanner-group-prototype")]
        if let Some(frozen) = &self.frozen {
            return frozen.nfa_states;
        }
        #[cfg(feature = "precompiled-eager")]
        if let Some(portable) = &self.portable {
            return portable.nfa_states();
        }
        self.dfa.get_nfa().states().len()
    }

    /// Heap memory of the automata, in bytes, without any cache.
    pub(crate) fn memory_usage(&self) -> usize {
        let bytes = automata_memory_usage(&self.dfa, &self.search);
        #[cfg(feature = "precompiled-eager")]
        let bytes = bytes + self.portable.as_ref().map_or(0, |p| p.memory_usage());
        bytes
    }
}

/// Heap memory of the automata's NFAs and DFAs, in bytes, without any cache.
/// The forward NFA is shared by the overlapping DFA and the forward search
/// DFA, and counted once.
fn automata_memory_usage(dfa: &hybrid::DFA, search: &hybrid_regex::Regex) -> usize {
    dfa.get_nfa().memory_usage()
        + search.reverse().get_nfa().memory_usage()
        + search.forward().memory_usage()
        + search.reverse().memory_usage()
        + dfa.memory_usage()
}

/// A lazy DFA over the seeks' NFA for one of the search DFAs, with the
/// cache capacity and the give-up checks regex-automata's meta regex gives
/// its own lazy DFAs. `None` where it does not build.
fn search_dfa(nfa: thompson::NFA, match_kind: MatchKind) -> Option<hybrid::DFA> {
    hybrid::Builder::new()
        .configure(
            hybrid::Config::new()
                .match_kind(match_kind)
                .cache_capacity(SEARCH_CACHE_CAPACITY)
                .minimum_cache_clear_count(Some(MIN_CACHE_CLEARS))
                .minimum_bytes_per_state(Some(SEARCH_MIN_BYTES_PER_STATE)),
        )
        .build_from_nfa(nfa)
        .ok()
}

impl SetPrefilter {
    /// A set's pre-filter over `automata`, with fresh caches.
    pub(crate) fn new(automata: &Automata) -> Self {
        #[cfg(feature = "scanner-load-profile")]
        let _phase = crate::scanner::load_profile::scope(
            crate::scanner::load_profile::Phase::ScannerScratch,
        );
        let search_cache = automata.search.create_cache();
        let dfa_cache = automata.dfa.create_cache();
        let covered = automata.entries.len();
        SetPrefilter {
            search: automata.search.clone(),
            search_cache,
            dfa: automata.dfa.clone(),
            dfa_cache,
            patset: PatternBits::new(covered),
            entries: automata.entries.clone(),
            own: automata.own.clone(),
            long: automata.long.clone(),
            settle: automata.settle,
            ask_early: false,
            gave_up: false,
            walked: 0,
            dispatch: vec![[u64::MAX; 4]; covered],
            long_dispatch: [0; 4],
            any_dispatch: [0; 4],
            admissible: vec![0; covered],
            stamp: 0,
            candidates: Vec::new(),
            walked_at: None,
            search_memo: None,
            candidate_memo: CandidateMemo::default(),
            #[cfg(feature = "scanner-group-prototype")]
            frozen: automata.frozen.clone(),
            #[cfg(feature = "precompiled-eager")]
            portable: automata.portable.as_ref().map(|p| (p.clone(), p.caches())),
        }
    }

    /// Records, per covered entry, the bytes the set's first-byte table
    /// dispatches it on, for the admission a walk asks about.
    pub(crate) fn set_dispatch(&mut self, mut bytes: impl FnMut(u16) -> [u64; 4]) {
        for (pid, &index) in self.entries.iter().enumerate() {
            self.dispatch[pid] = bytes(index);
        }
        let union = |pids: &mut dyn Iterator<Item = usize>| {
            pids.fold([0u64; 4], |mut bits, pid| {
                for (word, dispatch) in bits.iter_mut().zip(self.dispatch[pid]) {
                    *word |= dispatch;
                }
                bits
            })
        };
        let long_dispatch = union(&mut self.long.iter().map(|&pid| pid as usize));
        let any_dispatch = union(&mut (0..self.entries.len()));
        self.long_dispatch = long_dispatch;
        self.any_dispatch = any_dispatch;
    }

    /// The bytes any covered entry is dispatched on: a position whose byte
    /// is not among them has no candidate.
    #[inline]
    pub(crate) fn any_dispatch(&self) -> [u64; 4] {
        self.any_dispatch
    }

    /// Entries the automata do not cover, in index order.
    pub(crate) fn own(&self) -> &[u16] {
        &self.own
    }

    /// Entries the automata cover, in index order.
    pub(crate) fn covered_entries(&self) -> &[u16] {
        &self.entries
    }

    /// Number of entries the automata cover.
    pub(crate) fn covered(&self) -> usize {
        self.entries.len()
    }

    /// The earliest position in `[from, until)` where some covered entry
    /// can decide, reading the subject only up to `until` plus the bounded
    /// seeks' length (`search_in`), and for a stable `subject` through the
    /// memo of what earlier searches found: a span already known to hold
    /// nothing is not read again, and a window past it is searched from
    /// where the known span ends.
    pub(crate) fn candidate_in(
        &mut self,
        haystack: &[u8],
        from: usize,
        until: usize,
        subject: Option<(crate::regset::FallbackMemoIdentity, usize)>,
        admits: &mut dyn FnMut(u16, usize) -> bool,
    ) -> Option<usize> {
        let mut search_from = from;
        let mut memo_from = from;
        if let (Some(subject), Some(memo)) = (subject, self.search_memo) {
            if memo.subject == subject && from >= memo.from {
                match memo.at {
                    Some(at) if from <= at => return (at < until).then_some(at),
                    None if until <= memo.until => return None,
                    None if from <= memo.until => {
                        search_from = memo.until;
                        memo_from = memo.from;
                    }
                    _ => {}
                }
            }
        }
        let at = self.search_in(haystack, search_from, until, admits);
        if let Some(subject) = subject {
            self.search_memo = Some(SearchMemo {
                subject,
                from: memo_from,
                until,
                at,
            });
        }
        at
    }

    /// Records what the loop head found at `at` for `subject`'s memo, where
    /// the known span ends there: a candidate, or nothing up to `next`.
    #[inline]
    pub(crate) fn note_position(
        &mut self,
        subject: Option<(crate::regset::FallbackMemoIdentity, usize)>,
        at: usize,
        candidate: bool,
        next: usize,
    ) {
        if let (Some(subject), Some(memo)) = (subject, self.search_memo.as_mut()) {
            if memo.subject == subject && memo.at.is_none() && memo.until == at {
                if candidate {
                    memo.at = Some(at);
                } else {
                    memo.until = next;
                }
            }
        }
    }

    /// The earliest position in `[from, until)` where some covered entry
    /// can decide, reading the subject only up to `until` plus the bounded
    /// seeks' length. The position `from` by a walk first: a greedy seek
    /// that matches there would make the search read on to its match end
    /// to report that start. Then the search DFAs over the span find every
    /// bounded seek's match that starts in the window (its match ends
    /// inside the span), and the long seeks, whose matches may end past it,
    /// are walked at the positions up to the search's find where their
    /// bytes dispatch (`candidates_at`, with its bound and admission stop).
    /// Where a search DFA gives up, `from` is returned: a position no later
    /// than the earliest one, which only costs walks, and the set retires
    /// the pre-filter after the search (`gave_up`).
    fn search_in(
        &mut self,
        haystack: &[u8],
        from: usize,
        until: usize,
        admits: &mut dyn FnMut(u16, usize) -> bool,
    ) -> Option<usize> {
        if from >= until || from > haystack.len() {
            return None;
        }
        // Only a long seek can make the search read far for a start here;
        // a set without one is spared the walk, and the search looks at
        // `from` itself.
        let mut next = from;
        if !self.long.is_empty() {
            if self
                .candidates_at(haystack, from, admits)
                .is_some_and(|candidates| !candidates.is_empty())
            {
                return Some(from);
            }
            next = from + 1;
            while next < haystack.len() && (haystack[next] & 0xC0) == 0x80 {
                next += 1;
            }
        }
        let span_end = haystack.len().min(until.saturating_add(self.settle));
        // An empty span at the end still holds the empty matches there.
        let found = if next <= span_end {
            #[cfg(test)]
            EARLIEST_CALLS.with(|calls| calls.set(calls.get() + 1));
            let mut ordinary = || {
                let input = Input::new(haystack).span(next..span_end);
                #[cfg(feature = "scanner-group-prototype")]
                if let Some(frozen) = &self.frozen {
                    return frozen.search.try_search(&input);
                }
                self.search.try_search(&mut self.search_cache, &input)
            };
            #[cfg(feature = "precompiled-eager")]
            let result = if let Some((p, c)) = &mut self.portable {
                Ok(p.search(c, haystack, next, span_end))
            } else {
                ordinary()
            };
            #[cfg(not(feature = "precompiled-eager"))]
            let result = ordinary();
            let Ok(found) = result else {
                // The lazy DFAs give up only on their cache's efficiency
                // (`MIN_CACHE_CLEARS`) and quit only on non-ASCII look-arounds,
                // which the seeks do not have: `from` is the earliest
                // position the search can name, and the set drops its
                // pre-filter after this search.
                self.gave_up = true;
                return Some(from);
            };
            #[cfg(test)]
            META_BYTES.with(|bytes| {
                // The forward scan to the match end, and the reverse scan
                // back to its start; the whole span without a match.
                let read = found.map_or(span_end - next, |m| {
                    (m.end() - next) + (m.end() - m.start())
                });
                bytes.set(bytes.get() + read as u64);
            });
            found.map(|m| m.start()).filter(|&at| at < until)
        } else {
            None
        };
        if self.long.is_empty() {
            return found;
        }
        let dispatch = self.long_dispatch;
        let limit = found.unwrap_or(until);
        let mut p = next;
        while p < limit {
            let admitted = haystack
                .get(p)
                .is_none_or(|&byte| (dispatch[byte as usize / 64] >> (byte % 64)) & 1 == 1);
            if admitted
                && self
                    .candidates_at(haystack, p, admits)
                    .is_some_and(|candidates| !candidates.is_empty())
            {
                return Some(p);
            }
            p += 1;
            while p < limit && p < haystack.len() && (haystack[p] & 0xC0) == 0x80 {
                p += 1;
            }
        }
        found
    }

    /// The covered entries whose seek matches at `at`, ascending, or `None`
    /// where none does: the patterns of every match state the overlapping
    /// DFA reaches from `at`, within `CANDIDATE_SCAN_BYTES`. The walk stops
    /// as soon as every covered entry has been recorded. Once the bounded
    /// seeks have settled (`settle`, right away while `ask_early`, after
    /// `LONG_WALK_BYTES` otherwise), it asks which entries of the long
    /// seeks the search attempts at `at` (`admits`, for those not recorded
    /// and dispatched on the byte at `at`), and stops as soon as every one
    /// of those has been recorded: the others never decide there, so
    /// nothing more can be learned. At the bound, or where the DFA gives
    /// up or quits, the recorded entries and the admissible long ones are
    /// the candidates, every covered one where nothing was asked.
    #[inline]
    pub(crate) fn candidates_at(
        &mut self,
        haystack: &[u8],
        at: usize,
        admits: &mut dyn FnMut(u16, usize) -> bool,
    ) -> Option<&[u16]> {
        self.candidates.clear();
        self.walked_at = Some(at);
        if self.candidate_memo.active {
            if let Some((memo, some)) = self.candidate_memo.get(at) {
                self.candidates.extend_from_slice(memo);
                return some.then_some(&self.candidates);
            }
        }
        self.patset.clear();
        let (end, asked) = self.scan_candidates(haystack, at, admits);
        self.ask_early = end == ScanEnd::Bound || (asked && end == ScanEnd::Settled);
        if end == ScanEnd::Finished && self.patset.is_empty() {
            if self.candidate_memo.active {
                self.candidate_memo.insert(at, &[], false);
            }
            return None;
        }
        let entries = &self.entries;
        if end == ScanEnd::Bound {
            let stamps = &self.admissible;
            let stamp = self.stamp;
            let patset = &self.patset;
            self.candidates.extend(
                entries
                    .iter()
                    .enumerate()
                    .filter(|&(pid, _)| {
                        !asked
                            || stamps[pid] == stamp
                            || patset.contains(PatternID::new_unchecked(pid))
                    })
                    .map(|(_, &index)| index),
            );
        } else {
            self.candidates
                .extend(self.patset.iter().map(|pid| entries[pid]));
        }
        if self.candidate_memo.active {
            self.candidate_memo.insert(at, &self.candidates, true);
        }
        Some(&self.candidates)
    }

    /// The candidates the last `candidates_at` found.
    #[inline]
    pub(crate) fn candidates(&self) -> &[u16] {
        &self.candidates
    }

    /// The position `candidates` holds the candidates of in the current
    /// search, so a walk the stretch search made at the position the loop
    /// goes on at is not made again.
    #[inline]
    pub(crate) fn walked_at(&self) -> Option<usize> {
        self.walked_at
    }

    /// Forgets the candidates of the previous search, and readies the
    /// walk memo for a search of `subject` from `start`.
    #[inline]
    pub(crate) fn begin_search(
        &mut self,
        subject: Option<(crate::regset::FallbackMemoIdentity, usize)>,
        start: usize,
    ) {
        self.walked_at = None;
        self.candidate_memo.begin(subject, start);
        self.walked = 0;
        self.dfa_cache.search_start(0);
    }

    /// The anchored walk of `candidates_at`, filling `patset`: how it ended,
    /// and whether it asked `admits` (then `admissible[pid] == stamp` marks
    /// the admissible long seeks). The bytes walked are recorded for the
    /// DFA's cache efficiency check (`MIN_CACHE_CLEARS`); a walk the DFA
    /// gave up on ends as at the bound and marks the set for retirement.
    fn scan_candidates(
        &mut self,
        haystack: &[u8],
        at: usize,
        admits: &mut dyn FnMut(u16, usize) -> bool,
    ) -> (ScanEnd, bool) {
        #[cfg(feature = "precompiled-eager")]
        if let Some((p, c)) = &mut self.portable {
            return p.scan(
                c,
                &mut self.patset,
                &self.entries,
                &self.long,
                self.settle,
                self.ask_early,
                &self.dispatch,
                &mut self.admissible,
                &mut self.stamp,
                haystack,
                at,
                admits,
            );
        }

        #[cfg(feature = "scanner-group-prototype")]
        if let Some(frozen) = &self.frozen {
            return frozen.scan(
                &mut self.patset,
                &self.entries,
                &self.long,
                self.settle,
                self.ask_early,
                &self.dispatch,
                &mut self.admissible,
                &mut self.stamp,
                haystack,
                at,
                admits,
            );
        }
        let Self {
            dfa,
            dfa_cache: cache,
            patset,
            entries,
            long,
            settle,
            ask_early,
            gave_up,
            walked,
            dispatch,
            admissible: stamps,
            stamp,
            ..
        } = self;
        let mut i = at;
        let (end, asked) = Self::walk(
            dfa, cache, patset, entries, long, *settle, *ask_early, dispatch, stamps, stamp,
            haystack, at, &mut i, admits,
        );
        *walked += i - at;
        cache.search_update(*walked);
        if end == ScanEnd::GaveUp {
            *gave_up = true;
            return (ScanEnd::Bound, asked);
        }
        (end, asked)
    }

    /// `scan_candidates` from `at`, leaving the position it read up to in
    /// `i`.
    #[allow(clippy::too_many_arguments)]
    fn walk(
        dfa: &hybrid::DFA,
        cache: &mut hybrid::Cache,
        patset: &mut PatternBits,
        entries: &[u16],
        long: &[u16],
        settle: usize,
        ask_early: bool,
        dispatch: &[[u64; 4]],
        stamps: &mut [u32],
        stamp: &mut u32,
        haystack: &[u8],
        at: usize,
        i: &mut usize,
        admits: &mut dyn FnMut(u16, usize) -> bool,
    ) -> (ScanEnd, bool) {
        let end = haystack.len();
        let input = Input::new(haystack).span(at..end).anchored(Anchored::Yes);
        let Ok(mut sid) = dfa.start_state_forward(cache, &input) else {
            return (ScanEnd::GaveUp, false);
        };
        let cut = end.min(at.saturating_add(CANDIDATE_SCAN_BYTES));
        // The position at which the walk asks about the long seeks.
        let ask_at = if ask_early {
            settle
        } else {
            settle.max(LONG_WALK_BYTES)
        };
        let ask_i = at.saturating_add(ask_at);
        // A match state stands for its patterns wherever the walk reaches
        // it; a run of word characters keeps the walk in one match state
        // for every identifier-like seek, which is recorded once.
        // The match state last recorded, with the cache's clear count: a
        // clear reassigns state IDs, so the same ID may name another state.
        let mut recorded: Option<(LazyStateID, usize)> = None;
        macro_rules! at_end {
            ($asked:expr) => {
                if let Ok(eoi) = dfa.next_eoi_state(cache, sid) {
                    if eoi.is_match() {
                        record_match(dfa, cache, patset, eoi);
                    }
                    return (ScanEnd::Finished, $asked);
                }
                return (ScanEnd::GaveUp, $asked);
            };
        }
        // Up to `ask_i`, the plain walk. All three byte limits are fixed
        // during the walk; compare their minimum once per byte, then retain
        // end-of-input's precedence over the scan bound at that boundary.
        let plain_end = cut.min(ask_i);
        loop {
            if sid.is_dead() {
                return (ScanEnd::Finished, false);
            }
            if sid.is_quit() {
                return (ScanEnd::Bound, false);
            }
            // A match state stands for the matches that ended before the
            // byte it was reached by (or at the end of the haystack).
            if sid.is_match() && recorded != Some((sid, cache.clear_count())) {
                recorded = Some((sid, cache.clear_count()));
                record_match(dfa, cache, patset, sid);
                if patset.is_full() {
                    return (ScanEnd::Settled, false);
                }
            }
            if *i >= plain_end {
                if *i == end {
                    at_end!(false);
                }
                if *i == cut {
                    return (ScanEnd::Bound, false);
                }
                break;
            }
            #[cfg(test)]
            SCAN_STEPS.with(|steps| steps.set(steps.get() + 1));
            sid = match dfa.next_state(cache, sid, haystack[*i]) {
                Ok(sid) => sid,
                Err(_) => return (ScanEnd::GaveUp, false),
            };
            *i += 1;
        }
        // The bounded seeks have settled: only an admissible long seek not
        // yet recorded can add a candidate.
        *stamp = stamp.wrapping_add(1);
        if *stamp == 0 {
            stamps.fill(0);
            *stamp = 1;
        }
        let byte = haystack[at];
        let mut needed = 0usize;
        for &pid in long.iter() {
            let bits = dispatch[pid as usize];
            if patset.contains(PatternID::new_unchecked(pid as usize))
                || (bits[byte as usize / 64] >> (byte % 64)) & 1 == 0
            {
                continue;
            }
            if admits(entries[pid as usize], at) {
                stamps[pid as usize] = *stamp;
                needed += 1;
            }
        }
        if needed == 0 {
            return (ScanEnd::Settled, true);
        }
        // On, until every admissible long seek has been recorded.
        loop {
            #[cfg(test)]
            SCAN_STEPS.with(|steps| steps.set(steps.get() + 1));
            sid = match dfa.next_state(cache, sid, haystack[*i]) {
                Ok(sid) => sid,
                Err(_) => return (ScanEnd::GaveUp, true),
            };
            *i += 1;
            if sid.is_dead() {
                return (ScanEnd::Finished, true);
            }
            if sid.is_quit() {
                return (ScanEnd::Bound, true);
            }
            if sid.is_match() && recorded != Some((sid, cache.clear_count())) {
                recorded = Some((sid, cache.clear_count()));
                needed -= record_needed(dfa, cache, patset, sid, stamps, *stamp);
                if needed == 0 || patset.is_full() {
                    return (ScanEnd::Settled, true);
                }
            }
            if *i == cut {
                if *i == end {
                    at_end!(true);
                }
                return (ScanEnd::Bound, true);
            }
        }
    }

    /// The overlapping DFA gave up on its cache during the last search
    /// (`MIN_CACHE_CLEARS`): the set should retire the pre-filter.
    pub(crate) fn gave_up(&self) -> bool {
        self.gave_up
    }

    /// NFA states of the overlapping DFA (the search DFAs hold about twice
    /// as many: a forward and a reverse NFA).
    pub(crate) fn nfa_states(&self) -> usize {
        #[cfg(feature = "scanner-group-prototype")]
        if let Some(frozen) = &self.frozen {
            return frozen.nfa_states;
        }
        #[cfg(feature = "precompiled-eager")]
        if let Some((portable, _)) = &self.portable {
            return portable.nfa_states();
        }
        self.dfa.get_nfa().states().len()
    }

    /// Heap memory of the automata (shared with every set over the same
    /// pattern list) and of this set's caches, in bytes.
    pub(crate) fn memory_usage(&self) -> usize {
        let bytes = automata_memory_usage(&self.dfa, &self.search) + self.cache_memory_usage();
        #[cfg(feature = "scanner-group-prototype")]
        let bytes = bytes + self.frozen.as_ref().map_or(0, |f| f.memory_usage());
        #[cfg(feature = "precompiled-eager")]
        let bytes = bytes + self.portable.as_ref().map_or(0, |(p, _)| p.memory_usage());
        bytes
    }

    /// Heap memory of this set's lazy DFA caches, in bytes.
    pub(crate) fn cache_memory_usage(&self) -> usize {
        let bytes = self.search_cache.memory_usage() + self.dfa_cache.memory_usage();
        #[cfg(feature = "precompiled-eager")]
        let bytes = bytes + self.portable.as_ref().map_or(0, |(_, c)| c.memory_usage());
        bytes
    }

    /// Times the overlapping DFA's cache was cleared because it filled up.
    pub(crate) fn cache_clears(&self) -> usize {
        #[cfg(feature = "precompiled-eager")]
        if let Some((_, c)) = &self.portable {
            return c.clears();
        }
        self.dfa_cache.clear_count()
    }
}

/// Rust-only (ADR-008): the seek of one `Regex`, which answers whether any
/// seek match starts in a subject from a position on. Production starts with
/// bounded hybrid DFAs and can promote eligible automata to immutable dense
/// DFAs after enough consultations.
///
/// Without an exact seek, "no seek match" proves "no match" and nothing else:
/// a seek match leaves the answer to the matcher. An exact seek's match is a
/// match of the pattern (`SeekCode::exact`). An inexact seek may come with
/// an accept seek ([`accept`]), whose match is a match of the pattern, and
/// whose "no match" is the pattern's where its `AcceptRejects` says so. A
/// search that a lazy DFA gives up on answers nothing, and the matcher runs.
pub(crate) struct SingleSeek {
    dfa: hybrid::DFA,
    accept: Option<(hybrid::DFA, accept::AcceptRejects)>,
    caches: Pool<SingleCaches, CacheMaker>,
    exact: bool,
    adaptive: Option<Box<SingleAdaptive>>,
}

/// Keep optional promotion state out of the hybrid DFA's hot object. NFAs
/// outside the small-table policy allocate no adaptive metadata.
struct SingleAdaptive {
    seek: Option<AdaptiveDfa>,
    accept: Option<AdaptiveDfa>,
}

/// A bounded boolean DFA for NFAs that fit in one machine-independent u64
/// state set and use only text anchors. Other assertions stay on hybrid.
/// Only existence is needed, so match states are terminal and NFA priority
/// cannot change the answer. No captures or match positions are computed.
struct SingleTable {
    transitions: Vec<u32>,
    classes: [u8; 256],
    starts: [u32; 2],
    eoi: usize,
}

impl SingleTable {
    fn supports(nfa: &thompson::NFA) -> bool {
        use regex_automata::util::look::Look;
        nfa.states().len() <= MAX_SINGLE_BITSET_NFA_STATES
            && !nfa.is_utf8()
            && nfa
                .look_set_any()
                .iter()
                .all(|look| matches!(look, Look::Start | Look::End))
    }

    /// Epsilon closure keeps a blocked end anchor in the frontier, so the
    /// EOI edge can evaluate it later. A blocked start anchor can never become
    /// true after consuming a byte and is discarded.
    fn closure(nfa: &thompson::NFA, mut pending: u64, start: bool, end: bool) -> u64 {
        use regex_automata::{nfa::thompson::State, util::look::Look};
        let mut seen = 0u64;
        let mut frontier = 0u64;
        while pending != 0 {
            let index = pending.trailing_zeros() as usize;
            let bit = 1u64 << index;
            pending &= !bit;
            if seen & bit != 0 {
                continue;
            }
            seen |= bit;
            match &nfa.states()[index] {
                State::Look {
                    look: Look::Start,
                    next,
                } if start => pending |= 1u64 << next.as_usize(),
                State::Look {
                    look: Look::End,
                    next,
                } if end => pending |= 1u64 << next.as_usize(),
                State::Look {
                    look: Look::End, ..
                } => frontier |= bit,
                State::Look { .. } | State::Fail => {}
                State::Union { alternates } => {
                    for next in alternates {
                        pending |= 1u64 << next.as_usize();
                    }
                }
                State::BinaryUnion { alt1, alt2 } => {
                    pending |= (1u64 << alt1.as_usize()) | (1u64 << alt2.as_usize())
                }
                State::Capture { next, .. } => pending |= 1u64 << next.as_usize(),
                State::ByteRange { .. }
                | State::Sparse(_)
                | State::Dense(_)
                | State::Match { .. } => frontier |= bit,
            }
        }
        frontier
    }

    fn build(nfa: &thompson::NFA, limits: SingleDenseLimits) -> Option<Self> {
        use regex_automata::nfa::thompson::State;
        if !Self::supports(nfa) {
            return None;
        }
        let classes = nfa.byte_classes();
        let stride = classes.alphabet_len();
        // Leave headroom for both buffers while shrink_to_fit compacts the
        // table; the original and replacement together stay within the cap.
        let max_rows = limits.dfa_bytes.checked_sub(std::mem::size_of::<Self>())?
            / 2
            / (stride * std::mem::size_of::<u32>());
        let max_rows = max_rows.min(
            limits
                .determinize_bytes
                .checked_sub(64 * std::mem::size_of::<u64>())?
                / std::mem::size_of::<(u64, bool)>(),
        );
        if max_rows == 0 {
            return None;
        }
        let mut closures = [0; 64];
        let mut matches = 0u64;
        for (i, state) in nfa.states().iter().enumerate() {
            closures[i] = Self::closure(nfa, 1u64 << i, false, false);
            if matches!(state, State::Match { .. }) {
                matches |= 1u64 << i;
            }
        }
        let mut states = Vec::with_capacity(max_rows);
        let mut transitions = Vec::with_capacity(max_rows * stride);
        fn intern(
            mask: u64,
            at_start: bool,
            matches: u64,
            states: &mut Vec<(u64, bool)>,
            stride: usize,
            max_rows: usize,
        ) -> Option<u32> {
            if mask & matches != 0 {
                return Some(1);
            }
            if mask == 0 {
                return Some(0);
            }
            let node = (mask, at_start);
            let index = match states.iter().position(|&known| known == node) {
                Some(index) => index,
                None if states.len() < max_rows => {
                    states.push(node);
                    states.len() - 1
                }
                None => return None,
            };
            u32::try_from(index * stride + 2).ok()
        }
        let root = 1u64 << nfa.start_unanchored().as_usize();
        let mut starts = [0; 2];
        for (i, slot) in starts.iter_mut().enumerate() {
            *slot = intern(
                Self::closure(nfa, root, i == 1, false),
                i == 1,
                matches,
                &mut states,
                stride,
                max_rows,
            )?;
        }
        let mut row = 0;
        while row < states.len() {
            let (mask, at_start) = states[row];
            for unit in classes.representatives(..) {
                let next = if let Some(byte) = unit.as_u8() {
                    let mut pending = mask;
                    let mut next = 0u64;
                    while pending != 0 {
                        let i = pending.trailing_zeros() as usize;
                        pending &= pending - 1;
                        let target = match &nfa.states()[i] {
                            State::ByteRange { trans } if trans.matches_byte(byte) => {
                                Some(trans.next)
                            }
                            State::Sparse(trans) => trans.matches_byte(byte),
                            State::Dense(trans) => trans.matches_byte(byte),
                            _ => None,
                        };
                        if let Some(target) = target {
                            next |= closures[target.as_usize()];
                        }
                    }
                    intern(next, false, matches, &mut states, stride, max_rows)?
                } else {
                    u32::from(Self::closure(nfa, mask, at_start, true) & matches != 0)
                };
                transitions.push(next);
            }
            row += 1;
        }
        let mut map = [0; 256];
        for (byte, slot) in map.iter_mut().enumerate() {
            *slot = classes.get(byte as u8);
        }
        transitions.shrink_to_fit();
        Some(Self {
            transitions,
            classes: map,
            starts,
            eoi: stride - 1,
        })
    }

    fn search(&self, text: &[u8], start: usize) -> bool {
        let mut state = self.starts[usize::from(start == 0)];
        for &byte in &text[start..] {
            if state <= 1 {
                return state == 1;
            }
            state =
                self.transitions[state as usize - 2 + usize::from(self.classes[usize::from(byte)])];
        }
        if state <= 1 {
            return state == 1;
        }
        self.transitions[state as usize - 2 + self.eoi] == 1
    }

    fn memory_usage(&self) -> usize {
        self.transitions.capacity() * std::mem::size_of::<u32>()
    }
}

/// The hybrid automaton remains available after promotion so threads already
/// consulting it stay valid, and its per-thread cache pool is retained. The
/// dense table is published once through `OnceLock`; its bytes are additional
/// to the NFA and caches already retained by the hybrid path.
struct AdaptiveDfa {
    limits: SingleDenseLimits,
    threshold: usize,
    consultations: AtomicUsize,
    promotion_attempted: AtomicBool,
    dense_decision: OnceLock<Option<Box<SingleTable>>>,
}

impl AdaptiveDfa {
    fn new(limits: SingleDenseLimits, threshold: usize) -> Self {
        Self {
            limits,
            threshold,
            consultations: AtomicUsize::new(0),
            promotion_attempted: AtomicBool::new(false),
            dense_decision: OnceLock::new(),
        }
    }

    fn dense(&self) -> Option<&SingleTable> {
        self.dense_decision.get().and_then(Option::as_deref)
    }

    fn initialize_dense_with(&self, build: impl FnOnce() -> Option<Box<SingleTable>>) {
        if self
            .promotion_attempted
            .compare_exchange(false, true, Ordering::Relaxed, Ordering::Relaxed)
            .is_ok()
        {
            // A normal build rejection is stored as `None`, so it is never
            // retried. If the builder panics, the flag remains set and later
            // consultations safely stay on the hybrid DFA.
            let _ = self.dense_decision.get_or_init(build);
        }
    }

    fn record_hybrid_consultation(&self, nfa: &thompson::NFA) {
        if self.promotion_attempted.load(Ordering::Relaxed) {
            return;
        }
        let mut count = self.consultations.load(Ordering::Relaxed);
        while count < self.threshold {
            match self.consultations.compare_exchange_weak(
                count,
                count + 1,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => {
                    count += 1;
                    break;
                }
                Err(observed) => count = observed,
            }
        }
        if count >= self.threshold {
            self.initialize_dense_with(|| SingleTable::build(nfa, self.limits).map(Box::new));
        }
    }

    #[cfg(test)]
    fn consultation_count(&self) -> usize {
        self.consultations.load(Ordering::Relaxed)
    }

    #[cfg(test)]
    fn promotion_attempted(&self) -> bool {
        self.promotion_attempted.load(Ordering::Relaxed)
    }
}

#[derive(Clone, Copy)]
struct SingleDenseLimits {
    dfa_bytes: usize,
    determinize_bytes: usize,
}

const PREFERRED_SINGLE_DENSE_LIMITS: SingleDenseLimits = SingleDenseLimits {
    dfa_bytes: SINGLE_DENSE_DFA_SIZE_LIMIT,
    determinize_bytes: SINGLE_DENSE_DETERMINIZE_SIZE_LIMIT,
};

/// Promote after this many actual hybrid DFA consultations of a seek or
/// accept DFA, rather than counting public Regex API calls.
const SINGLE_DENSE_PROMOTION_THRESHOLD: usize = 64;

/// The caches of a `SingleSeek`'s hybrid fallback DFAs.
struct SingleCaches {
    seek: hybrid::Cache,
    accept: Option<hybrid::Cache>,
}

/// The cache constructor of a `SingleSeek`'s pool.
type CacheMaker = Box<dyn Fn() -> SingleCaches + Send + Sync>;

/// Cache capacity of a single `Regex`'s hybrid seek and accept seek.
const SINGLE_CACHE_CAPACITY: usize = MIB;

/// An estimate of the NFA states `hir` compiles to, from above: a repetition
/// counts its body once per copy its bound makes, and the parts add up.
/// Saturating, so a nested bound cannot overflow it.
fn nfa_states_estimate(hir: &Hir) -> usize {
    states_estimate(hir, false)
}

/// `nfa_states_estimate`, with `utf8_classes` counting a Unicode class as
/// the UTF-8 sequences it compiles to, a state per byte of each (the accept
/// seek's classes; the seek's own are bytes or a few members).
fn states_estimate(hir: &Hir, utf8_classes: bool) -> usize {
    match hir.kind() {
        HirKind::Empty | HirKind::Look(_) => 1,
        HirKind::Literal(literal) => literal.0.len() + 1,
        HirKind::Class(Class::Unicode(class)) if utf8_classes => {
            class.ranges().iter().fold(2usize, |sum, range| {
                Utf8Sequences::new(range.start(), range.end())
                    .fold(sum, |sum, sequence| sum.saturating_add(sequence.len()))
            })
        }
        HirKind::Class(_) => 2,
        HirKind::Capture(capture) => states_estimate(&capture.sub, utf8_classes) + 2,
        HirKind::Repetition(rep) => {
            let copies = rep.max.unwrap_or(rep.min).max(rep.min).max(1) as usize;
            states_estimate(&rep.sub, utf8_classes)
                .saturating_mul(copies)
                .saturating_add(2)
        }
        HirKind::Concat(parts) => parts.iter().fold(0usize, |sum, part| {
            sum.saturating_add(states_estimate(part, utf8_classes))
        }),
        HirKind::Alternation(branches) => branches.iter().fold(2usize, |sum, branch| {
            sum.saturating_add(states_estimate(branch, utf8_classes))
        }),
    }
}

impl SingleSeek {
    /// Prepare both eligible boolean tables without counting or simulating
    /// searches. Failed attempts are memoized just as in adaptive promotion.
    pub(crate) fn prepare(&self) {
        if let Some(adaptive) = self.adaptive_seek() {
            adaptive.initialize_dense_with(|| {
                SingleTable::build(self.dfa.get_nfa(), adaptive.limits).map(Box::new)
            });
        }
        if let Some(adaptive) = self.adaptive_accept()
            && let Some((dfa, _)) = &self.accept
        {
            adaptive.initialize_dense_with(|| {
                SingleTable::build(dfa.get_nfa(), adaptive.limits).map(Box::new)
            });
        }
    }

    pub(crate) fn build(seek: &Seek, accept: Option<&AcceptCode>) -> Option<Self> {
        // A positive inexact seek still needs the matcher. Keep its original
        // hybrid path; dense promotion pays for complete boolean decisions.
        let seek_limits = match seek {
            Seek::Pattern(code) if code.exact() => Some(PREFERRED_SINGLE_DENSE_LIMITS),
            _ => None,
        };
        Self::assemble(
            seek,
            accept,
            seek_limits,
            Some(PREFERRED_SINGLE_DENSE_LIMITS),
            SINGLE_DENSE_PROMOTION_THRESHOLD,
            false,
        )
    }

    #[cfg(test)]
    fn build_with_adaptive_policy(
        seek: &Seek,
        accept: Option<&AcceptCode>,
        limits: Option<SingleDenseLimits>,
        threshold: usize,
    ) -> Option<Self> {
        Self::assemble(seek, accept, limits, limits, threshold, false)
    }

    #[cfg(test)]
    fn build_with_dense_limits(
        seek: &Seek,
        accept: Option<&AcceptCode>,
        limits: Option<SingleDenseLimits>,
    ) -> Option<Self> {
        Self::build_with_separate_dense_limits(seek, accept, limits, limits)
    }

    #[cfg(test)]
    fn build_with_separate_dense_limits(
        seek: &Seek,
        accept: Option<&AcceptCode>,
        seek_limits: Option<SingleDenseLimits>,
        accept_limits: Option<SingleDenseLimits>,
    ) -> Option<Self> {
        Self::assemble(seek, accept, seek_limits, accept_limits, 0, true)
    }

    fn assemble(
        seek: &Seek,
        accept: Option<&AcceptCode>,
        seek_limits: Option<SingleDenseLimits>,
        accept_limits: Option<SingleDenseLimits>,
        threshold: usize,
        eager: bool,
    ) -> Option<Self> {
        let Seek::Pattern(code) = seek else {
            return None;
        };
        let (dfa, dense) = single_dfa_adaptive(&code.decode(), seek_limits, threshold, eager)?;
        let accept = accept.and_then(|accept| {
            let (dfa, dense) =
                single_dfa_adaptive(&accept.code.decode(), accept_limits, threshold, eager)?;
            Some((dfa, accept.rejects.clone(), dense))
        });
        let (accept, accept_dense) = match accept {
            Some((dfa, rejects, dense)) => (Some((dfa, rejects)), dense),
            None => (None, None),
        };
        let make_seek = dfa.clone();
        let make_accept = accept.as_ref().map(|(dfa, _)| dfa.clone());
        let caches = Pool::new(Box::new(move || SingleCaches {
            seek: make_seek.create_cache(),
            accept: make_accept.as_ref().map(hybrid::DFA::create_cache),
        }) as CacheMaker);
        Some(Self {
            dfa,
            accept,
            caches,
            exact: code.exact(),
            adaptive: (dense.is_some() || accept_dense.is_some()).then(|| {
                Box::new(SingleAdaptive {
                    seek: dense,
                    accept: accept_dense,
                })
            }),
        })
    }

    /// Boolean search over the complete suffix, with the original hybrid
    /// representation and cache path retained beside the optional table.
    pub(crate) fn search(&self, text: &[u8], start: usize) -> Option<bool> {
        let Some(adaptive) = self.adaptive_seek() else {
            return self.search_hybrid(text, start);
        };
        if let Some(table) = adaptive.dense() {
            return Some(table.search(text, start));
        }
        let result = self.search_hybrid(text, start);
        adaptive.record_hybrid_consultation(self.dfa.get_nfa());
        result
    }

    /// Reject-only callers still need the matcher after every positive seek.
    /// Keep their original hybrid path without dense dispatch or promotion.
    pub(crate) fn search_hybrid(&self, text: &[u8], start: usize) -> Option<bool> {
        let input = Input::new(text).span(start..text.len()).earliest(true);
        let mut caches = self.caches.get();
        self.dfa
            .try_search_fwd(&mut caches.seek, &input)
            .ok()
            .map(|found| found.is_some())
    }

    fn adaptive_seek(&self) -> Option<&AdaptiveDfa> {
        self.adaptive.as_deref()?.seek.as_ref()
    }

    fn adaptive_accept(&self) -> Option<&AdaptiveDfa> {
        self.adaptive.as_deref()?.accept.as_ref()
    }

    pub(crate) fn exact(&self) -> bool {
        self.exact
    }
    pub(crate) fn has_accept(&self) -> bool {
        self.accept.is_some()
    }

    pub(crate) fn accept_answer(&self, text: &[u8], start: usize) -> Option<bool> {
        let (dfa, rejects) = self.accept.as_ref()?;
        let adaptive = self.adaptive_accept();
        let found = if let Some(table) = adaptive.and_then(AdaptiveDfa::dense) {
            table.search(text, start)
        } else {
            let input = Input::new(text).span(start..text.len()).earliest(true);
            let result = {
                let mut caches = self.caches.get();
                dfa.try_search_fwd(caches.accept.as_mut()?, &input)
                    .ok()
                    .map(|found| found.is_some())
            };
            if let Some(adaptive) = adaptive {
                adaptive.record_hybrid_consultation(dfa.get_nfa());
            }
            result?
        };
        if found {
            return Some(true);
        }
        match rejects {
            accept::AcceptRejects::Unless(triggers) => {
                (!triggers.occur_in(&text[start..])).then_some(false)
            }
            accept::AcceptRejects::Never => None,
        }
    }

    #[cfg(test)]
    pub(crate) fn memory_usage(&self) -> usize {
        self.automata_memory_usage() + self.cache_memory_usage()
    }
    #[cfg(test)]
    fn uses_dense_dfas(&self) -> bool {
        self.adaptive_seek().and_then(AdaptiveDfa::dense).is_some()
            && (self.accept.is_none()
                || self
                    .adaptive_accept()
                    .and_then(AdaptiveDfa::dense)
                    .is_some())
    }
    #[cfg(test)]
    pub(crate) fn backend_names(&self) -> (&'static str, Option<&'static str>) {
        (
            if self.adaptive_seek().and_then(AdaptiveDfa::dense).is_some() {
                "dense"
            } else {
                "hybrid"
            },
            self.accept.as_ref().map(|_| {
                if self
                    .adaptive_accept()
                    .and_then(AdaptiveDfa::dense)
                    .is_some()
                {
                    "dense"
                } else {
                    "hybrid"
                }
            }),
        )
    }
    #[cfg(test)]
    fn automata_memory_usage(&self) -> usize {
        fn table_bytes(adaptive: Option<&AdaptiveDfa>) -> usize {
            adaptive.and_then(AdaptiveDfa::dense).map_or(0, |table| {
                table.memory_usage() + std::mem::size_of_val(table)
            })
        }
        self.dfa.get_nfa().memory_usage()
            + std::mem::size_of_val(&self.dfa)
            + self.accept.as_ref().map_or(0, |(dfa, _)| {
                dfa.get_nfa().memory_usage() + std::mem::size_of_val(dfa)
            })
            + self.adaptive.as_deref().map_or(0, std::mem::size_of_val)
            + table_bytes(self.adaptive_seek())
            + table_bytes(self.adaptive_accept())
    }
    #[cfg(test)]
    fn cache_memory_usage(&self) -> usize {
        let caches = self.caches.get();
        caches.seek.memory_usage()
            + caches
                .accept
                .as_ref()
                .map_or(0, hybrid::Cache::memory_usage)
    }
}

/// Compile the bounded Thompson NFA once and return whether its measured and
/// estimated size also permits a dense DFA attempt.
fn single_nfa(hir: &Hir) -> Option<(thompson::NFA, bool)> {
    // Cut a seek that is clearly too large before compiling it: a compile
    // of a seek with nested counted repetitions can take far longer than
    // the automaton it would keep. (`derive_accept` estimated the accept
    // seek's Unicode classes already.)
    let estimated_states = nfa_states_estimate(hir);
    if estimated_states > MAX_NFA_STATES {
        return None;
    }
    let dense_eligible = estimated_states <= MAX_SINGLE_DENSE_ESTIMATED_NFA_STATES;
    // The seeks use ASCII look-arounds only, so the DFA never quits.
    let nfa = thompson::Compiler::new()
        .configure(
            thompson::Config::new()
                .utf8(false)
                .which_captures(thompson::WhichCaptures::None)
                .nfa_size_limit(Some(NFA_SIZE_LIMIT)),
        )
        .build_from_hir(hir)
        .ok()?;
    let actual_states = nfa.states().len();
    if actual_states > MAX_NFA_STATES {
        return None;
    }
    Some((
        nfa,
        dense_eligible && actual_states <= MAX_SINGLE_BITSET_NFA_STATES,
    ))
}

fn build_single_hybrid(nfa: thompson::NFA) -> Option<hybrid::DFA> {
    hybrid::Builder::new()
        .configure(
            hybrid::Config::new()
                .match_kind(MatchKind::LeftmostFirst)
                .cache_capacity(SINGLE_CACHE_CAPACITY),
        )
        .build_from_nfa(nfa)
        .ok()
}

/// Keep the original hybrid DFA inline. The additional state is present only
/// when this NFA meets the bitset and assertion guards.
fn single_dfa_adaptive(
    hir: &Hir,
    limits: Option<SingleDenseLimits>,
    threshold: usize,
    eager: bool,
) -> Option<(hybrid::DFA, Option<AdaptiveDfa>)> {
    let (nfa, eligible) = single_nfa(hir)?;
    let dense = if let Some(limits) = limits
        && eligible
        && SingleTable::supports(&nfa)
    {
        let adaptive = AdaptiveDfa::new(limits, threshold);
        if eager {
            adaptive.initialize_dense_with(|| SingleTable::build(&nfa, limits).map(Box::new));
        }
        Some(adaptive)
    } else {
        None
    };
    Some((build_single_hybrid(nfa)?, dense))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::encodings::utf8::ONIG_ENCODING_UTF8;
    use crate::oniguruma::{
        ONIG_OPTION_CAPTURE_GROUP, ONIG_OPTION_IGNORECASE, ONIG_OPTION_WORD_IS_ASCII,
        OnigOptionType,
    };
    use crate::regcomp::{onig_new_for_scanner, onig_new_for_single_seek};
    use crate::regsyntax::OnigSyntaxOniguruma;
    use crate::scanner::{Scanner, ScannerConfig, ScannerFindOptions};

    /// The production catalog's Django email domain and URL expressions.
    const DJANGO_EMAIL_LOCAL: &str = r#"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\z|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\z)"#;
    const DJANGO_DOMAIN: &str = r"^[a-z¡-￿0-9](?:[a-z¡-￿0-9-]{0,61}[a-z¡-￿0-9])?(?:\.(?!-)[a-z¡-￿0-9-]{1,63}(?<!-))*\.(?!-)(?:[a-z¡-￿-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\z";
    const DJANGO_URL: &str = r"^(?:[a-z0-9.+-]*)://(?:[^\s:@/]+(?::[^\s:@/]*)?@)?(?:(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)(?:\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}|\[[0-9a-f:.]+\]|([a-z¡-￿0-9](?:[a-z¡-￿0-9-]{0,61}[a-z¡-￿0-9])?(?:\.(?!-)[a-z¡-￿0-9-]{1,63}(?<!-))*\.(?!-)(?:[a-z¡-￿-]{2,63}|xn--[a-z0-9]{1,59})(?<!-)\.?|localhost))(?::[0-9]{1,5})?(?:[/?#][^\s]*)?\z";
    const DJANGO_OPTIONS: OnigOptionType = ONIG_OPTION_CAPTURE_GROUP
        .union(ONIG_OPTION_IGNORECASE)
        .union(crate::oniguruma::ONIG_OPTION_SINGLELINE);

    fn seek_with(
        pattern: &str,
        options: OnigOptionType,
    ) -> Result<Option<Seek>, crate::error::RegexError> {
        onig_new_for_scanner(
            pattern.as_bytes(),
            options,
            &ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
            false,
            true,
        )
        .map(|(_, seek)| seek)
    }

    fn seek(pattern: &str) -> Option<Seek> {
        seek_with(pattern, ONIG_OPTION_CAPTURE_GROUP).unwrap()
    }

    fn single_seek_with(
        pattern: &str,
        options: OnigOptionType,
        dense_limits: Option<SingleDenseLimits>,
    ) -> Option<SingleSeek> {
        let (_, seek, accept) = onig_new_for_single_seek(
            pattern.as_bytes(),
            options,
            &ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
            false,
            true,
        )
        .unwrap();
        SingleSeek::build_with_dense_limits(&seek?, accept.as_ref(), dense_limits)
    }

    fn adaptive_single_seek_with(
        pattern: &str,
        options: OnigOptionType,
        dense_limits: Option<SingleDenseLimits>,
        threshold: usize,
    ) -> Option<SingleSeek> {
        let (_, seek, accept) = onig_new_for_single_seek(
            pattern.as_bytes(),
            options,
            &ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
            false,
            true,
        )
        .unwrap();
        SingleSeek::build_with_adaptive_policy(&seek?, accept.as_ref(), dense_limits, threshold)
    }

    fn production_single_seek(pattern: &str, options: OnigOptionType) -> Option<SingleSeek> {
        let (_, seek, accept) = onig_new_for_single_seek(
            pattern.as_bytes(),
            options,
            &ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
            false,
            true,
        )
        .unwrap();
        SingleSeek::build(&seek?, accept.as_ref())
    }

    fn char_boundaries(text: &str) -> Vec<usize> {
        text.char_indices()
            .map(|(index, _)| index)
            .chain(std::iter::once(text.len()))
            .collect()
    }

    impl SingleSeek {
        fn adaptive_consultations(&self) -> (Option<usize>, Option<usize>) {
            (
                self.adaptive_seek().map(AdaptiveDfa::consultation_count),
                self.adaptive_accept().map(AdaptiveDfa::consultation_count),
            )
        }
    }

    /// Show why the estimate/bitset guards include the Django email local
    /// part and excludes the larger domain and URL seek and accept NFAs.
    #[test]
    fn django_catalog_nfa_size_diagnostic() {
        eprintln!(
            "small dense eligibility: estimated NFA states <= {}, actual <=64; final DFA <= {} B; determinization scratch <= {} B",
            MAX_SINGLE_DENSE_ESTIMATED_NFA_STATES,
            SINGLE_DENSE_DFA_SIZE_LIMIT,
            SINGLE_DENSE_DETERMINIZE_SIZE_LIMIT,
        );
        let local_options = DJANGO_OPTIONS;
        for (name, pattern, options, expected_eligible) in [
            (
                "django_email_local_part",
                DJANGO_EMAIL_LOCAL,
                local_options,
                true,
            ),
            ("django_email_domain", DJANGO_DOMAIN, DJANGO_OPTIONS, false),
            ("django_url_regex", DJANGO_URL, DJANGO_OPTIONS, false),
        ] {
            let (_, seek, accept) = onig_new_for_single_seek(
                pattern.as_bytes(),
                options,
                &ONIG_ENCODING_UTF8,
                &OnigSyntaxOniguruma,
                false,
                true,
            )
            .unwrap();
            let Seek::Pattern(seek) = seek.expect("catalog pattern has a seek") else {
                panic!("{name} seek is not a pattern");
            };
            let mut hirs = vec![("seek", seek.decode())];
            if let Some(accept) = accept.as_ref() {
                hirs.push(("accept", accept.code.decode()));
            }
            if name == "django_email_local_part" {
                assert_eq!(hirs.len(), 1, "local-part seek is exact");
            }
            let mut seek_eligible = false;
            for (kind, hir) in hirs {
                let gate_estimate = nfa_states_estimate(&hir);
                let estimated = if kind == "accept" {
                    states_estimate(&hir, true)
                } else {
                    gate_estimate
                };
                let (nfa, eligible) = single_nfa(&hir).expect("catalog NFA builds");
                let actual = nfa.states().len();
                assert_eq!(
                    eligible,
                    gate_estimate <= MAX_SINGLE_DENSE_ESTIMATED_NFA_STATES
                        && actual <= MAX_SINGLE_BITSET_NFA_STATES
                );
                assert_eq!(
                    eligible,
                    kind == "seek" && expected_eligible,
                    "{name} {kind} eligibility under the small policy"
                );
                eprintln!(
                    "{name} {kind}: estimated_states={estimated}, dense_gate_estimate={gate_estimate}, actual_states={actual}, dense_eligible={eligible}"
                );
                if kind == "seek" {
                    seek_eligible = eligible;
                }
            }
            assert_eq!(seek_eligible, expected_eligible, "{name} selection");
        }
    }

    /// Dense seeks answer exactly like the retained hybrid implementation,
    /// including look-around context, UTF-8 classes, accept-seek rejection
    /// triggers, and searches that begin inside a subject.
    #[test]
    fn dense_single_seeks_match_the_hybrid_fallback() {
        let cases = [
            (
                r"\A(?:ab|cd)[0-9]{1,3}\z",
                ONIG_OPTION_CAPTURE_GROUP,
                &["ab7", "x ab7", "cd123", "ab1234", "zz", "abc"] as &[&str],
            ),
            (
                r"(?i)k+\z",
                ONIG_OPTION_CAPTURE_GROUP | ONIG_OPTION_IGNORECASE,
                &["k", "Kk", "\u{212A}k", "xk", "k "] as &[&str],
            ),
            (
                r"(?m)^あ+$",
                ONIG_OPTION_CAPTURE_GROUP,
                &["あ", "x\nあ\n", "あい", "xあ"] as &[&str],
            ),
            (
                r"[é-ü]+x(?i:[ß])?",
                ONIG_OPTION_CAPTURE_GROUP,
                &["éx", "üx", "éxß", "éxss", "x", "éy"] as &[&str],
            ),
        ];

        let dense_limits = Some(PREFERRED_SINGLE_DENSE_LIMITS);
        for (pattern, options, subjects) in cases {
            let dense = single_seek_with(pattern, options, dense_limits)
                .unwrap_or_else(|| panic!("no single seek for {pattern:?}"));
            let hybrid =
                single_seek_with(pattern, options, None).expect("the hybrid fallback builds");

            for text in subjects {
                for start in char_boundaries(text) {
                    assert_eq!(
                        dense.search(text.as_bytes(), start),
                        hybrid.search(text.as_bytes(), start),
                        "seek for {pattern:?} on {text:?} from {start}"
                    );
                    assert_eq!(
                        dense.accept_answer(text.as_bytes(), start),
                        hybrid.accept_answer(text.as_bytes(), start),
                        "accept seek for {pattern:?} on {text:?} from {start}"
                    );
                }
            }
        }
    }

    /// A tiny dense budget rejects determinization and uses the hybrid DFA;
    /// when a table builds, searches use it while the hybrid pool is retained.
    #[test]
    fn dense_single_seek_is_bounded_and_falls_back_to_hybrid() {
        let pattern = r"\A(?:ab|cd)[0-9]{1,3}\z";
        let dense = single_seek_with(
            pattern,
            ONIG_OPTION_CAPTURE_GROUP,
            Some(SingleDenseLimits {
                dfa_bytes: SINGLE_DENSE_DFA_SIZE_LIMIT,
                determinize_bytes: SINGLE_DENSE_DETERMINIZE_SIZE_LIMIT,
            }),
        )
        .expect("seek builds");
        assert!(dense.uses_dense_dfas());

        assert!(dense.memory_usage() <= SINGLE_DENSE_DFA_SIZE_LIMIT);

        let forced = single_seek_with(
            pattern,
            ONIG_OPTION_CAPTURE_GROUP,
            Some(SingleDenseLimits {
                dfa_bytes: 0,
                determinize_bytes: 0,
            }),
        )
        .expect("hybrid fallback builds after dense rejection");
        assert_eq!(forced.backend_names().0, "hybrid");

        for text in ["ab1", "cd123", "ab1234", "zz"] {
            assert_eq!(
                dense.search(text.as_bytes(), 0),
                forced.search(text.as_bytes(), 0)
            );
        }
    }

    /// Adaptive seeks run the hybrid DFA until the exact per-DFA consultation
    /// threshold, then publish one immutable dense DFA. The pool remains for
    /// the hybrid accept member until that member promotes as well.
    #[test]
    fn adaptive_single_seek_promotes_each_dfa_after_its_consultation_threshold() {
        let pattern = r"[é-ü]+x(?i:[ß])?";
        let adaptive = adaptive_single_seek_with(
            pattern,
            ONIG_OPTION_CAPTURE_GROUP,
            Some(PREFERRED_SINGLE_DENSE_LIMITS),
            2,
        )
        .expect("adaptive seek builds");
        let hybrid = single_seek_with(pattern, ONIG_OPTION_CAPTURE_GROUP, None)
            .expect("forced-hybrid reference builds");
        assert_eq!(adaptive.backend_names(), ("hybrid", Some("hybrid")));
        assert_eq!(adaptive.adaptive_consultations(), (Some(0), Some(0)));

        assert_eq!(
            adaptive.search("éx".as_bytes(), 0),
            hybrid.search("éx".as_bytes(), 0)
        );
        assert_eq!(
            adaptive.accept_answer("éx".as_bytes(), 0),
            hybrid.accept_answer("éx".as_bytes(), 0)
        );
        assert_eq!(adaptive.adaptive_consultations(), (Some(1), Some(1)));
        assert_eq!(adaptive.backend_names(), ("hybrid", Some("hybrid")));

        assert_eq!(
            adaptive.search("éxß".as_bytes(), 0),
            hybrid.search("éxß".as_bytes(), 0)
        );
        assert_eq!(adaptive.backend_names(), ("dense", Some("hybrid")));
        assert_eq!(adaptive.adaptive_consultations(), (Some(2), Some(1)));

        assert_eq!(
            adaptive.accept_answer("éxß".as_bytes(), 0),
            hybrid.accept_answer("éxß".as_bytes(), 0)
        );
        assert_eq!(adaptive.backend_names(), ("dense", Some("dense")));
        assert_eq!(adaptive.adaptive_consultations(), (Some(2), Some(2)));

        // Once both immutable tables have been published, calls no longer
        // consult the retained hybrid DFAs or mutate the counters.
        for text in ["éx", "éxß", "x", "éy"] {
            assert_eq!(
                adaptive.search(text.as_bytes(), 0),
                hybrid.search(text.as_bytes(), 0)
            );
            assert_eq!(
                adaptive.accept_answer(text.as_bytes(), 0),
                hybrid.accept_answer(text.as_bytes(), 0)
            );
        }
        assert_eq!(adaptive.adaptive_consultations(), (Some(2), Some(2)));
    }

    /// A rejected bounded promotion is memoized once and leaves the hybrid
    /// backend as the exact fallback for all later calls.
    #[test]
    fn adaptive_single_seek_memoizes_dense_rejection_and_keeps_hybrid() {
        let pattern = r"(?:ab|cd)[0-9]{1,3}";
        let adaptive = adaptive_single_seek_with(
            pattern,
            ONIG_OPTION_CAPTURE_GROUP,
            Some(SingleDenseLimits {
                dfa_bytes: 0,
                determinize_bytes: 0,
            }),
            2,
        )
        .expect("adaptive seek builds");
        let hybrid = single_seek_with(pattern, ONIG_OPTION_CAPTURE_GROUP, None)
            .expect("forced-hybrid reference builds");

        for _ in 0..2 {
            assert_eq!(
                adaptive.search("cd123".as_bytes(), 0),
                hybrid.search("cd123".as_bytes(), 0)
            );
        }
        let adaptive_dfa = adaptive.adaptive_seek().expect("seek is adaptive");
        assert!(adaptive_dfa.promotion_attempted());
        assert!(matches!(adaptive_dfa.dense_decision.get(), Some(None)));
        assert_eq!(adaptive.adaptive_consultations().0, Some(2));
        assert_eq!(adaptive.backend_names().0, "hybrid");

        for text in ["ab7", "cd123", "cd1234", "none"] {
            assert_eq!(
                adaptive.search(text.as_bytes(), 0),
                hybrid.search(text.as_bytes(), 0)
            );
        }
        assert_eq!(adaptive.adaptive_consultations().0, Some(2));
        assert!(matches!(adaptive_dfa.dense_decision.get(), Some(None)));
    }

    /// A panic during dense construction cannot leave a poisoned OnceLock or
    /// cause an unbounded retry: later calls keep using the retained hybrid.
    #[test]
    fn adaptive_single_seek_promotion_panic_falls_back_without_retry() {
        let pattern = r"[é-ü]+x(?i:[ß])?";
        let adaptive = adaptive_single_seek_with(
            pattern,
            ONIG_OPTION_CAPTURE_GROUP,
            Some(PREFERRED_SINGLE_DENSE_LIMITS),
            1,
        )
        .expect("adaptive seek builds");
        let hybrid = single_seek_with(pattern, ONIG_OPTION_CAPTURE_GROUP, None)
            .expect("forced-hybrid reference builds");
        let adaptive_dfa = adaptive.adaptive_seek().expect("seek is adaptive");
        let attempts = AtomicUsize::new(0);
        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            adaptive_dfa.initialize_dense_with(|| {
                attempts.fetch_add(1, Ordering::Relaxed);
                panic!("injected dense builder panic");
            });
        }));
        assert!(panic.is_err());
        assert_eq!(attempts.load(Ordering::Relaxed), 1);
        assert!(adaptive_dfa.promotion_attempted());
        assert!(adaptive_dfa.dense_decision.get().is_none());

        // The failed initializer is never called again, and search remains
        // equivalent to a separately built hybrid DFA.
        adaptive_dfa.initialize_dense_with(|| {
            attempts.fetch_add(1, Ordering::Relaxed);
            None
        });
        assert_eq!(attempts.load(Ordering::Relaxed), 1);
        assert_eq!(
            adaptive.search("éxß".as_bytes(), 0),
            hybrid.search("éxß".as_bytes(), 0)
        );
        assert_eq!(adaptive.backend_names().0, "hybrid");
        assert_eq!(adaptive.adaptive_consultations().0, Some(0));
    }

    /// Concurrent calls share one immutable publication while each thread
    /// retains its own hybrid cache until the shared promotion completes.
    #[test]
    fn adaptive_single_seek_promotes_safely_across_threads() {
        let pattern = r"[é-ü]+x(?i:[ß])?";
        let adaptive = Arc::new(
            adaptive_single_seek_with(
                pattern,
                ONIG_OPTION_CAPTURE_GROUP,
                Some(PREFERRED_SINGLE_DENSE_LIMITS),
                64,
            )
            .expect("adaptive seek builds"),
        );
        let hybrid = Arc::new(
            single_seek_with(pattern, ONIG_OPTION_CAPTURE_GROUP, None)
                .expect("forced-hybrid reference builds"),
        );
        let mut workers = Vec::new();
        for _ in 0..4 {
            let adaptive = Arc::clone(&adaptive);
            let hybrid = Arc::clone(&hybrid);
            workers.push(std::thread::spawn(move || {
                for iteration in 0..24 {
                    let text = if iteration % 2 == 0 { "éx" } else { "éxß" };
                    assert_eq!(
                        adaptive.search(text.as_bytes(), 0),
                        hybrid.search(text.as_bytes(), 0)
                    );
                    assert_eq!(
                        adaptive.accept_answer(text.as_bytes(), 0),
                        hybrid.accept_answer(text.as_bytes(), 0)
                    );
                }
            }));
        }
        for worker in workers {
            worker.join().expect("worker completed without panic");
        }
        assert_eq!(adaptive.backend_names(), ("dense", Some("dense")));
        assert_eq!(adaptive.adaptive_consultations(), (Some(64), Some(64)));
    }

    /// The bounded eager helper keeps the larger domain and URL patterns on
    /// the hybrid backend.
    #[test]
    fn django_catalog_single_seek_backend_diagnostic() {
        eprintln!(
            concat!(
                "single-dense eligibility: estimated_states<={}, actual_states<=64; ",
                "dfa_bytes<={}, ",
                "determinize_scratch_bytes<={}; ",
                "hybrid fallback retained if any dense condition fails"
            ),
            MAX_SINGLE_DENSE_ESTIMATED_NFA_STATES,
            SINGLE_DENSE_DFA_SIZE_LIMIT,
            SINGLE_DENSE_DETERMINIZE_SIZE_LIMIT,
        );
        let mut dense_seek = false;
        let mut dense_accept = false;
        for (name, pattern, subjects) in [
            (
                "django_email_domain",
                DJANGO_DOMAIN,
                &[
                    "example.com",
                    "straße.de",
                    "strasse.de",
                    "a-.com",
                    "localhost",
                ] as &[&str],
            ),
            (
                "django_url_regex",
                DJANGO_URL,
                &[
                    "http://example.com/",
                    "http://straße.de/",
                    "http://strasse.de/",
                    "http://-a.com/",
                    "http://localhost/",
                    "not a url",
                ] as &[&str],
            ),
        ] {
            let seek =
                single_seek_with(pattern, DJANGO_OPTIONS, Some(PREFERRED_SINGLE_DENSE_LIMITS))
                    .unwrap_or_else(|| panic!("no seek for {name}"));
            let hybrid = single_seek_with(pattern, DJANGO_OPTIONS, None)
                .unwrap_or_else(|| panic!("no hybrid seek for {name}"));
            let (seek_backend, accept_backend) = seek.backend_names();
            dense_seek |= seek_backend == "dense";
            dense_accept |= accept_backend == Some("dense");
            assert!(seek.has_accept(), "{name} keeps its accept seek");
            assert_eq!(
                seek_backend, "hybrid",
                "{name} exceeds the small-table guards"
            );
            assert_eq!(
                accept_backend,
                Some("hybrid"),
                "{name} accept exceeds the gate"
            );
            assert!(
                seek.automata_memory_usage() <= 2 * SINGLE_DENSE_DFA_SIZE_LIMIT,
                "{name} diagnostic exceeds the combined small-table cap"
            );
            let mut comparisons = 0;
            for text in subjects {
                for start in char_boundaries(text) {
                    comparisons += 1;
                    assert_eq!(
                        seek.search(text.as_bytes(), start),
                        hybrid.search(text.as_bytes(), start),
                        "{name} seek on {text:?} from {start}"
                    );
                    assert_eq!(
                        seek.accept_answer(text.as_bytes(), start),
                        hybrid.accept_answer(text.as_bytes(), start),
                        "{name} accept seek on {text:?} from {start}"
                    );
                }
            }
            eprintln!(
                concat!(
                    "{}: seek={}, accept={:?}; ",
                    "configured automata_only={} B, warmed_current_thread_caches={} B; ",
                    "forced_hybrid automata_only={} B, warmed_current_thread_caches={} B; ",
                    "each backend ran search and accept_answer at {} ",
                    "character-boundary positions; cache sizes are after those calls ",
                    "(pool bookkeeping excluded)"
                ),
                name,
                seek_backend,
                accept_backend,
                seek.automata_memory_usage(),
                seek.cache_memory_usage(),
                hybrid.automata_memory_usage(),
                hybrid.cache_memory_usage(),
                comparisons,
            );
        }
        assert!(
            !dense_seek,
            "large catalog seeks stay hybrid under the small gate"
        );
        assert!(
            !dense_accept,
            "large catalog accepts stay hybrid under the small gate"
        );
    }

    /// Exercise the actual production promotion policy on Django's catalog
    /// validators. The memory values distinguish automata retained by the
    /// `SingleSeek` (including the hybrid after promotion) from this thread's
    /// warmed hybrid caches; Pool bookkeeping and other threads' caches are
    /// excluded.
    #[test]
    fn django_catalog_adaptive_single_seek_diagnostic() {
        eprintln!(
            concat!(
                "production adaptive policy: estimated_states<={}, actual<=64, text anchors only, promotion_after={} actual DFA consultations, ",
                "dense_bytes<={}, determinize_scratch_bytes<={}; ",
                "hybrid NFA/backend and per-thread caches remain allocated after promotion"
            ),
            MAX_SINGLE_DENSE_ESTIMATED_NFA_STATES,
            SINGLE_DENSE_PROMOTION_THRESHOLD,
            SINGLE_DENSE_DFA_SIZE_LIMIT,
            SINGLE_DENSE_DETERMINIZE_SIZE_LIMIT,
        );
        let mut dense_seek = false;
        let mut dense_accept = false;
        let mut local_part_promoted = false;
        let local_options = DJANGO_OPTIONS;
        for (name, pattern, options, text, eligible) in [
            (
                "django_email_local_part",
                DJANGO_EMAIL_LOCAL,
                local_options,
                "john.doe",
                true,
            ),
            (
                "django_email_domain",
                DJANGO_DOMAIN,
                DJANGO_OPTIONS,
                "example.com",
                false,
            ),
            (
                "django_url_regex",
                DJANGO_URL,
                DJANGO_OPTIONS,
                "http://example.com/",
                false,
            ),
        ] {
            let adaptive = production_single_seek(pattern, options)
                .unwrap_or_else(|| panic!("no production seek for {name}"));
            let initial_backends = adaptive.backend_names();
            assert_eq!(initial_backends.0, "hybrid");

            let initial_automata = adaptive.automata_memory_usage();
            if eligible {
                assert_eq!(adaptive.adaptive_consultations(), (Some(0), None));
                assert_eq!(initial_backends.1, None, "local-part seek is exact");
                for _ in 0..(SINGLE_DENSE_PROMOTION_THRESHOLD - 1) {
                    let _ = adaptive.search(text.as_bytes(), 0);
                }
                assert_eq!(adaptive.backend_names(), ("hybrid", None));
                let before_automata = adaptive.automata_memory_usage();
                let before_caches = adaptive.cache_memory_usage();
                let before_counts = adaptive.adaptive_consultations();
                assert_eq!(before_counts, (Some(63), None));

                let _ = adaptive.search(text.as_bytes(), 0);
                let after_backends = adaptive.backend_names();
                let after_automata = adaptive.automata_memory_usage();
                let after_caches = adaptive.cache_memory_usage();
                let after_counts = adaptive.adaptive_consultations();
                local_part_promoted = after_backends.0 == "dense";
                dense_seek |= local_part_promoted;
                dense_accept |= after_backends.1 == Some("dense");
                eprintln!(
                    concat!(
                        "{} eligible: initial_automata={} B; before_promotion={:?}, ",
                        "automata={} B, warmed_current_thread_caches={} B; ",
                        "after={:?}, automata={} B, retained_current_thread_caches={} B; counts={:?}"
                    ),
                    name,
                    initial_automata,
                    before_counts,
                    before_automata,
                    before_caches,
                    after_backends,
                    after_automata,
                    after_caches,
                    after_counts,
                );
                assert_eq!(after_counts, (Some(64), None));
                assert!(after_automata >= before_automata);
            } else {
                assert_eq!(adaptive.adaptive_consultations(), (None, None));
                for _ in 0..SINGLE_DENSE_PROMOTION_THRESHOLD {
                    let _ = adaptive.search(text.as_bytes(), 0);
                    let _ = adaptive.accept_answer(text.as_bytes(), 0);
                }
                let after_backends = adaptive.backend_names();
                let after_automata = adaptive.automata_memory_usage();
                let after_caches = adaptive.cache_memory_usage();
                eprintln!(
                    concat!(
                        "{} ineligible: initial_automata={} B; after_64_search_and_accept={:?}, ",
                        "automata={} B, warmed_current_thread_caches={} B; counts={:?}"
                    ),
                    name,
                    initial_automata,
                    after_backends,
                    after_automata,
                    after_caches,
                    adaptive.adaptive_consultations(),
                );
                assert_eq!(after_backends, ("hybrid", Some("hybrid")));
                assert_eq!(adaptive.adaptive_consultations(), (None, None));
                assert_eq!(after_automata, initial_automata);
            }
        }
        assert!(
            local_part_promoted && dense_seek,
            "production policy promotes the eligible local-part seek"
        );
        assert!(
            !dense_accept,
            "catalog accepts exceed the small-table guards"
        );
    }

    /// A mixed pair keeps a pool only for its hybrid member. Both methods
    /// still answer like the all-hybrid pair.
    #[test]
    fn mixed_dense_and_hybrid_seek_uses_only_hybrid_caches() {
        let pattern = r"[é-ü]+x(?i:[ß])?";
        let (_, seek, accept) = onig_new_for_single_seek(
            pattern.as_bytes(),
            ONIG_OPTION_CAPTURE_GROUP,
            &ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
            false,
            true,
        )
        .unwrap();
        let seek = seek.unwrap();
        let hybrid = SingleSeek::build_with_dense_limits(&seek, accept.as_ref(), None)
            .expect("hybrid pair builds");
        let mixed = SingleSeek::build_with_separate_dense_limits(
            &seek,
            accept.as_ref(),
            Some(PREFERRED_SINGLE_DENSE_LIMITS),
            Some(SingleDenseLimits {
                dfa_bytes: 0,
                determinize_bytes: 0,
            }),
        )
        .expect("mixed pair builds");
        assert_eq!(mixed.backend_names(), ("dense", Some("hybrid")));

        for text in ["éx", "éxß", "éxss", "x", "éy"] {
            assert_eq!(
                mixed.search(text.as_bytes(), 0),
                hybrid.search(text.as_bytes(), 0)
            );
            assert_eq!(
                mixed.accept_answer(text.as_bytes(), 0),
                hybrid.accept_answer(text.as_bytes(), 0)
            );
        }

        let reverse_mixed = SingleSeek::build_with_separate_dense_limits(
            &seek,
            accept.as_ref(),
            Some(SingleDenseLimits {
                dfa_bytes: 0,
                determinize_bytes: 0,
            }),
            Some(PREFERRED_SINGLE_DENSE_LIMITS),
        )
        .expect("reverse mixed pair builds");
        assert_eq!(reverse_mixed.backend_names(), ("hybrid", Some("dense")));

        for text in ["éx", "éxß", "éxss", "x", "éy"] {
            assert_eq!(
                reverse_mixed.search(text.as_bytes(), 0),
                hybrid.search(text.as_bytes(), 0)
            );
            assert_eq!(
                reverse_mixed.accept_answer(text.as_bytes(), 0),
                hybrid.accept_answer(text.as_bytes(), 0)
            );
        }
    }

    #[test]
    fn dense_single_seek_stays_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<SingleSeek>();
    }

    /// The seek of `pattern` under `options` in regex syntax, or what it is
    /// instead of a pattern.
    fn seek_pattern_with(pattern: &str, options: OnigOptionType) -> String {
        match seek_with(pattern, options) {
            Ok(Some(Seek::Pattern(seek))) => seek.decode().to_string(),
            other => format!("{other:?}"),
        }
    }

    fn seek_pattern(pattern: &str) -> String {
        seek_pattern_with(pattern, ONIG_OPTION_CAPTURE_GROUP)
    }

    /// Whether the seek of `pattern` under `options` is exact, as a single
    /// regex's seek is derived (`onig_new_for_single_seek`).
    fn exact_with(pattern: &str, options: OnigOptionType) -> Option<bool> {
        let seek = crate::regcomp::onig_new_for_single_seek(
            pattern.as_bytes(),
            options,
            &ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
            false,
            true,
        )
        .unwrap()
        .1;
        match seek {
            Some(Seek::Pattern(code)) => Some(code.exact()),
            _ => None,
        }
    }

    /// The constructs whose seek is exact, and those whose seek approximates
    /// the matcher (for existence): each `SeekCode::exact` is pinned.
    #[test]
    fn seeks_are_exact_exactly_where_the_matcher_reads_alike() {
        let exact = [
            "abc",
            "[a-c]",
            "a|bc",
            "ab{2,5}c",
            "[^a]",
            ".",
            "\u{3042}+",
            "\\x{1F600}",
            "x|$",
            "a$",
            "\\Aab\\z",
            "a\\Kb",
            "^a",
            "^[0-9]{8}$",
            "(?:^a|^b)c",
            "(?i)[0-9a-f]+",
            "(?i)k",
            "(?i)s",
            "[\u{e9}]",
            "(a)(b)",
            // Repeats that `tune_next` makes possessive: their bags keep the
            // language of the repeat, so the seek is exact.
            "^[a-z]+@[a-z]+\\.com$",
            "[a-z]*@",
            "[^\"]*\"",
            "(?:ab)*c",
            "([a-z]+)@([a-z]+)",
        ];
        let inexact = [
            "(?>abc|ab)c",
            "(?>a+)b",
            "a++b",
            "a*+b",
            "[a-z]++@",
            // A user-written atomic group stays inexact beside an automatic one.
            "^[a-z]+@(?>[a-z]+)\\.com$",
            "(?>[a-z]+)@",
            "\\b",
            "\\B",
            "(?=a)b",
            "(?<=a)b",
            "a(?!b)",
            "a(?<!b)",
            "\\Zb",
            "^",
            "^$",
            "(a)\\1",
            "\\W",
            "\\w",
            "\\d+",
            "[^\u{e9}]",
            "\\G\\w",
            "(?:ab|cd){100}",
            "(x)?(?(1)a|b)",
        ];
        for pattern in exact {
            assert_eq!(
                exact_with(pattern, ONIG_OPTION_CAPTURE_GROUP),
                Some(true),
                "{pattern}"
            );
        }
        for pattern in inexact {
            assert_eq!(
                exact_with(pattern, ONIG_OPTION_CAPTURE_GROUP),
                Some(false),
                "{pattern}"
            );
        }
        // ASCII word characters: the repeat before `:` is possessive and exact.
        let ascii_word = ONIG_OPTION_CAPTURE_GROUP | crate::oniguruma::ONIG_OPTION_WORD_IS_ASCII;
        assert_eq!(exact_with("\\w+:", ascii_word), Some(true));
        assert_eq!(exact_with("\\w+:", ONIG_OPTION_CAPTURE_GROUP), Some(false));
        // Without multi-line anchors `$` is `\Z`, which is exact at the end of
        // the pattern (where it is `(?:\n)?\z`) and approximated elsewhere.
        let singleline = ONIG_OPTION_CAPTURE_GROUP | crate::oniguruma::ONIG_OPTION_SINGLELINE;
        assert_eq!(exact_with("^a$", singleline), Some(true));
        assert_eq!(exact_with("a$|b$", singleline), Some(true));
        assert_eq!(exact_with("(?:a|b)\\Z", singleline), Some(true));
        assert_eq!(exact_with("a$b", singleline), Some(false));
        assert_eq!(exact_with("a$", ONIG_OPTION_CAPTURE_GROUP), Some(true));
        // The absent operator's range cutter has no seek of its own here, so
        // the pattern is searched on its own (no exactness to speak of).
        assert_eq!(exact_with("(?~abc)x", ONIG_OPTION_CAPTURE_GROUP), None);
        // `(*FAIL)` is a callout, which leaves the pattern without a seek.
        assert_eq!(exact_with("(*FAIL)|a", ONIG_OPTION_CAPTURE_GROUP), None);
        // Options that change what a line start, a line end or a match is.
        assert_eq!(exact_with("^a", ONIG_OPTION_NOTBOL), Some(false));
        assert_eq!(exact_with("a$", ONIG_OPTION_NOTEOL), Some(false));
        assert_eq!(exact_with("a", ONIG_OPTION_FIND_NOT_EMPTY), Some(false));
    }

    /// Each construct as the seek writes it. A seek matches wherever the
    /// pattern can match; the approximations are the documented ones.
    #[test]
    fn seeks_approximate_each_construct() {
        let cases: &[(&str, &str)] = &[
            // Exact: literals, classes, concatenation, alternation,
            // repetition; groups are transparent.
            ("abc", "(?:abc)"),
            ("[a-c]", "(?-u:[a-c])"),
            ("a|bc", "(?:a|(?:bc))"),
            ("ab{2,5}c", "(?:ab{2,5}c)"),
            // Greediness decides which match is preferred, not where one
            // exists, so every repetition is written greedy.
            ("(?:ab)+?", "(?:ab)+"),
            ("(a)(?:b)(?>c)d?", "(?:(?:abc)d?)"),
            ("(?:a|bc){70}", "(?:a|(?:bc)){64,}"),
            // A repetition of a repetition is flattened to a superset:
            // regex-syntax would print `(?:ab)+?`, a lazy plus.
            ("(?:(?:ab)+)?c", "(?:(?:ab)*c)"),
            ("(?:(?:ab){2,3}){2}", "(?:ab){4,6}"),
            ("(?:a*)+b", "(?:a*b)"),
            (
                "[^x]{2,70}",
                "(?:(?-u:[\\x00-wy-\\x7F])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3})){2,}",
            ),
            // Classes are byte-based: ASCII exact, non-ASCII as one
            // UTF-8 sequence.
            ("[é]", "(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3})"),
            (
                "[^a]",
                "(?:(?-u:[\\x00-`b-\\x7F])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))",
            ),
            (
                "\\w",
                "(?:(?-u:[0-9A-Z_a-z])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))",
            ),
            // Any character is an ASCII byte or one UTF-8 sequence.
            (
                ".",
                "(?:(?-u:[\\x00-\\x09\\x0B-\\x7F])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))",
            ),
            (
                "(?m:.)",
                "(?:(?-u:[\\x00-\\x7F])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))",
            ),
            // Anchors.
            ("\\Aa", "(?:\\Aa)"),
            ("a\\z", "(?:a\\z)"),
            ("a\\Z", "(?:a(?m:$))"),
            ("^a$", "(?:(?m:^)a(?m:$))"),
            (
                "\\ba",
                "(?:(?:(?-u:\\b)|(?-u:\\b{start-half})|(?-u:\\b{end-half}))a)",
            ),
            // Empty: look-behinds, negative look-aheads, `\G`, `\K`, `\y`.
            ("(?<=x)a", "a"),
            ("(?<!x)a", "a"),
            // A negative look at a class with every ASCII word character
            // is an ASCII half boundary.
            ("(?<!\\w)a", "(?:(?-u:\\b{start-half})a)"),
            (
                "(?<![-\\w])a(?![-\\w])",
                "(?:(?-u:\\b{start-half})a(?-u:\\b{end-half}))",
            ),
            ("(?<!\\W)a", "a"),
            ("(?<![^\\w])a", "a"),
            ("(?=ab)(?<!\\w)", "(?-u:\\b{start-half})"),
            ("(?!x)a", "a"),
            ("\\Ga", "a"),
            ("a\\Kb", "(?:ab)"),
            ("\\ya", "a"),
            // A positive look-ahead keeps its body where nothing consuming
            // follows it, and is dropped otherwise.
            (
                "\\s+(?=use\\b)",
                "(?:(?:(?-u:[\\x09-\\x0D\\x20])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))+(?:use)(?:(?-u:\\b)|(?-u:\\b{start-half})|(?-u:\\b{end-half})))",
            ),
            ("(?=a)(?<=b)", "a"),
            ("(?=a)b", "b"),
            ("(?=a)(?=b)", "a"),
            ("y(?:x(?=a))?", "(?:y(?:xa)?)"),
            ("y(?:x(?=a))+", "(?:yx+)"),
            ("(?:x(?=a))?y", "(?:x?y)"),
            // Anything: back references and calls.
            (
                "(a)\\1",
                "(?:a(?:(?-u:[\\x00-\\x7F])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))*)",
            ),
            (
                "a\\g<1>|(b)",
                "(?:(?:a(?:(?-u:[\\x00-\\x7F])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))*)|b)",
            ),
            // Both branches of a conditional.
            ("(a)?(?(1)b|c)", "(?:a?[bc])"),
            ("(?(a)b|c)", "(?:(?:ab)|c)"),
            // The matcher reads a class's bits for single-byte characters
            // and its code ranges for multibyte ones; nested negations leave
            // entries on the other side (a code range for the space here).
            (
                "[^[^[^İ]\\S]]",
                "(?:(?-u:[\\x00-\\x7F])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))",
            ),
            ("[^[^İ]\\S]", "[a&&b]"),
            (
                "\\W",
                "(?:(?-u:[\\x00-/:-@\\[-\\^`\\{-\\x7F])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))",
            ),
            // Case-insensitive strings as the tuner unravels them.
            ("(?i)ab", "(?:(?-u:[Aa])(?-u:[Bb]))"),
            (
                "(?i)[k]",
                "(?:(?-u:[Kk])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))",
            ),
            // Literal tries: the literals, or their ASCII case variants
            // with an escape for the non-ASCII folds the trie accepts.
            (
                "(?:error|warn|fatal|panic)",
                "(?:(?:error)|(?:warn)|(?:fatal)|(?:panic))",
            ),
            (
                "(?i)(?:ab|cd|ef|gh)",
                "(?:(?:(?-u:[Aa])(?-u:[Bb]))|(?:(?-u:[Cc])(?-u:[Dd]))|(?:(?-u:[Ee])(?-u:[Ff]))|(?:(?-u:[Gg])(?-u:[Hh]))|(?:(?-u:[\\x00-\\x7F])?[KSks\u{17f}\u{212a}](?:(?-u:[\\x00-\\x7F])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))?))",
            ),
            (
                "(?i)(?:kb|ss|st|xy)",
                "(?:(?:(?-u:[Kk])(?-u:[Bb]))|(?:(?-u:[Ss])(?-u:[Ss]))|(?:(?-u:[Ss])(?-u:[Tt]))|(?:(?-u:[Xx])(?-u:[Yy]))|(?:(?-u:[\\x00-\\x7F])?[KSks\u{df}\u{17f}\u{1e9e}\u{212a}\u{fb05}\u{fb06}\u{1df95}](?:(?-u:[\\x00-\\x7F])|(?:(?-u:[\\xC2-\\xF4])(?-u:[\\x80-\\xBF]){1,3}))?))",
            ),
        ];
        let mismatches: Vec<String> = cases
            .iter()
            .filter(|(pattern, expected)| seek_pattern(pattern) != *expected)
            .map(|(pattern, _)| format!("{pattern:?} => {:?}", seek_pattern(pattern)))
            .collect();
        assert!(mismatches.is_empty(), "{}", mismatches.join("\n"));
        // ASCII word characters and boundaries.
        let ascii_word = ONIG_OPTION_CAPTURE_GROUP | ONIG_OPTION_WORD_IS_ASCII;
        assert_eq!(seek_pattern_with(r"\w", ascii_word), "(?-u:[0-9A-Z_a-z])");
        assert_eq!(seek_pattern_with(r"\ba", ascii_word), "(?:(?-u:\\b)a)");
    }

    /// A seek that matches at every position narrows nothing.
    #[test]
    fn seeks_that_match_everywhere_leave_the_entry_on_its_own() {
        for pattern in [
            "",
            r"(?<=\))",
            r"(?!\s*\[)",
            "a*",
            r"(a)?\1",
            r"\G ?",
            r"(?<=}|%>)\s*",
            r"(?i)x*",
            // The absent operator reads any characters first.
            r"(?~abc)d",
        ] {
            assert_eq!(seek(pattern), Some(Seek::Everywhere), "{pattern}");
        }
        // Nullable with a look assertion: the assertion narrows.
        assert_eq!(seek_pattern("^"), "(?m:^)");
        assert_eq!(
            seek_pattern(r"\b"),
            "(?:(?-u:\\b)|(?-u:\\b{start-half})|(?-u:\\b{end-half}))"
        );
    }

    /// The seek code of every distinct pattern of the captured grammars
    /// decodes to the HIR it was made from (`derive` asserts that in debug
    /// builds as well), encodes to the same code again, and holds a few
    /// hundred bytes where the HIR held tens of KiB.
    #[test]
    fn seek_codes_round_trip_over_the_captured_grammars() {
        let mut patterns = std::collections::BTreeSet::new();
        for name in ["cpp", "java", "scss", "c", "php"] {
            let path = format!(
                "{}/benches/{name}_scanner/trace.json",
                env!("CARGO_MANIFEST_DIR")
            );
            let trace: serde_json::Value =
                serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
            for set in trace["scanners"].as_array().unwrap() {
                for pattern in set.as_array().unwrap() {
                    patterns.insert(pattern.as_str().unwrap().to_owned());
                }
            }
        }
        let mut codes = 0usize;
        let mut bytes = 0usize;
        for pattern in &patterns {
            let Some(Seek::Pattern(code)) = seek(pattern) else {
                continue;
            };
            let hir = code.decode();
            let again = SeekCode::encode(&hir, code.exact()).expect("the walk's nodes encode");
            assert_eq!(again, code, "{pattern}");
            assert_eq!(again.decode(), hir, "{pattern}");
            codes += 1;
            bytes += code.len();
        }
        assert!(
            codes > 600,
            "{codes} seeks over {} patterns",
            patterns.len()
        );
        assert!(bytes / codes < 1024, "{bytes} bytes over {codes} seeks");
    }

    /// The `match` and `begin` patterns of a TextMate grammar JSON, as
    /// `benches/grammar_loader.rs` extracts them for the flat scanners of
    /// `battle_bench`, those the scanner compiles.
    fn flat_grammar_patterns(json: &str) -> Vec<String> {
        fn collect(value: &serde_json::Value, out: &mut Vec<String>) {
            match value {
                serde_json::Value::Object(map) => {
                    for key in ["match", "begin"] {
                        if let Some(pattern) = map.get(key).and_then(|v| v.as_str()) {
                            if !out.iter().any(|p| p == pattern) {
                                out.push(pattern.to_owned());
                            }
                        }
                    }
                    for (_, value) in map {
                        collect(value, out);
                    }
                }
                serde_json::Value::Array(items) => {
                    for item in items {
                        collect(item, out);
                    }
                }
                _ => {}
            }
        }
        let root: serde_json::Value = serde_json::from_str(json).unwrap();
        let mut patterns = Vec::new();
        collect(&root, &mut patterns);
        patterns
            .into_iter()
            .filter(|pattern| Scanner::new(&[pattern.as_str()]).is_ok())
            .collect()
    }

    fn tokenize(
        scanner: &mut Scanner,
        line: &crate::scanner::OnigString,
    ) -> Vec<(usize, usize, usize)> {
        let len = line.utf16_len();
        let mut pos = 0;
        let mut tokens = Vec::new();
        while pos < len {
            let Some(m) = scanner.find_next_match_utf16(line, pos, ScannerFindOptions::NONE) else {
                break;
            };
            let end = m.captures()[0].end;
            tokens.push((m.index, m.captures()[0].start, end));
            pos = if end > pos { end } else { pos + 1 };
        }
        tokens
    }

    /// A set whose overlapping DFA cannot reuse its cache retires the
    /// pre-filter and answers as before: the flat scanner over every
    /// pattern of the CSS grammar, whose 116 case-insensitive property
    /// lists in one automaton make every DFA state hold thousands of NFA
    /// states, tokenizing a stylesheet where a `\G`-anchored zero-width
    /// entry wins at every position (`battle_bench`, see ADR-008).
    #[test]
    fn a_set_whose_cache_thrashes_retires_the_prefilter() {
        let _limits = crate::regexec::shared_limits();
        let json = std::fs::read_to_string(format!(
            "{}/benches/grammars/css.json",
            env!("CARGO_MANIFEST_DIR")
        ))
        .unwrap();
        let patterns = flat_grammar_patterns(&json);
        let refs: Vec<&str> = patterns.iter().map(String::as_str).collect();
        let mut filtered =
            Scanner::with_config(&refs, &ScannerConfig::default().prefilter_warmup(0)).unwrap();
        let mut plain =
            Scanner::with_config(&refs, &ScannerConfig::default().prefilter(false)).unwrap();
        let stylesheet = ".navbar-primary > .nav-item:first-child {\n\
            background-color: oklch(0.65 0.15 250);\n\
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;\n\
            transition: all 150ms cubic-bezier(0.4, 0, 0.2, 1);\n\
            --custom-property: var(--color-primary, #3b82f6);\n\
            @media (min-width: 768px) and (prefers-color-scheme: dark) {\n}\n";
        let line = crate::scanner::OnigString::new(stylesheet);
        let stats = filtered.prefilter_stats();
        assert!(stats.covered > 100 && !stats.retired, "{stats:?}");
        let want = tokenize(&mut plain, &line);
        let got = tokenize(&mut filtered, &line);
        assert_eq!(got, want);
        assert!(got.len() > 200);
        let stats = filtered.prefilter_stats();
        assert!(
            stats.retired && !stats.built && stats.own == refs.len(),
            "{stats:?}"
        );
        // Retired for good: the next pass answers alike without automata.
        assert_eq!(tokenize(&mut filtered, &line), want);
        assert!(filtered.prefilter_stats().retired);
    }

    /// A subject tokenized again reuses the walks (`CandidateMemo`): the
    /// first pass over a string records nothing and the second, which
    /// starts over, records, so the third walks a fraction of the steps; a
    /// string of the same content with another identity walks them all,
    /// and every pass answers alike.
    #[test]
    fn walks_of_a_subject_searched_again_are_kept() {
        let _limits = crate::regexec::shared_limits();
        let patterns = [r"[a-z]+:", r"\d+", r"[a-z]+\(", "b", "a"];
        let mut filtered =
            Scanner::with_config(&patterns, &ScannerConfig::default().prefilter_warmup(0)).unwrap();
        let mut plain =
            Scanner::with_config(&patterns, &ScannerConfig::default().prefilter(false)).unwrap();
        let text = "abc: 12 foo(bar) a b xyz: 7 quux(1) ba";
        let line = crate::scanner::OnigString::new(text);
        let steps = || SCAN_STEPS.with(|c| c.get());
        let want = tokenize(&mut plain, &line);
        let before = steps();
        assert_eq!(tokenize(&mut filtered, &line), want);
        let first = steps() - before;
        assert!(first > 0);
        // The second pass starts over: it records, and walks as the first.
        let before = steps();
        assert_eq!(tokenize(&mut filtered, &line), want);
        assert_eq!(steps() - before, first);
        let before = steps();
        assert_eq!(tokenize(&mut filtered, &line), want);
        let third = steps() - before;
        assert!(third < first / 4, "{third} steps after {first}");
        let before = steps();
        assert_eq!(tokenize(&mut filtered, &line), want);
        assert_eq!(steps() - before, third);
        // Another identity with the same content walks everything again.
        let other = crate::scanner::OnigString::new(text);
        let before = steps();
        assert_eq!(tokenize(&mut filtered, &other), want);
        assert_eq!(steps() - before, first);
    }

    /// Patterns compiled for a scanner without the pre-filter, with
    /// callouts, or under another encoding have no seek.
    #[test]
    fn no_seek_without_the_prefilter_or_with_callouts() {
        let plain = onig_new_for_scanner(
            b"abc",
            ONIG_OPTION_CAPTURE_GROUP,
            &ONIG_ENCODING_UTF8,
            &OnigSyntaxOniguruma,
            false,
            false,
        )
        .unwrap();
        assert_eq!(plain.1, None);
        // `(*FAIL)` and `(*MAX{n})` are built-in callouts.
        assert_eq!(seek("(*FAIL)"), None);
        assert_eq!(seek("(*MAX{1})a"), None);
        assert_eq!(
            seek_pattern_with("abc", ONIG_OPTION_IGNORECASE),
            "(?:(?-u:[Aa])(?-u:[Bb])(?-u:[Cc]))"
        );
        let ascii = onig_new_for_scanner(
            b"abc",
            ONIG_OPTION_CAPTURE_GROUP,
            &crate::encodings::ascii::ONIG_ENCODING_ASCII,
            &OnigSyntaxOniguruma,
            false,
            true,
        )
        .unwrap();
        assert_eq!(ascii.1, None);
    }

    /// A set whose automata would exceed `MAX_NFA_STATES` keeps the
    /// position-lead search, and answers alike.
    #[test]
    fn sets_over_the_state_cutoff_build_no_automata() {
        let _limits = crate::regexec::shared_limits();
        // 16 branches of 64 class states each, per pattern.
        let branches: Vec<String> = (0..16)
            .map(|i| format!("[{}{}]{{64}}{i:x}", (b'a' + i) as char, (b'A' + i) as char))
            .collect();
        let pattern = format!("(?:{})", branches.join("|"));
        let patterns: Vec<&str> = std::iter::repeat_n(pattern.as_str(), 70)
            .chain(["2"])
            .collect();
        let text = format!("1 {}0 2", "a".repeat(64));
        let config = ScannerConfig::default().prefilter_warmup(0);
        let mut big = Scanner::with_config(&patterns, &config).unwrap();
        let mut little = Scanner::with_config(&patterns[69..], &config).unwrap();
        // The automata are built by the first search.
        for scanner in [&big, &little] {
            let stats = scanner.prefilter_stats();
            assert!(!stats.built && stats.nfa_states == 0, "{stats:?}");
        }
        let found = |scanner: &mut Scanner, start: usize| {
            scanner
                .find_next_match(&text, start, ScannerFindOptions::NONE)
                .map(|m| (m.index, m.captures()[0].start, m.captures()[0].end))
        };
        assert_eq!(found(&mut big, 0), Some((0, 2, 67)));
        assert_eq!(found(&mut big, 3), Some((70, 68, 69)));
        assert_eq!(found(&mut little, 0), Some((0, 2, 67)));
        assert_eq!(found(&mut little, 3), Some((1, 68, 69)));
        let stats = big.prefilter_stats();
        assert!(
            !stats.built && stats.covered == 0 && stats.own == 71,
            "{stats:?}"
        );
        let stats = little.prefilter_stats();
        assert!(stats.built && stats.covered == 2 && stats.nfa_states < MAX_NFA_STATES);
    }

    /// Sets the overlapping DFA's cache capacity on this thread while it
    /// lives: the automata the thread builds then clear that cache as often
    /// as the capacity needs (`overlapping_config`).
    struct OverlappingCacheBytes;

    impl OverlappingCacheBytes {
        fn set(bytes: usize) -> Self {
            OVERLAPPING_CACHE_BYTES.with(|cell| cell.set(Some(bytes)));
            Self
        }
    }

    impl Drop for OverlappingCacheBytes {
        fn drop(&mut self) {
            OVERLAPPING_CACHE_BYTES.with(|cell| cell.set(None));
        }
    }

    /// A walk that clears the overlapping DFA's cache can reach a match
    /// state that takes the ID of the match state it recorded before the
    /// clear. Keyed by the ID alone, the walk took that state as already
    /// recorded and dropped its patterns: here the `zz` at 4 was lost to
    /// two `z` candidates, where the scanner without the pre-filter answers
    /// `zz`. The 2 KiB cache is cleared twice by the search of this subject,
    /// and the give-up, which would retire the pre-filter first, is off.
    #[test]
    fn a_walk_that_clears_the_cache_keeps_the_state_it_reaches() {
        let _limits = crate::regexec::shared_limits();
        let patterns = ["zz", "z", r"z\w*", "q:"];
        let _cache = OverlappingCacheBytes::set(2048);
        let mut filtered =
            Scanner::with_config(&patterns, &ScannerConfig::default().prefilter_warmup(0)).unwrap();
        let mut plain =
            Scanner::with_config(&patterns, &ScannerConfig::default().prefilter(false)).unwrap();
        let line = crate::scanner::OnigString::new("zqzzzz(");
        let want = tokenize(&mut plain, &line);
        let got = tokenize(&mut filtered, &line);
        let stats = filtered.prefilter_stats();
        assert!(stats.built && stats.cache_clears > 0, "{stats:?}");
        assert_eq!(want, [(1, 0, 1), (0, 2, 4), (0, 4, 6)]);
        assert_eq!(got, want);
    }
    /// Check the new bitset path against the retained library implementation,
    /// including empty input, anchors evaluated at EOI, Unicode bytes, and
    /// nonzero starts with every possible predecessor byte.
    #[test]
    fn single_table_matches_hybrid_at_every_byte_context() {
        for pattern in [
            r"",
            r"a*",
            r"\Aa+\z",
            r"\z\A",
            r"(?:ab|a)\z",
            r"[a-z]+",
            r"é+",
            r"a\z",
            r"(?:a?|b)*c",
            r"[^x]+",
            r"\A(?:a|bc){0,3}\z",
        ] {
            let nfa = thompson::Compiler::new()
                .configure(
                    thompson::Config::new()
                        .utf8(false)
                        .which_captures(thompson::WhichCaptures::None),
                )
                .build(pattern)
                .unwrap();
            let dfa = build_single_hybrid(nfa.clone()).unwrap();
            let mut cache = dfa.create_cache();
            let table = SingleTable::build(&nfa, PREFERRED_SINGLE_DENSE_LIMITS).unwrap();
            for previous in 0..=256 {
                for suffix in [
                    "", "a", "aa", "ab", "ba", "abc", "\n", "a\n", "a\r\n", "é", "éa",
                ] {
                    let mut text = vec![];
                    if previous < 256 {
                        text.push(previous as u8);
                    }
                    let start = text.len();
                    text.extend_from_slice(suffix.as_bytes());
                    let expected = dfa
                        .try_search_fwd(
                            &mut cache,
                            &Input::new(&text).span(start..text.len()).earliest(true),
                        )
                        .unwrap()
                        .is_some();
                    assert_eq!(
                        table.search(&text, start),
                        expected,
                        "{pattern:?} previous={previous} suffix={suffix:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn single_table_guards_bitset_width_and_assertions() {
        let mut saw_64 = false;
        let mut saw_65 = false;
        for count in 1..=80 {
            let nfa = thompson::Compiler::new()
                .configure(thompson::Config::new().utf8(false))
                .build(&format!("a{{{count}}}"))
                .unwrap();
            let size = nfa.states().len();
            saw_64 |= size == 64;
            saw_65 |= size == 65;
            assert_eq!(SingleTable::supports(&nfa), size <= 64);
            if size > 64 {
                assert!(SingleTable::build(&nfa, PREFERRED_SINGLE_DENSE_LIMITS).is_none());
            }
            if size == 64 {
                let table = SingleTable::build(&nfa, PREFERRED_SINGLE_DENSE_LIMITS).unwrap();
                assert!(table.search("a".repeat(count).as_bytes(), 0));
                assert!(!table.search("a".repeat(count - 1).as_bytes(), 0));
            }
        }
        assert!(saw_64 && saw_65);
        for pattern in [r"(?m)^a+$", r"(?-u:\b)a", r"(?-u:\b{start-half})a"] {
            let nfa = thompson::Compiler::new()
                .configure(thompson::Config::new().utf8(false))
                .build(pattern)
                .unwrap();
            assert!(!SingleTable::supports(&nfa));
            assert!(SingleTable::build(&nfa, PREFERRED_SINGLE_DENSE_LIMITS).is_none());
        }
    }
    /// Reject-only consultation does not pay promotion costs, even when the
    /// same automaton later serves complete boolean decisions.
    #[test]
    fn reject_only_search_keeps_the_hybrid_path_before_and_after_promotion() {
        let seek = adaptive_single_seek_with(
            r"\A(?:ab|cd)[0-9]{1,3}\z",
            ONIG_OPTION_CAPTURE_GROUP,
            Some(PREFERRED_SINGLE_DENSE_LIMITS),
            2,
        )
        .unwrap();
        for _ in 0..128 {
            assert_eq!(seek.search_hybrid(b"ab1", 0), Some(true));
            assert_eq!(seek.search_hybrid(b"xx", 0), Some(false));
        }
        assert_eq!(seek.adaptive_consultations(), (Some(0), None));
        assert_eq!(seek.backend_names().0, "hybrid");
        assert_eq!(seek.search(b"ab1", 0), Some(true));
        assert_eq!(seek.search(b"xx", 0), Some(false));
        assert_eq!(seek.backend_names().0, "dense");
        for _ in 0..128 {
            assert_eq!(seek.search_hybrid(b"ab1", 0), Some(true));
            assert_eq!(seek.search_hybrid(b"xx", 0), Some(false));
        }
        assert_eq!(seek.adaptive_consultations(), (Some(2), None));
    }
}