grippo 0.1.1

Parse, match and scrub data at scale.
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
// Project:   grippo
// File:      src/grok/plan.rs
// Purpose:   Lower a grok pattern to native steps that give the regex's answer
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A pattern of literals, native fields, character-class runs and choices
//! runs on the field scanners instead of the regex, when the steps can be
//! shown to give the regex's answer.
//!
//! A run of one class, `%{DATA}` or `%{NOTSPACE}`, tries its ends in the
//! regex's order, longest first or shortest first when lazy, and a choice its
//! branches in order, so each retry the regex would make is made here too,
//! under a work budget. Any other field's match is a run of bytes from its
//! alphabet. When no byte of that alphabet can start what follows, what
//! follows can only start where the run ends, so a field whose own answer ends
//! there has the only end the regex could use. Where that isn't so, the record
//! goes to the regex.

use std::ops::Range;

use regex_syntax::hir::{Class, ClassUnicode, Hir, HirKind};

use super::Library;
use super::ends::{self, End, Ends};
use crate::field::{FIELDS, Field, Scan};
use crate::kernel::ByteClass;

/// A set of characters.
type Set = ClassUnicode;

/// A set the steps test characters against, its ASCII members a bit each.
#[derive(Debug)]
struct Chars {
    ascii: u128,
    /// The ASCII members again, as the tables a vector run reads.
    class: ByteClass,
    /// Every character but a newline, so a run ends at the next newline.
    line: bool,
    set: Set,
}

impl Chars {
    fn new(set: Set) -> Self {
        let mut ascii = 0_u128;
        for r in set.ranges() {
            for c in u32::from(r.start())..=u32::from(r.end()).min(0x7F) {
                ascii |= 1 << c;
            }
        }
        let line = set == all_but_newline();
        Self {
            ascii,
            class: ByteClass::new(ascii),
            line,
            set,
        }
    }

    fn has(&self, c: char) -> bool {
        if c.is_ascii() {
            self.ascii >> u32::from(c) & 1 == 1
        } else {
            contains(&self.set, c)
        }
    }

    /// Bytes at the start of `h` that are characters in the set. `h` is
    /// valid UTF-8.
    fn run(&self, h: &[u8]) -> usize {
        if self.line {
            return memchr::memchr(b'\n', h).unwrap_or(h.len());
        }
        let mut at = 0;
        loop {
            at += self.class.run(h.get(at..).unwrap_or_default());
            // The run stops at a byte past ASCII as well as at a non-member.
            match char_at(h, at) {
                Some((c, w)) if !c.is_ascii() && contains(&self.set, c) => at += w,
                _ => return at,
            }
        }
    }
}

/// The definition `%{DATA}` has: a lazy run that never crosses a newline.
const DATA: &str = ".*?";

/// What a step run or an end tried costs the budget, where a byte scanned
/// costs 1: either does about the work of scanning this many bytes.
const STEP: usize = 16;

/// What a line the regex located may spend before the record goes to the
/// regex: units for each of its bytes, and steps for each step a hit runs.
const WORK_PER_BYTE: usize = 64;
const WORK_PER_STEP: usize = 4;

/// What a first try may spend, made before the regex has said the line
/// matches: units for each byte, steps for each step a hit runs, and steps
/// to spare. A miss that backtracks stops here and the DFA rejects it.
const FIRST_PER_BYTE: usize = 2;
const FIRST_PER_STEP: usize = 2;
const FIRST_SPARE: usize = 16;

/// The most steps of one plan that add to a budget.
const SIZE_CAP: usize = 256;

/// How deep definitions may nest.
const MAX_DEPTH: usize = 32;

/// The longest run an unanchored pattern may start with when it can't skip
/// starts: each start rescans this much.
const MAX_LEADING_RUN: usize = 16;

/// A field that can end where what follows starts, settled per record: the
/// regex's ends for it, and where what follows can start.
#[derive(Debug)]
struct Ambiguous {
    ends: &'static Ends,
    follow: Chars,
    eoi: bool,
    /// What follows may also match nothing, so every end is viable.
    open: bool,
}

/// A zero-width check at a point in the input.
#[derive(Debug, Clone, Copy)]
enum Look {
    /// `\b`: one side a word character, the other not.
    Word,
    /// `^`, at the start of the input.
    Start,
    /// `^` under Oniguruma: the start of a line.
    StartLine,
    /// `$`, at the end of the input.
    End,
    /// `$` under Oniguruma: before a newline or at the end.
    EndLine,
}

#[derive(Debug)]
enum Step {
    Literal(Vec<u8>),
    Look(Look),
    /// A field the regex gives one answer for, given what follows.
    Field {
        field: &'static Field,
        capture: Option<usize>,
        alphabet: Box<Chars>,
        /// What follows may match nothing, so any end will do.
        rest_nullable: bool,
        /// What follows is the end of the input.
        then_end: bool,
        /// Set when the field's characters overlap what follows.
        ambiguous: Option<Box<Ambiguous>>,
    },
    /// One class, repeated: every end the regex could try.
    Run {
        capture: Option<usize>,
        class: Box<Chars>,
        min: usize,
        max: Option<usize>,
        lazy: bool,
        /// PCRE's `x*+`: it never gives a character back.
        possessive: bool,
        /// Characters what follows can start with.
        next: Box<Chars>,
        /// ASCII bytes of the class that what follows can't start with: an
        /// unbounded lazy run steps over them without trying an end. `None`
        /// for every other run, and while what follows may match nothing.
        skip: Option<Box<ByteClass>>,
        /// What follows may match nothing.
        next_nullable: bool,
        /// What follows can match once the input has ended.
        next_eoi: bool,
    },
    /// Branches in the regex's order. An optional group has an empty last one.
    Choice(Vec<Vec<Self>>),
    /// A group or reference repeated `min` to `max` times, the most first
    /// unless lazy.
    Loop {
        body: Vec<Self>,
        min: usize,
        max: Option<usize>,
        lazy: bool,
    },
    /// Where capture `n` starts and ends, around a name with no native scanner.
    Open(usize),
    Close(usize),
    End,
    /// Oniguruma's final `$`: one optional line terminator, then the end of
    /// a line.
    LineEnd,
}

/// A lowered pattern. Parsing runs it from the regex's leftmost start, so
/// only the tests' every-start scan reads `lead`.
#[derive(Debug)]
#[cfg_attr(
    not(test),
    expect(dead_code, reason = "the every-start scan is test-only")
)]
pub(super) struct Plan {
    anchored: bool,
    /// `^` matches after every newline too, as Oniguruma reads it.
    lines: bool,
    /// The class of an unbounded run the pattern starts with. A start just
    /// after one of its characters reaches no end the run's own start
    /// can't, so the leftmost match never starts there.
    lead: Option<Set>,
    steps: Vec<Step>,
    /// Steps a hit runs, up to [`SIZE_CAP`], which sizes the budgets.
    size: usize,
    /// Group-start slots a run needs: one per capture when the pattern has a
    /// group step, else none.
    slots: usize,
}

/// What a first try made of a line.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum First {
    /// The regex's answer, as [`Outcome::Matched`].
    Matched,
    /// The steps say no from the start or can't say: the regex decides.
    Open,
    /// The budget ran out.
    Spent,
}

/// A run from where the regex located a match.
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Located {
    pub(super) outcome: Outcome,
    /// The run started at the input's start and a first try's budget covers it.
    pub(super) first_fits: bool,
}

/// What a plan's hit runs, counted by kind.
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct Terms {
    /// Steps of any kind.
    pub(super) steps: usize,
    /// The field scanners, by name, once per run.
    pub(super) fields: Vec<&'static str>,
    /// Fields whose end the regex settles from what follows.
    pub(super) settled: usize,
    /// The last step that can take any length, which on most lines takes
    /// the bytes that make one line longer than another.
    pub(super) tail: Option<Tail>,
}

/// How the last open-ended step reads its bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Tail {
    /// `memchr` to the line's end.
    Line,
    /// A class, byte by byte.
    Class,
    /// A field scanner.
    Field(&'static str),
}

