grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
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
// Project:   grippo
// File:      src/strmatch/dialect.rs
// Purpose:   Pattern and replacement readings other regex dialects expect
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Rewrites applied once at build time so matching pays nothing: ASCII-only
//! `\d \w \s`, ASCII-only case folding of a parsed pattern, Java's `$` and
//! `.`, and the Java reading of a replacement translated to the regex crate's
//! syntax.

use std::borrow::Cow;
use std::fmt::Write as _;

use super::ops::ReplaceError;
use regex_syntax::ast::{
    self, AssertionKind, Ast, ClassAsciiKind, ClassBracketed, ClassSet, ClassSetItem,
    ClassSetRange, ClassSetUnion, ClassUnicodeKind, Group, GroupKind, LiteralKind, Span,
};
use regex_syntax::hir::translate::TranslatorBuilder;
use regex_syntax::hir::{
    Capture, Class, ClassBytes, ClassBytesRange, ClassUnicode, ClassUnicodeRange, Hir, HirKind,
    Look, Repetition,
};

/// Why [`ascii_classes`] refused a pattern.
pub(super) const VERBOSE_REFUSED: &str =
    "verbose mode (the x flag) is not supported with ascii_classes; drop the flag and its comments";

/// Why [`java_line_ends`] refused a multi-line `$`.
pub(super) const MULTILINE_END_REFUSED: &str = "a multi-line `$` can't be read as Java's, which also \
     holds before \\r, U+0085, U+2028 and U+2029: drop the m flag, or build without java_line_end";

/// Why [`java_line_ends`] refused a `$` with more pattern after it.
pub(super) const NOT_LAST_END_REFUSED: &str = "a `$` followed by more pattern that can match \
     text or test a position can't be read at linear cost: end its branch with the \
     `$`, or turn on backtracking (the strmatch-backtracking feature)";

/// Why [`java_line_ends_text`] refused a verbose pattern.
#[cfg(feature = "strmatch-backtracking")]
pub(super) const VERBOSE_END_REFUSED: &str = "verbose mode (the x flag) is not supported with \
     java_line_end on the backtracking tier: drop the flag and its comments";

/// Why [`java_dots_text`] refused a verbose pattern.
#[cfg(feature = "strmatch-backtracking")]
pub(super) const VERBOSE_DOT_REFUSED: &str = "verbose mode (the x flag) is not supported with \
     java_dot on the backtracking tier: drop the flag and its comments";

/// Java's `$` as a lookahead, for the backtracking tier.
#[cfg(feature = "strmatch-backtracking")]
const JAVA_END_LOOKAHEAD: &str = r"(?:\z|(?=(?:\r\n|(?<!\r)\n|[\r\x{85}\x{2028}\x{2029}])\z))";

/// `$` before a final `\n` as a lookahead, for the backtracking tier.
#[cfg(feature = "strmatch-backtracking")]
const LF_END_LOOKAHEAD: &str = r"(?:\z|(?=\n\z))";

/// An ASCII `\b` as lookaround, for the backtracking tier.
pub(super) const WORD_BOUNDARY_LOOKAROUND: &str = r"(?:(?<=(?-i:[0-9A-Za-z_]))(?!(?-i:[0-9A-Za-z_]))|(?<!(?-i:[0-9A-Za-z_]))(?=(?-i:[0-9A-Za-z_])))";

/// An ASCII `\B` as lookaround, for the backtracking tier.
pub(super) const NOT_WORD_BOUNDARY_LOOKAROUND: &str = r"(?:(?<=(?-i:[0-9A-Za-z_]))(?=(?-i:[0-9A-Za-z_]))|(?<!(?-i:[0-9A-Za-z_]))(?!(?-i:[0-9A-Za-z_])))";

/// A pattern in a dialect's syntax, written in the regex crate's.
pub(super) struct Read {
    /// The pattern in the regex crate's syntax.
    pub(super) text: String,
    /// Why the pattern runs only on the backtracking tier, when it does.
    pub(super) backtrack: Option<&'static str>,
}

/// The line terminators a `$` stands before at the end of a haystack.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(super) enum Terminators {
    /// Java's: `\r\n`, `\n` not after `\r`, `\r`, U+0085, U+2028 and U+2029.
    #[default]
    Java,
    /// A final `\n` alone, as PCRE2 reads it with its default newline.
    Lf,
}

impl Terminators {
    /// Where the terminator that ends `hay` starts, or `None` when it ends
    /// in none.
    #[inline]
    pub(super) fn final_in(self, hay: &[u8]) -> Option<usize> {
        match self {
            Self::Java => final_terminator(hay),
            Self::Lf => hay.ends_with(b"\n").then(|| hay.len() - 1),
        }
    }
}

/// Java's `.` without DOTALL, for the backtracking tier.
#[cfg(feature = "strmatch-backtracking")]
const JAVA_DOT_CLASS: &str = r"[^\n\r\x{85}\x{2028}\x{2029}]";

/// The line terminators Java's `.` leaves out besides `\n`.
const DOT_TERMINATORS: [char; 4] = ['\r', '\u{85}', '\u{2028}', '\u{2029}'];

/// Rewrite `\d \D \w \W \s \S` to their ASCII sets, inside a class or out.
///
/// `Err` names the reason when the pattern turns on verbose mode, where a
/// comment can hold an unbalanced bracket this scan would misread.
pub(super) fn ascii_classes(pattern: &str) -> Result<Cow<'_, str>, &'static str> {
    rewrite_text(pattern, |spot| match spot {
        Spot::Escape(c, in_class) => Ok(ascii_set(c, in_class)),
        Spot::Flags(on) if on.contains(&b'x') => Err(VERBOSE_REFUSED),
        _ => Ok(None),
    })
}

/// `pattern` with each `$` read as Java's, for fancy-regex, which has the
/// lookahead the linear engines lack.
///
/// `Err` names the reason when the pattern turns on verbose or multi-line
/// mode.
#[cfg(feature = "strmatch-backtracking")]
pub(super) fn java_line_ends_text(
    pattern: &str,
    terminators: Terminators,
) -> Result<Cow<'_, str>, &'static str> {
    rewrite_text(pattern, |spot| match spot {
        Spot::Dollar => Ok(Some(match terminators {
            Terminators::Java => JAVA_END_LOOKAHEAD,
            Terminators::Lf => LF_END_LOOKAHEAD,
        })),
        Spot::Flags(on) if on.contains(&b'x') => Err(VERBOSE_END_REFUSED),
        Spot::Flags(on) if on.contains(&b'm') && terminators == Terminators::Java => {
            Err(MULTILINE_END_REFUSED)
        }
        _ => Ok(None),
    })
}

/// `pattern` with each `.` read as Java's, for fancy-regex.
///
/// `Err` names the reason when the pattern turns on verbose mode.
#[cfg(feature = "strmatch-backtracking")]
pub(super) fn java_dots_text(pattern: &str) -> Result<Cow<'_, str>, &'static str> {
    rewrite_text(pattern, |spot| match spot {
        Spot::Dot { dot_all: false } => Ok(Some(JAVA_DOT_CLASS)),
        Spot::Flags(on) if on.contains(&b'x') => Err(VERBOSE_DOT_REFUSED),
        _ => Ok(None),
    })
}

/// A place in a pattern's text that a rewrite may replace or refuse.
enum Spot<'p> {
    /// A backslash and the byte after it, and whether it sits in a class.
    Escape(u8, bool),
    /// A `$` outside a class.
    Dollar,
    /// A `.` outside a class, and whether the s flag is on there.
    Dot {
        #[cfg_attr(
            not(feature = "strmatch-backtracking"),
            expect(dead_code, reason = "only the backtracking tier's rewrite reads it")
        )]
        dot_all: bool,
    },
    /// The flags a `(?` turns on: those before any `-`.
    Flags(&'p [u8]),
}

