ferroni 1.4.1

Oniguruma-compatible regex engine
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
// api_test.rs - Integration tests for the idiomatic Rust API.

use ferroni::api::{Regex, RegexBuilder};
use ferroni::error::RegexError;
use ferroni::oniguruma::ONIGERR_INVALID_BACKREF;
use ferroni::prelude::*;
use ferroni::regint::DEFAULT_PARSE_DEPTH_LIMIT;

// === Regex::new ===

#[test]
fn recursive_capture_above_bitset_width() {
    let pattern = format!(r"{}(a\g<32>?b)", "()".repeat(31));
    let regex = Regex::new(&pattern).unwrap();
    assert_eq!(regex.find("aaabbb").unwrap().as_str(), "aaabbb");
    assert!(!regex.is_match("aaa"));
}

#[test]
fn simple_pattern() {
    let re = Regex::new(r"\d+").unwrap();
    let m = re.find("abc 123 def").unwrap();
    assert_eq!(m.as_str(), "123");
}

#[test]
fn unicode_pattern() {
    let re = Regex::new(r"\p{Hiragana}+").unwrap();
    let m = re.find("hello せかい world").unwrap();
    assert_eq!(m.as_str(), "せかい");
}

#[test]
fn no_match_returns_none() {
    let re = Regex::new(r"xyz").unwrap();
    assert!(re.find("abc").is_none());
}

#[test]
fn empty_pattern() {
    let re = Regex::new(r"").unwrap();
    let m = re.find("hello").unwrap();
    assert_eq!(m.start(), 0);
    assert_eq!(m.end(), 0);
    assert!(m.is_empty());
}

#[test]
fn invalid_pattern_syntax_error() {
    let err = Regex::new(r"(unclosed").unwrap_err();
    match err {
        RegexError::Syntax { code, .. } => assert!(code < 0),
        other => panic!("expected Syntax error, got {:?}", other),
    }
}

#[test]
fn invalid_pattern_empty_char_class() {
    let err = Regex::new(r"[]").unwrap_err();
    assert!(matches!(err, RegexError::Syntax { .. }));
}

#[test]
fn flat_patterns_exceeding_ast_depth_limit_fail_cleanly() {
    const HUGE_FLAT_PATTERN_ELEMENT_COUNT: usize = 50_000;

    let alternatives = format!("{}a", "a|".repeat(HUGE_FLAT_PATTERN_ELEMENT_COUNT - 1));
    let concatenation = ".".repeat(HUGE_FLAT_PATTERN_ELEMENT_COUNT);

    for pattern in [&alternatives, &concatenation] {
        let err = Regex::new(pattern).unwrap_err();
        assert_eq!(err, RegexError::ParseDepthLimitOver);
    }
}

#[test]
fn nested_wide_patterns_exceeding_ast_depth_limit_fail_cleanly() {
    const NESTED_GROUP_COUNT: usize = 20;
    const WIDE_ALTERNATIVE_COUNT: usize = 4_000;
    const LONG_CONCATENATION_COUNT: usize = 4_000;

    let mut pattern = ".".repeat(LONG_CONCATENATION_COUNT);
    for _ in 0..NESTED_GROUP_COUNT {
        pattern = format!("(?:{}{})", "a|".repeat(WIDE_ALTERNATIVE_COUNT), pattern);
    }

    let err = Regex::new(&pattern).unwrap_err();
    assert_eq!(err, RegexError::ParseDepthLimitOver);
}

#[test]
fn long_literal_larger_than_ast_depth_limit_is_supported() {
    let pattern = "a".repeat(DEFAULT_PARSE_DEPTH_LIMIT as usize * 2);
    let re = Regex::new(&pattern).unwrap();
    assert!(re.is_match(&pattern));
}

// === Regex::is_match ===

#[test]
fn is_match_true() {
    let re = Regex::new(r"world").unwrap();
    assert!(re.is_match("hello world"));
}

#[test]
fn is_match_false() {
    let re = Regex::new(r"world").unwrap();
    assert!(!re.is_match("hello earth"));
}

// === Regex::find ===

#[test]
fn find_start_end_range() {
    let re = Regex::new(r"bar").unwrap();
    let m = re.find("foobarbaz").unwrap();
    assert_eq!(m.start(), 3);
    assert_eq!(m.end(), 6);
    assert_eq!(m.range(), 3..6);
    assert_eq!(m.len(), 3);
    assert!(!m.is_empty());
}

#[test]
fn find_as_bytes() {
    let re = Regex::new(r"\w+").unwrap();
    let m = re.find("hello world").unwrap();
    assert_eq!(m.as_bytes(), b"hello");
}

#[test]
fn unset_backreference_does_not_reuse_prior_capture() {
    let prior = Regex::new(r"(abc)(def)").unwrap();
    assert!(prior.captures("abcdef").is_some());

    let re = Regex::new(r"(?:(foo)|bar)\1").unwrap();
    assert!(re.find("barbar").is_none());
}

// === Regex::captures ===

#[test]
fn captures_groups() {
    let re = Regex::new(r"(\w+)\s+(\w+)").unwrap();
    let caps = re.captures("hello world").unwrap();
    assert_eq!(caps.get(0).unwrap().as_str(), "hello world");
    assert_eq!(caps.get(1).unwrap().as_str(), "hello");
    assert_eq!(caps.get(2).unwrap().as_str(), "world");
    assert_eq!(caps.len(), 3); // group 0 + 2 captures
}

#[test]
fn captures_optional_group() {
    let re = Regex::new(r"(a)(b)?c").unwrap();
    let caps = re.captures("ac").unwrap();
    assert_eq!(caps.get(0).unwrap().as_str(), "ac");
    assert_eq!(caps.get(1).unwrap().as_str(), "a");
    assert!(caps.get(2).is_none()); // group 2 didn't participate
}

#[test]
fn captures_optional_group_is_not_reused_from_prior_regex() {
    let prior = Regex::new(r"(aaa)(bbb)(ccc)").unwrap();
    assert!(prior.captures("aaabbbccc").is_some());

    let re = Regex::new(r"(x)?z").unwrap();
    let caps = re.captures("z").unwrap();

    // A stale range here used to make safe Match::as_str() panic when slicing "z".
    assert!(caps.get(1).is_none());
}

#[test]
fn captures_named() {
    let re = Regex::new(r"(?<first>\w+)\s+(?<last>\w+)").unwrap();
    let caps = re.captures("John Doe").unwrap();
    assert_eq!(caps.name("first").unwrap().as_str(), "John");
    assert_eq!(caps.name("last").unwrap().as_str(), "Doe");
    assert!(caps.name("middle").is_none());
}

#[test]
fn captures_multiplex_name_returns_last_participating_group() {
    let re = Regex::new(r"(?<letter>a)(?<letter>b)").unwrap();
    let caps = re.captures("ab").unwrap();

    assert_eq!(caps.name("letter").unwrap().as_str(), "b");
}

#[test]
fn captures_multiplex_name_returns_earlier_participating_group() {
    let re = Regex::new(r"(?:(?<letter>a)|(?<letter>b))").unwrap();
    let caps = re.captures("a").unwrap();

    assert_eq!(caps.name("letter").unwrap().as_str(), "a");
}

#[test]
fn captures_multiplex_name_returns_later_participating_group() {
    let re = Regex::new(r"(?:(?<letter>a)|(?<letter>b))").unwrap();
    let caps = re.captures("b").unwrap();

    assert_eq!(caps.name("letter").unwrap().as_str(), "b");
}

#[test]
fn captures_multiplex_name_returns_none_when_no_group_participates() {
    let re = Regex::new(r"(?:(?<letter>a)|(?<letter>b))?").unwrap();
    let caps = re.captures("").unwrap();

    assert!(caps.name("letter").is_none());
}

#[test]
fn captures_name_returns_unique_named_group() {
    let re = Regex::new(r"(?<letter>a)").unwrap();
    let caps = re.captures("a").unwrap();

    assert_eq!(caps.name("letter").unwrap().as_str(), "a");
}

#[test]
fn captures_no_match() {
    let re = Regex::new(r"(\d+)").unwrap();
    assert!(re.captures("no digits").is_none());
}

#[test]
fn captures_len() {
    let re = Regex::new(r"(a)(b)(c)(d)").unwrap();
    assert_eq!(re.captures_len(), 4);
}

#[test]
fn captures_iter() {
    let re = Regex::new(r"(a)(b)").unwrap();
    let caps = re.captures("ab").unwrap();
    let items: Vec<_> = caps.iter().collect();
    assert_eq!(items.len(), 3);
    assert_eq!(items[0].unwrap().as_str(), "ab");
    assert_eq!(items[1].unwrap().as_str(), "a");
    assert_eq!(items[2].unwrap().as_str(), "b");
}

// === Regex::find_iter ===