fn tally(steps: &[Step], times: usize, t: &mut Terms) {
    for step in steps {
        t.steps += times;
        match step {
            Step::Field {
                field, ambiguous, ..
            } => {
                t.fields.extend(std::iter::repeat_n(field.name, times));
                if ambiguous.is_some() {
                    t.settled += times;
                }
                t.tail = Some(Tail::Field(field.name));
            }
            Step::Run {
                class, max: None, ..
            } => t.tail = Some(if class.line { Tail::Line } else { Tail::Class }),
            Step::Choice(branches) => {
                if let Some(first) = branches.first() {
                    tally(first, times, t);
                }
            }
            Step::Loop { body, min, .. } => tally(body, times * min, t),
            _ => {}
        }
    }
}

/// The steps a hit runs, as [`tally`] counts them, up to [`SIZE_CAP`].
fn count(steps: &[Step], times: usize, n: &mut usize) {
    for step in steps {
        *n = n.saturating_add(times).min(SIZE_CAP);
        if *n == SIZE_CAP {
            return;
        }
        match step {
            Step::Choice(branches) => {
                if let Some(first) = branches.first() {
                    count(first, times, n);
                }
            }
            Step::Loop { body, min, .. } => count(body, times.saturating_mul(*min), n),
            _ => {}
        }
    }
}

/// What the native steps made of an input.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Outcome {
    /// The regex's answer: these captures, by capture index.
    Matched,
    /// The regex can't match either.
    NoMatch,
    /// Only the regex can say.
    Unsure,
}

struct Lowerer<'l> {
    library: &'l Library,
    captures: usize,
    stack: Vec<String>,
    dialect: super::Dialect,
    /// Case is folded, as under `(?i)`.
    fold: bool,
    /// `.` matches a newline, as under Rust's `(?s)` or Oniguruma's `(?m)`.
    dotall: bool,
}

impl Plan {
    /// Lower `pattern` over `span`, or say what kept it on the regex.
    pub(super) fn lower(
        pattern: &str,
        library: &Library,
        dialect: super::Dialect,
        span: super::Span,
    ) -> Result<Self, &'static str> {
        let onig = dialect == super::Dialect::Oniguruma;
        let whole = span == super::Span::Whole;
        let pattern = &*super::as_rust(pattern, dialect, super::Possessive::Kept);
        let mut l = Lowerer {
            library,
            captures: 0,
            stack: Vec::new(),
            dialect,
            fold: false,
            dotall: whole,
        };
        let (pattern, fold) = fold_prefix(pattern);
        l.fold = fold;
        // A whole-line pattern keeps its own `^` and `$` as steps: the line's
        // ends are the anchors.
        let (body, anchored, end) = if whole {
            (pattern, true, true)
        } else {
            let (body, anchored) = pattern
                .strip_prefix('^')
                .map_or((pattern, false), |rest| (rest, true));
            match body.strip_suffix('$') {
                Some(rest) if !rest.ends_with('\\') => (rest, anchored, true),
                _ => (body, anchored, false),
            }
        };
        let (mut branches, rest) = l.alternation(body)?;
        if !rest.is_empty() {
            return Err("an unbalanced parenthesis");
        }
        if !whole && (anchored || end) && branches.len() > 1 {
            return Err("an anchor beside a top-level alternation");
        }
        let mut steps = if branches.len() == 1 {
            branches.pop().unwrap_or_default()
        } else {
            vec![Step::Choice(branches)]
        };
        if end {
            steps.push(if onig && !whole {
                Step::LineEnd
            } else {
                Step::End
            });
        }
        if steps.is_empty() {
            return Err("an empty pattern");
        }
        let lead = match steps.iter().find(|s| !matches!(s, Step::Open(_))) {
            Some(Step::Run {
                class, max: None, ..
            }) if !anchored => Some(class.set.clone()),
            _ => None,
        };
        // Tried from every start, any other long leading run rescans the
        // line each time: the regex is the faster engine there. A leading
        // `^` lets only line starts through, so nothing rescans.
        let starts_at_line = matches!(
            steps.iter().find(|s| !matches!(s, Step::Open(_))),
            Some(Step::Look(Look::Start | Look::StartLine))
        );
        let first = steps
            .iter()
            .find(|s| !matches!(s, Step::Open(_) | Step::Look(_)));
        let long = |max: &Option<usize>| max.is_none_or(|m| m > MAX_LEADING_RUN);
        if !anchored
            && !starts_at_line
            && lead.is_none()
            && matches!(first, Some(Step::Run { max, .. }) if long(max))
        {
            return Err("an unanchored pattern that starts with a run");
        }
        check(&mut steps, &Follow::nothing())?;
        // Only a group step reads a slot, so a pattern without one needs none.
        let slots = if opens(&steps) { l.captures } else { 0 };
        let mut size = 0;
        count(&steps, 1, &mut size);
        Ok(Self {
            anchored,
            lines: onig && !whole,
            lead,
            steps,
            size,
            slots,
        })
    }

    /// `true` when a match can only start at the input's start.
    pub(super) const fn starts_at_zero(&self) -> bool {
        self.anchored && !self.lines
    }

    /// What a hit runs, for pricing it: the first branch of each choice and
    /// each loop's minimum.
    pub(super) fn terms(&self) -> Terms {
        let mut t = Terms::default();
        tally(&self.steps, 1, &mut t);
        t
    }

    /// Run on `h`, valid UTF-8, from `at` only, filling `caps` with each
    /// capture's range on a match. `at` is the input's start, or the leftmost
    /// start the regex found.
    pub(super) fn run_at(
        &self,
        h: &[u8],
        at: usize,
        caps: &mut Vec<(usize, Range<usize>)>,
    ) -> Located {
        let budget = self.located(h);
        let (outcome, left, _) = self.run_within(h, at, caps, budget);
        Located {
            outcome,
            first_fits: at == 0 && budget - left <= self.first(h),
        }
    }

    /// The steps from the input's start on a small budget, for a line the
    /// regex hasn't seen.
    pub(super) fn first_try(&self, h: &[u8], caps: &mut Vec<(usize, Range<usize>)>) -> First {
        match self.run_within(h, 0, caps, self.first(h)) {
            (Outcome::Matched, ..) => First::Matched,
            (_, _, true) => First::Spent,
            _ => First::Open,
        }
    }

    /// The budget for a line the regex located.
    const fn located(&self, h: &[u8]) -> usize {
        h.len()
            .saturating_add(1)
            .saturating_mul(WORK_PER_BYTE)
            .saturating_add(self.size * WORK_PER_STEP * STEP)
    }

    /// The budget for a first try.
    const fn first(&self, h: &[u8]) -> usize {
        h.len()
            .saturating_mul(FIRST_PER_BYTE)
            .saturating_add((self.size * FIRST_PER_STEP + FIRST_SPARE) * STEP)
    }

    /// What the steps spend on `h` from its start with no budget to stop
    /// them, what they found, and the budget a first try gets.
    #[cfg(test)]
    pub(super) fn first_try_units(&self, h: &[u8]) -> (Outcome, usize, usize) {
        let whole = 1 << 40;
        let (outcome, left, _) = self.run_within(h, 0, &mut Vec::new(), whole);
        (outcome, whole - left, self.first(h))
    }

    /// The outcome, what is left of `budget`, and whether it ran out.
    fn run_within(
        &self,
        h: &[u8],
        at: usize,
        caps: &mut Vec<(usize, Range<usize>)>,
        budget: usize,
    ) -> (Outcome, usize, bool) {
        let mut ctx = Ctx {
            h,
            caps,
            opens: vec![0; self.slots],
            budget,
            spent: false,
        };
        ctx.caps.clear();
        let outcome = seq(&self.steps, None, at, &mut ctx);
        if outcome == Outcome::Matched {
            ctx.caps.sort_by_key(|(i, _)| *i);
        }
        (outcome, ctx.budget, ctx.spent)
    }

    /// Run on `h` from every start, filling `caps` with each capture's range
    /// on a match: the native steps' own answer, which the tests hold to the
    /// regex's.
    #[cfg(test)]
    pub(super) fn run(&self, h: &[u8], caps: &mut Vec<(usize, Range<usize>)>) -> Outcome {
        let mut ctx = Ctx {
            h,
            caps,
            opens: vec![0; self.slots],
            budget: self.located(h),
            spent: false,
        };
        let last = if self.anchored { 0 } else { h.len() };
        let line_starts = (self.anchored && self.lines)
            .then(|| {
                h.iter()
                    .enumerate()
                    .filter(|&(_, &b)| b == b'\n')
                    .map(|(i, _)| i + 1)
            })
            .into_iter()
            .flatten();
        for at in (0..=last).chain(line_starts) {
            if let Some(lead) = &self.lead
                && char_before(h, at).is_some_and(|(c, _)| contains(lead, c))
            {
                continue;
            }
            ctx.caps.clear();
            match seq(&self.steps, None, at, &mut ctx) {
                Outcome::NoMatch => {}
                Outcome::Matched => {
                    ctx.caps.sort_by_key(|(i, _)| *i);
                    return Outcome::Matched;
                }
                Outcome::Unsure => return Outcome::Unsure,
            }
        }
        Outcome::NoMatch
    }
}