/// `pattern` with each spot `edit` returns text for replaced by that text.
fn rewrite_text<'p>(
    pattern: &'p str,
    mut edit: impl FnMut(Spot<'p>) -> Result<Option<&'static str>, &'static str>,
) -> Result<Cow<'p, str>, &'static str> {
    let b = pattern.as_bytes();
    let mut out = String::new();
    let mut copied = 0;
    let mut depth = 0_usize;
    // The s flag, and its value outside each open group: a flag group such
    // as `(?s)` holds to the end of the group it sits in.
    let mut dot_all = false;
    let mut outer: Vec<bool> = Vec::new();
    let mut i = 0;
    while i < b.len() {
        let (spot, width) = match b[i] {
            b'\\' => {
                let Some(&c) = b.get(i + 1) else { break };
                (Some(Spot::Escape(c, depth > 0)), 2)
            }
            b'[' => {
                depth += 1;
                i += 1;
                if b.get(i) == Some(&b'^') {
                    i += 1;
                }
                // A `]` first in a class is a literal.
                if b.get(i) == Some(&b']') {
                    i += 1;
                }
                continue;
            }
            b']' if depth > 0 => {
                depth -= 1;
                (None, 1)
            }
            b'(' if depth == 0 => {
                outer.push(dot_all);
                if b.get(i + 1) != Some(&b'?') {
                    i += 1;
                    continue;
                }
                let (on, off, rest) = flag_runs(&b[i + 2..]);
                edit(Spot::Flags(on))?;
                if on.contains(&b's') {
                    dot_all = true;
                }
                if off.contains(&b's') {
                    dot_all = false;
                }
                // A flag group such as `(?s)` opens no group, so its `)` is
                // read here and never closes the group it sits in.
                if rest.first() == Some(&b')') {
                    outer.pop();
                    (None, b.len() - i - rest.len() + 1)
                } else {
                    (None, 2)
                }
            }
            b')' if depth == 0 => {
                if let Some(was) = outer.pop() {
                    dot_all = was;
                }
                (None, 1)
            }
            b'$' if depth == 0 => (Some(Spot::Dollar), 1),
            b'.' if depth == 0 => (Some(Spot::Dot { dot_all }), 1),
            _ => (None, 1),
        };
        if let Some(spot) = spot
            && let Some(with) = edit(spot)?
        {
            out.push_str(&pattern[copied..i]);
            out.push_str(with);
            copied = i + width;
        }
        i += width;
    }
    if copied == 0 {
        return Ok(Cow::Borrowed(pattern));
    }
    out.push_str(&pattern[copied..]);
    Ok(Cow::Owned(out))
}

/// The flags after a `(?`, split into those turned on, those turned off after
/// a `-`, and the text after them.
fn flag_runs(text: &[u8]) -> (&[u8], &[u8], &[u8]) {
    let letters = |t: &[u8]| t.iter().take_while(|f| f.is_ascii_alphabetic()).count();
    let (on, rest) = text.split_at(letters(text));
    match rest.split_first() {
        Some((b'-', after)) => {
            let (off, rest) = after.split_at(letters(after));
            (on, off, rest)
        }
        _ => (on, &[], rest),
    }
}

/// The ASCII set for a Perl class letter, in the form its position needs.
pub const fn ascii_set(letter: u8, in_class: bool) -> Option<&'static str> {
    Some(match (letter, in_class) {
        (b'd', false) => "[0-9]",
        (b'd', true) => "0-9",
        (b'w', false) => "[0-9A-Za-z_]",
        (b'w', true) => "0-9A-Za-z_",
        (b's', false) => r"[\t\n\x0B\x0C\r ]",
        (b's', true) => r"\t\n\x0B\x0C\r ",
        (b'D', _) => "[^0-9]",
        (b'W', _) => "[^0-9A-Za-z_]",
        (b'S', _) => r"[^\t\n\x0B\x0C\r ]",
        _ => return None,
    })
}

/// `pattern` parsed for the engines, read the ways `reading` asks.
pub(super) fn parse(pattern: &str, reading: Reading) -> Result<Hir, Box<regex_syntax::Error>> {
    read(pattern, reading, false)
}

/// How [`parse`] reads a pattern beyond the regex crate's syntax.
#[derive(Debug, Clone, Copy)]
pub(super) struct Reading {
    /// Every ASCII letter also matches its other case, and nothing else
    /// folds, the reading aho-corasick's `ascii_case_insensitive` gives. The
    /// fold is applied before translation, so a negated class folds before it
    /// negates, as `(?i)` does: `[^a]` matches neither `a` nor `A`.
    pub(super) fold: bool,
    /// Each `.` without the s flag leaves out Java's line terminators.
    pub(super) java_dot: bool,
    /// The terminators a `$` stands before.
    pub(super) terminators: Terminators,
    /// `\r\n`, `\n` and a lone `\r` end a line, as the regex crate's `(?R)`
    /// flag reads them: `.` leaves out `\r` and `\n`, and a multi-line `^`
    /// and `$` never hold between the two bytes of a `\r\n`.
    pub(super) crlf: bool,
}

fn read(
    pattern: &str,
    reading: Reading,
    mark_dollars: bool,
) -> Result<Hir, Box<regex_syntax::Error>> {
    let mut ast = parse_ast(pattern)?;
    if reading.fold {
        fold_ast(&mut ast, pattern);
    }
    if reading.java_dot {
        mark(&mut ast, DOT_MARK, &|a| matches!(a, Ast::Dot(_)));
    }
    if mark_dollars {
        mark(
            &mut ast,
            MARK,
            &|a| matches!(a, Ast::Assertion(x) if x.kind == AssertionKind::EndLine),
        );
    }
    let hir = translate(pattern, &ast, reading.crlf)?;
    if !reading.java_dot {
        return Ok(hir);
    }
    Ok(rebuild(&hir, &|c, sub| {
        if c.index == DOT_MARK {
            java_dot(sub)
        } else {
            Hir::capture(Capture {
                index: c.index,
                name: c.name.clone(),
                sub: Box::new(sub),
            })
        }
    }))
}

/// `dot`, a translated `.`, without Java's line terminators, unless it
/// matches `\n` as the s flag makes it. A byte-level `.` leaves out `\r`.
fn java_dot(dot: Hir) -> Hir {
    match dot.kind() {
        HirKind::Class(Class::Unicode(set))
            if !set
                .ranges()
                .iter()
                .any(|r| r.start() <= '\n' && '\n' <= r.end()) =>
        {
            let mut set = set.clone();
            set.difference(&ClassUnicode::new(
                DOT_TERMINATORS.map(|c| ClassUnicodeRange::new(c, c)),
            ));
            Hir::class(Class::Unicode(set))
        }
        HirKind::Class(Class::Bytes(set))
            if !set
                .ranges()
                .iter()
                .any(|r| r.start() <= b'\n' && b'\n' <= r.end()) =>
        {
            let mut set = set.clone();
            set.difference(&ClassBytes::new([ClassBytesRange::new(b'\r', b'\r')]));
            Hir::class(Class::Bytes(set))
        }
        _ => dot,
    }
}

fn parse_ast(pattern: &str) -> Result<Ast, Box<regex_syntax::Error>> {
    ast::parse::Parser::new()
        .parse(pattern)
        .map_err(|e| Box::new(e.into()))
}

/// The translation `regex_syntax::ParserBuilder` makes with `utf8(false)`, and
/// `crlf` set when asked.
fn translate(pattern: &str, ast: &Ast, crlf: bool) -> Result<Hir, Box<regex_syntax::Error>> {
    TranslatorBuilder::new()
        .utf8(false)
        .crlf(crlf)
        .build()
        .translate(pattern, ast)
        .map_err(|e| Box::new(e.into()))
}

/// The capture index a `$` is wrapped in to find it again after translation,
/// where `$` and `\z` are both `Look::End`. No pattern reaches it.
const MARK: u32 = u32::MAX;

/// The capture index a `.` is wrapped in, to read after translation whether
/// the s flag was on, which `.` and `[^\n]` can't otherwise show.
const DOT_MARK: u32 = u32::MAX - 1;

/// What stops [`java_line_ends`] reading a pattern.
pub(super) enum EndRefusal {
    /// The pattern doesn't parse.
    Syntax(Box<regex_syntax::Error>),
    /// A `$` has more pattern after it that matches text or tests a position.
    NotLast,
    /// A `$` is multi-line.
    Multiline,
}

/// A pattern with each `$` found, to read as Java's.
pub(super) struct JavaEnds {
    /// The pattern, each `$` wrapped in a group of index [`MARK`].
    hir: Hir,
    /// The terminators each `$` stands before.
    pub(super) terminators: Terminators,
    /// How many `$` it has.
    pub(super) count: usize,
}