#[test]
fn find_iter_multiple() {
    let re = Regex::new(r"\d+").unwrap();
    let results: Vec<&str> = re
        .find_iter("1 and 22 and 333")
        .map(|m| m.as_str())
        .collect();
    assert_eq!(results, vec!["1", "22", "333"]);
}

#[test]
fn find_iter_no_matches() {
    let re = Regex::new(r"\d+").unwrap();
    let results: Vec<_> = re.find_iter("no digits").collect();
    assert!(results.is_empty());
}

#[test]
fn find_iter_empty_pattern() {
    let re = Regex::new(r"").unwrap();
    let results: Vec<_> = re.find_iter("ab").collect();
    // Should find empty match at positions 0, 1, 2
    assert_eq!(results.len(), 3);
    for (i, m) in results.iter().enumerate() {
        assert_eq!(m.start(), i);
        assert!(m.is_empty());
    }
}

#[test]
fn find_iter_overlapping_region() {
    let re = Regex::new(r"\w+").unwrap();
    let results: Vec<&str> = re.find_iter("a bb ccc").map(|m| m.as_str()).collect();
    assert_eq!(results, vec!["a", "bb", "ccc"]);
}

// === RegexBuilder ===

#[test]
fn builder_case_insensitive() {
    let re = RegexBuilder::new(r"hello")
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(re.is_match("HELLO"));
    assert!(re.is_match("HeLlO"));
}

#[test]
fn builder_dot_matches_newline() {
    let re = Regex::builder(r"a.b")
        .dot_matches_newline(true)
        .build()
        .unwrap();
    assert!(re.is_match("a\nb"));

    let re2 = Regex::builder(r"a.b").build().unwrap();
    assert!(!re2.is_match("a\nb"));
}

#[test]
fn builder_extended_mode() {
    let re = Regex::builder(
        r"
        \d+   # digits
        \s+   # space
        \w+   # word
    ",
    )
    .extended(true)
    .build()
    .unwrap();
    assert!(re.is_match("42 hello"));
}

#[test]
fn builder_syntax() {
    use ferroni::regsyntax::OnigSyntaxPerl;
    let re = Regex::builder(r"\d+")
        .syntax(&OnigSyntaxPerl)
        .build()
        .unwrap();
    assert!(re.is_match("42"));
}

#[test]
fn prototype_ecmascript_negative_lookbehind_is_opt_in() {
    use ferroni::regsyntax::prototype_ecmascript_lookbehind_syntax;

    assert!(Regex::new(r"(?<!(a))b").is_err());
    assert!(Regex::new(r"(?<!a(?=b))b").is_err());

    let capture = Regex::builder(r"(?<!(a+|bc))d")
        .syntax(prototype_ecmascript_lookbehind_syntax())
        .build()
        .unwrap();
    assert!(capture.is_match("d"));
    assert!(!capture.is_match("ad"));
    assert!(!capture.is_match("bcd"));

    let positive = Regex::builder(r"(?<!a(?=b))b")
        .syntax(prototype_ecmascript_lookbehind_syntax())
        .build()
        .unwrap();
    assert!(positive.is_match("b"));
    assert!(!positive.is_match("ab"));

    let negative = Regex::builder(r"(?<!a(?!c))b")
        .syntax(prototype_ecmascript_lookbehind_syntax())
        .build()
        .unwrap();
    assert!(!negative.is_match("ab"));
    assert!(negative.is_match("acb"));
}

#[test]
fn prototype_ecmascript_unmatched_backreferences_are_empty() {
    use ferroni::regsyntax::prototype_ecmascript_lookbehind_syntax;

    for pattern in [r"(a)?b\1", r"(a)(b)?c\2", r"(a)(b)(c)?d\3"] {
        let re = Regex::builder(pattern)
            .syntax(prototype_ecmascript_lookbehind_syntax())
            .build()
            .unwrap();
        assert!(re.is_match(match pattern {
            r"(a)?b\1" => "b",
            r"(a)(b)?c\2" => "ac",
            _ => "abd",
        }));
    }

    let insensitive = Regex::builder(r"(a)(b)(c)?d\3")
        .syntax(prototype_ecmascript_lookbehind_syntax())
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(insensitive.is_match("ABD"));

    let named = Regex::builder(r"(?:(?<x>a)|(?<x>b))?c\k<x>")
        .syntax(prototype_ecmascript_lookbehind_syntax())
        .build()
        .unwrap();
    assert!(named.is_match("c"));

    let named_insensitive = Regex::builder(r"(?:(?<x>a)|(?<x>b))?c\k<x>")
        .syntax(prototype_ecmascript_lookbehind_syntax())
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(named_insensitive.is_match("C"));
}

#[test]
fn builder_chaining() {
    let re = Regex::builder(r"hello world")
        .case_insensitive(true)
        .dot_matches_newline(true)
        .extended(false)
        .build()
        .unwrap();
    assert!(re.is_match("HELLO WORLD"));
}

// === Byte API ===

#[test]
fn find_bytes() {
    let re = Regex::new_bytes(b"\\d+").unwrap();
    let m = re.find_bytes(b"abc 42 def").unwrap();
    assert_eq!(m.as_bytes(), b"42");
    assert_eq!(m.start(), 4);
}

#[test]
fn is_match_bytes() {
    let re = Regex::new_bytes(b"hello").unwrap();
    assert!(re.is_match_bytes(b"say hello"));
    assert!(!re.is_match_bytes(b"goodbye"));
}

#[test]
fn byte_matching_clamps_truncated_utf8_word_steps() {
    let cases: &[(&str, &[u8])] = &[
        (r"\w+", b"hello\xf0\x9f\x92"),
        (r"\b\w+\b", b"\xf0\x9f"),
        (r"\w\b", b"\xf0\x9f"),
        (r"\w+", b"abc\xc2"),
        (r"(?W)\W", b"\xf0"),
    ];

    for &(pattern, input) in cases {
        let re = Regex::new(pattern).unwrap();
        assert!(re.is_match_bytes(input), "pattern {pattern:?}");

        let matched = re.find_bytes(input).expect("matching input");
        assert_eq!(matched.range(), 0..input.len(), "pattern {pattern:?}");
        assert_eq!(matched.as_bytes(), input, "pattern {pattern:?}");
    }
}

#[test]
fn byte_matching_clamps_truncated_utf8_negated_class_steps() {
    let input = b"\xf0";
    let re = Regex::new_bytes(b"([^a]+)").unwrap();

    let matched = re.find_bytes(input).expect("matching input");
    assert_eq!(matched.range(), 0..input.len());
    assert_eq!(matched.as_bytes(), input);

    let captures = re.captures_bytes(input).expect("matching input");
    for index in 0..captures.len() {
        let capture = captures.get(index).expect("participating capture");
        assert_eq!(capture.range(), 0..input.len());
        assert_eq!(capture.as_bytes(), input);
    }
}

// === RegexError ===

#[test]
fn error_display() {
    let err = Regex::new(r"(").unwrap_err();
    let msg = format!("{}", err);
    assert!(!msg.is_empty());
}

#[test]
fn error_is_std_error() {
    let err: Box<dyn std::error::Error> = Box::new(Regex::new(r"[").unwrap_err());
    assert!(!err.to_string().is_empty());
}

#[test]
fn error_code() {
    let err = Regex::new(r"(").unwrap_err();
    assert!(err.code() < 0);
}

// === Prelude ===

#[test]
fn prelude_imports_work() {
    // This test verifies that the prelude re-exports are accessible.
    let re = Regex::new(r"(\w+)").unwrap();
    let caps: Captures = re.captures("hello").unwrap();
    let m: Match = caps.get(0).unwrap();
    assert_eq!(m.as_str(), "hello");
    let _: &RegexError = &Regex::new(r"(").unwrap_err();
}

// === as_raw escape hatch ===

#[test]
fn as_raw_access() {
    use ferroni::regexec::onig_number_of_captures;
    let re = Regex::new(r"(a)(b)(c)").unwrap();
    let raw = re.as_raw();
    assert_eq!(onig_number_of_captures(raw), 3);
}

// === Complex patterns ===

#[test]
fn alternation() {
    let re = Regex::new(r"cat|dog|bird").unwrap();
    assert_eq!(re.find("I have a dog").unwrap().as_str(), "dog");
}

#[test]
fn backreference() {
    let re = Regex::new(r"(\w+)\s+\1").unwrap();
    let m = re.find("hello hello world").unwrap();
    assert_eq!(m.as_str(), "hello hello");
}

#[test]
fn numbered_backreferences_validate_capture_group_bounds() {
    for pattern in [
        b"\\1".as_slice(),
        b"\\8",
        b"\\9",
        b"(a)\\2",
        b"\\k<2>",
        b"\\k<8>",
        b"\\k<9>",
        b"\\k<80>",
        b"(a)\\k<2>",
    ] {
        let err = Regex::new_bytes(pattern).unwrap_err();
        assert_eq!(err.code(), ONIGERR_INVALID_BACKREF, "pattern: {pattern:?}");
    }
}