impl Lowerer<'_> {
    const fn onig(&self) -> bool {
        matches!(self.dialect, super::Dialect::Oniguruma)
    }

    /// The pattern is PCRE's, so `x*+` is a possessive repeat.
    const fn pcre(&self) -> bool {
        matches!(self.dialect, super::Dialect::Pcre)
    }

    /// Branches separated by `|`, up to an unmatched `)` or the end.
    fn alternation<'t>(
        &mut self,
        mut text: &'t str,
    ) -> Result<(Vec<Vec<Step>>, &'t str), &'static str> {
        let mut branches = Vec::new();
        loop {
            let (steps, rest) = self.sequence(text)?;
            branches.push(steps);
            match rest.strip_prefix('|') {
                Some(after) => text = after,
                None => return Ok((branches, rest)),
            }
        }
    }

    /// `(?:...)`, `(...)`, `(?<name>...)` or a flag group at the start of
    /// `rest`, with any quantifier after it. An unnamed group writes no field
    /// on either path, and a named one captures as expand numbers it.
    fn group<'t>(&mut self, rest: &'t str) -> Result<Option<(Vec<Step>, &'t str)>, &'static str> {
        let opened = if let Some(after) = rest.strip_prefix("(?:") {
            (None, after, None)
        } else if let Some(after) = rest.strip_prefix("(?i:") {
            (None, after, Some(Flag::Fold))
        } else if let Some(after) = rest.strip_prefix("(?s:").filter(|_| !self.onig()) {
            (None, after, Some(Flag::Dotall))
        } else if let Some((_, after)) = super::named_group(rest) {
            self.captures += 1;
            (Some(self.captures - 1), after, None)
        } else if rest.starts_with('(') && !rest.starts_with("(?") {
            (None, &rest[1..], None)
        } else {
            return Ok(None);
        };
        let (capture, after, flag) = opened;
        let outer = (self.fold, self.dotall);
        self.fold |= flag == Some(Flag::Fold);
        self.dotall |= flag == Some(Flag::Dotall);
        let lowered = self.alternation(after);
        (self.fold, self.dotall) = outer;
        let (mut branches, tail) = lowered?;
        if let Some(c) = capture {
            let inner = if branches.len() == 1 {
                branches.pop().unwrap_or_default()
            } else {
                vec![Step::Choice(branches)]
            };
            let mut wrapped = vec![Step::Open(c)];
            wrapped.extend(inner);
            wrapped.push(Step::Close(c));
            branches = vec![wrapped];
        }
        let tail = tail.strip_prefix(')').ok_or("an unclosed group")?;
        let group = if branches.len() == 1 {
            branches.pop().unwrap_or_default()
        } else {
            vec![Step::Choice(branches)]
        };
        repeated(group, tail).map(Some)
    }

    /// Steps up to `|`, an unmatched `)`, or the end.
    fn sequence<'t>(&mut self, mut rest: &'t str) -> Result<(Vec<Step>, &'t str), &'static str> {
        let mut steps = Vec::new();
        let mut literal = Vec::new();
        // A flag holds to the end of its group, later branches included.
        let mut fold_from = self.fold.then_some(0);
        while let Some(c) = rest.chars().next() {
            if c == '|' || c == ')' {
                break;
            }
            if let Some((flag, len)) = inline_flag(rest, self.onig()) {
                flush(&mut literal, &mut steps);
                match flag {
                    Flag::Fold => {
                        fold_from.get_or_insert(steps.len());
                        self.fold = true;
                    }
                    Flag::Dotall => self.dotall = true,
                }
                rest = &rest[len..];
                continue;
            }
            if let Some(after) = rest.strip_prefix("%{") {
                let end = after.find('}').ok_or("an unclosed reference")?;
                flush(&mut literal, &mut steps);
                let mark = steps.len();
                self.reference(&after[..end], &mut steps)?;
                let inner = steps.split_off(mark);
                let (inner, after) = repeated(inner, &after[end + 1..])?;
                steps.extend(inner);
                rest = after;
                continue;
            }
            if rest.starts_with('(') {
                flush(&mut literal, &mut steps);
            }
            if let Some((group, after)) = self.group(rest)? {
                steps.extend(group);
                rest = after;
                continue;
            }
            if let Some((class, after)) = raw_class(rest, self.onig(), self.fold, self.dotall)? {
                flush(&mut literal, &mut steps);
                let (step, after) = quantified(&class, after, self.pcre())?;
                steps.push(step);
                rest = after;
                continue;
            }
            let look = match c {
                '\\' if rest.starts_with("\\b") => Some((Look::Word, 2)),
                '^' => Some((
                    if self.onig() {
                        Look::StartLine
                    } else {
                        Look::Start
                    },
                    1,
                )),
                '$' => Some((
                    if self.onig() {
                        Look::EndLine
                    } else {
                        Look::End
                    },
                    1,
                )),
                _ => None,
            };
            if let Some((look, len)) = look {
                flush(&mut literal, &mut steps);
                steps.push(Step::Look(look));
                rest = &rest[len..];
                continue;
            }
            if c == '\\' {
                let next = rest[1..].chars().next().ok_or("a trailing backslash")?;
                let byte = match next {
                    'n' => b'\n',
                    't' => b'\t',
                    'r' => b'\r',
                    // Oniguruma has no word-boundary escape: the bracket itself.
                    '<' if self.onig() => b'<',
                    '>' if self.onig() => b'>',
                    // Otherwise only where the regex reads the escape as that
                    // character: `\<` and `\>` are word boundaries there.
                    n if n.is_ascii() && regex_syntax::is_escapeable_character(n) => {
                        u8::try_from(n).unwrap_or_else(|_| unreachable!("invariant: ASCII"))
                    }
                    _ => return Err("an escape that isn't a literal"),
                };
                literal.push(byte);
                rest = &rest[1 + next.len_utf8()..];
                continue;
            }
            // Oniguruma reads a `{` that opens no interval as the brace.
            if c == '{' && self.onig() && super::interval(rest).is_none() {
                literal.push(b'{');
                rest = &rest[1..];
                continue;
            }
            if "+*?{".contains(c) {
                // A quantifier on a literal applies to its last character.
                let last = std::str::from_utf8(&literal)
                    .ok()
                    .and_then(|l| l.chars().next_back())
                    .ok_or("a quantifier after a reference or group")?;
                literal.truncate(literal.len() - last.len_utf8());
                flush(&mut literal, &mut steps);
                let class = if self.fold {
                    fold_class(last)?
                } else {
                    ClassUnicode::new([regex_syntax::hir::ClassUnicodeRange::new(last, last)])
                };
                let (step, after) = quantified(&class, rest, self.pcre())?;
                steps.push(step);
                rest = after;
                continue;
            }
            // A lone `]` or `}` is a literal to both dialects.
            if ".[(?*+{".contains(c) {
                return Err("regex syntax outside a reference");
            }
            let mut buf = [0; 4];
            literal.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
            rest = &rest[c.len_utf8()..];
        }
        flush(&mut literal, &mut steps);
        if let Some(from) = fold_from {
            let folded = fold_literals(steps.split_off(from))?;
            steps.extend(folded);
        }
        Ok((steps, rest))
    }

    /// `%{NAME}`, `%{NAME:field}` or `%{NAME:field:type}`, as steps.
    fn reference(&mut self, inner: &str, steps: &mut Vec<Step>) -> Result<(), &'static str> {
        let mut parts = inner.splitn(3, ':');
        let mut name = parts.next().unwrap_or_default();
        let capture = parts.next().filter(|f| !f.is_empty()).map(|_| {
            self.captures += 1;
            self.captures - 1
        });
        let generated;
        let mut def = match parts.next().and_then(super::date_format) {
            Some(format) if name.is_empty() => {
                generated =
                    super::date_pattern(format).map_err(|_| "a date format with no matcher")?;
                generated.as_str()
            }
            _ => self.library.get(name).ok_or("an unknown name")?,
        };
        // A definition that is one bare reference is that reference.
        for _ in 0..MAX_DEPTH {
            match def.strip_prefix("%{").and_then(|d| d.strip_suffix('}')) {
                Some(n) if !n.contains(['%', '}', ':']) => {
                    name = n;
                    def = self.library.get(n).ok_or("an unknown name")?;
                }
                _ => break,
            }
        }
        if def == DATA {
            let class = if self.dotall {
                anything()
            } else {
                all_but_newline()
            };
            steps.push(run(capture, &class, 0, None, true));
            return Ok(());
        }
        if let Some(f) = FIELDS.iter().find(|f| {
            f.name == name
                && f.regex == def
                && (!self.fold || unchanged_by("i", f.regex))
                && (!self.dotall || unchanged_by("s", f.regex))
        }) {
            steps.push(field_step(f, capture)?);
            return Ok(());
        }
        if self.stack.iter().any(|s| s == name) || self.stack.len() == MAX_DEPTH {
            return Err("a definition that refers to itself");
        }
        self.stack.push(name.to_owned());
        let (mut branches, rest) = self.alternation(def)?;
        self.stack.pop();
        if !rest.is_empty() {
            return Err("an unbalanced parenthesis in a definition");
        }
        if let Some(c) = capture {
            steps.push(Step::Open(c));
        }
        if branches.len() == 1 {
            steps.append(&mut branches[0]);
        } else {
            steps.push(Step::Choice(branches));
        }
        if let Some(c) = capture {
            steps.push(Step::Close(c));
        }
        Ok(())
    }
}