/// The `$` of `pattern`, read the ways `reading` asks. `None` when it has
/// none.
///
/// Java's `$` holds at the end and before a line terminator that ends the
/// haystack. With nothing after it that reads the haystack, it reads as an
/// optional terminator then `\z`, the terminator marked so the match ends
/// before it. Anything after it that matches text or tests a position would
/// see the terminator consumed, so that form, and a multi-line `$`, is
/// refused.
pub(super) fn java_line_ends(
    pattern: &str,
    reading: Reading,
) -> Result<Option<JavaEnds>, EndRefusal> {
    let hir = read(pattern, reading, true).map_err(EndRefusal::Syntax)?;
    let mut count = 0;
    check_ends(&hir, false, &mut count)?;
    Ok((count > 0).then_some(JavaEnds {
        hir,
        terminators: reading.terminators,
        count,
    }))
}

impl JavaEnds {
    /// The pattern with each `$` read as Java's, its terminator in group
    /// `marker`, the pattern's own groups kept or dropped.
    pub(super) fn rewrite(&self, marker: u32, keep_groups: bool) -> Hir {
        rewrite_ends(&self.hir, marker, keep_groups, self.terminators)
    }
}

/// Wrap each node `hit` picks in a group of capture index `index`.
fn mark(node: &mut Ast, index: u32, hit: &impl Fn(&Ast) -> bool) {
    if hit(node) {
        let span = *node.span();
        let inner = std::mem::replace(node, Ast::empty(span));
        *node = Ast::group(Group {
            span,
            kind: GroupKind::CaptureIndex(index),
            ast: Box::new(inner),
        });
        return;
    }
    match node {
        Ast::Repetition(r) => mark(&mut r.ast, index, hit),
        Ast::Group(g) => mark(&mut g.ast, index, hit),
        Ast::Alternation(a) => a.asts.iter_mut().for_each(|n| mark(n, index, hit)),
        Ast::Concat(c) => c.asts.iter_mut().for_each(|n| mark(n, index, hit)),
        _ => {}
    }
}

/// `hir` rebuilt with each capture replaced by what `capture` makes of it and
/// its rebuilt sub.
fn rebuild(hir: &Hir, capture: &impl Fn(&Capture, Hir) -> Hir) -> Hir {
    match hir.kind() {
        HirKind::Capture(c) => capture(c, rebuild(&c.sub, capture)),
        HirKind::Concat(parts) => Hir::concat(parts.iter().map(|p| rebuild(p, capture)).collect()),
        HirKind::Alternation(branches) => {
            Hir::alternation(branches.iter().map(|b| rebuild(b, capture)).collect())
        }
        HirKind::Repetition(r) => Hir::repetition(Repetition {
            min: r.min,
            max: r.max,
            greedy: r.greedy,
            sub: Box::new(rebuild(&r.sub, capture)),
        }),
        HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => hir.clone(),
    }
}

/// Count the marked `$`, refusing one `followed` by something that reads the
/// haystack after it, or one the m flag made multi-line.
fn check_ends(hir: &Hir, followed: bool, count: &mut usize) -> Result<(), EndRefusal> {
    match hir.kind() {
        HirKind::Capture(c) if c.index == MARK => match c.sub.kind() {
            HirKind::Look(Look::End) if followed => Err(EndRefusal::NotLast),
            HirKind::Look(Look::End) => {
                *count += 1;
                Ok(())
            }
            _ => Err(EndRefusal::Multiline),
        },
        HirKind::Capture(c) => check_ends(&c.sub, followed, count),
        HirKind::Concat(parts) => {
            let mut followed = followed;
            for part in parts.iter().rev() {
                check_ends(part, followed, count)?;
                followed |= reads_on(part);
            }
            Ok(())
        }
        HirKind::Alternation(branches) => branches
            .iter()
            .try_for_each(|b| check_ends(b, followed, count)),
        HirKind::Repetition(r) => {
            let again = r.max.is_none_or(|max| max > 1) && reads_on(&r.sub);
            check_ends(&r.sub, followed || again, count)
        }
        HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => Ok(()),
    }
}

/// Whether `hir`, after a `$` that consumed the terminator, would answer
/// differently from Java, where the `$` consumed nothing: it can match text,
/// or it asserts anything but another `$`.
fn reads_on(hir: &Hir) -> bool {
    hir.properties().maximum_len() != Some(0)
        || (!hir.properties().look_set().is_empty() && asserts(hir))
}

fn asserts(hir: &Hir) -> bool {
    match hir.kind() {
        HirKind::Look(_) => true,
        HirKind::Capture(c) => c.index != MARK && asserts(&c.sub),
        HirKind::Concat(parts) | HirKind::Alternation(parts) => parts.iter().any(asserts),
        HirKind::Repetition(r) => asserts(&r.sub),
        HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) => false,
    }
}

fn rewrite_ends(hir: &Hir, marker: u32, keep: bool, terminators: Terminators) -> Hir {
    rebuild(hir, &|c, sub| {
        if c.index == MARK {
            java_end(marker, terminators)
        } else if keep {
            Hir::capture(Capture {
                index: c.index,
                name: c.name.clone(),
                sub: Box::new(sub),
            })
        } else {
            sub
        }
    })
}

/// `(T)?\z`, with T in group `marker`: the terminators Java's `$` stands
/// before. `\n` needs no `\r` before it, as Java's `$` never holds between the
/// two, which `Look::EndCRLF` checks.
fn java_end(marker: u32, terminators: Terminators) -> Hir {
    let terminator = match terminators {
        Terminators::Java => Hir::alternation(vec![
            Hir::literal(*b"\r\n"),
            Hir::literal(*b"\r"),
            Hir::concat(vec![Hir::look(Look::EndCRLF), Hir::literal(*b"\n")]),
            Hir::literal("\u{85}".as_bytes()),
            Hir::literal("\u{2028}".as_bytes()),
            Hir::literal("\u{2029}".as_bytes()),
        ]),
        Terminators::Lf => Hir::literal(*b"\n"),
    };
    let group = Hir::capture(Capture {
        index: marker,
        name: None,
        sub: Box::new(terminator),
    });
    Hir::concat(vec![
        Hir::repetition(Repetition {
            min: 0,
            max: Some(1),
            greedy: true,
            sub: Box::new(group),
        }),
        Hir::look(Look::End),
    ])
}

/// Where the line terminator that ends `hay` starts, as Java's `$` reads one,
/// or `None` when it ends in none. `\r\n` is one terminator. U+0085, U+2028
/// and U+2029 count in UTF-8 only.
#[inline]
pub(super) fn final_terminator(hay: &[u8]) -> Option<usize> {
    let n = hay.len();
    match hay.last()? {
        b'\n' if n >= 2 && hay[n - 2] == b'\r' => Some(n - 2),
        b'\n' | b'\r' => Some(n - 1),
        0x85 if hay[..n - 1].ends_with(&[0xC2]) => Some(n - 2),
        0xA8 | 0xA9 if hay[..n - 1].ends_with(&[0xE2, 0x80]) => Some(n - 3),
        _ => None,
    }
}

fn fold_ast(node: &mut Ast, pattern: &str) {
    match node {
        Ast::Literal(lit) if lit.c.is_ascii_alphabetic() => {
            let span = lit.span;
            *node = Ast::class_bracketed(ClassBracketed {
                span,
                negated: false,
                kind: ClassSet::Item(both_cases(lit)),
            });
        }
        Ast::ClassBracketed(class) => fold_set(&mut class.kind, pattern),
        Ast::ClassUnicode(class) => {
            if let Some(folded) = fold_unicode(class, pattern) {
                *node = Ast::class_bracketed(folded);
            }
        }
        Ast::Repetition(r) => fold_ast(&mut r.ast, pattern),
        Ast::Group(g) => fold_ast(&mut g.ast, pattern),
        Ast::Alternation(a) => a.asts.iter_mut().for_each(|n| fold_ast(n, pattern)),
        Ast::Concat(c) => c.asts.iter_mut().for_each(|n| fold_ast(n, pattern)),
        _ => {}
    }
}

fn fold_set(set: &mut ClassSet, pattern: &str) {
    match set {
        ClassSet::Item(item) => fold_item(item, pattern),
        ClassSet::BinaryOp(op) => {
            fold_set(&mut op.lhs, pattern);
            fold_set(&mut op.rhs, pattern);
        }
    }
}