#[test]
fn group_reference_numbers_reject_overflow_and_missing_terminators() {
    for pattern in [
        br"(a)\k<a+999999999999999>".as_slice(),
        br"(?(9999999999999)a|b)".as_slice(),
        br"(a)(?(1+9999999999999)a|b)".as_slice(),
        br"(a)\k<1".as_slice(),
        br"(a)\g<1".as_slice(),
        br"(a)\k'1".as_slice(),
    ] {
        assert!(Regex::new_bytes(pattern).is_err(), "{pattern:?}");
    }
}

#[test]
fn valid_numbered_backreferences_compile_and_match() {
    for (pattern, input) in [
        (b"(a)\\1".as_slice(), "aa"),
        (b"(a)\\k<1>".as_slice(), "aa"),
        (b"(a)(b)(c)(d)(e)(f)(g)(h)\\8".as_slice(), "abcdefghh"),
        (b"(a)(b)(c)(d)(e)(f)(g)(h)\\k<8>".as_slice(), "abcdefghh"),
    ] {
        let re = Regex::new_bytes(pattern).unwrap();
        assert!(re.is_match(input), "pattern: {pattern:?}, input: {input:?}");
    }
}

#[test]
fn lookahead() {
    let re = Regex::new(r"\d+(?= dollars)").unwrap();
    let m = re.find("I have 42 dollars").unwrap();
    assert_eq!(m.as_str(), "42");
}

#[test]
fn lookbehind() {
    let re = Regex::new(r"(?<=\$)\d+").unwrap();
    let m = re.find("price: $99").unwrap();
    assert_eq!(m.as_str(), "99");
}

#[test]
fn possessive_quantifier() {
    let re = Regex::new(r"a++b").unwrap();
    // "aab" should match since possessive consumes all 'a's, then finds 'b'
    assert!(re.is_match("aab"));
    // "aa" should not match since possessive consumes 'a's but no 'b'
    assert!(!re.is_match("aa"));
}

#[test]
fn date_extraction() {
    let re = Regex::new(r"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})").unwrap();
    let caps = re.captures("Today is 2026-02-14.").unwrap();
    assert_eq!(caps.name("year").unwrap().as_str(), "2026");
    assert_eq!(caps.name("month").unwrap().as_str(), "02");
    assert_eq!(caps.name("day").unwrap().as_str(), "14");
    assert_eq!(caps.get(0).unwrap().as_str(), "2026-02-14");
}

#[test]
fn debug_impl() {
    let re = Regex::new(r"\d+").unwrap();
    let dbg = format!("{:?}", re);
    assert!(dbg.contains("Regex"));
}

#[test]
fn captures_debug_impl() {
    let re = Regex::new(r"(\d+)").unwrap();
    let caps = re.captures("42").unwrap();
    let dbg = format!("{:?}", caps);
    assert!(!dbg.is_empty());
}

// =========================================================================
// Coverage-targeted tests: Unicode case folding (unicode/mod.rs)
// =========================================================================

#[test]
fn case_insensitive_unicode_latin() {
    // Exercises apply_case_fold1 for non-ASCII Latin characters (ä/Ä, ö/Ö, etc.)
    let re = Regex::builder(r"straße")
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(re.is_match("STRASSE"));
    assert!(re.is_match("Straße"));
}

#[test]
fn case_insensitive_latin1_simple_fold_uses_multibyte_class() {
    let re = Regex::new(r"(?i)ö").unwrap();

    assert!(re.is_match("ö"));
    assert!(re.is_match("Ö"));
    assert!(!re.is_match_bytes(&[0xd6, 0x96])); // U+0596, not Ö
}

#[test]
fn case_insensitive_unicode_greek() {
    let re = Regex::builder(r"σ").case_insensitive(true).build().unwrap();
    assert!(re.is_match("Σ")); // capital sigma
    assert!(re.is_match("ς")); // final sigma
}

#[test]
fn case_insensitive_multi_char_fold() {
    // Exercises folds2/folds3 paths: ffi (U+FB03) folds to "ffi"
    let re = Regex::builder(r"ffi")
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(re.is_match("ffi"));
    assert!(re.is_match("FFI"));
}

#[test]
fn case_insensitive_char_class_unicode() {
    // Character class with case-insensitive Unicode
    let re = Regex::builder(r"[äöü]+")
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(re.is_match("ÄÖÜ"));
    assert!(re.is_match("äöü"));
}

// =========================================================================
// Coverage-targeted tests: Word boundary opcodes (regexec.rs WordStar etc.)
// =========================================================================

#[test]
fn word_star_non_ascii() {
    // Exercises WordStar non-ASCII path in match engine
    let re = Regex::new(r"\w*").unwrap();
    let m = re.find("café").unwrap();
    assert_eq!(m.as_str(), "café");
}

#[test]
fn word_star_peek_next() {
    // Exercises WordAsciiStarPeekNext opcode: \w* followed by specific char
    let re = Regex::new(r"\w*:").unwrap();
    let m = re.find("key: value").unwrap();
    assert_eq!(m.as_str(), "key:");
}

#[test]
fn word_boundary_unicode() {
    // Exercises Unicode word boundary code paths
    let re = Regex::new(r"\b\w+\b").unwrap();
    let results: Vec<&str> = re
        .find_iter("hello·world café")
        .map(|m| m.as_str())
        .collect();
    assert!(results.contains(&"hello"));
    assert!(results.contains(&"café"));
}

// =========================================================================
// Coverage-targeted tests: Subexpression calls (regcomp.rs tune_called_state)
// =========================================================================

#[test]
fn subexpression_call_in_quantifier() {
    // Exercises tune_called_state_call Quant branch
    let re = Regex::new(r"(?<digit>\d)(\g<digit>)+").unwrap();
    assert!(re.is_match("123"));
}

#[test]
fn subexpression_call_in_lookahead() {
    // Exercises tune_called_state_call Anchor/PREC_READ branch
    // \g<d> calls the pattern \d, not the captured value
    let re = Regex::new(r"(?<d>\d)(?=\g<d>)\d").unwrap();
    assert!(re.is_match("11"));
    assert!(re.is_match("12")); // \g<d> matches any digit
}

#[test]
fn subexpression_call_in_negative_lookahead() {
    // Exercises tune_called_state_call PREC_READ_NOT branch
    let re = Regex::new(r"(?<d>\d)(?!\g<d>)x").unwrap();
    assert!(re.is_match("1x")); // \g<d> matches digit but 'x' is not a digit
    assert!(!re.is_match("12")); // no 'x' after digit
}

#[test]
fn subexpression_call_in_lookbehind() {
    // Exercises tune_called_state_call LOOK_BEHIND branch
    let re = Regex::new(r"(?<d>\d)(?<=\g<d>)\w").unwrap();
    assert!(re.is_match("1a"));
}

#[test]
fn if_else_conditional() {
    // Exercises tune_called_state_call IfElse branch
    let re = Regex::new(r"^(a)?(?(1)b|c)$").unwrap();
    assert!(re.is_match("ab"));
    assert!(re.is_match("c"));
}

// =========================================================================
// Coverage-targeted tests: BackRef with nesting level (regexec.rs)
// =========================================================================

#[test]
fn backref_with_level() {
    // Exercises BackRefWithLevel opcode (backrefs in subexpression calls)
    // \k<b+0> is level-backref syntax from Oniguruma
    let re = Regex::new(r"\A(?<a>|.|(?:(?<b>.)\g<a>\k<b+0>))\z").unwrap();
    // Palindrome detector via recursive subexpression call with level-backref
    assert!(re.is_match("a"));
    assert!(re.is_match("aba"));
}

// =========================================================================
// Coverage-targeted tests: Anchors in search (regexec.rs sub_anchor paths)
// =========================================================================

#[test]
fn begin_line_anchor_multiline() {
    // Default: ^ matches start of string only
    let re = Regex::new(r"^\w+").unwrap();
    let results: Vec<&str> = re
        .find_iter("hello\nworld\nfoo")
        .map(|m| m.as_str())
        .collect();
    // Oniguruma: ^ is multiline by default
    assert!(!results.is_empty());
}

#[test]
fn end_line_anchor() {
    let re = Regex::new(r"\w+$").unwrap();
    let m = re.find("hello world").unwrap();
    assert_eq!(m.as_str(), "world");
}

#[test]
fn multiline_anchors() {
    let re = Regex::builder(r"^\w+$")
        .dot_matches_newline(false)
        .build()
        .unwrap();
    let m = re.find("hello").unwrap();
    assert_eq!(m.as_str(), "hello");
}

// =========================================================================
// Coverage-targeted tests: Callout patterns (regexec.rs callout paths)
// =========================================================================

#[test]
fn callout_max_count() {
    // Exercises CALLOUT_BUILTIN_MAX progress/retraction paths
    let re = Regex::new(r"(?:(*MAX{5})a)*").unwrap();
    let m = re.find("aaaaaa").unwrap();
    assert!(m.len() <= 6);
}