/// A class written raw at the start of `rest`: `[...]`, `.`, or `\d`, `\s`,
/// `\w` and their negations, read by regex-syntax as the regex reads it.
/// `pattern` without a leading `(?i)`, and whether it had one.
fn fold_prefix(pattern: &str) -> (&str, bool) {
    pattern
        .strip_prefix("(?i)")
        .map_or((pattern, false), |rest| (rest, true))
}

/// An inline flag the steps follow.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Flag {
    Fold,
    Dotall,
}

/// The flag `(?i)`, or the dotall one, at the start of `rest`, and its
/// length. Oniguruma spells dotall `(?m)`.
fn inline_flag(rest: &str, onig: bool) -> Option<(Flag, usize)> {
    if rest.starts_with("(?i)") {
        Some((Flag::Fold, 4))
    } else if rest.starts_with(if onig { "(?m)" } else { "(?s)" }) {
        Some((Flag::Dotall, 4))
    } else {
        None
    }
}

/// Whether `regex` matches the same under the inline `flag`.
fn unchanged_by(flag: &str, regex: &str) -> bool {
    let flagged = regex_syntax::parse(&format!("(?{flag}:{regex})"));
    flagged.is_ok() && flagged == regex_syntax::parse(&format!("(?:{regex})"))
}

/// The characters `c` matches with case folded, as the regex folds it.
fn fold_class(c: char) -> Result<ClassUnicode, &'static str> {
    let hir = regex_syntax::parse(&format!(
        "(?i){}",
        regex_syntax::escape(c.encode_utf8(&mut [0; 4]))
    ))
    .map_err(|_| "a character that doesn't fold")?;
    match hir.into_kind() {
        HirKind::Class(Class::Unicode(class)) => Ok(class),
        _ => Ok(ClassUnicode::new([
            regex_syntax::hir::ClassUnicodeRange::new(c, c),
        ])),
    }
}

/// `steps` with each literal character that has another case as a
/// one-character run of its folded class.
fn fold_literals(steps: Vec<Step>) -> Result<Vec<Step>, &'static str> {
    let mut out = Vec::with_capacity(steps.len());
    for step in steps {
        let Step::Literal(bytes) = step else {
            out.push(step);
            continue;
        };
        let text = std::str::from_utf8(&bytes).map_err(|_| "a literal that isn't UTF-8")?;
        let mut plain = Vec::new();
        for c in text.chars() {
            let class = fold_class(c)?;
            if class.ranges().len() == 1 && class.ranges()[0].start() == class.ranges()[0].end() {
                plain.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes());
            } else {
                flush(&mut plain, &mut out);
                out.push(run(None, &class, 1, Some(1), false));
            }
        }
        flush(&mut plain, &mut out);
    }
    Ok(out)
}

fn raw_class(
    rest: &str,
    onig: bool,
    fold: bool,
    dotall: bool,
) -> Result<Option<(ClassUnicode, &str)>, &'static str> {
    if onig && rest.starts_with("\\h") {
        let hex = regex_syntax::parse("[0-9A-Fa-f]").map_err(|_| "a class that doesn't parse")?;
        if let HirKind::Class(Class::Unicode(c)) = hex.into_kind() {
            return Ok(Some((c, &rest[2..])));
        }
    }
    let len = if rest.starts_with('.') {
        1
    } else if rest.len() >= 2 && rest.starts_with('\\') && "dswDSW".contains(&rest[1..2]) {
        2
    } else if rest.starts_with('[') {
        class_end(rest).ok_or("an unclosed class")?
    } else {
        return Ok(None);
    };
    let flags = match (fold, dotall) {
        (true, true) => "(?is)",
        (true, false) => "(?i)",
        (false, true) => "(?s)",
        (false, false) => "",
    };
    let text = format!("{flags}{}", &rest[..len]);
    let hir = regex_syntax::parse(&text).map_err(|_| "a class that doesn't parse")?;
    match hir.into_kind() {
        HirKind::Class(Class::Unicode(c)) => Ok(Some((c, &rest[len..]))),
        // `[.]` is one character, which the regex reads as a literal.
        HirKind::Literal(l) => {
            let mut chars = std::str::from_utf8(&l.0).unwrap_or_default().chars();
            match (chars.next(), chars.next()) {
                (Some(c), None) => Ok(Some((
                    ClassUnicode::new([regex_syntax::hir::ClassUnicodeRange::new(c, c)]),
                    &rest[len..],
                ))),
                _ => Err("a class that isn't one character"),
            }
        }
        _ => Err("a class that isn't one character"),
    }
}

/// Where the bracket class at the start of `rest` ends, just past its `]`.
fn class_end(rest: &str) -> Option<usize> {
    let b = rest.as_bytes();
    let mut i = 1;
    if b.get(i) == Some(&b'^') {
        i += 1;
    }
    if b.get(i) == Some(&b']') {
        i += 1;
    }
    let mut depth = 1;
    while i < b.len() {
        match b[i] {
            b'\\' => i += 1,
            b'[' if b.get(i + 1) == Some(&b':') => {
                i += rest[i..].find(":]")? + 1;
            }
            b'[' => depth += 1,
            b']' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i + 1);
                }
            }
            _ => {}
        }
        i += 1;
    }
    None
}

/// The quantifier at the start of `rest`: its counts, how it takes
/// characters, and what follows.
struct Quant<'t> {
    min: usize,
    max: Option<usize>,
    lazy: bool,
    possessive: bool,
    rest: &'t str,
}

/// `None` when `rest` starts with no quantifier.
fn quantifier(rest: &str) -> Result<Option<Quant<'_>>, &'static str> {
    let (min, max, rest) = match rest.chars().next() {
        Some('+') => (1, None, &rest[1..]),
        Some('*') => (0, None, &rest[1..]),
        Some('?') => (0, Some(1), &rest[1..]),
        Some('{') => {
            let end = rest.find('}').ok_or("an unclosed repetition")?;
            let inner = &rest[1..end];
            let num = |t: &str| {
                t.parse::<usize>()
                    .map_err(|_| "a repetition that isn't counts")
            };
            let (min, max) = match inner.split_once(',') {
                None => (num(inner)?, Some(num(inner)?)),
                Some((lo, "")) => (num(lo)?, None),
                Some((lo, hi)) => (num(lo)?, Some(num(hi)?)),
            };
            (min, max, &rest[end + 1..])
        }
        _ => return Ok(None),
    };
    let (lazy, possessive) = (rest.starts_with('?'), rest.starts_with('+'));
    Ok(Some(Quant {
        min,
        max,
        lazy,
        possessive,
        rest: if lazy || possessive { &rest[1..] } else { rest },
    }))
}