fn fold_item(item: &mut ClassSetItem, pattern: &str) {
    match item {
        ClassSetItem::Literal(lit) if lit.c.is_ascii_alphabetic() => {
            *item = both_cases(lit);
        }
        ClassSetItem::Range(range) => {
            let extra: Vec<ClassSetItem> =
                other_case(u32::from(range.start.c), u32::from(range.end.c))
                    .map(|(a, z)| range_item(range.span, a, z))
                    .collect();
            if !extra.is_empty() {
                let mut items = vec![ClassSetItem::Range(range.clone())];
                items.extend(extra);
                *item = ClassSetItem::Union(ClassSetUnion {
                    span: range.span,
                    items,
                });
            }
        }
        ClassSetItem::Ascii(ascii) => {
            if matches!(ascii.kind, ClassAsciiKind::Upper | ClassAsciiKind::Lower) {
                ascii.kind = ClassAsciiKind::Alpha;
            }
        }
        ClassSetItem::Unicode(class) => {
            if let Some(folded) = fold_unicode(class, pattern) {
                *item = ClassSetItem::Bracketed(Box::new(folded));
            }
        }
        ClassSetItem::Bracketed(class) => fold_set(&mut class.kind, pattern),
        ClassSetItem::Union(union) => union.items.iter_mut().for_each(|i| fold_item(i, pattern)),
        _ => {}
    }
}

/// `lit` and its other case, as one class item.
fn both_cases(lit: &ast::Literal) -> ClassSetItem {
    let mut other = lit.clone();
    other.kind = LiteralKind::Verbatim;
    other.c = if lit.c.is_ascii_lowercase() {
        lit.c.to_ascii_uppercase()
    } else {
        lit.c.to_ascii_lowercase()
    };
    ClassSetItem::Union(ClassSetUnion {
        span: lit.span,
        items: vec![
            ClassSetItem::Literal(lit.clone()),
            ClassSetItem::Literal(other),
        ],
    })
}

fn range_item(span: Span, a: u8, z: u8) -> ClassSetItem {
    let literal = |c: u8| ast::Literal {
        span,
        kind: LiteralKind::Verbatim,
        c: char::from(c),
    };
    ClassSetItem::Range(ClassSetRange {
        span,
        start: literal(a),
        end: literal(z),
    })
}

/// A Unicode class with the other case of its ASCII letters added, negated
/// after the fold when the class is. `None` when it holds no ASCII letter.
fn fold_unicode(class: &ast::ClassUnicode, pattern: &str) -> Option<ClassBracketed> {
    let mut positive = class.clone();
    positive.negated = false;
    if matches!(
        positive.kind,
        ClassUnicodeKind::NamedValue {
            op: ast::ClassUnicodeOpKind::NotEqual,
            ..
        }
    ) {
        return None;
    }
    let text = &pattern[class.span.start.offset..class.span.end.offset];
    let parsed = regex_syntax::ParserBuilder::new()
        .build()
        .parse(text)
        .ok()?;
    let HirKind::Class(Class::Unicode(mut set)) = parsed.into_kind() else {
        return None;
    };
    if class.negated {
        set.negate();
    }
    let extra: Vec<ClassSetItem> = set
        .iter()
        .flat_map(|r| other_case(u32::from(r.start()), u32::from(r.end())))
        .map(|(a, z)| range_item(class.span, a, z))
        .collect();
    if extra.is_empty() {
        return None;
    }
    let mut items = vec![ClassSetItem::Unicode(positive)];
    items.extend(extra);
    Some(ClassBracketed {
        span: class.span,
        negated: class.negated,
        kind: ClassSet::Item(ClassSetItem::Union(ClassSetUnion {
            span: class.span,
            items,
        })),
    })
}

/// The ASCII letters inside `lo..=hi`, as the other case's range.
fn other_case(lo: u32, hi: u32) -> impl Iterator<Item = (u8, u8)> {
    [
        (u32::from(b'a'), u32::from(b'z')),
        (u32::from(b'A'), u32::from(b'Z')),
    ]
    .into_iter()
    .filter_map(move |(a, z)| {
        let (from, to) = (lo.max(a), hi.min(z));
        let from = u8::try_from(from).ok()?;
        let to = u8::try_from(to).ok()?;
        (from <= to).then_some((from ^ 0x20, to ^ 0x20))
    })
}

/// A Java `Matcher.replaceAll` replacement, written in the regex crate's
/// syntax for a pattern with `group_len` groups counting group 0.
///
/// Where Java throws (a group that doesn't exist, a bare `$`, a trailing
/// backslash) the text is kept as written, and a missing group writes nothing.
pub(super) fn java_replacement(text: &[u8], group_len: usize) -> Vec<u8> {
    let mut out: Vec<u8> = Vec::with_capacity(text.len() + 8);
    let mut i = 0;
    while i < text.len() {
        match text[i] {
            b'\\' => {
                match text.get(i + 1) {
                    Some(b'$') => out.extend_from_slice(b"$$"),
                    Some(&c) => out.push(c),
                    None => out.push(b'\\'),
                }
                i += 2;
            }
            b'$' => i = java_reference(text, i + 1, group_len, &mut out),
            c => {
                out.push(c);
                i += 1;
            }
        }
    }
    out
}

/// The first place Java's `Matcher.replaceAll` throws on `text`, for a
/// pattern with `group_len` groups counting group 0 and `named` saying
/// whether a group has a name.
pub(super) fn java_replacement_check(
    text: &[u8],
    group_len: usize,
    named: impl Fn(&str) -> bool,
) -> Result<(), ReplaceError> {
    let mut i = 0;
    while i < text.len() {
        i = match text[i] {
            b'\\' if i + 1 == text.len() => return Err(ReplaceError::TrailingBackslash { at: i }),
            b'\\' => i + 2,
            b'$' => java_reference_check(text, i, group_len, &named)?,
            _ => i + 1,
        };
    }
    Ok(())
}

/// Check the reference after the `$` at `at`, returning where the text
/// resumes. Digits after the first extend the number or are text, as Java
/// reads them, so neither throws.
fn java_reference_check(
    text: &[u8],
    at: usize,
    group_len: usize,
    named: &impl Fn(&str) -> bool,
) -> Result<usize, ReplaceError> {
    match text.get(at + 1) {
        None => Err(ReplaceError::MissingGroup { at }),
        Some(d) if d.is_ascii_digit() => {
            let number = usize::from(d - b'0');
            if number < group_len {
                Ok(at + 2)
            } else {
                Err(ReplaceError::NoGroup { number, at })
            }
        }
        Some(b'{') => {
            let name = &text[at + 2..];
            let name = &name[..name
                .iter()
                .take_while(|c| c.is_ascii_alphanumeric())
                .count()];
            let close = at + 2 + name.len();
            if !name.first().is_some_and(u8::is_ascii_alphabetic) || text.get(close) != Some(&b'}')
            {
                return Err(ReplaceError::BadName { at });
            }
            let name = String::from_utf8_lossy(name);
            if named(&name) {
                Ok(close + 1)
            } else {
                Err(ReplaceError::NoGroupNamed {
                    name: name.into_owned(),
                    at,
                })
            }
        }
        Some(_) => Err(ReplaceError::IllegalReference { at }),
    }
}

/// Read the reference after a `$` at `at`, returning where the text resumes.
fn java_reference(text: &[u8], at: usize, group_len: usize, out: &mut Vec<u8>) -> usize {
    match text.get(at) {
        Some(d) if d.is_ascii_digit() => {
            // The first digit always binds. Java keeps taking digits while the
            // number still names a group it has.
            let mut number = usize::from(d - b'0');
            let mut end = at + 1;
            while let Some(next) = text.get(end).filter(|c| c.is_ascii_digit()) {
                let longer = number * 10 + usize::from(next - b'0');
                if longer >= group_len {
                    break;
                }
                number = longer;
                end += 1;
            }
            out.extend_from_slice(b"${");
            out.extend_from_slice(&text[at..end]);
            out.push(b'}');
            end
        }
        Some(b'{') => {
            let name_len = text[at + 1..]
                .iter()
                .take_while(|c| c.is_ascii_alphanumeric() || **c == b'_')
                .count();
            let close = at + 1 + name_len;
            if name_len > 0 && text.get(close) == Some(&b'}') {
                out.extend_from_slice(&text[at - 1..=close]);
                close + 1
            } else {
                out.extend_from_slice(b"$$");
                at
            }
        }
        _ => {
            out.extend_from_slice(b"$$");
            at
        }
    }
}

/// Java's `\h`, the horizontal whitespace, as the inside of a class.
const JAVA_H: &str = r"\x20\t\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{202F}\x{205F}\x{3000}";