#[test]
fn callout_count() {
    // Exercises CALLOUT_BUILTIN_COUNT path
    let re = Regex::new(r"(?:(*COUNT)a)+").unwrap();
    assert!(re.is_match("aaa"));
}

// =========================================================================
// Coverage-targeted tests: Various parser paths (regparse.rs)
// =========================================================================

#[test]
fn possessive_repeat() {
    let re = Regex::new(r"[a-z]++").unwrap();
    assert!(re.is_match("abc"));
}

#[test]
fn named_group_multiple_alternation() {
    // Named groups in alternation
    let re = Regex::new(r"(?<x>a)|(?<x>b)").unwrap();
    assert!(re.is_match("a"));
    assert!(re.is_match("b"));
}

#[test]
fn unicode_property_negated() {
    let re = Regex::new(r"\P{Lu}+").unwrap();
    let m = re.find("ABCdef").unwrap();
    assert_eq!(m.as_str(), "def");
}

#[test]
fn extended_grapheme_cluster() {
    // Exercises EGCB path in unicode/mod.rs
    let re = Regex::new(r"\X").unwrap();
    // Flag emoji: regional indicators
    let m = re.find("🇩🇪x").unwrap();
    assert!(m.len() > 1); // Should match the whole flag as one cluster
}

#[test]
fn word_boundary_types() {
    // Exercises WB algorithm paths including Hebrew, Katakana, ExtendNumLet
    let re = Regex::new(r"\b\w+\b").unwrap();

    // Katakana
    assert!(re.is_match("カタカナ"));

    // Numbers
    let m = re.find("abc123def").unwrap();
    assert_eq!(m.as_str(), "abc123def");
}

#[test]
fn absent_expression() {
    // Exercises absent group compilation in regparse + regcomp
    let re = Regex::new(r"(?~abc)").unwrap();
    let m = re.find("xxabcyy").unwrap();
    assert_eq!(m.as_str(), "xx");
}

#[test]
fn nested_repeat_with_capture() {
    let re = Regex::new(r"((a){2,4}){1,3}").unwrap();
    let m = re.find("aaaa").unwrap();
    assert_eq!(m.as_str(), "aaaa");
}

#[test]
fn character_class_intersection() {
    // Exercises char class intersection parsing
    let re = Regex::new(r"[a-z&&[^aeiou]]+").unwrap();
    let m = re.find("abcde").unwrap();
    assert_eq!(m.as_str(), "bcd");
}

#[test]
fn hex_escape_unicode() {
    let re = Regex::new(r"\x{1F600}").unwrap();
    assert!(re.is_match("😀"));
}

#[test]
fn keep_marker() {
    // \K resets the match start
    let re = Regex::new(r"foo\Kbar").unwrap();
    let m = re.find("foobar").unwrap();
    assert_eq!(m.as_str(), "bar");
}

#[test]
fn atomic_group() {
    let re = Regex::new(r"(?>abc|ab)c").unwrap();
    // "abc" is consumed atomically, then "c" fails → no match for "abc"
    assert!(!re.is_match("abc"));
    assert!(re.is_match("abcc"));
}

#[test]
fn lazy_quantifier_in_capture() {
    let re = Regex::new(r"(a+?)(a+)").unwrap();
    let caps = re.captures("aaaa").unwrap();
    assert_eq!(caps.get(1).unwrap().as_str(), "a");
    assert_eq!(caps.get(2).unwrap().as_str(), "aaa");
}

#[test]
fn char_class_posix() {
    let re = Regex::new(r"[[:upper:]]+").unwrap();
    let m = re.find("abcDEF").unwrap();
    assert_eq!(m.as_str(), "DEF");
}

#[test]
fn non_greedy_repeat() {
    let re = Regex::new(r"<.+?>").unwrap();
    let m = re.find("<a><b>").unwrap();
    assert_eq!(m.as_str(), "<a>");
}

// =========================================================================
// Coverage-targeted: Parser paths (regparse.rs)
// =========================================================================

#[test]
fn quote_literal_syntax() {
    // Exercises \Q...\E literal quoting (TokenType::QuoteOpen) — only in Perl syntax
    use ferroni::regsyntax::OnigSyntaxPerl;
    let re = Regex::builder(r"\Q.+*\E")
        .syntax(&OnigSyntaxPerl)
        .build()
        .unwrap();
    assert!(re.is_match(".+*"));
    assert!(!re.is_match("abc"));
}

#[test]
fn char_class_dash_at_end() {
    // Exercises CC dash handling: [a-z-] → literal dash at end
    let re = Regex::new(r"[a-z-]+").unwrap();
    assert!(re.is_match("abc-"));
    let m = re.find("ABC-def").unwrap();
    assert_eq!(m.as_str(), "-def");
}

#[test]
fn char_class_range_and_dash() {
    // Exercises double-range handling: [0-9-a]
    let re = Regex::new(r"[0-9-a]+").unwrap();
    assert!(re.is_match("5-a"));
}

#[test]
fn named_backref_with_level() {
    // Exercises level syntax parsing in fetch_name: \k<name+1>
    let re = Regex::new(r"(?<a>x)\g<a>\k<a+0>").unwrap();
    assert!(re.is_match("xxx"));
}

#[test]
fn numbered_backref_with_level() {
    // Exercises numeric level backref parsing: \k<1+0>
    let re = Regex::new(r"(x)\g<1>\k<1+0>").unwrap();
    assert!(re.is_match("xxx"));
}

#[test]
fn char_class_negated_intersection() {
    // Exercises negated char class with intersection
    let re = Regex::new(r"[^a-z&&[^m-z]]+").unwrap();
    // [^a-z&&[^m-z]] = not(a-z AND not(m-z)) = not(a-l) = anything except a-l
    assert!(re.is_match("M"));
}

#[test]
fn control_escape_sequences() {
    // Exercises control code syntax path
    let re = Regex::new(r"\ca").unwrap(); // \ca = control-A = 0x01
    assert!(re.is_match("\x01"));
}

#[test]
fn hex_escape_2digit() {
    let re = Regex::new(r"\x41").unwrap(); // 0x41 = 'A'
    assert!(re.is_match("A"));
}

#[test]
fn octal_escape() {
    let re = Regex::new(r"\101").unwrap(); // 0101 octal = 65 = 'A'
    assert!(re.is_match("A"));
}

#[test]
fn backref_with_negative_level() {
    // Exercises level syntax with negative sign: \k<name-1>
    // This tests the level_sign = -1 path
    let re = Regex::new(r"(?<a>(?<b>x)\g<a>|\w)\k<b-0>");
    // Either succeeds or fails at compile — either way exercises the parser
    if let Ok(re) = re {
        let _ = re.is_match("xyx");
    }
}

#[test]
fn unicode_named_property() {
    // Various Unicode property names to exercise property_name_to_ctype
    let re = Regex::new(r"\p{Katakana}+").unwrap();
    assert!(re.is_match("カタカナ"));

    let re = Regex::new(r"\p{Han}+").unwrap();
    assert!(re.is_match("漢字"));
}

#[test]
fn absent_clear_expression() {
    // Exercises absent group range stop: (?~|pattern|absent)
    let re = Regex::new(r"(?~|abc|[a-z]+)");
    if let Ok(re) = re {
        let _ = re.find("xyzabcdef");
    }
}

// =========================================================================
// Coverage-targeted: Compiler paths (regcomp.rs)
// =========================================================================

#[test]
fn alternation_many_branches() {
    // Exercises select_opt_map/trie path in regcomp
    let re = Regex::new(r"apple|banana|cherry|date|elderberry|fig|grape").unwrap();
    assert_eq!(re.find("I like banana").unwrap().as_str(), "banana");
}

#[test]
fn nested_quantifier() {
    // Exercises nested quantifier optimization in regcomp
    let re = Regex::new(r"(a{2,3}){2,4}").unwrap();
    assert!(re.is_match("aaaaaa"));
}

#[test]
fn complex_lookbehind() {
    // Exercises lookbehind compilation with variable-length content
    let re = Regex::new(r"(?<=ab|cd)\w+").unwrap();
    assert_eq!(re.find("cdHello").unwrap().as_str(), "Hello");
}

#[test]
fn case_insensitive_backref() {
    // Exercises BackRefIc opcode generation
    let re = Regex::builder(r"(\w+)\s+\1")
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(re.is_match("Hello HELLO"));
}

#[test]
fn many_capture_groups() {
    // Exercises capture group region handling with many groups
    let re = Regex::new(r"(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)").unwrap();
    let caps = re.captures("abcdefghij").unwrap();
    assert_eq!(caps.len(), 11); // group 0 + 10 captures
    assert_eq!(caps.get(10).unwrap().as_str(), "j");
}