/// `class` with the quantifier at the start of `rest`, if any, as a run.
/// Only a PCRE pattern has a possessive one: elsewhere `x*+` repeats a repeat.
fn quantified<'t>(
    class: &ClassUnicode,
    rest: &'t str,
    pcre: bool,
) -> Result<(Step, &'t str), &'static str> {
    let Some(q) = quantifier(rest)? else {
        return Ok((run(None, class, 1, Some(1), false), rest));
    };
    if q.possessive && !pcre {
        return Err("a possessive repetition");
    }
    let mut step = run(None, class, q.min, q.max, q.lazy);
    if let Step::Run { possessive, .. } = &mut step {
        *possessive = q.possessive;
    }
    Ok((step, q.rest))
}

/// `inner` with the quantifier at the start of `rest`, if any: `?` as a
/// choice of it or nothing, any other as a loop.
fn repeated(mut inner: Vec<Step>, rest: &str) -> Result<(Vec<Step>, &str), &'static str> {
    Ok(match quantifier(rest)? {
        None => (inner, rest),
        Some(Quant {
            possessive: true, ..
        }) => return Err("a possessive repetition"),
        Some(Quant {
            min: 0,
            max: Some(1),
            lazy: false,
            rest,
            ..
        }) => (
            vec![Step::Choice(vec![std::mem::take(&mut inner), Vec::new()])],
            rest,
        ),
        Some(Quant {
            min,
            max,
            lazy,
            rest,
            ..
        }) => (
            vec![Step::Loop {
                body: inner,
                min,
                max,
                lazy,
            }],
            rest,
        ),
    })
}

/// A field, as a run when its regex is one class repeated.
fn field_step(f: &'static Field, capture: Option<usize>) -> Result<Step, &'static str> {
    let hir = regex_syntax::parse(f.regex).map_err(|_| "a field regex that doesn't parse")?;
    if let HirKind::Repetition(r) = hir.kind()
        && let HirKind::Class(Class::Unicode(class)) = r.sub.kind()
    {
        let min = usize::try_from(r.min).map_err(|_| "a repetition too long")?;
        let max = r
            .max
            .map(usize::try_from)
            .transpose()
            .map_err(|_| "a repetition too long")?;
        return Ok(run(capture, class, min, max, !r.greedy));
    }
    let mut alphabet = Set::empty();
    add_alphabet(&hir, &mut alphabet);
    Ok(Step::Field {
        field: f,
        capture,
        alphabet: Box::new(Chars::new(alphabet)),
        rest_nullable: false,
        then_end: false,
        ambiguous: None,
    })
}

fn run(
    capture: Option<usize>,
    class: &ClassUnicode,
    min: usize,
    max: Option<usize>,
    lazy: bool,
) -> Step {
    Step::Run {
        capture,
        class: Box::new(Chars::new(class.clone())),
        min,
        max,
        lazy,
        possessive: false,
        next: Box::new(Chars::new(Set::empty())),
        skip: None,
        next_nullable: false,
        next_eoi: false,
    }
}

/// `.` as Rust reads it: any character but a newline.
fn all_but_newline() -> ClassUnicode {
    let mut c = ClassUnicode::new([regex_syntax::hir::ClassUnicodeRange::new('\n', '\n')]);
    c.negate();
    c
}

fn flush(literal: &mut Vec<u8>, steps: &mut Vec<Step>) {
    if !literal.is_empty() {
        steps.push(Step::Literal(std::mem::take(literal)));
    }
}

/// What can follow a point in the pattern.
#[derive(Clone)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "four facts about what follows, each read alone"
)]
struct Follow {
    first: Set,
    nullable: bool,
    /// It's exactly the end of the input.
    end: bool,
    /// It can match once the input has ended.
    eoi: bool,
    /// `nullable` holds on some passes of a loop only: short of the loop's
    /// minimum, another pass has to follow.
    partly: bool,
}

impl Follow {
    fn nothing() -> Self {
        Self {
            first: Set::empty(),
            nullable: true,
            end: false,
            eoi: true,
            partly: false,
        }
    }

    /// `first` and `nullable` of a step, then `self` when it can match nothing.
    fn after(&self, mut first: Set, nullable: bool) -> Self {
        if nullable {
            first.union(&self.first);
        }
        Self {
            first,
            nullable: nullable && self.nullable,
            end: false,
            eoi: nullable && self.eoi,
            partly: nullable && self.partly,
        }
    }
}

/// Settle each step against what follows it, back to front, and refuse a
/// boundary the steps can't decide. Returns what the steps can start with.
fn check(steps: &mut [Step], after: &Follow) -> Result<Follow, &'static str> {
    let mut f = after.clone();
    for step in steps.iter_mut().rev() {
        f = match step {
            Step::Open(_) | Step::Close(_) => f,
            // A check can hold inside a field's characters, so every end of
            // what comes before it stays open.
            Step::Look(_) => Follow {
                first: anything(),
                nullable: false,
                end: false,
                eoi: true,
                partly: false,
            },
            Step::Literal(l) => {
                let mut first = Set::empty();
                if let Some(c) = std::str::from_utf8(l).ok().and_then(|t| t.chars().next()) {
                    first.push(regex_syntax::hir::ClassUnicodeRange::new(c, c));
                }
                f.after(first, false)
            }
            Step::LineEnd => {
                let mut first = Set::empty();
                first.push(regex_syntax::hir::ClassUnicodeRange::new('\n', '\n'));
                first.push(regex_syntax::hir::ClassUnicodeRange::new('\r', '\r'));
                Follow {
                    first,
                    nullable: false,
                    end: false,
                    eoi: true,
                    partly: false,
                }
            }
            Step::End => Follow {
                first: Set::empty(),
                nullable: false,
                end: true,
                eoi: true,
                partly: false,
            },
            Step::Field {
                field,
                alphabet,
                rest_nullable,
                then_end,
                ambiguous,
                ..
            } => {
                *rest_nullable = f.nullable;
                *then_end = f.end;
                let mut overlap = alphabet.set.clone();
                overlap.intersect(&f.first);
                let moves = !f.nullable || f.partly;
                *ambiguous = if moves && !overlap.ranges().is_empty() {
                    let ends =
                        ends::of(field).ok_or("a field that can end where the next step starts")?;
                    Some(Box::new(Ambiguous {
                        ends,
                        follow: Chars::new(f.first.clone()),
                        eoi: f.eoi,
                        open: f.nullable,
                    }))
                } else {
                    None
                };
                let hir = regex_syntax::parse(field.regex)
                    .map_err(|_| "a field regex that doesn't parse")?;
                let mut first = Set::empty();
                let nullable = add_first(&hir, &mut first);
                f.after(first, nullable)
            }
            Step::Run {
                class,
                min,
                max,
                lazy,
                possessive,
                next,
                skip,
                next_nullable,
                next_eoi,
                ..
            } => {
                // A possessive run is the greedy one when a shorter end
                // never helps: what follows always matches, or can't start
                // with a character the run would give back.
                if *possessive {
                    let mut back = class.set.clone();
                    back.intersect(&f.first);
                    let always = f.nullable && !f.partly;
                    if !always && (f.nullable || !back.ranges().is_empty()) {
                        return Err("a possessive repetition that could give characters back");
                    }
                }
                **next = Chars::new(f.first.clone());
                *skip = (*lazy && max.is_none() && !f.nullable)
                    .then(|| Box::new(ByteClass::new(class.ascii & !next.ascii)));
                *next_nullable = f.nullable;
                *next_eoi = f.eoi;
                f.after(class.set.clone(), *min == 0)
            }
            Step::Choice(branches) => {
                let mut union = Follow {
                    first: Set::empty(),
                    nullable: false,
                    end: true,
                    eoi: false,
                    partly: false,
                };
                for b in branches.iter_mut() {
                    let bf = check(b, &f)?;
                    union.first.union(&bf.first);
                    union.nullable |= bf.nullable;
                    union.end &= bf.end;
                    union.eoi |= bf.eoi;
                    union.partly |= bf.partly;
                }
                union
            }
            Step::Loop { body, min, .. } => {
                if captures(body) {
                    // The regex keeps only the last iteration's capture.
                    return Err("a repeated group with a capture");
                }
                let own = check(body, &Follow::nothing())?;
                if own.nullable {
                    return Err("a repeated group that can match nothing");
                }
                // After an iteration comes another, or what follows the loop.
                // Short of `min` it has to be another, so the rest is empty
                // on some passes only.
                let mut inside = f.clone();
                inside.first.union(&own.first);
                inside.end = false;
                inside.partly |= f.nullable && *min >= 2;
                check(body, &inside)?;
                f.after(own.first, *min == 0)
            }
        };
    }
    Ok(f)
}