/// Java's `\v`, the vertical whitespace, as the inside of a class.
const JAVA_V: &str = r"\n\x0B\f\r\x85\x{2028}\x{2029}";

/// Java's `\R`: `\r\n`, else one character of `\v`, tried in that order.
const JAVA_LINEBREAK: &str = r"(?:\r\n|[\n\x0B\f\r\x85\x{2028}\x{2029}])";

/// Java's POSIX property names, each ASCII-only as Java reads them, and the
/// regex crate's ASCII class of the same set.
const JAVA_POSIX: [(&str, &str); 13] = [
    ("Lower", "lower"),
    ("Upper", "upper"),
    ("ASCII", "ascii"),
    ("Alpha", "alpha"),
    ("Digit", "digit"),
    ("Alnum", "alnum"),
    ("Punct", "punct"),
    ("Graph", "graph"),
    ("Print", "print"),
    ("Blank", "blank"),
    ("Cntrl", "cntrl"),
    ("XDigit", "xdigit"),
    ("Space", "space"),
];

/// The Unicode general categories both engines name the same way. `Cs` is
/// left out, as no UTF-8 text holds a surrogate.
pub(super) const JAVA_CATEGORIES: &[&str] = &[
    "L", "Lu", "Ll", "Lt", "Lm", "Lo", "M", "Mn", "Mc", "Me", "N", "Nd", "Nl", "No", "P", "Pc",
    "Pd", "Ps", "Pe", "Pi", "Pf", "Po", "S", "Sm", "Sc", "Sk", "So", "Z", "Zs", "Zl", "Zp", "C",
    "Cc", "Cf", "Co", "Cn",
];

/// The Unicode scripts read by name, which Java matches without regard to
/// case.
pub(super) const JAVA_SCRIPTS: &[&str] = &[
    "Arabic",
    "Armenian",
    "Bengali",
    "Bopomofo",
    "Cherokee",
    "Common",
    "Cyrillic",
    "Devanagari",
    "Ethiopic",
    "Georgian",
    "Greek",
    "Gujarati",
    "Gurmukhi",
    "Han",
    "Hangul",
    "Hebrew",
    "Hiragana",
    "Inherited",
    "Kannada",
    "Katakana",
    "Khmer",
    "Lao",
    "Latin",
    "Malayalam",
    "Mongolian",
    "Myanmar",
    "Oriya",
    "Sinhala",
    "Syriac",
    "Tamil",
    "Telugu",
    "Thaana",
    "Thai",
    "Tibetan",
    "Yi",
];

/// Why a pattern with a leading `(?i)` and a property class is refused.
const FOLD_PROPERTY: &str = "under Java's (?i) a \\p{...} class takes the other cases of its \
     members, which isn't read: drop the (?i) or the \\p{...}";

/// How deep groups and classes may nest, so reading a pattern can't run out
/// of stack.
pub(super) const NEST_LIMIT: usize = 128;

/// Why a pattern nested past [`NEST_LIMIT`] is refused.
pub(super) const TOO_DEEP: &str = "groups and classes nested more than 128 deep";

/// Why a repeated `\R` is refused: Java repeats it without giving back the
/// `\n` of a `\r\n` it took, which only an atomic group reads.
pub(super) const LINEBREAK_REPEATED: &str = "a repeated Java \\R, alone or in a group, which never \
     gives back the \\n of a \\r\\n it took";

/// Why a pattern whose empty match a non-empty one may follow is refused.
pub(super) const EMPTY_RETRY: &str = "a pattern that can match empty and has a lazy repeat or \
     an alternation with an empty branch before another, where PCRE2 and Python look for a \
     non-empty match at the place an empty one was found: make the pattern need at least one \
     character";

/// Whether `hir` has a lazy repeat that may match nothing before text, or an
/// alternation with an empty-capable branch before one that reads text, where
/// a search that gave an empty match could still give a longer one at the same
/// place.
pub(super) fn empty_retry(hir: &Hir) -> bool {
    let reads = |h: &Hir| h.properties().maximum_len() != Some(0);
    match hir.kind() {
        HirKind::Repetition(r) => (!r.greedy && r.min == 0 && reads(&r.sub)) || empty_retry(&r.sub),
        HirKind::Alternation(branches) => {
            let empty_then_reads = branches.iter().enumerate().any(|(i, b)| {
                b.properties().minimum_len() == Some(0) && branches[i + 1..].iter().any(reads)
            });
            empty_then_reads || branches.iter().any(empty_retry)
        }
        HirKind::Capture(c) => empty_retry(&c.sub),
        HirKind::Concat(parts) => parts.iter().any(empty_retry),
        HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => false,
    }
}

/// Why a possessive quantifier needs the backtracking tier.
pub(super) const POSSESSIVE: &str = "a possessive quantifier, *+ ++ ?+ or {n,m}+, runs only on the \
     backtracking tier: turn on StrMatcherBuilder::backtracking (the strmatch-backtracking \
     feature)";

/// Why an atomic group needs the backtracking tier.
pub(super) const ATOMIC: &str = "an atomic group, (?>...), runs only on the backtracking tier: turn on \
     StrMatcherBuilder::backtracking (the strmatch-backtracking feature)";

/// Why lookaround needs the backtracking tier.
pub(super) const LOOKAROUND: &str = "lookaround, (?=...) (?!...) (?<=...) (?<!...), runs only on the \
     backtracking tier: turn on StrMatcherBuilder::backtracking (the strmatch-backtracking \
     feature)";

/// Why a backreference needs the backtracking tier.
pub(super) const BACKREFERENCE: &str = "a backreference, \\1 or \\k<name>, runs only on the backtracking \
     tier: turn on StrMatcherBuilder::backtracking (the strmatch-backtracking feature)";

/// A Java pattern in the regex crate's syntax, and what the rest of the build
/// needs to read it as Java does.
pub(super) struct JavaPattern {
    /// The pattern in the regex crate's syntax.
    pub(super) text: String,
    /// A leading `(?i)` asked for Java's ASCII-only case folding.
    pub(super) fold: bool,
    /// Why the pattern runs only on the backtracking tier, when it does.
    pub(super) backtrack: Option<&'static str>,
}

/// `pattern` in Java's syntax rewritten to the regex crate's.
///
/// The pass reads an allowlist of Java's grammar: literals, the escapes Java
/// and the regex crate share or that have a rewrite, classes without the
/// regex crate's extra set operators, groups, the s flag, and quantifiers.
/// `Err` names the first construct outside it.
pub(super) fn java_syntax(pattern: &str) -> Result<JavaPattern, &'static str> {
    if pattern.starts_with("(?iu)") || pattern.starts_with("(?ui)") {
        return Err(
            "Java's (?iu) folds case by Java's own Unicode rules, which aren't read: \
             drop the u, or the flag",
        );
    }
    let (body, fold) = pattern
        .strip_prefix("(?i)")
        .map_or((pattern, false), |rest| (rest, true));
    let mut java = read_java(body, false)?;
    if java.backtrack.is_some() && java.boundary {
        java = read_java(body, true)?;
    }
    if fold && java.property {
        return Err(FOLD_PROPERTY);
    }
    Ok(JavaPattern {
        text: java.out,
        fold,
        backtrack: java.backtrack,
    })
}

/// `body` read once. `lookaround_boundary` writes `\b` and `\B` as lookaround,
/// which fancy-regex reads where it refuses `(?-u:\b)`.
fn read_java(body: &str, lookaround_boundary: bool) -> Result<Java<'_>, &'static str> {
    let mut java = Java {
        src: body,
        at: 0,
        out: String::with_capacity(body.len() + 16),
        groups: 0,
        backtrack: None,
        property: false,
        names: Vec::new(),
        depth: 0,
        linebreaks: Vec::new(),
        lookaround_boundary,
        boundary: false,
    };
    java.sequence()?;
    Ok(java)
}

/// The reader's place in a Java pattern and the text written so far.
struct Java<'p> {
    src: &'p str,
    at: usize,
    out: String,
    /// The capture groups opened so far, which bound a numbered backreference.
    groups: usize,
    backtrack: Option<&'static str>,
    /// A `\p` or `\P` was read.
    property: bool,
    /// The group names given so far.
    names: Vec<&'p str>,
    /// The groups and classes open around the reader.
    depth: usize,
    /// For each group open around the reader, whether it holds a `\R`.
    linebreaks: Vec<bool>,
    /// Write `\b` and `\B` as lookaround.
    lookaround_boundary: bool,
    /// A `\b` or `\B` was read.
    boundary: bool,
}

