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
/// Sequence matching - combine multiple pattern elements
///
/// Supports patterns like:
/// - ab+c* (char followed by quantified char followed by quantified char)
/// - \d+\w* (escape sequence followed by quantified escape)
/// - hello\d+ (literal followed by quantified escape)
use crate::parser::boundary::BoundaryType;
use crate::parser::charclass::CharClass;
use crate::parser::group::Group;
use crate::parser::quantifier::Quantifier;
/// A single element in a sequence
#[derive(Debug, Clone, PartialEq)]
pub enum SequenceElement {
/// A literal character (e.g., 'a' in "abc")
Char(char),
/// Dot wildcard (matches any character except newline)
Dot,
/// A quantified character (e.g., 'a+' in "a+bc")
QuantifiedChar(char, Quantifier),
/// A character class (e.g., [a-z])
CharClass(CharClass),
/// A quantified character class (e.g., [0-9]+)
QuantifiedCharClass(CharClass, Quantifier),
/// A literal string (e.g., "hello" in "hello\d+")
Literal(String),
/// A group element (e.g., (?:foo|bar) or (abc) in a sequence)
Group(Group),
/// A quantified group (e.g., (?:foo|bar)+ in a sequence)
QuantifiedGroup(Group, Quantifier),
/// A word boundary (e.g., \b or \B)
Boundary(BoundaryType),
}
impl SequenceElement {
/// Try to match this element at a specific position in text
/// Returns number of bytes consumed if successful, None otherwise
pub fn match_at(&self, text: &str, pos: usize) -> Option<usize> {
let remaining = &text[pos..];
// Don't reject empty remaining for quantified elements (they can match zero times)
// and boundaries (they are zero-width)
if remaining.is_empty() {
return match self {
SequenceElement::QuantifiedChar(_, quantifier) => {
let (min, _) = quantifier_bounds(quantifier);
if min == 0 {
Some(0)
} else {
None
}
}
SequenceElement::QuantifiedCharClass(_, quantifier) => {
let (min, _) = quantifier_bounds(quantifier);
if min == 0 {
Some(0)
} else {
None
}
}
SequenceElement::QuantifiedGroup(_, quantifier) => {
let (min, _) = quantifier_bounds(quantifier);
if min == 0 {
Some(0)
} else {
None
}
}
SequenceElement::Boundary(boundary_type) => {
// Boundary is zero-width, check if it matches at end of text
if boundary_type.matches_at(text, pos) {
Some(0)
} else {
None
}
}
_ => None, // Other elements need at least one char
};
}
match self {
SequenceElement::Char(ch) => {
if remaining.starts_with(*ch) {
Some(ch.len_utf8())
} else {
None
}
}
SequenceElement::Dot => {
// Dot matches any character except newline
let first_char = remaining.chars().next()?;
if first_char != '\n' {
Some(first_char.len_utf8())
} else {
None
}
}
SequenceElement::QuantifiedChar(ch, quantifier) => {
match_quantified_char(*ch, quantifier, remaining)
}
SequenceElement::CharClass(cc) => {
let first_char = remaining.chars().next()?;
if cc.matches(first_char) {
Some(first_char.len_utf8())
} else {
None
}
}
SequenceElement::QuantifiedCharClass(cc, quantifier) => {
match_quantified_charclass(cc, quantifier, remaining)
}
SequenceElement::Literal(lit) => {
if remaining.starts_with(lit) {
Some(lit.len())
} else {
None
}
}
SequenceElement::Group(group) => group.match_at(text, pos),
SequenceElement::QuantifiedGroup(group, quantifier) => {
match_quantified_group(group, quantifier, text, pos)
}
SequenceElement::Boundary(boundary_type) => {
// Boundary is zero-width, so we return 0 if it matches, None otherwise
if boundary_type.matches_at(text, pos) {
Some(0)
} else {
None
}
}
}
}
}
/// Match a quantified character
/// For lazy quantifiers, this returns minimum match; backtracking will try more
fn match_quantified_char(ch: char, quantifier: &Quantifier, text: &str) -> Option<usize> {
let (min, max) = quantifier_bounds(quantifier);
let is_lazy = quantifier.is_lazy();
// Count matching characters WITHOUT collecting into Vec
let mut count = 0;
for c in text.chars() {
if c == ch {
count += 1;
} else {
break;
}
}
if count < min {
return None; // Not enough matches
}
// Lazy: return minimum match; Greedy: return maximum match
let actual_count = if is_lazy { min } else { count.min(max) };
Some(text.chars().take(actual_count).map(|c| c.len_utf8()).sum())
}
/// Match a quantified character class
/// For lazy quantifiers, this returns minimum match; backtracking will try more
fn match_quantified_charclass(
cc: &CharClass,
quantifier: &Quantifier,
text: &str,
) -> Option<usize> {
let (min, max) = quantifier_bounds(quantifier);
let is_lazy = quantifier.is_lazy();
// OPTIMIZATION: For negated single-char class like [^"], use memchr to find terminator
if cc.negated && cc.chars.len() == 1 && cc.ranges.is_empty() {
let forbidden_char = *cc.chars.first().unwrap();
if (forbidden_char as u32) < 128 {
// Use memchr to find the forbidden character (terminator)
use memchr::memchr;
let terminator_pos =
memchr(forbidden_char as u8, text.as_bytes()).unwrap_or(text.len());
// Count chars up to terminator
let matched_text = &text[..terminator_pos];
let char_count = matched_text.chars().count();
if char_count < min {
return None;
}
// Lazy: return minimum match; Greedy: return maximum match
let actual_count = if is_lazy { min } else { char_count.min(max) };
return Some(
matched_text
.chars()
.take(actual_count)
.map(|c| c.len_utf8())
.sum(),
);
}
}
// Count matching characters WITHOUT collecting into Vec
let mut count = 0;
for c in text.chars() {
if cc.matches(c) {
count += 1;
} else {
break;
}
}
if count < min {
return None; // Not enough matches
}
// Lazy: return minimum match; Greedy: return maximum match
let actual_count = if is_lazy { min } else { count.min(max) };
Some(text.chars().take(actual_count).map(|c| c.len_utf8()).sum())
}
/// Match a quantified group (greedy: max match, lazy: min match)
fn match_quantified_group(
group: &Group,
quantifier: &Quantifier,
text: &str,
pos: usize,
) -> Option<usize> {
let (min, max) = quantifier_bounds(quantifier);
let is_lazy = quantifier.is_lazy();
// Find all possible match lengths by repeatedly matching the group
let mut byte_positions: Vec<usize> = Vec::new();
byte_positions.push(0); // 0 repetitions = 0 bytes
let mut current_pos = pos;
let mut count = 0;
while count < max && current_pos <= text.len() {
if let Some(consumed) = group.match_at(text, current_pos) {
if consumed == 0 {
break; // Prevent infinite loop on zero-width matches
}
current_pos += consumed;
count += 1;
byte_positions.push(current_pos - pos);
} else {
break;
}
}
if count < min {
return None;
}
// Lazy: return minimum match; Greedy: return maximum match
let actual_count = if is_lazy { min } else { count.min(max) };
Some(byte_positions[actual_count])
}
/// Get min/max bounds for a quantifier
fn quantifier_bounds(q: &Quantifier) -> (usize, usize) {
match q {
Quantifier::ZeroOrMore | Quantifier::ZeroOrMoreLazy => (0, usize::MAX),
Quantifier::OneOrMore | Quantifier::OneOrMoreLazy => (1, usize::MAX),
Quantifier::ZeroOrOne | Quantifier::ZeroOrOneLazy => (0, 1),
Quantifier::Exactly(n) => (*n, *n),
Quantifier::AtLeast(n) => (*n, usize::MAX),
Quantifier::Between(n, m) => (*n, *m),
}
}
/// Pre-computed NFA transition table for fast is_match
#[derive(Debug, Clone, PartialEq)]
struct NfaTable {
/// For each ASCII byte, bitmask of which elements match it
byte_elem_mask: [u32; 128],
/// Bitmask for the accept state (last element)
accept_mask: u32,
/// Bitmask of elements that can "stay" (quantified with +, *, etc.)
/// Char elements (exact match) cannot stay - they advance immediately
quantified_bits: u32,
/// Bitmask of elements that are optional (min=0, can be skipped via epsilon transition)
optional_bits: u32,
/// Number of elements
n: usize,
}
/// A sequence of pattern elements
#[derive(Debug, Clone, PartialEq)]
pub struct Sequence {
pub elements: Vec<SequenceElement>,
/// Cached NFA table for fast is_match (computed once at construction)
nfa_table: Option<NfaTable>,
}
impl Sequence {
/// Create a new sequence, pre-computing NFA table if applicable
pub fn new(elements: Vec<SequenceElement>) -> Self {
let nfa_table = Self::build_nfa_table(&elements);
Sequence {
elements,
nfa_table,
}
}
/// Build NFA transition table for sequences of QuantifiedCharClass and Char elements
fn build_nfa_table(elements: &[SequenceElement]) -> Option<NfaTable> {
let n = elements.len();
if !(2..=16).contains(&n) {
return None;
}
// Validate elements and compute quantified_bits and optional_bits
let mut quantified_bits: u32 = 0;
let mut optional_bits: u32 = 0;
let _has_mid_optional = false; // Track if there are optional elements not at end
for (i, elem) in elements.iter().enumerate() {
match elem {
SequenceElement::QuantifiedCharClass(_, quantifier) => {
let (min, _max) = quantifier_bounds(quantifier);
// Elements that are optional (min=0) can be skipped
if min == 0 {
optional_bits |= 1u32 << i;
}
// Elements with quantifiers that can match multiple times can "stay"
match quantifier {
Quantifier::OneOrMore
| Quantifier::OneOrMoreLazy
| Quantifier::ZeroOrMore
| Quantifier::ZeroOrMoreLazy => {
quantified_bits |= 1u32 << i; // Can stay
}
_ => {} // ZeroOrOne, Exactly(1), etc. don't stay
}
}
SequenceElement::Char(_) => {
// Char elements don't stay (match exactly 1 char)
}
_ => return None, // Not supported
}
}
// Check for optional elements - NFA doesn't handle them correctly
// The NFA model can't properly track "just finished matching element i" state
// which is needed to epsilon-transition past optional elements
if optional_bits != 0 {
// There's at least one optional element
// NFA doesn't handle skipping correctly, fall back to backtracking
return None;
}
// Pre-compute byte→element match table
let mut byte_elem_mask = [0u32; 128];
for b in 0..128u8 {
let idx = b as usize;
let word_idx = idx / 64;
let bit = 1u64 << (idx % 64);
for (i, elem) in elements.iter().enumerate() {
match elem {
SequenceElement::QuantifiedCharClass(cc, _) => {
if let Some(bm) = cc.get_ascii_bitmap() {
let hit = (bm[word_idx] & bit) != 0;
if hit != cc.negated {
byte_elem_mask[b as usize] |= 1u32 << i;
}
} else {
return None;
}
}
SequenceElement::Char(ch) => {
if (*ch as u32) < 128 && b == *ch as u8 {
byte_elem_mask[b as usize] |= 1u32 << i;
}
}
_ => return None,
}
}
}
Some(NfaTable {
byte_elem_mask,
accept_mask: 1u32 << (n - 1),
quantified_bits,
optional_bits,
n,
})
}
/// Check if the sequence matches at the start of text
/// Returns bytes consumed if match, None otherwise
pub fn match_at(&self, text: &str) -> Option<usize> {
// Use backtracking-enabled matching from start
self.match_elements_backtracking(text, 0, 0)
}
/// Check if the sequence matches at a specific position in text
/// Returns bytes consumed if match, None otherwise
/// This preserves the full text context for boundary checks
fn match_at_pos(&self, text: &str, pos: usize) -> Option<usize> {
self.match_elements_backtracking(text, 0, pos)
}
/// Check if the sequence matches anywhere in text (optimized)
/// Returns immediately on first match without computing position
pub fn is_match(&self, text: &str) -> bool {
// Try element-level NFA first (much faster for quantified charclass sequences)
if let Some(result) = self.is_match_nfa(text) {
return result;
}
self.find(text).is_some()
}
/// Check if the sequence matches with flags applied
/// Flags can modify behavior (e.g., DOTALL makes . match newlines)
pub fn is_match_with_flags(&self, text: &str, flags: &crate::parser::flags::Flags) -> bool {
self.find_with_flags(text, flags).is_some()
}
/// Find match with flags applied
pub fn find_with_flags(
&self,
text: &str,
flags: &crate::parser::flags::Flags,
) -> Option<(usize, usize)> {
// If DOTALL flag is set, replace Dot elements with "any char" matching
if flags.dot_matches_newline {
// For DOTALL mode, we need to match . against any character including \n
// We do this by modifying the matching logic for Dot elements
for start_pos in 0..text.len() {
if let Some(end_pos) = self.match_at_with_dotall(text, start_pos) {
return Some((start_pos, end_pos));
}
}
return None;
}
// No special flags, use normal find
self.find(text)
}
/// Match at position with DOTALL flag (. matches newlines)
fn match_at_with_dotall(&self, text: &str, start_pos: usize) -> Option<usize> {
self.match_elements_backtracking_dotall(text, 0, start_pos)
}
/// Backtracking match with DOTALL mode
fn match_elements_backtracking_dotall(
&self,
text: &str,
elem_idx: usize,
text_pos: usize,
) -> Option<usize> {
// Base case: matched all elements
if elem_idx >= self.elements.len() {
return Some(text_pos);
}
let element = &self.elements[elem_idx];
// Ensure text_pos is at a char boundary for Unicode safety
let text_pos = if text_pos < text.len() && !text.is_char_boundary(text_pos) {
// Find the next char boundary
let mut pos = text_pos;
while pos < text.len() && !text.is_char_boundary(pos) {
pos += 1;
}
pos
} else {
text_pos
};
let remaining = if text_pos < text.len() {
&text[text_pos..]
} else {
""
};
match element {
// Handle Dot specially in DOTALL mode - match ANY character
SequenceElement::Dot => {
if let Some(ch) = remaining.chars().next() {
// In DOTALL mode, dot matches ANY character including newline
let consumed = ch.len_utf8();
self.match_elements_backtracking_dotall(text, elem_idx + 1, text_pos + consumed)
} else {
None
}
}
// QuantifiedChar with backtracking in DOTALL mode
SequenceElement::QuantifiedChar(ch, quantifier) => {
let (min, max) = (quantifier.min_matches(), quantifier.max_matches());
let is_lazy = quantifier.is_lazy();
let ch_len = ch.len_utf8();
let mut max_count = 0;
let mut byte_positions: Vec<usize> = Vec::new();
byte_positions.push(0);
let mut byte_offset = 0;
for c in remaining.chars() {
if c == *ch {
max_count += 1;
byte_offset += ch_len;
byte_positions.push(byte_offset);
if max_count >= max {
break;
}
} else {
break;
}
}
if max_count < min {
return None;
}
let max_count = max_count.min(max);
if is_lazy {
for try_count in min..=max_count {
let consumed = byte_positions[try_count];
if let Some(final_pos) = self.match_elements_backtracking_dotall(
text,
elem_idx + 1,
text_pos + consumed,
) {
return Some(final_pos);
}
}
} else {
for try_count in (min..=max_count).rev() {
let consumed = byte_positions[try_count];
if let Some(final_pos) = self.match_elements_backtracking_dotall(
text,
elem_idx + 1,
text_pos + consumed,
) {
return Some(final_pos);
}
}
}
None
}
// QuantifiedCharClass - handle both dot class (matches newlines in DOTALL) and normal
SequenceElement::QuantifiedCharClass(cc, quantifier) => {
// Check if this is a "dot class" [^\n] - if so, match everything in DOTALL mode
let is_dot_class = cc.negated
&& cc.chars.len() == 1
&& cc.chars[0] == '\n'
&& cc.ranges.is_empty();
let (min, max) = (quantifier.min_matches(), quantifier.max_matches());
let is_lazy = quantifier.is_lazy();
if is_dot_class {
// In DOTALL mode, dot class matches any character including newlines
let max_count = remaining.chars().count().min(max);
if max_count < min {
return None;
}
// Build byte positions
let mut byte_positions: Vec<usize> = Vec::new();
byte_positions.push(0);
let mut byte_offset = 0;
for (i, ch) in remaining.chars().enumerate() {
if i >= max_count {
break;
}
byte_offset += ch.len_utf8();
byte_positions.push(byte_offset);
}
if is_lazy {
for try_count in min..=max_count {
let consumed = byte_positions[try_count];
if let Some(final_pos) = self.match_elements_backtracking_dotall(
text,
elem_idx + 1,
text_pos + consumed,
) {
return Some(final_pos);
}
}
} else {
for try_count in (min..=max_count).rev() {
let consumed = byte_positions[try_count];
if let Some(final_pos) = self.match_elements_backtracking_dotall(
text,
elem_idx + 1,
text_pos + consumed,
) {
return Some(final_pos);
}
}
}
None
} else {
// Normal quantified charclass - backtrack with DOTALL continuation
let mut max_count = 0;
let mut byte_positions: Vec<usize> = Vec::new();
byte_positions.push(0);
let mut byte_offset = 0;
for c in remaining.chars() {
if cc.matches(c) {
max_count += 1;
byte_offset += c.len_utf8();
byte_positions.push(byte_offset);
if max_count >= max {
break;
}
} else {
break;
}
}
if max_count < min {
return None;
}
let max_count = max_count.min(max);
if is_lazy {
for try_count in min..=max_count {
let consumed = byte_positions[try_count];
if let Some(final_pos) = self.match_elements_backtracking_dotall(
text,
elem_idx + 1,
text_pos + consumed,
) {
return Some(final_pos);
}
}
} else {
for try_count in (min..=max_count).rev() {
let consumed = byte_positions[try_count];
if let Some(final_pos) = self.match_elements_backtracking_dotall(
text,
elem_idx + 1,
text_pos + consumed,
) {
return Some(final_pos);
}
}
}
None
}
}
// Quantified group with backtracking in DOTALL mode
SequenceElement::QuantifiedGroup(group, quantifier) => {
let (min, max) = (quantifier.min_matches(), quantifier.max_matches());
let is_lazy = quantifier.is_lazy();
// Find all possible match lengths
let mut byte_positions: Vec<usize> = Vec::new();
byte_positions.push(0);
let mut current_pos = text_pos;
let mut count = 0;
while count < max && current_pos <= text.len() {
if let Some(consumed) = group.match_at(text, current_pos) {
if consumed == 0 {
break;
}
current_pos += consumed;
count += 1;
byte_positions.push(current_pos - text_pos);
} else {
break;
}
}
if count < min {
return None;
}
let max_count = count.min(max);
if is_lazy {
for try_count in min..=max_count {
let consumed = byte_positions[try_count];
if let Some(final_pos) = self.match_elements_backtracking_dotall(
text,
elem_idx + 1,
text_pos + consumed,
) {
return Some(final_pos);
}
}
} else {
for try_count in (min..=max_count).rev() {
let consumed = byte_positions[try_count];
if let Some(final_pos) = self.match_elements_backtracking_dotall(
text,
elem_idx + 1,
text_pos + consumed,
) {
return Some(final_pos);
}
}
}
None
}
// Other elements use standard matching
_ => {
if let Some(consumed) = element.match_at(text, text_pos) {
self.match_elements_backtracking_dotall(text, elem_idx + 1, text_pos + consumed)
} else {
None
}
}
}
}
/// Element-level Thompson NFA simulation using pre-computed transition table.
/// Returns Some(bool) if NFA table is available, None otherwise.
#[inline]
fn is_match_nfa(&self, text: &str) -> Option<bool> {
let table = self.nfa_table.as_ref()?;
// OPTIMIZATION: If pattern has a single Char element (inner literal),
// use memchr to find it first, then verify context.
if let Some(result) = self.is_match_nfa_with_char_prefilter(table, text) {
return Some(result);
}
// Full NFA scan
Some(self.run_nfa(table, text.as_bytes()))
}
/// Try memchr-based prefilter for patterns with a Char element.
/// Returns Some(bool) if applicable, None to fall through to full NFA.
#[inline]
fn is_match_nfa_with_char_prefilter(&self, table: &NfaTable, text: &str) -> Option<bool> {
// Find the Char element (if exactly one exists and not at position 0 or n-1)
let n = table.n;
let mut char_idx = None;
let mut char_byte = 0u8;
for (i, elem) in self.elements.iter().enumerate() {
if let SequenceElement::Char(ch) = elem {
if i > 0 && i < n - 1 && (*ch as u32) < 128 {
char_idx = Some(i);
char_byte = *ch as u8;
break;
}
}
}
let char_pos = char_idx?;
// Use memchr to find the literal char
let bytes = text.as_bytes();
let mut search_pos = 0;
while search_pos < bytes.len() {
let found = memchr::memchr(char_byte, &bytes[search_pos..])?;
let abs_pos = search_pos + found;
// Verify left side: elements[0..char_pos] must match ending at abs_pos
let left_ok = if char_pos == 0 {
true
} else {
// Need at least char_pos bytes before (min 1 char per element)
abs_pos >= char_pos && self.verify_left(table, &bytes[..abs_pos], char_pos)
};
if left_ok {
// Verify right side: elements[char_pos+1..n] must match starting after abs_pos
let right_start = abs_pos + 1;
let right_ok = if char_pos + 1 >= n {
true
} else {
right_start < bytes.len()
&& self.verify_right(table, &bytes[right_start..], char_pos + 1)
};
if right_ok {
return Some(true);
}
}
search_pos = abs_pos + 1;
}
Some(false)
}
/// Verify left side of pattern matches (elements[0..end_idx] in text ending at text end)
#[inline]
fn verify_left(&self, table: &NfaTable, text: &[u8], end_idx: usize) -> bool {
// Check that at least one char at the end matches elements[end_idx-1]
// and recursively backward. For simplicity, just check min-length matching.
let byte_elem_mask = &table.byte_elem_mask;
// Run NFA on the left text, checking if we reach state end_idx-1 (min met)
let target_mask = 1u32 << (end_idx - 1);
let quantified_bits = table.quantified_bits;
let mut active: u32 = 0;
for &byte in text {
let elem_mask = if byte < 128 {
byte_elem_mask[byte as usize]
} else {
0
};
active = (active & elem_mask & quantified_bits)
| ((active << 1) & elem_mask)
| (elem_mask & 1u32);
// Only keep bits for elements before the char
active &= (1u32 << end_idx) - 1;
if active & target_mask != 0 {
return true;
}
}
false
}
/// Verify right side of pattern matches (elements[start_idx..n] in text)
#[inline]
fn verify_right(&self, table: &NfaTable, text: &[u8], start_idx: usize) -> bool {
let byte_elem_mask = &table.byte_elem_mask;
let accept_mask = table.accept_mask;
let quantified_bits = table.quantified_bits;
let start_bit = 1u32 << start_idx;
let mut active: u32 = 0;
for &byte in text {
let elem_mask = if byte < 128 {
byte_elem_mask[byte as usize]
} else {
0
};
// Start at start_idx instead of 0
let starts = if elem_mask & start_bit != 0 {
start_bit
} else {
0
};
active = (active & elem_mask & quantified_bits) | ((active << 1) & elem_mask) | starts;
// Only keep bits for elements at or after start_idx
active &= !((1u32 << start_idx) - 1);
if active & accept_mask != 0 {
return true;
}
}
false
}
/// Run the full NFA scan on byte slice
#[inline]
fn run_nfa(&self, table: &NfaTable, bytes: &[u8]) -> bool {
let accept_mask = table.accept_mask;
let quantified_bits = table.quantified_bits;
let optional_bits = table.optional_bits;
let byte_elem_mask = &table.byte_elem_mask;
// Start at element 0, then compute initial epsilon closure
let mut active: u32 = 1u32; // Initially at element 0
active = self.compute_epsilon_closure(active, optional_bits, table.n);
// Check if we can accept before processing any bytes (e.g., pattern "a*" matching "")
if active & accept_mask != 0 {
return true;
}
for &byte in bytes {
let elem_mask = if byte < 128 {
byte_elem_mask[byte as usize]
} else {
let mut mask = 0u32;
for (i, elem) in self.elements.iter().enumerate() {
if let SequenceElement::QuantifiedCharClass(cc, _) = elem {
if cc.negated {
mask |= 1u32 << i;
}
}
}
mask
};
// Standard NFA transition
let mut next_active = (active & elem_mask & quantified_bits) // Stay in quantified element
| ((active << 1) & elem_mask) // Advance to next element
| (elem_mask & 1u32); // Start at element 0 (for ".*" patterns)
// Compute epsilon closure after transition
next_active = self.compute_epsilon_closure(next_active, optional_bits, table.n);
active = next_active;
if active & accept_mask != 0 {
return true;
}
}
false
}
/// Compute epsilon closure: for each active state, follow epsilon transitions
/// An epsilon transition exists from element i to element i+1 if element i is optional (min=0)
#[inline]
fn compute_epsilon_closure(&self, mut active: u32, optional_bits: u32, n: usize) -> u32 {
// Repeatedly follow epsilon transitions until no new states are added
loop {
let before = active;
// For each active position i, if element i is optional, we can also be at i+1
for i in 0..n {
if (active & (1u32 << i)) != 0 && (optional_bits & (1u32 << i)) != 0 {
// Element i is active and optional, so we can skip it
if i + 1 < n {
active |= 1u32 << (i + 1);
}
}
}
if active == before {
break;
}
}
active
}
/// Find the sequence anywhere in text
pub fn find(&self, text: &str) -> Option<(usize, usize)> {
// FAST PRECHECK: For adjacent non-overlapping quantified charclasses
// Check if pattern CAN match before trying expensive backtracking
if self.elements.len() == 2 {
if let (
Some(SequenceElement::QuantifiedCharClass(cc1, _)),
Some(SequenceElement::QuantifiedCharClass(cc2, _)),
) = (self.elements.first(), self.elements.get(1))
{
if !cc1.overlaps_with(cc2) {
// Pattern requires cc1 followed by cc2 with no overlap
// Quick scan to see if this is even possible
let bytes = text.as_bytes();
let mut found_possible = false;
for i in 0..bytes.len().saturating_sub(1) {
let ch1 = bytes[i] as char;
let ch2 = bytes[i + 1] as char;
if cc1.matches(ch1) && cc2.matches(ch2) {
found_possible = true;
break;
}
}
if !found_possible {
// Pattern is impossible - fail fast
return None;
}
}
}
}
// OPTIMIZATION 1: Extract literal prefix for memchr acceleration
if let Some((prefix_bytes, skip_count)) = self.extract_literal_prefix() {
if prefix_bytes.len() >= 3 {
// Multi-byte prefix: use memmem
use memchr::memmem;
let finder = memmem::Finder::new(&prefix_bytes);
let mut pos = 0;
while pos < text.len() {
if let Some(found) = finder.find(text[pos..].as_bytes()) {
let match_start = pos + found;
let after_prefix = match_start + prefix_bytes.len();
// Validate remaining elements
if let Some(consumed) =
self.match_at_skip_from(text, after_prefix, skip_count)
{
return Some((match_start, after_prefix + consumed));
}
pos = match_start + 1;
} else {
break;
}
}
return None;
} else if prefix_bytes.len() == 1 {
// Single byte prefix: use memchr
use memchr::memchr;
let byte = prefix_bytes[0];
let mut pos = 0;
while pos < text.len() {
if let Some(found) = memchr(byte, &text.as_bytes()[pos..]) {
let match_start = pos + found;
let after_prefix = match_start + 1;
// Validate remaining elements
if let Some(consumed) =
self.match_at_skip_from(text, after_prefix, skip_count)
{
return Some((match_start, after_prefix + consumed));
}
pos = match_start + 1;
} else {
break;
}
}
return None;
}
}
// OPTIMIZATION 2: Inner literal with bidirectional matching
// For patterns like \w+\s*>=\s*\d+ with anchor '>=' in middle
if let Some((anchor_literal, before_count, after_count)) = self.extract_inner_literal() {
if anchor_literal.len() >= 2 {
use memchr::memmem;
let finder = memmem::Finder::new(&anchor_literal);
for anchor_pos in finder.find_iter(text.as_bytes()) {
if let Some((match_start, match_end)) = self.match_around_anchor(
text,
anchor_pos,
anchor_literal.len(),
before_count,
after_count,
) {
return Some((match_start, match_end));
}
}
return None;
} else if anchor_literal.len() == 1 {
// Single char inner literal - use memchr for rare/distinctive chars
let byte = anchor_literal[0];
if !byte.is_ascii_alphanumeric() && byte != b' ' && byte != b'.' {
// Rare char (like @, #, :, !, etc.) - memchr is effective
let mut pos = 0;
while pos < text.len() {
if let Some(found) = memchr::memchr(byte, &text.as_bytes()[pos..]) {
let anchor_pos = pos + found;
if let Some((match_start, match_end)) = self.match_around_anchor(
text,
anchor_pos,
1,
before_count,
after_count,
) {
return Some((match_start, match_end));
}
pos = anchor_pos + 1;
} else {
return None;
}
}
return None;
}
}
}
// OPTIMIZATION 3: Bidirectional anchored search for wildcard patterns
// For patterns like [a-z]+.+[0-9]+ where wildcard causes expensive backtracking
// Strategy: Use first element as forward prefilter, then validate full match
// NOTE: Byte-based scanning only works correctly for ASCII text
let has_wildcard = self.elements.iter().any(|e| {
matches!(e, SequenceElement::QuantifiedChar('.', _))
|| matches!(e, SequenceElement::QuantifiedCharClass(cc, _) if cc.is_dot_class())
});
if has_wildcard && self.elements.len() >= 3 && text.is_ascii() {
// Check if first element is a selective charclass we can use as prefilter
if let Some(SequenceElement::QuantifiedCharClass(first_cc, first_q)) =
self.elements.first()
{
let (first_min, _) = quantifier_bounds(first_q);
// Only use as prefilter if first element must match (min > 0)
// and is selective enough (letters or similar)
if first_min > 0 && Self::selectivity(first_cc) <= 52 {
// Also check if last element is selective (for early termination)
let last_is_selective =
if let Some(SequenceElement::QuantifiedCharClass(last_cc, _)) =
self.elements.last()
{
last_cc.is_digit_class() || Self::selectivity(last_cc) <= 26
} else {
false
};
if last_is_selective {
// Use memchr-style prefilter on first element
let bytes = text.as_bytes();
let mut pos = 0;
// Find first char that matches first_cc using vectorized search
while pos < bytes.len() {
// Find next position where first_cc matches
let found = bytes[pos..]
.iter()
.position(|&b| first_cc.matches(b as char));
if let Some(offset) = found {
let start_pos = pos + offset;
// Try full match from this position
if let Some(end_pos) = self.match_at_pos(text, start_pos) {
return Some((start_pos, end_pos));
}
pos = start_pos + 1;
} else {
break;
}
}
return None;
}
}
}
}
// OPTIMIZATION 4: Charclass prefilter - use most selective element
if let (Some(first), Some(last)) = (self.elements.first(), self.elements.last()) {
let first_cc = match first {
SequenceElement::QuantifiedCharClass(cc, q) => {
// Only use as prefilter if NOT optional (min > 0)
let (min, _) = quantifier_bounds(q);
if min > 0 {
Some(cc)
} else {
None
}
}
_ => None,
};
let last_cc = match last {
SequenceElement::QuantifiedCharClass(cc, _) => Some(cc),
_ => None,
};
// Choose the most selective element as prefilter
let use_last = match (first_cc, last_cc) {
(Some(fc), Some(lc)) => Self::selectivity(lc) < Self::selectivity(fc),
_ => false,
};
// For patterns like \w+\s+\d+, use most selective element as prefilter
// For 3 elements: first, middle, last - find most selective, then expand
// NOTE: This optimization only works correctly for ASCII text!
// For Unicode text, byte-based scanning can give false matches
if use_last && self.elements.len() == 3 && text.is_ascii() {
if let Some(SequenceElement::QuantifiedCharClass(mid_cc, mid_q)) =
self.elements.get(1)
{
let fc = first_cc.unwrap();
let lc = last_cc.unwrap();
let bytes = text.as_bytes();
let (mid_min, _) = quantifier_bounds(mid_q);
let first_min = match first {
SequenceElement::QuantifiedCharClass(_, q) => quantifier_bounds(q).0,
_ => 1,
};
let last_min = match last {
SequenceElement::QuantifiedCharClass(_, q) => quantifier_bounds(q).0,
_ => 1,
};
// Strategy: Find digit run first (most selective), then scan backward
// Precompute minimum required position for early termination
let min_pos = first_min + mid_min;
let len = bytes.len();
let mut pos = 0;
while pos < len {
// Skip until we find last element (e.g., digit) - inline
let b = bytes[pos];
if !lc.matches(b as char) {
pos += 1;
continue;
}
// Early check: need space for first + middle before
if pos < min_pos {
pos += 1;
continue;
}
let last_start = pos;
// Find end of last element run
while pos < len && lc.matches(bytes[pos] as char) {
pos += 1;
}
let last_end = pos;
// EARLY CHECK 1: last element long enough?
if last_end - last_start < last_min {
continue;
}
// EARLY CHECK 2: middle element exists before last?
if !mid_cc.matches(bytes[last_start - 1] as char) {
continue;
}
// Find start of middle element
let mut mid_start = last_start - 1;
while mid_start > 0 && mid_cc.matches(bytes[mid_start - 1] as char) {
mid_start -= 1;
}
// Check middle length
if last_start - mid_start < mid_min {
continue;
}
// EARLY CHECK 3: first element exists before middle?
if mid_start == 0 || !fc.matches(bytes[mid_start - 1] as char) {
continue;
}
// Find start of first element
let mut first_start = mid_start - 1;
while first_start > 0 && fc.matches(bytes[first_start - 1] as char) {
first_start -= 1;
}
// Check first length
if mid_start - first_start < first_min {
continue;
}
// CRITICAL: Char boundary validation for Unicode safety!
// The byte-based scan works for ASCII but may give incorrect positions
// for multi-byte UTF-8 chars. We MUST validate and adjust.
// Strategy: If positions aren't on char boundaries, skip this candidate
// and let the fallback matching handle it correctly
if !text.is_char_boundary(first_start) || !text.is_char_boundary(last_end) {
continue;
}
// Found valid match with correct char boundaries
return Some((first_start, last_end));
}
return None;
}
} else if use_last && self.elements.len() >= 2 && text.is_ascii() {
// General case for more elements (ASCII-only optimization)
if let Some(SequenceElement::QuantifiedCharClass(mid_cc, mid_q)) =
self.elements.get(1)
{
let fc = first_cc.unwrap();
let bytes = text.as_bytes();
let (mid_min, _) = quantifier_bounds(mid_q);
let first_min = match first {
SequenceElement::QuantifiedCharClass(_, q) => quantifier_bounds(q).0,
_ => 1,
};
let mut pos = 0;
while pos < bytes.len() {
while pos < bytes.len() && !mid_cc.matches(bytes[pos] as char) {
pos += 1;
}
if pos >= bytes.len() {
break;
}
let mid_start = pos;
while pos < bytes.len() && mid_cc.matches(bytes[pos] as char) {
pos += 1;
}
if pos - mid_start >= mid_min
&& mid_start >= first_min
&& fc.matches(bytes[mid_start - 1] as char)
{
let mut start_pos = mid_start;
while start_pos > 0 && fc.matches(bytes[start_pos - 1] as char) {
start_pos -= 1;
}
if mid_start - start_pos >= first_min {
if let Some(final_pos) = self.match_at_pos(text, start_pos) {
return Some((start_pos, final_pos));
}
}
}
}
return None;
}
}
// Fallback: use forward prefilter
if let Some(fc) = first_cc {
// Forward prefilter: find first element, then try full match
let mut pos = 0;
while pos < text.len() {
if let Some(offset) = fc.find_first(&text[pos..]) {
let start_pos = pos + offset;
if let Some(final_pos) = self.match_at_pos(text, start_pos) {
return Some((start_pos, final_pos));
}
pos = start_pos + 1;
} else {
break;
}
}
return None;
}
}
// Fallback: sequential search
for (start_pos, _) in text.char_indices() {
if let Some(final_pos) = self.match_at_pos(text, start_pos) {
return Some((start_pos, final_pos));
}
}
None
}
/// Check if charclass is good candidate for memchr (selective + ASCII)
fn is_memchr_candidate(cc: &CharClass) -> bool {
if cc.negated {
return false;
}
// Digits [0-9] - perfect for memchr
if cc.is_digit_class() {
return true;
}
// Small selective sets (like single chars or small ranges)
Self::selectivity(cc) <= 10
}
/// Find first occurrence of charclass in bytes using memchr when possible
fn memchr_find_charclass(cc: &CharClass, bytes: &[u8]) -> Option<usize> {
if cc.is_digit_class() {
// Use memchr for digits
for (i, &b) in bytes.iter().enumerate() {
if b.is_ascii_digit() {
return Some(i);
}
}
return None;
}
// For small selective sets, scan directly
for (i, &b) in bytes.iter().enumerate() {
if cc.matches(b as char) {
return Some(i);
}
}
None
}
/// Estimate how many characters a CharClass matches (lower = more selective)
fn selectivity(cc: &CharClass) -> usize {
if cc.negated {
return 1000; // Negated classes match almost everything
}
let mut count = cc.chars.len();
for &(start, end) in &cc.ranges {
count += (end as usize) - (start as usize) + 1;
}
count
}
/// Extract literal prefix from sequence
/// Returns (prefix_bytes, elements_to_skip_after_prefix)
fn extract_literal_prefix(&self) -> Option<(Vec<u8>, usize)> {
let mut prefix = Vec::new();
let mut elements_scanned = 0;
for elem in &self.elements {
match elem {
SequenceElement::Char(ch) => {
prefix.push(*ch as u8);
elements_scanned += 1;
}
SequenceElement::Literal(s) => {
prefix.extend_from_slice(s.as_bytes());
elements_scanned += 1;
}
_ => {
// Stop at first non-literal element
break;
}
}
}
if prefix.is_empty() {
None
} else {
let skip_count = self.elements.len() - elements_scanned;
Some((prefix, skip_count))
}
}
/// Extract inner literal anchor from sequence
/// Returns (literal_bytes, elements_before, elements_after)
fn extract_inner_literal(&self) -> Option<(Vec<u8>, usize, usize)> {
// Look for consecutive Char/Literal elements not at start
for (start_idx, _window) in self.elements.windows(2).enumerate() {
if start_idx == 0 {
// Skip if at start (that's a prefix, not inner)
continue;
}
// Check if this position has literal elements
let mut literal_bytes = Vec::new();
let mut elements_consumed = 0;
for elem in &self.elements[start_idx..] {
match elem {
SequenceElement::Char(ch) => {
literal_bytes.push(*ch as u8);
elements_consumed += 1;
}
SequenceElement::Literal(s) => {
literal_bytes.extend_from_slice(s.as_bytes());
elements_consumed += 1;
}
_ => break,
}
}
if !literal_bytes.is_empty() {
let before_count = start_idx;
let after_count = self.elements.len() - start_idx - elements_consumed;
return Some((literal_bytes, before_count, after_count));
}
}
None
}
/// Match pattern around an anchor literal (bidirectional matching)
/// Returns (match_start, match_end) if successful
fn match_around_anchor(
&self,
text: &str,
anchor_byte_pos: usize,
anchor_len: usize,
before_count: usize,
after_count: usize,
) -> Option<(usize, usize)> {
let anchor_end = anchor_byte_pos + anchor_len;
// Match elements AFTER anchor (forward direction) WITH BACKTRACKING
// Use backtracking for quantified elements like .* to avoid greedy over-matching
let after_start_idx = self.elements.len() - after_count;
let match_end = if after_count > 0 {
// Use backtracking for forward matching
self.match_elements_backtracking(text, after_start_idx, anchor_end)?
} else {
anchor_end
};
// Match elements BEFORE anchor (backward direction - OPTIMIZED)
// For greedy quantifiers, match backwards from anchor
let before_elements = &self.elements[..before_count];
if before_elements.is_empty() {
return Some((anchor_byte_pos, match_end));
}
// SIMPLIFIED: Use forward matching with backtracking instead of complex backward logic
// Try to find where before_elements match and end exactly at anchor_byte_pos
// We search backwards from anchor position
let text_before = &text[..anchor_byte_pos];
// Calculate minimum bytes needed for before_elements
let min_bytes_needed: usize = before_elements
.iter()
.map(|e| match e {
SequenceElement::Char(c) => c.len_utf8(),
SequenceElement::CharClass(_) => 1,
SequenceElement::Dot => 1,
SequenceElement::QuantifiedChar(_, q)
| SequenceElement::QuantifiedCharClass(_, q)
| SequenceElement::QuantifiedGroup(_, q) => {
let (min, _) = quantifier_bounds(q);
min
}
SequenceElement::Boundary(_) => 0,
SequenceElement::Literal(s) => s.len(),
SequenceElement::Group(_) => 0,
})
.sum();
if text_before.len() < min_bytes_needed {
return None;
}
// Try matching before_elements forward from different start positions
// Start from the earliest possible position
let search_start = anchor_byte_pos.saturating_sub(1024.max(min_bytes_needed * 10));
let mut match_start = None;
for try_pos in search_start..=anchor_byte_pos.saturating_sub(min_bytes_needed) {
let mut pos = try_pos;
let mut matched = true;
// Try to match all before_elements forward from try_pos
for elem in before_elements {
match elem.match_at(text, pos) {
Some(consumed) => pos += consumed,
None => {
matched = false;
break;
}
}
}
// Check if forward matching lands exactly at anchor_byte_pos
if matched && pos == anchor_byte_pos {
match_start = Some(try_pos);
break; // Found leftmost match
}
}
let match_start = match_start?; // Failed to find a match before the anchor
Some((match_start, match_end))
}
/// Match starting from position, skipping first N elements
fn match_at_skip(&self, text: &str, skip_count: usize) -> Option<usize> {
if skip_count == 0 {
return Some(0); // No more elements to match
}
let start_idx = self.elements.len() - skip_count;
// Use backtracking-enabled matching
self.match_elements_backtracking(text, start_idx, 0)
}
/// Match remaining elements starting from a specific position in the full text
/// This preserves context needed for boundary checks
/// Returns the number of bytes consumed (not absolute position)
fn match_at_skip_from(&self, text: &str, text_pos: usize, skip_count: usize) -> Option<usize> {
if skip_count == 0 {
return Some(0); // No more elements to match
}
let start_idx = self.elements.len() - skip_count;
// Use backtracking with the full text and actual position
// Returns absolute end position, convert to bytes consumed
self.match_elements_backtracking(text, start_idx, text_pos)
.map(|end_pos| end_pos - text_pos)
}
/// Match elements with backtracking support for quantified elements
fn match_elements_backtracking(
&self,
text: &str,
elem_idx: usize,
text_pos: usize,
) -> Option<usize> {
// Base case: all elements matched
if elem_idx >= self.elements.len() {
return Some(text_pos);
}
let elem = &self.elements[elem_idx];
match elem {
// Quantified elements: try different match lengths (greedy first, then backtrack)
SequenceElement::QuantifiedChar(ch, quantifier) => {
self.backtrack_quantified_char(*ch, quantifier, text, text_pos, elem_idx)
}
SequenceElement::QuantifiedCharClass(cc, quantifier) => {
self.backtrack_quantified_charclass(cc, quantifier, text, text_pos, elem_idx)
}
SequenceElement::QuantifiedGroup(group, quantifier) => {
self.backtrack_quantified_group(group, quantifier, text, text_pos, elem_idx)
}
// Non-quantified elements: simple match
_ => {
if let Some(consumed) = elem.match_at(text, text_pos) {
self.match_elements_backtracking(text, elem_idx + 1, text_pos + consumed)
} else {
None
}
}
}
}
/// Backtracking for quantified char: try greedy first (or lazy first for lazy quantifiers)
fn backtrack_quantified_char(
&self,
ch: char,
quantifier: &Quantifier,
text: &str,
text_pos: usize,
elem_idx: usize,
) -> Option<usize> {
let (min, max) = quantifier_bounds(quantifier);
let is_lazy = quantifier.is_lazy();
let remaining = &text[text_pos..];
let ch_len = ch.len_utf8();
// Count maximum possible matches and build byte position table
let mut max_count = 0;
let mut byte_offset = 0;
// Pre-compute cumulative byte positions to avoid O(n²)
let mut byte_positions: Vec<usize> = Vec::new();
byte_positions.push(0);
for c in remaining.chars() {
if c == ch {
max_count += 1;
byte_offset += ch_len;
byte_positions.push(byte_offset);
if max_count >= max {
break;
}
} else {
break;
}
}
if max_count < min {
return None;
}
max_count = max_count.min(max);
if is_lazy {
// Lazy: try from min to max_count (prefer shorter matches first)
for try_count in min..=max_count {
let consumed = byte_positions[try_count];
if let Some(final_pos) =
self.match_elements_backtracking(text, elem_idx + 1, text_pos + consumed)
{
return Some(final_pos);
}
}
} else {
// Greedy: try from max_count down to min (prefer longer matches first)
for try_count in (min..=max_count).rev() {
let consumed = byte_positions[try_count];
if let Some(final_pos) =
self.match_elements_backtracking(text, elem_idx + 1, text_pos + consumed)
{
return Some(final_pos);
}
}
}
None
}
/// Backtracking for quantified charclass: try greedy first (or lazy first for lazy quantifiers)
fn backtrack_quantified_charclass(
&self,
cc: &CharClass,
quantifier: &Quantifier,
text: &str,
text_pos: usize,
elem_idx: usize,
) -> Option<usize> {
let (min, max) = quantifier_bounds(quantifier);
let is_lazy = quantifier.is_lazy();
let remaining = &text[text_pos..];
let rem_bytes = remaining.as_bytes();
// Fast path for ASCII-only remaining text
// TODO: ASCII fast path has a bug with complex range quantifier patterns
// Disabling for correctness - will investigate and fix in future release
let is_ascii = false;
let _is_ascii_detect = rem_bytes
.iter()
.take(rem_bytes.len().min(256))
.all(|&b| b < 128);
if is_ascii {
// FAST: For negated single-char class (like [^\n] from .+), use memchr
let max_count;
if cc.negated && cc.chars.len() == 1 && cc.ranges.is_empty() {
let forbidden = cc.chars[0] as u8;
let term_pos = memchr::memchr(forbidden, rem_bytes).unwrap_or(rem_bytes.len());
max_count = term_pos.min(max);
} else {
// Count matching bytes
// OPTIMIZATION: For digit class, use vectorized check
let mut count = 0;
if cc.is_digit_class() && !cc.negated {
// Vectorized digit check: process 8 bytes at a time
let mut i = 0;
while i + 8 <= rem_bytes.len() && count < max {
// Check 8 bytes in parallel
let chunk = &rem_bytes[i..i + 8];
let mut all_digits = true;
let mut chunk_count = 0;
for &byte in chunk {
if byte >= b'0' && byte <= b'9' {
chunk_count += 1;
} else {
all_digits = false;
break;
}
}
if all_digits {
count += chunk_count;
i += 8;
} else {
count += chunk_count;
break;
}
}
// Process remaining bytes
while i < rem_bytes.len() && count < max {
if rem_bytes[i] >= b'0' && rem_bytes[i] <= b'9' {
count += 1;
i += 1;
} else {
break;
}
}
} else if !cc.negated && cc.chars.is_empty() && cc.ranges.len() == 1 {
// Single range like [a-z] or [A-Z] - vectorized check
let (start_byte, end_byte) = (cc.ranges[0].0 as u8, cc.ranges[0].1 as u8);
let mut i = 0;
// Process 8 bytes at a time
while i + 8 <= rem_bytes.len() && count < max {
let chunk = &rem_bytes[i..i + 8];
let mut all_match = true;
let mut chunk_count = 0;
for &byte in chunk {
if byte >= start_byte && byte <= end_byte {
chunk_count += 1;
} else {
all_match = false;
break;
}
}
if all_match {
count += chunk_count;
i += 8;
} else {
count += chunk_count;
break;
}
}
// Process remaining bytes
while i < rem_bytes.len() && count < max {
if rem_bytes[i] >= start_byte && rem_bytes[i] <= end_byte {
count += 1;
i += 1;
} else {
break;
}
}
} else if cc.is_whitespace_class() && !cc.negated {
// Whitespace class \s - vectorized check for common whitespace
let mut i = 0;
// Process bytes looking for space, tab, newline, carriage return
while i < rem_bytes.len() && count < max {
let byte = rem_bytes[i];
if byte == b' ' || byte == b'\t' || byte == b'\n' || byte == b'\r' {
count += 1;
i += 1;
} else {
break;
}
}
} else {
// General case
for &byte in rem_bytes {
if cc.matches(byte as char) {
count += 1;
if count >= max {
break;
}
} else {
break;
}
}
}
max_count = count;
}
if max_count < min {
return None;
}
if is_lazy {
for try_count in min..=max_count {
let consumed = try_count; // ASCII fast path: each matched char is one byte.
if let Some(final_pos) =
self.match_elements_backtracking(text, elem_idx + 1, text_pos + consumed)
{
return Some(final_pos);
}
}
return None;
}
// OPTIMIZATION: For dot class (.+) followed by digit class, use memchr
// to find digit positions instead of blind backtracking
if cc.is_dot_class() {
if let Some(next_cc) = self.peek_next_charclass(elem_idx + 1) {
if next_cc.is_digit_class() {
// .+ followed by \d+ - find first digit in range [min, max_count]
let search_start = text_pos + min;
let search_end = (text_pos + max_count).min(text.len());
if search_start < text.len() {
let search_range = &text.as_bytes()[search_start..search_end];
// Use memchr to find digit positions quickly
// memchr can find any of '0'-'9' using memchr3 for common digits
let mut offset = 0;
while offset < search_range.len() {
// Find next digit using vectorized scan
let next_digit = search_range[offset..]
.iter()
.position(|&b| b >= b'0' && b <= b'9');
if let Some(found) = next_digit {
let consumed = min + offset + found;
if let Some(final_pos) = self.match_elements_backtracking(
text,
elem_idx + 1,
text_pos + consumed,
) {
return Some(final_pos);
}
// Try next digit position
offset += found + 1;
} else {
break;
}
}
return None;
}
}
}
}
// OPTIMIZATION: If next element is a QuantifiedCharClass, use smarter backtracking
// For patterns like .+[0-9]+, instead of trying every position, jump to positions
// where the next element could potentially match
// TEMPORARILY DISABLED: This optimization has bugs with range quantifiers
let _enable_optimization = false;
if _enable_optimization {
if let Some(next_cc) = self.peek_next_charclass(elem_idx + 1) {
let end = text_pos + max_count;
let remaining = &text[text_pos..end];
// EARLY TERMINATION: If current and next charclass don't overlap,
// and we can't find next charclass in the range we'll search, fail fast
// NOTE: Only apply this check for patterns that will definitely fail,
// not for cases where backtracking might succeed
if !cc.overlaps_with(next_cc) && min == max {
// Fixed quantifier (like {5} not {1,10}) and non-overlapping
// Check if next charclass appears in remaining text after our fixed match
let fixed_end = text_pos + max_count;
if fixed_end < text.len() {
let text_after = &text[fixed_end..];
let mut found_next = false;
// Only scan a reasonable window (e.g., 100 chars) to avoid perf hit
let scan_limit = text_after.len().min(100);
for ch in text_after[..scan_limit].chars() {
if next_cc.matches(ch) {
found_next = true;
break;
}
}
if !found_next {
// Next element cannot match anywhere in reasonable range
return None;
}
}
}
// Use memchr-style search for common cases
if !next_cc.negated && next_cc.ranges.is_empty() && next_cc.chars.len() == 1 {
// Single character class like [0] or [a] - use memchr
let target = next_cc.chars[0];
let target_byte = if target.is_ascii() { target as u8 } else { 0 };
if target_byte > 0 {
// Use memchr for ASCII single char
let mut search_pos = 0;
while search_pos < remaining.len() {
if let Some(found) =
memchr::memchr(target_byte, &remaining.as_bytes()[search_pos..])
{
let candidate_pos = text_pos + search_pos + found;
let consumed = candidate_pos - text_pos;
if consumed >= min {
if let Some(final_pos) = self.match_elements_backtracking(
text,
elem_idx + 1,
candidate_pos,
) {
return Some(final_pos);
}
}
search_pos += found + 1;
} else {
break;
}
}
// If memchr didn't find anything or matches failed, fall through
}
}
// NOTE: Removed buggy is_digit_class optimization that was causing
// range quantifier bugs. Standard greedy backtracking below handles all cases correctly.
}
}
// Standard greedy backtracking for ASCII - no Vec allocation needed
// since for ASCII, byte position = char count
for try_count in (min..=max_count).rev() {
if let Some(final_pos) =
self.match_elements_backtracking(text, elem_idx + 1, text_pos + try_count)
{
return Some(final_pos);
}
}
return None;
}
// UTF-8 path: pre-compute cumulative byte positions
let mut max_count = 0;
let mut byte_offset = 0;
let mut byte_positions: Vec<usize> = Vec::new();
byte_positions.push(0);
for c in remaining.chars() {
if cc.matches(c) {
max_count += 1;
byte_offset += c.len_utf8();
byte_positions.push(byte_offset);
if max_count >= max {
break;
}
} else {
break;
}
}
if max_count < min {
return None;
}
max_count = max_count.min(max);
if is_lazy {
// Lazy: try from min to max_count (prefer shorter matches first)
for try_count in min..=max_count {
let consumed = byte_positions[try_count];
if let Some(final_pos) =
self.match_elements_backtracking(text, elem_idx + 1, text_pos + consumed)
{
return Some(final_pos);
}
}
} else {
// Greedy: try from max_count down to min (prefer longer matches first)
for try_count in (min..=max_count).rev() {
let consumed = byte_positions[try_count];
if let Some(final_pos) =
self.match_elements_backtracking(text, elem_idx + 1, text_pos + consumed)
{
return Some(final_pos);
}
}
}
None
}
/// Backtracking for quantified group: try greedy first (or lazy first for lazy quantifiers)
fn backtrack_quantified_group(
&self,
group: &Group,
quantifier: &Quantifier,
text: &str,
text_pos: usize,
elem_idx: usize,
) -> Option<usize> {
let (min, max) = quantifier_bounds(quantifier);
let is_lazy = quantifier.is_lazy();
// Find all possible match lengths by repeatedly matching the group
let mut byte_positions: Vec<usize> = Vec::new();
byte_positions.push(0); // 0 repetitions = 0 bytes consumed
let mut current_pos = text_pos;
let mut count = 0;
while count < max && current_pos <= text.len() {
if let Some(consumed) = group.match_at(text, current_pos) {
if consumed == 0 {
break; // Prevent infinite loop on zero-width matches
}
current_pos += consumed;
count += 1;
byte_positions.push(current_pos - text_pos);
} else {
break;
}
}
if count < min {
return None;
}
let max_count = count.min(max);
if is_lazy {
// Lazy: try from min to max_count (prefer shorter matches first)
for try_count in min..=max_count {
let consumed = byte_positions[try_count];
if let Some(final_pos) =
self.match_elements_backtracking(text, elem_idx + 1, text_pos + consumed)
{
return Some(final_pos);
}
}
} else {
// Greedy: try from max_count down to min (prefer longer matches first)
for try_count in (min..=max_count).rev() {
let consumed = byte_positions[try_count];
if let Some(final_pos) =
self.match_elements_backtracking(text, elem_idx + 1, text_pos + consumed)
{
return Some(final_pos);
}
}
}
None
}
/// Peek at the next element's CharClass if it's a QuantifiedCharClass
fn peek_next_charclass(&self, next_idx: usize) -> Option<&CharClass> {
match self.elements.get(next_idx) {
Some(SequenceElement::QuantifiedCharClass(cc, _)) => Some(cc),
_ => None,
}
}
/// Find all occurrences of the sequence in text
pub fn find_all(&self, text: &str) -> Vec<(usize, usize)> {
let mut results: Vec<(usize, usize)> = Vec::new();
// OPTIMIZATION 1: Use literal prefix with memchr
if let Some((prefix_bytes, skip_count)) = self.extract_literal_prefix() {
if prefix_bytes.len() >= 3 {
// Multi-byte prefix: use memmem
use memchr::memmem;
let finder = memmem::Finder::new(&prefix_bytes);
for found_pos in finder.find_iter(text.as_bytes()) {
let after_prefix = found_pos + prefix_bytes.len();
if let Some(consumed) = self.match_at_skip_from(text, after_prefix, skip_count)
{
let match_start = found_pos;
let match_end = after_prefix + consumed;
// Check if this match overlaps with previous
if results.is_empty() || match_start >= results.last().unwrap().1 {
results.push((match_start, match_end));
}
}
}
return results;
} else if prefix_bytes.len() == 1 {
// Single byte prefix: use memchr_iter
use memchr::memchr_iter;
let byte = prefix_bytes[0];
for found_pos in memchr_iter(byte, text.as_bytes()) {
let after_prefix = found_pos + 1;
if let Some(consumed) = self.match_at_skip_from(text, after_prefix, skip_count)
{
let match_start = found_pos;
let match_end = after_prefix + consumed;
// Check if this match overlaps with previous
if results.is_empty() || match_start >= results.last().unwrap().1 {
results.push((match_start, match_end));
}
}
}
return results;
}
}
// OPTIMIZATION 2: Inner literal with bidirectional matching
if let Some((anchor_literal, before_count, after_count)) = self.extract_inner_literal() {
if anchor_literal.len() >= 2 {
use memchr::memmem;
let finder = memmem::Finder::new(&anchor_literal);
for anchor_pos in finder.find_iter(text.as_bytes()) {
if let Some((match_start, match_end)) = self.match_around_anchor(
text,
anchor_pos,
anchor_literal.len(),
before_count,
after_count,
) {
// Check if this match overlaps with previous
if results.is_empty() || match_start >= results.last().unwrap().1 {
results.push((match_start, match_end));
}
}
}
return results;
}
}
// Fallback: sequential search
let byte_positions: Vec<usize> = text.char_indices().map(|(i, _)| i).collect();
let mut i = 0;
while i < byte_positions.len() {
let start_pos = byte_positions[i];
if let Some(consumed) = self.match_at(&text[start_pos..]) {
let end_pos = start_pos + consumed;
results.push((start_pos, end_pos));
// Skip past this match
while i < byte_positions.len() && byte_positions[i] < end_pos {
i += 1;
}
} else {
i += 1;
}
}
results
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple_sequence() {
// "abc"
let seq = Sequence::new(vec![
SequenceElement::Char('a'),
SequenceElement::Char('b'),
SequenceElement::Char('c'),
]);
assert_eq!(seq.match_at("abc"), Some(3));
assert_eq!(seq.match_at("abcdef"), Some(3));
assert_eq!(seq.match_at("ab"), None);
assert_eq!(seq.match_at("xyz"), None);
}
#[test]
fn test_quantified_sequence() {
// "a+b"
let seq = Sequence::new(vec![
SequenceElement::QuantifiedChar('a', Quantifier::OneOrMore),
SequenceElement::Char('b'),
]);
assert_eq!(seq.match_at("ab"), Some(2));
assert_eq!(seq.match_at("aaab"), Some(4));
assert_eq!(seq.match_at("aaaabcd"), Some(5));
assert_eq!(seq.match_at("b"), None); // Need at least one 'a'
}
#[test]
fn test_charclass_sequence() {
// "[0-9]+[a-z]"
let mut digits = CharClass::new();
digits.add_range('0', '9');
digits.finalize();
let mut letters = CharClass::new();
letters.add_range('a', 'z');
letters.finalize();
let seq = Sequence::new(vec![
SequenceElement::QuantifiedCharClass(digits, Quantifier::OneOrMore),
SequenceElement::CharClass(letters),
]);
assert_eq!(seq.match_at("123a"), Some(4));
assert_eq!(seq.match_at("9z"), Some(2));
assert_eq!(seq.match_at("abc"), None); // No digits
}
#[test]
fn test_find() {
// "ab+"
let seq = Sequence::new(vec![
SequenceElement::Char('a'),
SequenceElement::QuantifiedChar('b', Quantifier::OneOrMore),
]);
assert_eq!(seq.find("xyzabbc"), Some((3, 6)));
assert_eq!(seq.find("nope"), None);
}
#[test]
fn test_find_all() {
// "a+b"
let seq = Sequence::new(vec![
SequenceElement::QuantifiedChar('a', Quantifier::OneOrMore),
SequenceElement::Char('b'),
]);
let matches = seq.find_all("ab aab aaab");
assert_eq!(matches, vec![(0, 2), (3, 6), (7, 11)]);
}
#[test]
fn test_literal_sequence() {
// "hello[0-9]+"
let mut digits = CharClass::new();
digits.add_range('0', '9');
digits.finalize();
let seq = Sequence::new(vec![
SequenceElement::Literal("hello".to_string()),
SequenceElement::QuantifiedCharClass(digits, Quantifier::OneOrMore),
]);
assert_eq!(seq.match_at("hello123"), Some(8));
assert_eq!(seq.match_at("hello"), None); // Need digits
}
}