/// `true` when any step writes a field.
fn captures(steps: &[Step]) -> bool {
    steps.iter().any(|s| match s {
        Step::Field { capture, .. } | Step::Run { capture, .. } => capture.is_some(),
        Step::Open(_) | Step::Close(_) => true,
        Step::Choice(bs) => bs.iter().any(|b| captures(b)),
        Step::Loop { body, .. } => captures(body),
        Step::Literal(_) | Step::Look(_) | Step::End | Step::LineEnd => false,
    })
}

impl Plan {
    /// The steps as ops for generated code, or why they aren't in the
    /// subset where every op has one end the regex could pick.
    pub(super) fn ops(&self) -> Result<Vec<super::spec::Op>, &'static str> {
        if !self.starts_at_zero() {
            return Err("a pattern that doesn't start with ^");
        }
        convert(&self.steps, &[])
    }
}

/// `steps`, then `tail` after them, as ops. A lazy run's later miss is the
/// regex's to settle, so the code it writes hands that line over.
fn convert(steps: &[Step], tail: &[&Step]) -> Result<Vec<super::spec::Op>, &'static str> {
    use super::spec::Op;
    let mut ops = Vec::with_capacity(steps.len());
    let mut k = 0;
    while k < steps.len() {
        let (capture, step, width) = match (&steps[k], steps.get(k + 2)) {
            (Step::Open(c), Some(Step::Close(d))) if c == d => (Some(*c), &steps[k + 1], 3),
            // A group of several steps writes where it opened and closed.
            (Step::Open(c), _) => {
                ops.push(Op::Open(*c));
                k += 1;
                continue;
            }
            (Step::Close(c), _) => {
                ops.push(Op::Close(*c));
                k += 1;
                continue;
            }
            (step, _) => (None, step, 1),
        };
        let rest: Vec<&Step> = steps[k + width..]
            .iter()
            .chain(tail.iter().copied())
            .collect();
        if let Step::Choice(branches) = step
            && let [taken, empty] = branches.as_slice()
            && empty.is_empty()
        {
            ops.push(optional(taken, capture, &rest)?);
        } else if let Step::Choice(branches) = step
            && op(step, capture, None).is_err()
        {
            // Branches tried in order, as the regex tries them.
            let mut each = Vec::with_capacity(branches.len());
            // Each branch runs with what follows the choice after it.
            for b in branches {
                each.push(convert(b, &rest)?);
            }
            if let Some(c) = capture {
                ops.push(Op::Open(c));
            }
            ops.push(Op::Choice(each));
            if let Some(c) = capture {
                ops.push(Op::Close(c));
            }
        } else {
            let next = rest
                .iter()
                .copied()
                .find(|s| !matches!(s, Step::Open(_) | Step::Close(_)));
            match (capture, step) {
                // A literal or the end can't write a capture: the group's
                // ends mark it.
                (Some(c), Step::Literal(_) | Step::End) => {
                    ops.push(Op::Open(c));
                    ops.push(op(step, None, next)?);
                    ops.push(Op::Close(c));
                }
                _ => ops.push(op(step, capture, next)?),
            }
        }
        k += width;
    }
    Ok(ops)
}

/// An optional group `taken`. The code tries the group first, as the
/// regex does, and keeps it when it matches. Should what follows then miss,
/// the regex would try without the group, so the code hands that line over.
fn optional(
    taken: &[Step],
    group: Option<usize>,
    rest: &[&Step],
) -> Result<super::spec::Op, &'static str> {
    // Untaken, the regex leaves the group's capture unset.
    if group.is_some() {
        return Err("a named optional group");
    }
    Ok(super::spec::Op::Optional(convert(taken, rest)?))
}

/// `step` as one op, writing `capture`, with `next` the step after it.
fn op(
    step: &Step,
    group: Option<usize>,
    next: Option<&Step>,
) -> Result<super::spec::Op, &'static str> {
    use super::spec::Op;
    let pick = |own: Option<usize>| match (own, group) {
        (Some(_), Some(_)) => Err("a field inside a named group"),
        (own, group) => Ok(own.or(group)),
    };
    Ok(match step {
        Step::Literal(l) if group.is_none() => Op::Literal(l.clone()),
        Step::End if group.is_none() => Op::End,
        Step::Field {
            field,
            capture,
            alphabet,
            rest_nullable,
            then_end,
            ambiguous: None,
        } => Op::Field {
            index: FIELDS
                .iter()
                .position(|f| std::ptr::eq(f, *field))
                .ok_or("a field not in the table")?,
            capture: pick(*capture)?,
            alphabet: class_of(alphabet),
            then_end: *then_end,
            rest_nullable: *rest_nullable,
        },
        Step::Field {
            field,
            capture,
            ambiguous: Some(a),
            ..
        } => Op::Settle {
            index: FIELDS
                .iter()
                .position(|f| std::ptr::eq(f, *field))
                .ok_or("a field not in the table")?,
            capture: pick(*capture)?,
            follow: class_of(&a.follow),
            eoi: a.eoi,
            open: a.open,
        },
        Step::Run {
            capture,
            class,
            min,
            max,
            lazy: false,
            next: follow,
            ..
        } => {
            let c = class_of(class);
            if c.line && (*min > 1 || max.is_some()) {
                return Err("a counted run of any character");
            }
            // A fixed count has one end whatever follows.
            let mut overlap = class.set.clone();
            overlap.intersect(&follow.set);
            if *max != Some(*min) && !overlap.ranges().is_empty() {
                Op::GiveBack {
                    capture: pick(*capture)?,
                    class: c,
                    min: *min,
                    max: *max,
                    lazy: false,
                }
            } else {
                Op::Span {
                    capture: pick(*capture)?,
                    class: c,
                    min: *min,
                    max: *max,
                }
            }
        }
        Step::Run {
            capture,
            class,
            min,
            max: None,
            lazy: true,
            ..
        } if *min <= 1 => match next {
            Some(Step::Literal(l)) if !l.is_empty() => Op::Until {
                capture: pick(*capture)?,
                class: class_of(class),
                min: *min,
                literal: l.clone(),
            },
            // No literal to search for: each end tried from the shortest.
            _ => Op::GiveBack {
                capture: pick(*capture)?,
                class: class_of(class),
                min: *min,
                max: None,
                lazy: true,
            },
        },
        Step::Choice(branches) => {
            let mut literals = Vec::with_capacity(branches.len());
            for b in branches {
                match b.as_slice() {
                    [Step::Literal(l)] if !l.is_empty() => literals.push(l.clone()),
                    _ => return Err("a choice that isn't between literals"),
                }
            }
            let prefix = literals.iter().enumerate().any(|(i, a)| {
                literals
                    .iter()
                    .enumerate()
                    .any(|(j, b)| i != j && b.starts_with(a))
            });
            if prefix {
                return Err("a choice where one literal starts another");
            }
            Op::Alt {
                capture: group,
                literals,
            }
        }
        Step::Look(_) => return Err("a zero-width check such as \\b"),
        Step::Loop {
            body,
            min,
            max,
            lazy,
        } if group.is_none() => {
            // Each pass runs with what follows the loop after it.
            let tail: Vec<&Step> = next.into_iter().collect();
            let body = convert(body, &tail)?;
            if body.iter().any(|o| {
                matches!(
                    o,
                    Op::Choice(_) | Op::Optional(_) | Op::GiveBack { .. } | Op::Loop { .. }
                )
            }) {
                return Err("a repeated group of choices");
            }
            Op::Loop {
                body,
                min: *min,
                max: *max,
                lazy: *lazy,
            }
        }
        Step::Loop { .. } => return Err("a repeated group"),
        Step::Literal(_) | Step::End => return Err("a literal or end inside a named group"),
        _ => return Err("a step outside the compiled subset"),
    })
}