#[test]
fn forward_reference() {
    // Exercises forward backref in parser
    let re = Regex::new(r"(\2?(a))+").unwrap();
    assert!(re.is_match("aaa"));
}

// =========================================================================
// Coverage-targeted: Execution engine paths (regexec.rs)
// =========================================================================

#[test]
fn match_at_end_of_string() {
    let re = Regex::new(r"\w+\z").unwrap();
    let m = re.find("hello world").unwrap();
    assert_eq!(m.as_str(), "world");
}

#[test]
fn empty_match_progression() {
    // Tests empty match handling and advancement logic
    let re = Regex::new(r"(?:)+").unwrap();
    let results: Vec<_> = re.find_iter("ab").collect();
    assert!(!results.is_empty());
}

#[test]
fn long_alternation_literal() {
    // Exercises literal trie optimization in search
    let re = Regex::new(r"cat|car|cap|can|cam|cab").unwrap();
    assert_eq!(re.find("a cab ride").unwrap().as_str(), "cab");
}

#[test]
fn unicode_case_fold_in_char_class_range() {
    // Exercises get_case_fold_codes_by_str for multi-char sequences
    let re = Regex::builder(r"[a-ÿ]+")
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(re.is_match("Ä"));
    assert!(re.is_match("ß"));
}

#[test]
fn word_boundary_at_boundaries() {
    // Exercises edge cases in word boundary checking
    let re = Regex::new(r"\bword\b").unwrap();
    assert!(re.is_match("word"));
    assert!(re.is_match("a word b"));
    assert!(!re.is_match("sword"));
    assert!(!re.is_match("wordy"));
}

#[test]
fn dotall_mode() {
    let re = Regex::builder(r"a.b")
        .dot_matches_newline(true)
        .build()
        .unwrap();
    assert!(re.is_match("a\nb"));
    assert!(re.is_match("a\rb"));
}

#[test]
fn captures_iter_with_optional_groups() {
    let re = Regex::new(r"(?:(a)|(b))+").unwrap();
    let caps = re.captures("abba").unwrap();
    // Groups 1 and 2 alternately match
    assert!(caps.get(0).is_some());
}

// =========================================================================
// Coverage-targeted: Extended grapheme cluster / word break (unicode/mod.rs)
// =========================================================================

#[test]
fn egcb_flag_emoji_sequence() {
    // Regional indicators: 🇩🇪 = U+1F1E9 U+1F1EA
    let re = Regex::new(r"\X+").unwrap();
    let m = re.find("🇩🇪🇫🇷x").unwrap();
    // Each flag pair is one grapheme cluster
    assert!(m.len() > 4);
}

#[test]
fn egcb_zwj_sequence() {
    // ZWJ sequence: 👨‍👩‍👧 (man + ZWJ + woman + ZWJ + girl)
    let re = Regex::new(r"\X").unwrap();
    let m = re.find("👨\u{200D}👩\u{200D}👧x").unwrap();
    // Should match the whole ZWJ family as one grapheme cluster
    assert!(m.len() > 4);
}

#[test]
fn word_boundary_hebrew() {
    // Exercises HebrewLetter WB rules (WB7a, WB7b, WB7c)
    let re = Regex::new(r"\b\w+\b").unwrap();
    assert!(re.is_match("שלום")); // Hebrew "shalom"
}

#[test]
fn word_boundary_regional_indicators() {
    // Exercises WB15/WB16 RI x RI counting
    let re = Regex::new(r"\b.+\b").unwrap();
    let _ = re.find("🇩🇪🇫🇷"); // just exercise the path
}

#[test]
fn word_boundary_extend_num_let() {
    // Exercises WB13a/WB13b ExtendNumLet rules
    // Underscore (U+005F) is ExtendNumLet type
    let re = Regex::new(r"\b\w+\b").unwrap();
    let m = re.find("hello_world").unwrap();
    assert_eq!(m.as_str(), "hello_world"); // underscore connects words
}

// =========================================================================
// Coverage-targeted: Unicode multi-char case folds (unicode/mod.rs)
// =========================================================================

#[test]
fn case_insensitive_2char_fold() {
    // fi (U+FB01) folds to "fi" — exercises folds2 paths (apply_case_fold2, get_case_fold_codes folds2)
    let re = Regex::builder("fi").case_insensitive(true).build().unwrap();
    assert!(re.is_match("fi"));
    assert!(re.is_match("FI"));
}

#[test]
fn case_insensitive_3char_fold() {
    // ffi (U+FB03) folds to "ffi" — exercises folds3 paths
    let re = Regex::builder("ffi")
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(re.is_match("ffi"));
    assert!(re.is_match("FFI"));
}

#[test]
fn case_insensitive_eszett() {
    // ß folds to "ss" — another 2-char fold
    let re = Regex::builder("ss").case_insensitive(true).build().unwrap();
    assert!(re.is_match("ss"));
    assert!(re.is_match("SS"));
    assert!(re.is_match("ß"));
}

#[test]
fn case_insensitive_char_class_with_unicode_folds() {
    // Character class with case-insensitive: exercises get_case_fold_codes_by_str
    let re = Regex::builder("[ß]")
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(re.is_match("ß"));
    assert!(re.is_match("SS")); // ss should match ß case-insensitively
}

#[test]
fn case_insensitive_turkish_dotted_i() {
    // İ (U+0130) and ı (U+0131) — locale-specific fold entries
    let re = Regex::builder("i").case_insensitive(true).build().unwrap();
    assert!(re.is_match("I"));
    assert!(re.is_match("i"));
}

#[test]
fn case_insensitive_full_width() {
    // Full-width letters: A (U+FF21) should fold to a (U+FF41)
    let re = Regex::builder("\u{FF21}")
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(re.is_match("\u{FF21}"));
    assert!(re.is_match("\u{FF41}"));
}

// =========================================================================
// Coverage-targeted: EGCB and WB edge cases (unicode/mod.rs)
// =========================================================================

#[test]
fn egcb_regional_indicator_pairs() {
    // 🇩🇪🇫🇷🇯🇵 = 3 flag sequences, each 2 RI codepoints
    // Exercises BreakUndefRiRi counting
    let re = Regex::new(r"\X").unwrap();
    let input = "🇩🇪🇫🇷🇯🇵";
    let clusters: Vec<_> = re.find_iter(input).collect();
    // Should be 3 grapheme clusters (one per flag)
    assert_eq!(clusters.len(), 3);
}

#[test]
fn wb_midletter_between_letters() {
    // WB6/WB7: AHLetter x (MidLetter|MidNumLetQ) x AHLetter
    // · (U+00B7, MidLetter) between letters should NOT break
    let re = Regex::new(r"\b\w+\b").unwrap();
    // Test with apostrophe (U+2019, MidNumLetQ) in word
    let m = re.find("it's").unwrap();
    assert!(!m.as_str().is_empty());
}

#[test]
fn wb_numeric_sequences() {
    // WB8-WB11: Numeric x Numeric, Numeric x (MidNum|MidNumLetQ) x Numeric
    let re = Regex::new(r"\b[\w.]+\b").unwrap();
    assert!(re.is_match("3.14"));
}

#[test]
fn wb_katakana_extend_num_let() {
    // WB13: Katakana x Katakana + WB13a/b with ExtendNumLet
    let re = Regex::new(r"\b\w+\b").unwrap();
    let m = re.find("カタカナ_テスト").unwrap();
    // Katakana + underscore + Katakana should be one word
    assert_eq!(m.as_str(), "カタカナ_テスト");
}

// =========================================================================
// Coverage-targeted: Perl-style subexpression call syntax (regparse.rs)
// =========================================================================

#[test]
fn perl_named_call_syntax() {
    // (?&name) - named subroutine call (Perl_NG syntax)
    // Exercises ONIG_SYN_OP2_QMARK_PERL_SUBEXP_CALL parser path
    use ferroni::regsyntax::OnigSyntaxPerl_NG;
    let re = Regex::builder(r"(?<d>\d+)x(?&d)")
        .syntax(&OnigSyntaxPerl_NG)
        .build()
        .unwrap();
    assert!(re.is_match("123x456"));
    assert!(!re.is_match("123xabc"));
}

#[test]
fn perl_numbered_subexp_call() {
    // (?1) - absolute numbered call (Perl_NG syntax)
    use ferroni::regsyntax::OnigSyntaxPerl_NG;
    let re = Regex::builder(r"(\d+)-(?1)")
        .syntax(&OnigSyntaxPerl_NG)
        .build()
        .unwrap();
    assert!(re.is_match("123-456"));
}

#[test]
fn perl_relative_subexp_call() {
    // (?-1) - relative backward call (Perl_NG syntax)
    use ferroni::regsyntax::OnigSyntaxPerl_NG;
    let re = Regex::builder(r"(\d+)-(?-1)")
        .syntax(&OnigSyntaxPerl_NG)
        .build()
        .unwrap();
    assert!(re.is_match("42-99"));
}