/// What a class item was, for the `-` or `&&` after it.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Item {
    Start,
    Char,
    Range,
    Set,
    And,
}

impl<'p> Java<'p> {
    fn byte(&self, ahead: usize) -> Option<u8> {
        self.src.as_bytes().get(self.at + ahead).copied()
    }

    fn rest(&self) -> &'p str {
        &self.src[self.at..]
    }

    fn push(&mut self, text: &str, width: usize) {
        self.out.push_str(text);
        self.at += width;
    }

    /// Read the whole pattern outside a class. A quantifier needs an atom
    /// before it, so one after `(`, `|`, an anchor or another quantifier is
    /// refused.
    fn sequence(&mut self) -> Result<(), &'static str> {
        let mut atom = false;
        while let Some(b) = self.byte(0) {
            let now = match b {
                b'\\' => self.escape()?,
                b'[' => {
                    self.class()?;
                    Some(true)
                }
                b'(' => {
                    self.group()?;
                    Some(false)
                }
                b')' => {
                    self.close_group()?;
                    Some(true)
                }
                b'.' => {
                    self.push(".", 1);
                    Some(true)
                }
                b'|' | b'^' | b'$' => {
                    let src = self.src;
                    self.push(&src[self.at..=self.at], 1);
                    Some(false)
                }
                b'*' | b'+' | b'?' | b'{' if !atom => {
                    return Err(
                        "a quantifier with nothing before it to repeat, or after an \
                                anchor or another quantifier",
                    );
                }
                b'*' | b'+' | b'?' | b'{' => {
                    self.quantifier()?;
                    Some(false)
                }
                _ => {
                    let c = self.rest().chars().next().unwrap_or_default();
                    literal(c, &mut self.out);
                    self.at += c.len_utf8();
                    Some(true)
                }
            };
            if let Some(now) = now {
                atom = now;
            }
        }
        Ok(())
    }

    /// Read `* + ? {n} {n,} {n,m}` and a lazy `?` or possessive `+` after it.
    fn quantifier(&mut self) -> Result<(), &'static str> {
        if self.byte(0) == Some(b'{') {
            let rest = self.rest().as_bytes();
            let digits = |from: usize| {
                rest[from..]
                    .iter()
                    .take_while(|d| d.is_ascii_digit())
                    .count()
            };
            let low = digits(1);
            let mut end = 1 + low;
            if rest.get(end) == Some(&b',') {
                end += 1 + digits(end + 1);
            }
            if low == 0 || rest.get(end) != Some(&b'}') {
                return Err(
                    "a { that isn't a Java interval {n}, {n,} or {n,m}: write \\{ for the \
                            brace",
                );
            }
            let interval = &self.rest()[..=end];
            self.push(interval, end + 1);
        } else {
            let q = &self.rest()[..1];
            self.push(q, 1);
        }
        match self.byte(0) {
            Some(b'?') => self.push("?", 1),
            Some(b'+') => {
                self.backtrack = Some(POSSESSIVE);
                self.push("+", 1);
            }
            _ => {}
        }
        Ok(())
    }

    /// Read a group's opening: `(`, `(?:`, `(?<name>`, lookaround, an atomic
    /// group, or a flag group of the s flag alone.
    fn group(&mut self) -> Result<(), &'static str> {
        self.enter()?;
        self.linebreaks.push(false);
        if self.byte(1) != Some(b'?') {
            self.groups += 1;
            self.push("(", 1);
            return Ok(());
        }
        match (self.byte(2), self.byte(3)) {
            (Some(b':'), _) => self.push("(?:", 3),
            (Some(b'='), _) => self.backtracking("(?=", 3, LOOKAROUND),
            (Some(b'!'), _) => self.backtracking("(?!", 3, LOOKAROUND),
            (Some(b'>'), _) => self.backtracking("(?>", 3, ATOMIC),
            (Some(b'<'), Some(b'=')) => self.backtracking("(?<=", 4, LOOKAROUND),
            (Some(b'<'), Some(b'!')) => self.backtracking("(?<!", 4, LOOKAROUND),
            (Some(b'<'), _) => {
                let name = group_name(&self.rest()[3..])?;
                if self.names.contains(&name) {
                    return Err("a group name used twice, which Java rejects");
                }
                self.names.push(name);
                let open = format!("(?<{name}>");
                self.groups += 1;
                self.push(&open, 4 + name.len());
            }
            (Some(b'P'), _) => {
                return Err("Java names a group (?<name>...), and has no (?P<name>...)");
            }
            _ => self.flags()?,
        }
        Ok(())
    }

    fn backtracking(&mut self, text: &str, width: usize, why: &'static str) {
        self.backtrack = Some(why);
        self.push(text, width);
    }

    /// Read a flag group, `(?s)`, `(?-s:` and the like. The s flag reads the
    /// same in both engines, and every other Java flag is refused by name.
    fn flags(&mut self) -> Result<(), &'static str> {
        let (on, off, rest) = flag_runs(&self.rest().as_bytes()[2..]);
        if let Some(hint) = [on, off].iter().find_map(|f| java_flag_refusal(f)) {
            return Err(hint);
        }
        let close = match rest.first() {
            Some(b')' | b':') if !on.is_empty() || !off.is_empty() => rest[0],
            _ => return Err("a (? construct Java's regex doesn't have"),
        };
        let width = self.rest().len() - rest.len() + 1;
        if close == b')' {
            self.depth -= 1;
            self.linebreaks.pop();
        }
        let text = format!(
            "(?{}{}{}{}",
            String::from_utf8_lossy(on),
            if off.is_empty() { "" } else { "-" },
            String::from_utf8_lossy(off),
            char::from(close),
        );
        self.push(&text, width);
        Ok(())
    }

    /// Read the escape at the reader, returning whether it is an atom a
    /// quantifier may follow, or `None` when it writes nothing.
    fn escape(&mut self) -> Result<Option<bool>, &'static str> {
        if let Some((c, width)) = escaped_char(self.rest())? {
            literal(c, &mut self.out);
            self.at += width;
            return Ok(Some(true));
        }
        let Some(letter) = self.byte(1) else {
            return Err("a pattern can't end in a backslash");
        };
        match letter {
            b'Q' => return Ok(self.quote().then_some(true)),
            b'E' => {
                self.at += 2;
                return Ok(None);
            }
            b'd' | b'D' | b'w' | b'W' | b's' | b'S' => {
                let class = &self.rest()[..2];
                self.push(class, 2);
            }
            b'h' | b'H' | b'v' | b'V' => self.space(letter),
            b'R' if self.quantified(2) => return Err(LINEBREAK_REPEATED),
            b'R' => {
                if let Some(last) = self.linebreaks.last_mut() {
                    *last = true;
                }
                self.push(JAVA_LINEBREAK, 2);
            }
            b'p' | b'P' => self.property(false)?,
            b'1'..=b'9' => self.backreference(),
            b'k' => self.named_backreference()?,
            _ => return self.anchor(letter).map(|()| Some(false)),
        }
        Ok(Some(true))
    }

    /// Read an anchor escape, `\A \z \Z \b \B`, or refuse the escape.
    fn anchor(&mut self, letter: u8) -> Result<(), &'static str> {
        match letter {
            b'A' => self.push(r"\A", 2),
            b'z' => self.push(r"\z", 2),
            // Java's \Z is its $ without MULTILINE, which the dialect refuses.
            b'Z' => self.push("$", 2),
            b'b' | b'B' if self.byte(2) == Some(b'{') => {
                return Err("Java's \\b{g} grapheme boundary isn't read");
            }
            b'b' | b'B' => {
                self.boundary = true;
                let text = match (self.lookaround_boundary, letter) {
                    (false, b'b') => r"(?-u:\b)",
                    (false, _) => r"(?-u:\B)",
                    (true, b'b') => WORD_BOUNDARY_LOOKAROUND,
                    (true, _) => NOT_WORD_BOUNDARY_LOOKAROUND,
                };
                self.push(text, 2);
            }
            b'G' => return Err("Java's \\G, the end of the last match, isn't read"),
            b'X' => return Err("Java's \\X grapheme cluster isn't read"),
            b'N' => return Err("Java's \\N{name} named character isn't read"),
            _ => {
                return Err(
                    "a backslash before a letter or digit Java's regex has no escape \
                            for, or one this dialect doesn't read",
                );
            }
        }
        Ok(())
    }

    /// Write `\h \H \v \V` as a bracketed class, so `&&` in a class takes it
    /// whole.
    fn space(&mut self, letter: u8) {
        let set = if matches!(letter, b'h' | b'H') {
            JAVA_H
        } else {
            JAVA_V
        };
        let caret = if letter.is_ascii_uppercase() { "^" } else { "" };
        let class = format!("[{caret}{set}]");
        self.push(&class, 2);
    }

    /// Read `\Q...\E`, or to the end, writing each character as itself.
    /// Returns whether it wrote any.
    fn quote(&mut self) -> bool {
        let text = &self.src[self.at + 2..];
        let end = text.find("\\E").unwrap_or(text.len());
        let quoted = &text[..end];
        for c in quoted.chars() {
            literal(c, &mut self.out);
        }
        let wrote = !quoted.is_empty();
        self.at += 2 + end + if end < text.len() { 2 } else { 0 };
        wrote
    }

    /// Read `\p{name}`, `\P{name}`, `\pL` or `\PL`.
    fn property(&mut self, in_class: bool) -> Result<(), &'static str> {
        let negated = self.byte(1) == Some(b'P');
        let (name, width) = if self.byte(2) == Some(b'{') {
            let close = self.rest()[3..].find('}').ok_or("a \\p{ with no }")?;
            (&self.rest()[3..3 + close], 4 + close)
        } else {
            match self.byte(2) {
                Some(c) if c.is_ascii_alphabetic() => (&self.rest()[2..3], 3),
                _ => return Err("a \\p with no name after it"),
            }
        };
        let class = java_property(name, negated, in_class)?;
        self.property = true;
        self.push(&class, width);
        Ok(())
    }

    /// Read `\n`, `\nn` and on: Java takes the first digit, then each next
    /// digit while the number still names a group opened before it.
    fn backreference(&mut self) {
        let digits = self.rest().as_bytes()[1..]
            .iter()
            .take_while(|d| d.is_ascii_digit())
            .count();
        let mut number = usize::from(self.rest().as_bytes()[1] - b'0');
        let mut len = 1;
        while len < digits {
            let longer = number * 10 + usize::from(self.rest().as_bytes()[1 + len] - b'0');
            if longer > self.groups {
                break;
            }
            number = longer;
            len += 1;
        }
        // The group keeps a digit after it from joining the number.
        let text = format!(r"(?:\{number})");
        self.backtrack = Some(BACKREFERENCE);
        self.push(&text, 1 + len);
    }

    /// Read `\k<name>`.
    fn named_backreference(&mut self) -> Result<(), &'static str> {
        if self.byte(2) != Some(b'<') {
            return Err("Java's \\k needs a group name in <>");
        }
        let name = group_name(&self.rest()[3..])?;
        let text = format!(r"(?:\k<{name}>)");
        self.backtrack = Some(BACKREFERENCE);
        self.push(&text, 4 + name.len());
        Ok(())
    }

    /// Read a class from its `[` to its `]`, nested classes and `&&`
    /// included. The regex crate's `--` and `~~` are refused, as are a `-`
    /// either engine could read as a range or an operator, and a nested
    /// class inside a negated one, where Java's negation reads differently.
    fn class(&mut self) -> Result<(), &'static str> {
        self.enter()?;
        self.at += 1;
        let negated = self.byte(0) == Some(b'^');
        if negated {
            self.at += 1;
        }
        self.out.push_str(if negated { "[^" } else { "[" });
        let mut last = Item::Start;
        loop {
            let Some(b) = self.byte(0) else {
                return Err("a [ with no ] to close it");
            };
            last = match b {
                b']' if last != Item::Start => break,
                b'[' if negated => {
                    return Err("a class nested in a negated class, which Java reads \
                                differently: write the negation inside the nested class");
                }
                b'[' => {
                    self.class()?;
                    Item::Set
                }
                b'&' if self.byte(1) == Some(b'&') => self.and(last, negated)?,
                b'~' if self.byte(1) == Some(b'~') => {
                    return Err("~~ in a class, which the regex crate reads as symmetric \
                                difference: escape the ~");
                }
                b'-' if last != Item::Start && self.byte(1) != Some(b']') => {
                    return Err(
                        "a - in a class after a range, a class or &&, which Java and \
                                the regex crate read differently: escape it as \\-",
                    );
                }
                b'\\' => self.class_escape()?,
                _ => {
                    let c = self.rest().chars().next().unwrap_or_default();
                    self.at += c.len_utf8();
                    self.class_char(c)?
                }
            };
        }
        self.depth -= 1;
        self.push("]", 1);
        Ok(())
    }

    /// Whether a quantifier starts `ahead` bytes on.
    fn quantified(&self, ahead: usize) -> bool {
        matches!(self.byte(ahead), Some(b'*' | b'+' | b'?' | b'{'))
    }

    /// Read a group's `)`. A repeated group holding a `\R` is refused, and
    /// the `\R` counts for the group around it too.
    fn close_group(&mut self) -> Result<(), &'static str> {
        self.depth = self.depth.saturating_sub(1);
        let linebreak = self.linebreaks.pop().unwrap_or(false);
        if linebreak && self.quantified(1) {
            return Err(LINEBREAK_REPEATED);
        }
        if linebreak && let Some(outer) = self.linebreaks.last_mut() {
            *outer = true;
        }
        self.push(")", 1);
        Ok(())
    }

    /// Count one more group or class open, refusing past [`NEST_LIMIT`].
    const fn enter(&mut self) -> Result<(), &'static str> {
        self.depth += 1;
        if self.depth > NEST_LIMIT {
            return Err(TOO_DEEP);
        }
        Ok(())
    }

    /// Read `&&`, which needs a class on both sides.
    fn and(&mut self, last: Item, negated: bool) -> Result<Item, &'static str> {
        if matches!(last, Item::Start | Item::And) || self.byte(2) == Some(b']') {
            return Err("an && with no class on one side, which Java reads loosely");
        }
        if negated {
            return Err("an && in a negated class, which Java reads differently");
        }
        self.push("&&", 2);
        Ok(Item::And)
    }

    /// Read an escape in a class.
    fn class_escape(&mut self) -> Result<Item, &'static str> {
        if let Some((c, width)) = escaped_char(self.rest())? {
            self.at += width;
            return self.class_char(c);
        }
        let Some(letter) = self.byte(1) else {
            return Err("a pattern can't end in a backslash");
        };
        match letter {
            b'Q' => {
                self.quote();
                if self.byte(0) == Some(b'-') && self.byte(1) != Some(b']') {
                    return Err("a range from a \\Q...\\E quote, which isn't read");
                }
                return Ok(Item::Char);
            }
            b'E' => {
                self.at += 2;
                return Ok(Item::Char);
            }
            b'd' | b'D' | b'w' | b'W' | b's' | b'S' => {
                let class = &self.rest()[..2];
                self.push(class, 2);
            }
            b'h' | b'H' | b'v' | b'V' => self.space(letter),
            b'p' | b'P' => self.property(true)?,
            _ => {
                return Err(
                    "an escape Java doesn't read in a class, such as \\R, \\Z, \\b or \
                            a backreference",
                );
            }
        }
        if self.byte(0) == Some(b'-') && self.byte(1) != Some(b']') {
            return Err(
                "a class escape such as \\v or \\h as a range end, which Java reads \
                        as a single character",
            );
        }
        Ok(Item::Set)
    }

    /// Write `c`, read already, and the range it opens when a `-` follows.
    fn class_char(&mut self, c: char) -> Result<Item, &'static str> {
        literal(c, &mut self.out);
        let next = match (self.byte(0), self.byte(1)) {
            (Some(b'-'), Some(next)) if next != b']' => next,
            _ => return Ok(Item::Char),
        };
        let end = match next {
            b'-' => return Err("-- in a class, which the regex crate reads as set difference"),
            b'[' => return Err("a - before a nested class, which Java reads as a literal"),
            b'\\' => {
                let Some((end, width)) = escaped_char(&self.rest()[1..])? else {
                    return Err(
                        "a class escape such as \\v or \\h as a range end, which Java \
                                reads as a single character",
                    );
                };
                self.at += 1 + width;
                end
            }
            _ => {
                let end = self.rest()[1..].chars().next().unwrap_or_default();
                self.at += 1 + end.len_utf8();
                end
            }
        };
        self.out.push('-');
        literal(end, &mut self.out);
        Ok(Item::Range)
    }
}