/// `chars` as the byte tests generated code makes.
fn class_of(chars: &Chars) -> super::spec::Class {
    super::spec::Class {
        ascii: chars.ascii,
        other: chars.set.ranges().last().is_some_and(|r| r.end() > '\x7f'),
        line: chars.line,
    }
}

/// `true` when any step opens a group.
fn opens(steps: &[Step]) -> bool {
    steps.iter().any(|s| match s {
        Step::Open(_) => true,
        Step::Choice(bs) => bs.iter().any(|b| opens(b)),
        Step::Loop { body, .. } => opens(body),
        _ => false,
    })
}

/// The rest of a pattern once a sequence finishes: the steps left in each
/// enclosing sequence, and the loops to go round again.
enum Cont<'a> {
    Steps {
        steps: &'a [Step],
        next: Option<&'a Self>,
    },
    /// Iteration `n` of a loop that started at `start` has just ended.
    Again {
        body: &'a [Step],
        min: usize,
        max: Option<usize>,
        lazy: bool,
        n: usize,
        start: usize,
        next: Option<&'a Self>,
    },
}

/// Run what's left once a sequence finishes at `i`.
fn resume(cont: Option<&Cont<'_>>, i: usize, ctx: &mut Ctx<'_, '_>) -> Outcome {
    match cont {
        None => Outcome::Matched,
        Some(Cont::Steps { steps, next }) => seq(steps, *next, i, ctx),
        Some(&Cont::Again {
            body,
            min,
            max,
            lazy,
            n,
            start,
            next,
        }) => repeat(body, (min, max, lazy), n, start, i, next, ctx),
    }
}

/// A loop at iteration `n`, ended at `i`: go round again or stop, in the
/// regex's order. An iteration that matched nothing ends the loop.
fn repeat(
    body: &[Step],
    (min, max, lazy): (usize, Option<usize>, bool),
    n: usize,
    start: usize,
    i: usize,
    next: Option<&Cont<'_>>,
    ctx: &mut Ctx<'_, '_>,
) -> Outcome {
    let empty = n > 0 && i == start;
    let more = !empty && max.is_none_or(|m| n < m);
    let stop = n >= min || empty;
    for go_on in if lazy { [false, true] } else { [true, false] } {
        let mark = ctx.caps.len();
        let out = if go_on {
            if !more {
                continue;
            }
            let again = Cont::Again {
                body,
                min,
                max,
                lazy,
                n: n + 1,
                start: i,
                next,
            };
            seq(body, Some(&again), i, ctx)
        } else {
            if !stop {
                continue;
            }
            resume(next, i, ctx)
        };
        match out {
            Outcome::NoMatch => ctx.caps.truncate(mark),
            done => return done,
        }
    }
    Outcome::NoMatch
}

struct Ctx<'h, 'c> {
    h: &'h [u8],
    caps: &'c mut Vec<(usize, Range<usize>)>,
    opens: Vec<usize>,
    budget: usize,
    /// The budget ran out.
    spent: bool,
}

/// Spend `n` of the budget: 1 for a byte scanned, [`STEP`] for a step run or
/// an end tried. `false` once it's gone.
const fn charge(ctx: &mut Ctx<'_, '_>, n: usize) -> bool {
    if let Some(left) = ctx.budget.checked_sub(n) {
        ctx.budget = left;
        true
    } else {
        ctx.spent = true;
        false
    }
}

/// Run `steps` from `i`, then `cont`.
fn seq(steps: &[Step], cont: Option<&Cont<'_>>, mut i: usize, ctx: &mut Ctx<'_, '_>) -> Outcome {
    let h = ctx.h;
    for (k, step) in steps.iter().enumerate() {
        if !charge(ctx, STEP) {
            return Outcome::Unsure;
        }
        match step {
            Step::Literal(l) => {
                if !h[i..].starts_with(l) {
                    return Outcome::NoMatch;
                }
                i += l.len();
            }
            Step::Open(c) => ctx.opens[*c] = i,
            Step::Look(look) => {
                if !holds(*look, h, i) {
                    return Outcome::NoMatch;
                }
            }
            Step::Close(c) => ctx.caps.push((*c, ctx.opens[*c]..i)),
            Step::LineEnd => {
                let line_end = |j: usize| j == h.len() || h[j] == b'\n';
                let terminator = [&b"\r\n"[..], b"\n", b"\r"]
                    .iter()
                    .any(|t| h[i..].starts_with(t) && line_end(i + t.len()));
                if !(line_end(i) || terminator) {
                    return Outcome::NoMatch;
                }
            }
            Step::End => {
                if i != h.len() {
                    return Outcome::NoMatch;
                }
            }
            Step::Field {
                field,
                capture,
                alphabet,
                rest_nullable,
                then_end,
                ambiguous,
            } => {
                if let Some(a) = ambiguous {
                    let viable =
                        |p: usize| a.open || char_at(h, p).map_or(a.eoi, |(c, _)| a.follow.has(c));
                    match a.ends.only(h, i, &mut ctx.budget, viable) {
                        End::At(end) => {
                            if let Some(c) = capture {
                                ctx.caps.push((*c, i..end));
                            }
                            i = end;
                            continue;
                        }
                        End::Nowhere => return Outcome::NoMatch,
                        End::Unsure => return Outcome::Unsure,
                        End::Spent => {
                            ctx.spent = true;
                            return Outcome::Unsure;
                        }
                    }
                }
                let end = match (field.scan)(h, i) {
                    Scan::Defer => return Outcome::Unsure,
                    Scan::NoMatch => {
                        // A branch that fails still pays for what it read.
                        let read = alphabet.run(&h[i..]);
                        return if charge(ctx, read) {
                            Outcome::NoMatch
                        } else {
                            Outcome::Unsure
                        };
                    }
                    Scan::Match(end) => end,
                };
                if !charge(ctx, end - i) {
                    return Outcome::Unsure;
                }
                // When what follows can match nothing it succeeds from the
                // scanner's end, so the regex never moves that end. Otherwise
                // the regex could move it unless the field's characters stop
                // there.
                if *then_end {
                    if end != h.len() {
                        let read = alphabet.run(&h[i..]);
                        let run = i + read;
                        return if !charge(ctx, read) {
                            Outcome::Unsure
                        } else if run < h.len() {
                            Outcome::NoMatch
                        } else {
                            Outcome::Unsure
                        };
                    }
                } else if !*rest_nullable && char_at(h, end).is_some_and(|(c, _)| alphabet.has(c)) {
                    return Outcome::Unsure;
                }
                if let Some(c) = capture {
                    ctx.caps.push((*c, i..end));
                }
                i = end;
            }
            Step::Choice(branches) => {
                let after = Cont::Steps {
                    steps: &steps[k + 1..],
                    next: cont,
                };
                for b in branches {
                    let mark = ctx.caps.len();
                    match seq(b, Some(&after), i, ctx) {
                        Outcome::NoMatch => ctx.caps.truncate(mark),
                        done => return done,
                    }
                }
                return Outcome::NoMatch;
            }
            Step::Loop {
                body,
                min,
                max,
                lazy,
            } => {
                let after = Cont::Steps {
                    steps: &steps[k + 1..],
                    next: cont,
                };
                return repeat(body, (*min, *max, *lazy), 0, i, i, Some(&after), ctx);
            }
            Step::Run { .. } => return run_class_step(step, &steps[k + 1..], cont, i, ctx),
        }
    }
    resume(cont, i, ctx)
}