// =========================================================================
// Coverage-targeted: Meta and control escape sequences (regparse.rs)
// =========================================================================

#[test]
fn ruby_meta_escape() {
    // \M-a sets the high bit: 'a' (0x61) | 0x80 = 0xe1
    // Using new_bytes since \M-a produces a non-UTF8 byte
    use ferroni::regsyntax::OnigSyntaxRuby;
    let re = Regex::builder(r"\M-a")
        .syntax(&OnigSyntaxRuby)
        .build()
        .unwrap();
    // In UTF-8, 0xe1 starts a 3-byte sequence. Test with raw bytes.
    assert!(re.is_match_bytes(&[0xc3, 0xa1])); // UTF-8 for U+00E1 (á)
}

#[test]
fn ruby_control_escape_c_bar() {
    // \C-a = control-A = 0x01
    use ferroni::regsyntax::OnigSyntaxRuby;
    let re = Regex::builder(r"\C-a")
        .syntax(&OnigSyntaxRuby)
        .build()
        .unwrap();
    assert!(re.is_match_bytes(&[0x01]));
}

// =========================================================================
// Coverage-targeted: Variable-length lookbehind (regcomp.rs)
// =========================================================================

#[test]
fn variable_length_lookbehind() {
    // (?<=a|ab) - lookbehind with variable-length alternatives
    let re = Regex::new(r"(?<=a|ab)x").unwrap();
    assert!(re.is_match("ax"));
    assert!(re.is_match("abx"));
    assert!(!re.is_match("bx"));
}

#[test]
fn variable_length_negative_lookbehind() {
    // (?<!ab|abc) - negative lookbehind with variable lengths
    let re = Regex::new(r"(?<!ab|abc)x").unwrap();
    assert!(re.is_match("cx"));
    assert!(!re.is_match("abx"));
}

// =========================================================================
// Coverage-targeted: Subroutine calls in compiler (regcomp.rs)
// =========================================================================

#[test]
fn subroutine_call_with_quantifier() {
    // (?<r>a+)\g<r> - subroutine call re-executes the pattern (not the captured text)
    let re = Regex::new(r"(?<r>a+)\g<r>").unwrap();
    assert!(re.is_match("aaa"));
    assert!(!re.is_match("b"));
}

#[test]
fn subroutine_call_in_if_else() {
    // Conditional pattern with subroutine call in then-branch
    // Exercises tune_called_state for if-else structures
    let re = Regex::new(r"(?<a>x)?(?(<a>)\g<a>|y)").unwrap();
    // When "x" is present, the conditional matches and \g<a> matches another "x"
    assert!(re.is_match("xx"));
    // When no "x", the else branch matches "y"
    assert!(re.is_match("y"));
}

#[test]
fn recursive_capture_group() {
    // Recursive pattern with captures - exercises MemEndPushRec
    let re = Regex::new(r"^(?<r>a(?:\g<r>)?b)$").unwrap();
    assert!(re.is_match("ab"));
    assert!(re.is_match("aabb"));
    assert!(re.is_match("aaabbb"));
    assert!(!re.is_match("aab"));
}

// =========================================================================
// Coverage-targeted: Backref with level syntax (regparse.rs + regcomp.rs)
// =========================================================================

#[test]
fn backref_with_level_named() {
    // \k<name+0> - backreference with explicit level in recursive context
    // In a recursive call, level 0 refers to the current recursion's capture
    let re = Regex::new(r"(?<a>[a-z])(?:\g<a>\k<a+0>)?").unwrap();
    assert!(re.is_match("a"));
    assert!(re.is_match("abc"));
}

// =========================================================================
// Coverage-targeted: WordAsciiStar opcode (regexec.rs)
// =========================================================================

#[test]
fn word_ascii_star_optimization() {
    // (?W)\w* triggers WordAsciiStar opcode (ASCII-only word matching)
    let re = Regex::new(r"(?W)\w*$").unwrap();
    assert!(re.is_match("hello"));
    assert!(re.is_match(""));
}

#[test]
fn word_ascii_star_peek_next_optimization() {
    // (?W)\w*x triggers WordAsciiStarPeekNext opcode
    let re = Regex::new(r"(?W)\w*x").unwrap();
    assert!(re.is_match("abcx"));
    assert!(re.is_match("x"));
    assert!(!re.is_match("abc"));
}

// =========================================================================
// Coverage-targeted: Scanner \G anchor (scanner.rs)
// =========================================================================

#[test]
fn scanner_g_anchor_pattern() {
    use ferroni::scanner::{Scanner, ScannerFindOptions};
    // A scanner with a \G anchor pattern exercises search_g_anchor_with_msa
    let mut scanner = Scanner::new(&[r"\G\w+", r"\s+"]).unwrap();
    let input = "hello world";
    let result = scanner.find_next_match(input, 0, ScannerFindOptions::NONE);
    assert!(result.is_some());
    let m = result.unwrap();
    assert_eq!(m.index, 0); // \G\w+ matches at start
    assert_eq!(m.capture_indices[0].start, 0);
}

// =========================================================================
// Coverage-targeted: Character class with range and dash (regparse.rs)
// =========================================================================

#[test]
fn char_class_dash_in_range_context() {
    // [!--] - dash at end of range (exercises CS_RANGE with dash)
    let re = Regex::new(r"[!--]").unwrap();
    assert!(re.is_match("!"));
    assert!(re.is_match("-"));
    assert!(re.is_match("#"));
    assert!(!re.is_match("0"));
}

#[test]
fn char_class_double_range() {
    // [0-9-a] - double range operator (exercises ALLOW_DOUBLE_RANGE_OP_IN_CC)
    let re = Regex::new(r"[0-9-a]").unwrap();
    assert!(re.is_match("5"));
    assert!(re.is_match("a"));
    assert!(re.is_match("-"));
}

// =========================================================================
// Coverage-targeted: Absent expression (regparse.rs + regcomp.rs)
// =========================================================================

#[test]
fn absent_expression_basic() {
    // (?~|pattern) - absent stopper expression
    let re = Regex::new(r"(?~abc)").unwrap();
    assert!(re.is_match("xyz"));
}

#[test]
fn absent_expression_with_range() {
    // (?~|...) - absent with explicit range
    let re = Regex::new(r"\w+(?~abc)\w+").unwrap();
    assert!(re.is_match("xyzdef"));
}

// =========================================================================
// Coverage-targeted: Conditional with DEFINE (regparse.rs)
// =========================================================================

#[test]
fn conditional_define_pattern() {
    // (?(DEFINE)(?<d>\d+)) - define-only group, not directly matched
    // Uses the defined pattern later via \g<d>
    let re = Regex::new(r"(?(DEFINE)(?<d>\d+))\g<d>-\g<d>").unwrap();
    assert!(re.is_match("123-456"));
    assert!(!re.is_match("abc-def"));
}

// =========================================================================
// Coverage-targeted: Named capture in anchors (regcomp.rs)
// =========================================================================

#[test]
fn named_capture_in_lookahead() {
    // Named capture inside lookahead exercises make_named_capture_number_map
    let re = Regex::new(r"(?=(?<word>\w+))\w+").unwrap();
    let caps = re.captures("hello").unwrap();
    assert_eq!(caps.get(1).unwrap().as_str(), "hello");
}

#[test]
fn named_capture_in_lookbehind() {
    // Named capture inside lookbehind
    let re = Regex::new(r"(?<=(?<prefix>ab))cd").unwrap();
    assert!(re.is_match("abcd"));
}

// =========================================================================
// Coverage-targeted: Infinite recursion check (regcomp.rs)
// =========================================================================

#[test]
fn subroutine_with_alternation_avoids_infinite_recursion() {
    // (?<r>a|b\g<r>c) - recursion in one branch only (valid, not infinite)
    let re = Regex::new(r"(?<r>a|b\g<r>c)").unwrap();
    assert!(re.is_match("a"));
    assert!(re.is_match("bac"));
    assert!(re.is_match("bbaccc")); // not valid - tests recursion depth
}

// =========================================================================
// Coverage-targeted: Literal trie optimization (regcomp.rs)
// =========================================================================

#[test]
fn many_literal_alternatives_trigger_trie() {
    // Many literal alternatives with common prefixes trigger literal trie optimization
    let re = Regex::new(r"abc|abd|abe|abf|abg|abh|abi|abj").unwrap();
    assert!(re.is_match("abc"));
    assert!(re.is_match("abj"));
    assert!(!re.is_match("abz"));
}

#[test]
fn literal_alternatives_preserve_ordered_backtracking() {
    let re = Regex::new(r"(?:foo|foobar|a1|a2|a3|a4|a5|a6)bar").unwrap();
    let matched = re.find("foobar").expect("shorter first branch matches");
    assert_eq!(matched.as_str(), "foobar");

    let ordered = Regex::new(r"foo|foobar|a1|a2|a3|a4|a5|a6").unwrap();
    assert_eq!(ordered.find("foobar").unwrap().as_str(), "foo");
}