/// A Java group name, `[A-Za-z][A-Za-z0-9]*`, at the start of `text` and
/// closed by `>`.
fn group_name(text: &str) -> Result<&str, &'static str> {
    let len = text.bytes().take_while(u8::is_ascii_alphanumeric).count();
    let name = &text[..len];
    if !name.starts_with(|c: char| c.is_ascii_alphabetic())
        || text.as_bytes().get(len) != Some(&b'>')
    {
        return Err("a Java group name is an ASCII letter then letters and digits, closed by >");
    }
    Ok(name)
}

/// The one character the escape at the start of `text` stands for and the
/// escape's length, or `None` when it stands for something else.
fn escaped_char(text: &str) -> Result<Option<(char, usize)>, &'static str> {
    let b = text.as_bytes();
    let Some(&letter) = b.get(1) else {
        return Ok(None);
    };
    let simple = match letter {
        b't' => '\t',
        b'n' => '\n',
        b'r' => '\r',
        b'f' => '\u{c}',
        b'a' => '\u{7}',
        b'e' => '\u{1b}',
        b'x' => return hex_escape(text).map(Some),
        b'u' => return unicode_escape(text).map(Some),
        b'0' => return octal_escape(b).map(Some),
        b'c' => {
            return match b.get(2) {
                Some(&x) if x.is_ascii() => Ok(Some((char::from(x ^ 0x40), 3))),
                _ => Err("Java's \\c needs an ASCII character after it"),
            };
        }
        _ if letter.is_ascii_alphanumeric() => return Ok(None),
        _ => {
            let c = text[1..].chars().next().unwrap_or_default();
            return Ok(Some((c, 1 + c.len_utf8())));
        }
    };
    Ok(Some((simple, 2)))
}