/// A run step from `i`, then `rest`: its ends tried in the regex's order,
/// shortest first when lazy, longest first otherwise.
fn run_class_step(
    step: &Step,
    rest: &[Step],
    cont: Option<&Cont<'_>>,
    i: usize,
    ctx: &mut Ctx<'_, '_>,
) -> Outcome {
    let Step::Run {
        capture,
        class,
        min,
        max,
        lazy,
        next,
        skip,
        next_nullable,
        next_eoi,
        ..
    } = step
    else {
        unreachable!("invariant: seq hands run_class_step only a run step");
    };
    let h = ctx.h;
    let viable =
        |end: usize| *next_nullable || char_at(h, end).map_or(*next_eoi, |(c, _)| next.has(c));
    let (mut at, mut taken) = (i, 0);
    if *lazy {
        // An ASCII byte of the class that what follows can't start with is
        // never an end, so the run steps over it without a try.
        loop {
            if let Some(skip) = skip {
                let from = at;
                at += skip.run(h.get(at..).unwrap_or_default());
                taken += at - from;
                if !charge(ctx, at - from) {
                    return Outcome::Unsure;
                }
            }
            if !charge(ctx, STEP) {
                return Outcome::Unsure;
            }
            if taken >= *min
                && viable(at)
                && let Some(done) = take_end(rest, cont, *capture, i..at, ctx)
            {
                return done;
            }
            match run_step(h, at, class, taken, *max) {
                Some(w) => (at, taken) = (at + w, taken + 1),
                None => return Outcome::NoMatch,
            }
        }
    }
    if max.is_none() && *min <= 1 {
        // No count to keep: any end past the minimum will do.
        at += class.run(&h[i..]);
        if !charge(ctx, at - i + 1) {
            return Outcome::Unsure;
        }
        loop {
            if (at > i || *min == 0)
                && viable(at)
                && let Some(done) = take_end(rest, cont, *capture, i..at, ctx)
            {
                return done;
            }
            if at == i {
                return Outcome::NoMatch;
            }
            at = char_start_before(h, at);
        }
    }
    while let Some(w) = run_step(h, at, class, taken, *max) {
        (at, taken) = (at + w, taken + 1);
    }
    if !charge(ctx, taken + 1) {
        return Outcome::Unsure;
    }
    while taken >= *min {
        if viable(at)
            && let Some(done) = take_end(rest, cont, *capture, i..at, ctx)
        {
            return done;
        }
        if taken == 0 {
            break;
        }
        at = char_start_before(h, at);
        taken -= 1;
    }
    Outcome::NoMatch
}

/// The width of the character at `at` when a run of `class` already
/// `count` long can take it. A byte that isn't valid UTF-8 ends the run, as
/// it does for the regex.
fn run_step(h: &[u8], at: usize, class: &Chars, count: usize, max: Option<usize>) -> Option<usize> {
    if max == Some(count) {
        return None;
    }
    let (c, w) = char_at(h, at)?;
    class.has(c).then_some(w)
}

/// The start of the character that ends at `at`.
const fn char_start_before(h: &[u8], at: usize) -> usize {
    let mut start = at - 1;
    while start > 0 && h[start] & 0xC0 == 0x80 {
        start -= 1;
    }
    start
}

/// Write `capture` over `span` and run `rest` from its end: the outcome
/// unless it's no match, which leaves `caps` as it found them.
fn take_end(
    rest: &[Step],
    cont: Option<&Cont<'_>>,
    capture: Option<usize>,
    span: Range<usize>,
    ctx: &mut Ctx<'_, '_>,
) -> Option<Outcome> {
    let mark = ctx.caps.len();
    let end = span.end;
    if let Some(c) = capture {
        ctx.caps.push((c, span));
    }
    match seq(rest, cont, end, ctx) {
        Outcome::NoMatch => {
            ctx.caps.truncate(mark);
            None
        }
        done => Some(done),
    }
}

/// Every character.
fn anything() -> Set {
    Set::new([regex_syntax::hir::ClassUnicodeRange::new('\0', char::MAX)])
}

/// Whether `look` holds at `i`, as the regex reads it.
fn holds(look: Look, h: &[u8], i: usize) -> bool {
    static WORD: std::sync::LazyLock<Chars> =
        std::sync::LazyLock::new(|| match regex_syntax::parse(r"\w").map(Hir::into_kind) {
            Ok(HirKind::Class(Class::Unicode(c))) => Chars::new(c),
            _ => unreachable!("invariant: \\w is a Unicode class"),
        });
    let word = |c: Option<(char, usize)>| c.is_some_and(|(c, _)| WORD.has(c));
    match look {
        Look::Word => word(char_before(h, i)) != word(char_at(h, i)),
        Look::Start => i == 0,
        Look::StartLine => i == 0 || h[i - 1] == b'\n',
        Look::End => i == h.len(),
        Look::EndLine => i == h.len() || h[i] == b'\n',
    }
}

/// The character that ends just before `i`.
fn char_before(h: &[u8], i: usize) -> Option<(char, usize)> {
    if i == 0 {
        return None;
    }
    char_at(h, char_start_before(h, i))
}

fn char_at(h: &[u8], at: usize) -> Option<(char, usize)> {
    let rest = h.get(at..)?;
    let width = match *rest.first()? {
        b if b < 0x80 => return Some((char::from(b), 1)),
        b if b >= 0xF0 => 4,
        b if b >= 0xE0 => 3,
        _ => 2,
    };
    let c = std::str::from_utf8(rest.get(..width)?)
        .ok()?
        .chars()
        .next()?;
    Some((c, width))
}

/// Add every character a match of `hir` can hold.
fn add_alphabet(hir: &Hir, out: &mut Set) {
    match hir.kind() {
        HirKind::Literal(l) => add_literal(&l.0, out, false),
        HirKind::Class(c) => add_class(c, out),
        HirKind::Repetition(r) => add_alphabet(&r.sub, out),
        HirKind::Capture(c) => add_alphabet(&c.sub, out),
        HirKind::Concat(hs) | HirKind::Alternation(hs) => {
            for h in hs {
                add_alphabet(h, out);
            }
        }
        HirKind::Empty | HirKind::Look(_) => {}
    }
}

/// Add the characters a match of `hir` can start with. `true` when it can
/// match nothing, so what follows can start the match too.
fn add_first(hir: &Hir, out: &mut Set) -> bool {
    match hir.kind() {
        HirKind::Empty | HirKind::Look(_) => true,
        HirKind::Literal(l) => {
            add_literal(&l.0, out, true);
            l.0.is_empty()
        }
        HirKind::Class(c) => {
            add_class(c, out);
            false
        }
        HirKind::Repetition(r) => add_first(&r.sub, out) || r.min == 0,
        HirKind::Capture(c) => add_first(&c.sub, out),
        HirKind::Concat(hs) => hs.iter().all(|h| add_first(h, out)),
        HirKind::Alternation(hs) => {
            // Every branch adds its characters, so no short circuit.
            let mut nullable = false;
            for h in hs {
                nullable |= add_first(h, out);
            }
            nullable
        }
    }
}

/// A literal's characters, or only its first. Bytes that aren't UTF-8 stand
/// for every non-ASCII character.
fn add_literal(bytes: &[u8], out: &mut Set, first_only: bool) {
    use regex_syntax::hir::ClassUnicodeRange as R;
    match std::str::from_utf8(bytes) {
        Ok(t) => {
            for c in t.chars().take(if first_only { 1 } else { usize::MAX }) {
                out.push(R::new(c, c));
            }
        }
        Err(_) => out.push(R::new('\u{80}', char::MAX)),
    }
}

fn add_class(class: &Class, out: &mut Set) {
    use regex_syntax::hir::ClassUnicodeRange as R;
    match class {
        Class::Unicode(c) => out.union(c),
        Class::Bytes(c) => {
            for r in c.ranges() {
                if r.end() < 0x80 {
                    out.push(R::new(char::from(r.start()), char::from(r.end())));
                } else {
                    out.push(R::new(char::from(r.start().min(0x7F)), char::MAX));
                }
            }
        }
    }
}

/// `true` when `c` is in `set`.
fn contains(set: &Set, c: char) -> bool {
    set.ranges()
        .binary_search_by(|r| {
            if r.end() < c {
                std::cmp::Ordering::Less
            } else if r.start() > c {
                std::cmp::Ordering::Greater
            } else {
                std::cmp::Ordering::Equal
            }
        })
        .is_ok()
}