#[test]
fn literal_alternatives_preserve_per_branch_case_options() {
    let re = Regex::new(r"(?i)foo|bar|baz|(?-i:QUX)").unwrap();
    assert!(!re.is_match("qux"));
    assert!(re.is_match("QUX"));
}

#[test]
fn case_insensitive_literal_alternatives() {
    // Case-insensitive alternations exercise literal path classification
    let re = Regex::builder("ABC|DEF|GHI|JKL")
        .case_insensitive(true)
        .build()
        .unwrap();
    assert!(re.is_match("abc"));
    assert!(re.is_match("jkl"));
}

// =========================================================================
// Coverage-targeted: API methods (api.rs)
// =========================================================================

#[test]
fn find_iter_bytes_method() {
    // Exercises find_iter_bytes code path
    let re = Regex::new_bytes(b"\\d+").unwrap();
    let matches: Vec<_> = re.find_iter_bytes(b"12 34 56").collect();
    assert_eq!(matches.len(), 3);
    assert_eq!(matches[0].as_bytes(), b"12");
    assert_eq!(matches[2].as_bytes(), b"56");
}

#[test]
fn builder_multi_line_anchors_default_matches_each_line() {
    let re = Regex::builder(r"^b$").build().unwrap();

    assert_eq!(re.find("a\nb\nc").unwrap().as_str(), "b");
}

#[test]
fn builder_multi_line_anchors_true_matches_each_line() {
    let re = Regex::builder(r"^b$")
        .multi_line_anchors(true)
        .build()
        .unwrap();

    assert_eq!(re.find("a\nb\nc").unwrap().as_str(), "b");
}

#[test]
fn builder_multi_line_anchors_false_matches_only_input_boundaries() {
    let re = Regex::builder(r"^b$")
        .multi_line_anchors(false)
        .build()
        .unwrap();

    assert!(re.find("a\nb\nc").is_none());
}

#[test]
fn builder_multi_line_anchors_toggles_without_affecting_other_options() {
    let re = Regex::builder(" ^ a . b $ ")
        .case_insensitive(true)
        .dot_matches_newline(true)
        .extended(true)
        .multi_line_anchors(false)
        .multi_line_anchors(true)
        .multi_line_anchors(true)
        .build()
        .unwrap();

    assert_eq!(re.find("before\nA\nB\nafter").unwrap().as_str(), "A\nB");
}

#[test]
fn builder_multi_line_anchors_overrides_syntax_defaults() {
    use ferroni::regsyntax::{
        OnigSyntaxJava, OnigSyntaxPerl, OnigSyntaxPosixBasic, OnigSyntaxPosixExtended,
    };

    for (name, syntax) in [
        ("Java", &OnigSyntaxJava),
        ("Perl", &OnigSyntaxPerl),
        ("POSIX basic", &OnigSyntaxPosixBasic),
        ("POSIX extended", &OnigSyntaxPosixExtended),
    ] {
        let default = Regex::builder(r"^b$").syntax(syntax).build().unwrap();
        assert!(default.find("a\nb\nc").is_none(), "{name} default");

        let enabled = Regex::builder(r"^b$")
            .syntax(syntax)
            .multi_line_anchors(true)
            .build()
            .unwrap();
        assert_eq!(
            enabled.find("a\nb\nc").unwrap().as_str(),
            "b",
            "{name} enabled"
        );

        let disabled = Regex::builder(r"^b$")
            .syntax(syntax)
            .multi_line_anchors(false)
            .build()
            .unwrap();
        assert!(disabled.find("a\nb\nc").is_none(), "{name} disabled");
    }
}

#[test]
fn captures_len_and_is_empty() {
    // Exercises Captures::len() and is_empty()
    let re = Regex::new(r"(a)(b)(c)").unwrap();
    let caps = re.captures("abc").unwrap();
    assert_eq!(caps.len(), 4); // group 0 + 3 captures
    assert!(!caps.is_empty());
}

#[test]
fn captures_named_group_lookup() {
    // Exercises the named group lookup (captures_by_name path)
    let re = Regex::new(r"(?<year>\d{4})-(?<month>\d{2})").unwrap();
    let caps = re.captures("2024-03").unwrap();
    let year = caps.name("year");
    assert!(year.is_some());
    assert_eq!(year.unwrap().as_str(), "2024");
}

// =========================================================================
// Coverage-targeted: Octal escapes (regparse.rs)
// =========================================================================

#[test]
fn null_byte_octal_escape() {
    // \0 in regex matches null byte - exercises scan_octal_number path
    let re = Regex::new_bytes(b"\\0").unwrap();
    assert!(re.is_match_bytes(&[0x00]));
    assert!(!re.is_match_bytes(&[0x30])); // '0'
}

#[test]
fn ruby_u_hex_escape() {
    // \uXXXX hex escape in Ruby syntax - exercises ESC_U_HEX4 path
    use ferroni::regsyntax::OnigSyntaxRuby;
    let re = Regex::builder(r"\u0041")
        .syntax(&OnigSyntaxRuby)
        .build()
        .unwrap();
    assert!(re.is_match("A")); // U+0041 = 'A'
    assert!(!re.is_match("B"));
}

// =========================================================================
// Coverage-targeted: Non-ASCII escaped char in pattern (regparse.rs)
// =========================================================================

#[test]
fn escaped_non_ascii_literal() {
    // Backslash before a non-ASCII character treats it as literal
    // Exercises the non-ASCII escape fallback path
    let re = Regex::new(r"\ä").unwrap();
    assert!(re.is_match("ä"));
}

// =========================================================================
// Coverage-targeted: Subroutine in lookbehind check (regcomp.rs)
// =========================================================================

#[test]
fn subroutine_call_in_lookbehind_context() {
    // Subroutine call validated inside lookbehind - exercises check_called_node_in_look_behind
    let re = Regex::new(r"(?<d>ab)(?<=\g<d>)x");
    // This may or may not compile depending on lookbehind restrictions
    // Just exercise the validation path
    if let Ok(re) = re {
        let _ = re.is_match("abx");
    }
}

// =========================================================================
// Coverage-targeted: Recursion in alternation check (regcomp.rs)
// =========================================================================

#[test]
fn recursive_pattern_in_alternation() {
    // (?<r>a|b\g<r>c) exercises infinite_recursive_call_check with alternation
    let re = Regex::new(r"^(?<r>a|b\g<r>c)$").unwrap();
    assert!(re.is_match("a"));
    assert!(re.is_match("bac"));
    assert!(re.is_match("bbacc"));
}

// =========================================================================
// Coverage-targeted: Quantifier + subroutine state (regcomp.rs)
// =========================================================================

#[test]
fn subroutine_in_quantifier_state() {
    // Subroutine call inside quantifier exercises tune_called_state_call Quant branch
    let re = Regex::new(r"(?<r>\w)\g<r>{2,5}").unwrap();
    assert!(re.is_match("abcde"));
}

#[test]
fn subroutine_in_lookahead_state() {
    // Subroutine in lookahead exercises tune_called_state_call Anchor branch
    let re = Regex::new(r"(?<d>\d)(?=\g<d>)\d").unwrap();
    assert!(re.is_match("12"));
}

#[test]
fn subroutine_in_negative_lookbehind_state() {
    // Subroutine call in negative lookbehind exercises the state tuning path
    let re = Regex::new(r"(?<d>[a-z]{2})(?<!\g<d>)\d");
    if let Ok(re) = re {
        let _ = re.is_match("ab1");
    }
}

// =========================================================================
// Regression: positions must never leave the haystack (found by fuzzing)
// =========================================================================

#[test]
fn scanner_begin_position_anchor_at_end_of_text_does_not_panic() {
    use ferroni::scanner::{Scanner, ScannerFindOptions};
    // A begin-position anchor narrows the search range to `start + 1`. With
    // `start == text.len()` that range pointed one past the haystack and the
    // position loop subtracted past zero. A TextMate host reaches this
    // position on every line once it has consumed the last character.
    let mut scanner = Scanner::new(&[r"^\G"]).unwrap();
    assert!(
        scanner
            .find_next_match("h", 0, ScannerFindOptions::NONE)
            .is_some()
    );
    assert!(
        scanner
            .find_next_match("h", 1, ScannerFindOptions::NONE)
            .is_none()
    );

    // The same shape with a literal after the anchor exercises the skip
    // needle, whose slice also ran up to the overshooting range.
    let mut scanner = Scanner::new(&[r"^\Ga"]).unwrap();
    assert!(
        scanner
            .find_next_match("a", 1, ScannerFindOptions::NONE)
            .is_none()
    );
}