/// `\xhh` or `\x{h...h}`.
fn hex_escape(text: &str) -> Result<(char, usize), &'static str> {
    let b = text.as_bytes();
    let (digits, width) = if b.get(2) == Some(&b'{') {
        let close = text[3..].find('}').ok_or("a \\x{ with no }")?;
        (&text[3..3 + close], 4 + close)
    } else {
        (text.get(2..4).unwrap_or_default(), 4)
    };
    let valid = !digits.is_empty() && digits.bytes().all(|d| d.is_ascii_hexdigit());
    let value = if valid {
        u32::from_str_radix(digits, 16).ok()
    } else {
        None
    };
    let c = value
        .and_then(char::from_u32)
        .ok_or("Java's \\x needs two hex digits, or hex digits naming a character in {}")?;
    Ok((c, width))
}

/// `\uhhhh`, and a surrogate pair written as two of them.
fn unicode_escape(text: &str) -> Result<(char, usize), &'static str> {
    let unit = |at: usize| {
        text.get(at..at + 4)
            .filter(|d| d.bytes().all(|x| x.is_ascii_hexdigit()))
            .and_then(|d| u32::from_str_radix(d, 16).ok())
    };
    let first = unit(2).ok_or("Java's \\u needs four hex digits")?;
    if let Some(c) = char::from_u32(first) {
        return Ok((c, 6));
    }
    let low = text
        .get(6..8)
        .filter(|u| *u == "\\u")
        .and_then(|_| unit(8))
        .filter(|low| (0xDC00..=0xDFFF).contains(low));
    match low {
        Some(low) if (0xD800..=0xDBFF).contains(&first) => {
            let c = char::from_u32(0x10000 + ((first - 0xD800) << 10) + (low - 0xDC00))
                .ok_or("a \\u surrogate pair that names no character")?;
            Ok((c, 12))
        }
        _ => Err("a \\u surrogate without its other half"),
    }
}

/// `\0n`, `\0nn` or `\0mnn` with m at most 3, the longest that fits.
fn octal_escape(b: &[u8]) -> Result<(char, usize), &'static str> {
    let octal = |at: usize| b.get(at).filter(|d| (b'0'..=b'7').contains(*d)).copied();
    let Some(first) = octal(2) else {
        return Err("Java's \\0 needs an octal digit after it");
    };
    let mut value = u32::from(first - b'0');
    let mut len = 1;
    if let Some(second) = octal(3) {
        value = value * 8 + u32::from(second - b'0');
        len = 2;
        if first <= b'3'
            && let Some(third) = octal(4)
        {
            value = value * 8 + u32::from(third - b'0');
            len = 3;
        }
    }
    let c = char::from_u32(value).unwrap_or_default();
    Ok((c, 2 + len))
}

/// Write `c` so the regex crate reads it as that one character, in a class or
/// out: ASCII punctuation, space and controls as `\x{..}`.
pub(super) fn literal(c: char, out: &mut String) {
    if c.is_ascii_alphanumeric() || !c.is_ascii() {
        out.push(c);
    } else {
        let _ = write!(out, "\\x{{{:X}}}", u32::from(c));
    }
}

/// Why a flag group's letters can't be read the Java way, if they can't.
fn java_flag_refusal(flags: &[u8]) -> Option<&'static str> {
    flags.iter().find_map(|f| match f {
        b's' => None,
        b'i' => Some(
            "Java's (?i) folds ASCII alone: only a (?i) on its own at the start of the pattern \
             is read, so move the flag there",
        ),
        b'u' => Some("Java's (?u) folds case by Java's own Unicode rules, which aren't read"),
        b'U' => Some(
            "Java's (?U) makes the classes Unicode, where the regex crate's swaps greed: \
             build without the Java dialect and write the classes as wanted",
        ),
        b'd' => Some("Java's (?d) UNIX_LINES isn't read: drop it"),
        b'm' => Some(
            "Java's (?m) also holds ^ and $ at \\r, U+0085, U+2028 and U+2029: drop the m flag",
        ),
        b'x' => Some("Java's (?x) isn't read: drop it and its comments"),
        b'c' => Some("Java's (?c) canonical equivalence isn't read"),
        _ => Some("a flag Java's regex doesn't have"),
    })
}

/// Java's `\p{name}`, negated when `negated`, written the regex crate's way.
///
/// Three namespaces, each by allowlist: the bare POSIX names are ASCII, the
/// general categories and `Is` scripts are Unicode as in the regex crate, and
/// anything else, the `Is` POSIX names, binary properties, blocks and most
/// `java` names among them, is refused.
fn java_property(name: &str, negated: bool, in_class: bool) -> Result<String, &'static str> {
    let p = if negated { 'P' } else { 'p' };
    if let Some((_, class)) = JAVA_POSIX.iter().find(|(java, _)| *java == name) {
        let caret = if negated { "^" } else { "" };
        return Ok(if in_class {
            format!("[:{caret}{class}:]")
        } else {
            format!("[[:{caret}{class}:]]")
        });
    }
    match name {
        "javaLowerCase" => return Ok(format!("\\{p}{{Lowercase}}")),
        "javaUpperCase" => return Ok(format!("\\{p}{{Uppercase}}")),
        _ if name.starts_with("java") => return Err("this \\p{java...} class isn't read"),
        _ if name.starts_with("In") || name.starts_with("blk=") || name.starts_with("block=") => {
            return Err("Java's Unicode block classes, \\p{In...}, aren't read");
        }
        _ => {}
    }
    let found = match name.split_once('=') {
        Some(("gc" | "general_category", value)) => category(value),
        Some(("sc" | "script", value)) => script(value),
        Some(_) => None,
        None => match name.strip_prefix("Is") {
            Some(base)
                if JAVA_POSIX
                    .iter()
                    .any(|(java, _)| java.eq_ignore_ascii_case(base)) =>
            {
                return Err(
                    "Java's \\p{Is...} POSIX names are Unicode classes of Java's own, \
                            which aren't read: use the ASCII \\p{Alpha} form or a category",
                );
            }
            Some(base) => category(base).or_else(|| script(base)),
            None => category(name),
        },
    };
    found
        .map(|canonical| format!("\\{p}{{{canonical}}}"))
        .ok_or("a \\p{...} name outside the categories and scripts the Java dialect reads")
}

fn category(name: &str) -> Option<&'static str> {
    JAVA_CATEGORIES.iter().find(|c| **c == name).copied()
}

fn script(name: &str) -> Option<&'static str> {
    JAVA_SCRIPTS
        .iter()
        .find(|s| s.eq_ignore_ascii_case(name))
        .copied()
}