#[test]
fn search_over_truncated_multibyte_lead_stays_inside_haystack() {
    use ferroni::encodings::utf8::ONIG_ENCODING_UTF8;
    use ferroni::oniguruma::{ONIG_MISMATCH, ONIG_OPTION_NONE, OnigRegion};
    use ferroni::regcomp::onig_new;
    use ferroni::regexec::onig_search;
    use ferroni::regsyntax::OnigSyntaxOniguruma;

    // The byte API accepts arbitrary bytes. 0xE6 announces a three-byte
    // sequence, so stepping over it from position 1 used to land on 4 in a
    // three-byte haystack, and the next attempt indexed past the end.
    let reg = onig_new(
        b"$",
        ONIG_OPTION_NONE,
        &ONIG_ENCODING_UTF8,
        &OnigSyntaxOniguruma,
    )
    .unwrap();
    let haystack: &[u8] = &[0x00, 0xE6, 0xE6];
    for region in [None, Some(OnigRegion::new())] {
        let (position, _) = onig_search(
            &reg,
            haystack,
            haystack.len(),
            0,
            haystack.len(),
            region,
            ONIG_OPTION_NONE,
        );
        // The truncated character is consumed up to the logical end, where `$`
        // matches as it does for any other input.
        assert_eq!(position, haystack.len() as i32);
    }

    // A pattern that cannot match reports a mismatch rather than a panic.
    let reg = onig_new(
        b"x$",
        ONIG_OPTION_NONE,
        &ONIG_ENCODING_UTF8,
        &OnigSyntaxOniguruma,
    )
    .unwrap();
    let (position, _) = onig_search(
        &reg,
        haystack,
        haystack.len(),
        0,
        haystack.len(),
        None,
        ONIG_OPTION_NONE,
    );
    assert_eq!(position, ONIG_MISMATCH);
}

#[test]
fn optimizer_retry_over_truncated_multibyte_lead_stays_inside_haystack() {
    use ferroni::encodings::utf8::ONIG_ENCODING_UTF8;
    use ferroni::oniguruma::{ONIG_MISMATCH, ONIG_OPTION_NONE};
    use ferroni::regcomp::onig_new;
    use ferroni::regexec::onig_search;
    use ferroni::regsyntax::OnigSyntaxOniguruma;

    // `^\s$` is a byte-map search with a begin-line sub-anchor. The map
    // reports the 0xC8 lead byte as a candidate, the sub-anchor rejects it,
    // and the retry used to step two bytes past a two-byte haystack before
    // slicing it for the next map search.
    let reg = onig_new(
        br"^\s$",
        ONIG_OPTION_NONE,
        &ONIG_ENCODING_UTF8,
        &OnigSyntaxOniguruma,
    )
    .unwrap();
    let haystack: &[u8] = &[b'w', 0xC8];
    let (position, _) = onig_search(
        &reg,
        haystack,
        haystack.len(),
        0,
        haystack.len(),
        None,
        ONIG_OPTION_NONE,
    );
    assert_eq!(position, ONIG_MISMATCH);

    // The same retry over valid UTF-8 with a search range that ends inside
    // the haystack; the helpers must answer "not found" for a start past
    // the range instead of slicing it.
    let text = "w\u{3000}\u{3000}\n\u{3000}";
    let (position, _) = onig_search(
        &reg,
        text.as_bytes(),
        text.len(),
        0,
        2,
        None,
        ONIG_OPTION_NONE,
    );
    assert_eq!(position, ONIG_MISMATCH);
}

#[test]
fn stacked_possessive_quantifiers_compile_and_match() {
    use ferroni::encodings::utf8::ONIG_ENCODING_UTF8;
    use ferroni::oniguruma::{ONIG_OPTION_NONE, OnigRegion};
    use ferroni::regcomp::onig_new;
    use ferroni::regexec::onig_search;
    use ferroni::regsyntax::OnigSyntaxPerl_NG;

    // In a syntax where `++` is possessive, every further `+` wraps the
    // previous quantifier in an atomic group and quantifies it again. The
    // compiler used to emit the body twice per level for the mandatory
    // first pass, so 43 stacked `+` asked for gigabytes of bytecode. C jumps
    // into the loop body once the body exceeds the expansion limit.
    let mut pattern = b"un".to_vec();
    pattern.extend(std::iter::repeat_n(b'+', 43));
    pattern.extend_from_slice(b"ct?");

    // The bytecode size itself is asserted by a unit test in regcomp.rs; this
    // test pins the behavior of the compiled program.
    let reg = onig_new(
        &pattern,
        ONIG_OPTION_NONE,
        &ONIG_ENCODING_UTF8,
        &OnigSyntaxPerl_NG,
    )
    .unwrap();

    let haystack = b"xunnnct";
    let (position, region) = onig_search(
        &reg,
        haystack,
        haystack.len(),
        0,
        haystack.len(),
        Some(OnigRegion::new()),
        ONIG_OPTION_NONE,
    );
    assert_eq!(position, 1);
    assert_eq!(region.unwrap().end[0], 7);
}

#[test]
fn left_recursive_subexpression_call_is_rejected_at_compile_time() {
    use ferroni::scanner::Scanner;

    // A whole-pattern call at the head of an alternative re-enters the
    // pattern at the same position without end. C rejects it as never-ending
    // recursion when compiling; the port used to accept it and the matcher
    // then grew its stack until the process ran out of memory.
    assert!(Scanner::new(&["\\g<0>a|b|"]).is_err());
    assert!(Regex::new(r"\g<0>|a").is_err());

    // Recursion after consumed input stays valid.
    let re = Regex::new(r"a\g<0>|b").unwrap();
    assert_eq!(re.find("aab").unwrap().as_str(), "aab");
}

#[test]
fn scanner_reports_the_keep_adjusted_match() {
    use ferroni::scanner::{Scanner, ScannerFindOptions};

    // `\K` moves the match start to where it appears, so the whole match is
    // the region and not the position the winning attempt began at plus the
    // length that attempt reported. Without a capture group the scanner used
    // the position and the length, and reported the attempt's span instead.
    // Every expectation below is C Oniguruma's, taken from its own scanner
    // through the `ffi` feature.
    let spans = |patterns: &[&str], text: &str, position: usize| {
        Scanner::new(patterns)
            .unwrap()
            .find_next_match(text, position, ScannerFindOptions::NONE)
            .map(|m| {
                (
                    m.index,
                    m.capture_indices[0].start,
                    m.capture_indices[0].end,
                )
            })
    };

    assert_eq!(spans(&[r"a\Kb"], "xxabxx", 0), Some((0, 3, 4)));
    // `\K` at the end of the pattern keeps a zero-width match there.
    assert_eq!(spans(&[r"ab\K"], "xxabxx", 0), Some((0, 4, 4)));
    // A capture group already took the region path and stays as it was.
    assert_eq!(spans(&[r"a\K(b)"], "xxabxx", 0), Some((0, 3, 4)));
    // `\K` before anything consumed leaves the match start alone.
    assert_eq!(spans(&[r"\Kab"], "xxabxx", 0), Some((0, 2, 4)));
    // A set of several patterns reports the winner's own kept match.
    assert_eq!(spans(&[r"zz", r"a\Kb"], "xxabxx", 0), Some((1, 3, 4)));

    // Repeated calls from one position hand the scanner over to its cached
    // per-regex route after ROUTE_MIN_SAME_START_FOR_PROBE calls. Both routes
    // report the same match.
    let mut scanner = Scanner::new(&[r"a\Kb"]).unwrap();
    for _ in 0..32 {
        let m = scanner
            .find_next_match_with_id("xxabxx", 1, 0, ScannerFindOptions::NONE)
            .unwrap();
        assert_eq!(
            (m.capture_indices[0].start, m.capture_indices[0].end),
            (3, 4)
        );
    }
}

#[test]
fn scanner_keep_match_stays_on_character_boundaries() {
    use ferroni::scanner::{Scanner, ScannerFindOptions};

    // Minimized from the `scanner-api` fuzz target: the harness derives the
    // pattern `.*\K\u{FFFD}` and the text below from the 11 input bytes
    // `2e 2a 5c 4b b9 00 20 ff ff 61 ff`. `.*` consumes to the end of the
    // line and backtracks, so the winning attempt begins before the match
    // `\K` keeps. The scanner reported that attempt's span, 3..6, which ends
    // inside the trailing replacement character.
    let text = "\u{FFFD}a\u{FFFD}";
    let pattern = format!(".*\\K{}", '\u{FFFD}');
    let mut scanner = Scanner::new(&[pattern.as_str()]).unwrap();

    for position in (0..=text.len()).filter(|p| text.is_char_boundary(*p)) {
        let Some(m) = scanner.find_next_match(text, position, ScannerFindOptions::NONE) else {
            // Only a start past the last replacement character has no match.
            assert_eq!(position, text.len());
            continue;
        };
        let whole = &m.capture_indices[0];
        assert_eq!(
            (whole.start, whole.end),
            (4, 7),
            "match from position {position}"
        );
        assert!(text.is_char_boundary(whole.start) && text.is_char_boundary(whole.end));
    }
}