grippo 0.3.1

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
// Project:   grippo
// File:      src/strmatch/pcre.rs
// Purpose:   Read a PCRE2 pattern as pcre2test reads it, or refuse it by name
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The PCRE2 dialect: a pattern read in UTF mode without UCP, with the
//! default newline (LF) and `\R` as every Unicode line break. The pass reads
//! an allowlist of PCRE2's grammar and writes the regex crate's syntax, or
//! `fancy-regex`'s for what only backtracking reads. Anything outside the
//! list is refused with the construct's name.

use super::charset::{self, Set};
use super::dialect::{
    self, ATOMIC, BACKREFERENCE, JAVA_CATEGORIES, JAVA_SCRIPTS, LOOKAROUND, NEST_LIMIT, POSSESSIVE,
    Read, TOO_DEEP, literal,
};

/// The most a PCRE2 interval's count may be.
const INTERVAL_MAX: u32 = 65535;

/// Why a multi-line `^` or `$` needs the backtracking tier.
const MULTILINE: &str = "a multi-line ^ or $ runs only on the backtracking tier, since PCRE2's ^ \
     skips the end after a final newline: turn on StrMatcherBuilder::backtracking (the \
     strmatch-backtracking feature)";

/// Why `\R` needs the backtracking tier.
const LINEBREAK: &str = "\\R is atomic in PCRE2, which gives back nothing of a \\r\\n it took, \
     and only the backtracking tier reads that: turn on StrMatcherBuilder::backtracking (the \
     strmatch-backtracking feature)";

/// Why `\R` after a repeat is refused.
const LINEBREAK_AFTER_REPEAT: &str = "\\R after a repeat, where PCRE2's automatic possessive \
     repeats stop the repeat giving back a character \\R could take, which this dialect doesn't \
     read: put \\R first, or write the repeat as a possessive one";

/// Why a repeat of `\h` or `\v` before `\S`, `\W` or `\D` is refused.
const SPACE_THEN_NOT: &str = "a repeat of \\h or \\v before \\S, \\W or \\D, where PCRE2's \
     automatic possessive repeats treat \\h and \\v as inside white space, which they aren't \
     for U+0085 and U+00A0, and so skip a match: write the repeat as a possessive one, or \
     use \\s";

/// What the last token was, for the `\h` and `\v` quirk.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
enum Space {
    /// Neither a `\h` or `\v` nor a repeat of one.
    #[default]
    No,
    /// A `\h` or `\v` just read, which the loop's `next` carries one step.
    Atom,
    /// The token before this one is a `\h` or `\v`.
    After,
    /// A repeated `\h` or `\v` just read.
    Repeat,
    /// The token before this one is a repeated `\h` or `\v`.
    AfterRepeat,
}

impl Space {
    /// The state at the start of the next token.
    const fn next(self) -> Self {
        match self {
            Self::Atom => Self::After,
            Self::Repeat => Self::AfterRepeat,
            _ => Self::No,
        }
    }

    /// The state once a quantifier is read after the current token.
    const fn repeat(self) -> Self {
        match self {
            Self::After => Self::Repeat,
            other => other,
        }
    }

    /// Whether the previous token was a repeated `\h` or `\v`.
    const fn repeated(self) -> bool {
        matches!(self, Self::AfterRepeat)
    }
}

/// Flags a pattern can switch with `(?...)`.
#[derive(Clone, Copy, Default)]
struct Flags {
    i: bool,
    m: bool,
    x: bool,
}

/// What the reader holds for a group that is open.
struct Open {
    /// The flags in force outside the group, back again at its `)`.
    outer: Flags,
    /// The group is lookaround, which no quantifier may follow.
    look: bool,
    /// The capture group's number, `0` for a group that isn't one.
    number: usize,
}

/// A class member, read one at a time.
enum Member {
    /// One character, which a `-` may make a range start.
    Char(char),
    /// A set, whole: a class escape, a property or a POSIX class.
    Set(Set),
    /// Nothing, such as an `\E`.
    None,
}

/// `pattern` in PCRE2's syntax rewritten to the regex crate's.
pub(super) fn syntax(pattern: &str) -> Result<Read, &'static str> {
    let first = read(pattern, false)?;
    let read = if first.0.backtrack.is_some() && first.1 {
        read(pattern, true)?.0
    } else {
        first.0
    };
    check_empty_retry(&read.text)?;
    Ok(read)
}

/// Refuse a pattern that can match empty where PCRE2's search would try
/// again for a non-empty match at the place it found an empty one.
pub(super) fn check_empty_retry(text: &str) -> Result<(), &'static str> {
    let proxy = proxy_of(text);
    let hir = regex_syntax::ParserBuilder::new()
        .utf8(false)
        .build()
        .parse(&proxy)
        .map_err(|_| dialect::EMPTY_RETRY)?;
    if hir.properties().minimum_len() == Some(0) && dialect::empty_retry(&hir) {
        return Err(dialect::EMPTY_RETRY);
    }
    Ok(())
}

/// `text`, written for fancy-regex, as the regex crate can parse it with the
/// same shortest match: lookaround repeated zero times, atomic groups plain,
/// possessive repeats greedy and backreferences empty. The reader writes
/// every literal ASCII punctuation as `\x{..}`, so a bare `*`, `+` or `?` is a
/// quantifier.
pub(super) fn proxy_of(text: &str) -> String {
    let b = text.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut look: Vec<bool> = Vec::new();
    let (mut i, mut after_quantifier) = (0, false);
    while i < b.len() {
        let was_quantifier = std::mem::take(&mut after_quantifier);
        match b[i] {
            b'\\' => {
                let end = if b.get(i + 1) == Some(&b'x') && b.get(i + 2) == Some(&b'{') {
                    text[i..].find('}').map_or(b.len(), |n| i + n + 1)
                } else {
                    i + 2
                };
                out.push_str(&text[i..end.min(b.len())]);
                i = end;
            }
            b'[' => {
                let mut j = i + 1;
                while j < b.len() && b[j] != b']' {
                    j += if b[j] == b'\\' && b.get(j + 1) == Some(&b'x') {
                        text[j..].find('}').map_or(b.len() - j, |n| n + 1)
                    } else {
                        1
                    };
                }
                out.push_str(&text[i..(j + 1).min(b.len())]);
                i = j + 1;
            }
            b'(' => {
                let rest = &text[i..];
                if rest.starts_with("(?:\\")
                    && (rest[4..].starts_with(|c: char| c.is_ascii_digit())
                        || rest[4..].starts_with("k<"))
                {
                    let close = rest.find(')').unwrap_or(rest.len() - 1);
                    out.push_str("(?:)");
                    i += close + 1;
                    continue;
                }
                let lookaround = ["(?=", "(?!", "(?<=", "(?<!"]
                    .iter()
                    .find(|p| rest.starts_with(**p));
                if let Some(p) = lookaround {
                    out.push_str("(?:");
                    look.push(true);
                    i += p.len();
                } else if rest.starts_with("(?>") {
                    out.push_str("(?:");
                    look.push(false);
                    i += 3;
                } else if rest.starts_with("(?") {
                    let end = rest.find([')', ':', '>']).map_or(rest.len(), |n| n + 1);
                    out.push_str(&rest[..end]);
                    if !rest[..end].ends_with(')') {
                        look.push(false);
                    }
                    i += end;
                } else {
                    out.push('(');
                    look.push(false);
                    i += 1;
                }
            }
            b')' => {
                out.push_str(if look.pop().unwrap_or(false) {
                    "){0}"
                } else {
                    ")"
                });
                i += 1;
            }
            b'+' if was_quantifier => i += 1,
            b'?' if was_quantifier => {
                out.push('?');
                i += 1;
            }
            c @ (b'*' | b'+' | b'?') => {
                out.push(char::from(c));
                after_quantifier = true;
                i += 1;
            }
            b'}' => {
                out.push('}');
                after_quantifier = true;
                i += 1;
            }
            _ => {
                let c = text[i..].chars().next().unwrap_or_default();
                out.push(c);
                i += c.len_utf8();
            }
        }
    }
    out
}

/// `pattern` read once. `lookaround_boundary` writes `\b` and `\B` as
/// lookaround, which fancy-regex reads where it refuses `(?-u:\b)`. The
/// boolean says whether the pattern has either.
fn read(pattern: &str, lookaround_boundary: bool) -> Result<(Read, bool), &'static str> {
    let mut p = Pcre {
        repeated: false,
        space: Space::default(),
        lookaround_boundary,
        boundary: false,
        src: pattern,
        at: 0,
        out: String::with_capacity(pattern.len() + 16),
        flags: Flags::default(),
        open: Vec::new(),
        closed: Vec::new(),
        names: Vec::new(),
        backtrack: None,
    };
    p.sequence()?;
    if !p.open.is_empty() {
        return Err("a ( with no ) to close it");
    }
    Ok((
        Read {
            text: p.out,
            backtrack: p.backtrack,
        },
        p.boundary,
    ))
}

struct Pcre<'p> {
    /// A variable repeat has been read.
    repeated: bool,
    /// Whether the last token was a `\h` or `\v`, or a repeat of one.
    space: Space,
    /// Write `\b` and `\B` as lookaround.
    lookaround_boundary: bool,
    /// A `\b` or `\B` was read.
    boundary: bool,
    src: &'p str,
    at: usize,
    out: String,
    flags: Flags,
    open: Vec<Open>,
    /// For each capture group opened, whether it has closed.
    closed: Vec<bool>,
    /// A name and its group's number, for each named group opened.
    names: Vec<(&'p str, usize)>,
    backtrack: Option<&'static str>,
}

impl<'p> Pcre<'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;
    }

    /// Write `set` so no `(?i)` around it folds it again.
    fn push_set(&mut self, set: &Set) {
        if self.flags.i {
            self.out.push_str(&charset::render_exact(set));
        } else {
            self.out.push_str(&charset::render(set));
        }
    }

    fn need_backtracking(&mut self, why: &'static str) {
        self.backtrack.get_or_insert(why);
    }

    /// Read the whole pattern outside a class.
    fn sequence(&mut self) -> Result<(), &'static str> {
        let mut atom = false;
        while let Some(b) = self.byte(0) {
            if self.flags.x && self.skip_extended()? {
                continue;
            }
            self.space = self.space.next();
            let now = match b {
                b'\\' => self.escape()?,
                b'[' => Some(self.class()?),
                b'(' => self.group()?,
                b')' => self.close_group()?,
                b'.' => {
                    self.push(".", 1);
                    Some(true)
                }
                b'|' => {
                    self.push("|", 1);
                    Some(false)
                }
                b'^' => {
                    self.caret();
                    Some(false)
                }
                b'$' => {
                    self.dollar(false);
                    Some(false)
                }
                b'*' | b'+' | b'?' if !atom => {
                    return Err(
                        "a quantifier with nothing before it to repeat, or after an \
                                anchor, a flag group or another quantifier",
                    );
                }
                b'*' | b'+' | b'?' => {
                    self.quantifier();
                    Some(false)
                }
                b'{' => match self.interval()? {
                    Some(()) if !atom => {
                        return Err("a quantifier with nothing before it to repeat, or after \
                                    an anchor, a flag group or another quantifier");
                    }
                    Some(()) => Some(false),
                    None => {
                        self.push("\\x{7B}", 1);
                        Some(true)
                    }
                },
                _ => {
                    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(())
    }

    /// Skip white space and a `#` comment where the x flag is on. Returns
    /// whether it skipped any.
    fn skip_extended(&mut self) -> Result<bool, &'static str> {
        let Some(c) = self.rest().chars().next() else {
            return Ok(false);
        };
        match c {
            ' ' | '\t' | '\n' | '\x0B' | '\x0C' | '\r' => {
                self.at += 1;
                Ok(true)
            }
            '#' => {
                let end = self
                    .rest()
                    .find('\n')
                    .map_or_else(|| self.rest().len(), |n| n + 1);
                self.at += end;
                Ok(true)
            }
            '\u{85}' | '\u{200E}' | '\u{200F}' | '\u{2028}' | '\u{2029}' => Err(
                "a Unicode white space character in an x-flag pattern, which PCRE2 skips as \
                 white space only in some builds: write it as \\x{...}",
            ),
            _ => Ok(false),
        }
    }

    /// `^`, read as PCRE2's: the start, or after each newline but the final
    /// one when the m flag is on.
    fn caret(&mut self) {
        if self.flags.m {
            self.need_backtracking(MULTILINE);
            self.push(r"(?:\A|(?<=\n)(?!\z))", 1);
        } else {
            self.push(r"\A", 1);
        }
    }

    /// `$`, or `\Z` (`z_upper`, which the m flag leaves at the end or before
    /// a final newline).
    fn dollar(&mut self, z_upper: bool) {
        let width = if z_upper { 2 } else { 1 };
        if self.flags.m && !z_upper {
            self.need_backtracking(MULTILINE);
            self.push(r"(?=\n|\z)", width);
        } else {
            self.push("(?-m:$)", width);
        }
    }

    /// Read `* + ?` and a lazy `?` or possessive `+` after it.
    fn quantifier(&mut self) {
        self.repeated = true;
        self.space = self.space.repeat();
        let q = &self.rest()[..1];
        self.push(q, 1);
        self.suffix();
    }

    /// Read the `?` or `+` after a quantifier.
    fn suffix(&mut self) {
        match self.byte(0) {
            Some(b'?') => self.push("?", 1),
            Some(b'+') => {
                self.need_backtracking(POSSESSIVE);
                self.push("+", 1);
            }
            _ => {}
        }
    }

    /// Read `{n}`, `{n,}` or `{n,m}` and its suffix. `None` when the `{`
    /// opens no interval, which PCRE2 reads as the brace.
    fn interval(&mut self) -> Result<Option<()>, &'static str> {
        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;
        let mut high = None;
        if rest.get(end) == Some(&b',') {
            let n = digits(end + 1);
            high = Some(&rest[end + 1..end + 1 + n]);
            end += 1 + n;
        }
        if rest.get(end) != Some(&b'}') || (low == 0 && high.is_none_or(<[u8]>::is_empty)) {
            if rest
                .get(1)
                .is_some_and(|b| matches!(b, b' ' | b'\t' | b','))
            {
                return Err(
                    "a { followed by a space or a comma that PCRE2 reads as an interval \
                            in some versions and as the brace in others: write \\{ for the \
                            brace, or {n,m} with no spaces",
                );
            }
            return Ok(None);
        }
        if low == 0 {
            return Err(
                "an interval with no lower count, {,m}, which PCRE2 reads as an \
                        interval from version 10.43 and as text before: write {0,m}",
            );
        }
        let number = |bytes: &[u8]| -> u32 {
            std::str::from_utf8(bytes)
                .ok()
                .and_then(|t| t.parse().ok())
                .unwrap_or(u32::MAX)
        };
        let (n, m) = (
            number(&rest[1..=low]),
            high.filter(|h| !h.is_empty()).map(number),
        );
        if n > INTERVAL_MAX || m.is_some_and(|m| m > INTERVAL_MAX || m < n) {
            return Err("an interval count past 65535, or an upper count under the lower");
        }
        if high.is_some() && m != Some(n) {
            self.repeated = true;
            self.space = self.space.repeat();
        }
        let interval = &self.rest()[..=end];
        self.push(interval, end + 1);
        self.suffix();
        Ok(Some(()))
    }

    /// Read a group's opening and push its state. Returns whether a
    /// quantifier may follow what it wrote: `Some(false)`, as it opens.
    fn group(&mut self) -> Result<Option<bool>, &'static str> {
        if self.open.len() >= NEST_LIMIT {
            return Err(TOO_DEEP);
        }
        let outer = self.flags;
        if self.byte(1) == Some(b'*') {
            return Err("a PCRE2 verb, (*NAME), which isn't read");
        }
        if self.byte(1) != Some(b'?') {
            let number = self.capture();
            self.open.push(Open {
                outer,
                look: false,
                number,
            });
            self.push("(", 1);
            return Ok(Some(false));
        }
        let (a, b) = (self.byte(2), self.byte(3));
        let (text, width, look, backtrack) = match (a, b) {
            (Some(b':'), _) => ("(?:", 3, false, None),
            (Some(b'='), _) => ("(?=", 3, true, Some(LOOKAROUND)),
            (Some(b'!'), _) => ("(?!", 3, true, Some(LOOKAROUND)),
            (Some(b'>'), _) => ("(?>", 3, false, Some(ATOMIC)),
            (Some(b'<'), Some(b'=')) => ("(?<=", 4, true, Some(LOOKAROUND)),
            (Some(b'<'), Some(b'!')) => ("(?<!", 4, true, Some(LOOKAROUND)),
            (Some(b'#'), _) => return self.comment(),
            (Some(b'<' | b'\''), _) => return self.named(3, a == Some(b'\'')),
            (Some(b'P'), Some(b'<')) => return self.named(4, false),
            (Some(b'P'), Some(b'=')) => return self.python_backreference(),
            (Some(b'P'), Some(b'>')) => {
                return Err("a recursion or subroutine call, (?P>name), which isn't read");
            }
            (Some(b'|'), _) => return Err("a branch reset group, (?|...), which isn't read"),
            (Some(b'('), _) => return Err("a conditional group, (?(...)...), which isn't read"),
            (Some(b'R' | b'&' | b'0'..=b'9' | b'+'), _) => {
                return Err(
                    "a recursion or subroutine call, such as (?R) or (?1), which isn't read",
                );
            }
            (Some(b'-'), Some(b'0'..=b'9')) => {
                return Err("a relative subroutine call, (?-1), which isn't read");
            }
            (Some(b'C'), _) => return Err("a callout, (?C...), which isn't read"),
            (Some(b'^'), _) => return Err("(?^), which resets every flag, isn't read"),
            _ => return self.flags_group(),
        };
        if let Some(why) = backtrack {
            self.need_backtracking(why);
        }
        self.open.push(Open {
            outer,
            look,
            number: 0,
        });
        self.push(text, width);
        Ok(Some(false))
    }

    /// The next capture group's number, with its room made.
    fn capture(&mut self) -> usize {
        self.closed.push(false);
        self.closed.len()
    }

    /// Skip a `(?#...)` comment.
    fn comment(&mut self) -> Result<Option<bool>, &'static str> {
        let end = self.rest().find(')').ok_or("a (?# comment with no )")?;
        self.at += end + 1;
        Ok(None)
    }

    /// Read `(?<name>` or `(?'name'` or `(?P<name>`, the name starting
    /// `skip` bytes in.
    fn named(&mut self, skip: usize, quoted: bool) -> Result<Option<bool>, &'static str> {
        let close = if quoted { '\'' } else { '>' };
        let (name, width) = group_name(&self.rest()[skip..], close)?;
        if self.names.iter().any(|(n, _)| *n == name) {
            return Err("a group name used twice, which PCRE2 allows only under (?J)");
        }
        let number = self.capture();
        self.names.push((name, number));
        self.open.push(Open {
            outer: self.flags,
            look: false,
            number,
        });
        let open = format!("(?<{name}>");
        self.push(&open, skip + width);
        Ok(Some(false))
    }

    /// Read `(?P=name)`.
    fn python_backreference(&mut self) -> Result<Option<bool>, &'static str> {
        let rest = &self.rest()[4..];
        let close = rest.find(')').ok_or("a (?P= with no )")?;
        let name = &rest[..close];
        let width = 4 + close + 1;
        self.named_backreference(name, width)
    }

    /// Read `(?i)`, `(?i-s:`, and the like. The i and s flags go on to the
    /// regex crate and the m and x flags are applied here.
    fn flags_group(&mut self) -> Result<Option<bool>, &'static str> {
        let rest = &self.rest()[2..];
        let end = rest
            .find([')', ':'])
            .ok_or("a (? construct PCRE2 doesn't have")?;
        let (on, off) = match rest[..end].split_once('-') {
            Some((on, off)) => (on, off),
            None => (&rest[..end], ""),
        };
        let mut flags = self.flags;
        let mut regex_on = String::new();
        let mut regex_off = String::new();
        for (letters, set, into) in [(on, true, &mut regex_on), (off, false, &mut regex_off)] {
            for f in letters.chars() {
                match f {
                    'i' => {
                        flags.i = set;
                        into.push('i');
                    }
                    's' => into.push('s'),
                    'm' => flags.m = set,
                    'x' if letters.matches('x').count() > 1 => {
                        return Err("PCRE2's (?xx) flag isn't read: use (?x)");
                    }
                    'x' => flags.x = set,
                    'J' => return Err("PCRE2's (?J) duplicate names flag isn't read"),
                    'U' => return Err("PCRE2's (?U) ungreedy flag isn't read"),
                    'n' => return Err("PCRE2's (?n) no-auto-capture flag isn't read"),
                    _ => {
                        return Err("a flag PCRE2's regex doesn't have, or a (? construct it \
                                     doesn't have");
                    }
                }
            }
        }
        if on.is_empty() && off.is_empty() {
            return Err("a (? construct PCRE2's regex doesn't have");
        }
        let closes = rest.as_bytes()[end] == b')';
        let mut text = String::from("(?");
        text.push_str(&regex_on);
        if !regex_off.is_empty() {
            text.push('-');
            text.push_str(&regex_off);
        }
        let width = 2 + end + 1;
        if closes {
            if regex_on.is_empty() && regex_off.is_empty() {
                text.clear();
            } else {
                text.push(')');
            }
            self.flags = flags;
            self.out.push_str(&text);
            self.at += width;
            return Ok(Some(false));
        }
        if self.open.len() >= NEST_LIMIT {
            return Err(TOO_DEEP);
        }
        let outer = self.flags;
        text.push(':');
        if regex_on.is_empty() && regex_off.is_empty() {
            text = String::from("(?:");
        }
        self.flags = flags;
        self.open.push(Open {
            outer,
            look: false,
            number: 0,
        });
        self.out.push_str(&text);
        self.at += width;
        Ok(Some(false))
    }

    /// Read a group's `)`.
    fn close_group(&mut self) -> Result<Option<bool>, &'static str> {
        let Some(open) = self.open.pop() else {
            return Err("a ) with no ( before it");
        };
        self.flags = open.outer;
        if open.number > 0 {
            self.closed[open.number - 1] = true;
        }
        self.push(")", 1);
        Ok(Some(!open.look))
    }

    /// 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'W' | b'S' if self.space.repeated() => {
                return Err(SPACE_THEN_NOT);
            }
            b'd' | b'D' | b'w' | b'W' | b's' | b'S' | b'h' | b'H' | b'v' | b'V' => {
                let set = space_set(letter);
                self.push_set(&set);
                self.at += 2;
                if matches!(letter, b'h' | b'v') {
                    self.space = Space::Atom;
                }
            }
            b'N' if self.byte(2) == Some(b'{') => {
                return Err("PCRE2's \\N{...} named character isn't read");
            }
            b'N' => {
                self.push(r"[^\n]", 2);
            }
            b'R' if self.repeated => return Err(LINEBREAK_AFTER_REPEAT),
            b'R' => {
                self.need_backtracking(LINEBREAK);
                self.push(r"(?>\r\n|[\n\x0B\f\r\x85\x{2028}\x{2029}])", 2);
            }
            b'p' | b'P' => {
                let set = self.property()?;
                self.push_set(&set);
            }
            b'1'..=b'9' => self.backreference()?,
            b'k' => self.k_backreference()?,
            b'g' => self.g_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),
            b'Z' => self.dollar(true),
            b'b' | b'B' => self.word_boundary(letter == b'B'),
            b'G' => return Err("PCRE2's \\G, where the last match ended, isn't read"),
            b'K' => return Err("PCRE2's \\K, which resets the match start, isn't read"),
            b'X' => return Err("PCRE2's \\X grapheme cluster isn't read"),
            b'C' => return Err("PCRE2's \\C single code unit isn't read"),
            _ => {
                return Err(
                    "a backslash before a letter or digit PCRE2 has no escape for, or \
                            one this dialect doesn't read",
                );
            }
        }
        Ok(())
    }

    /// Write `\b`, or `\B` when `not`, as an ASCII word boundary.
    fn word_boundary(&mut self, not: bool) {
        self.boundary = true;
        let text = match (self.lookaround_boundary, not) {
            (false, false) => r"(?-u:\b)",
            (false, true) => r"(?-u:\B)",
            (true, false) => dialect::WORD_BOUNDARY_LOOKAROUND,
            (true, true) => dialect::NOT_WORD_BOUNDARY_LOOKAROUND,
        };
        self.push(text, 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`, and `\p{^name}`.
    fn property(&mut self) -> Result<Set, &'static str> {
        let mut 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"),
            }
        };
        if name.starts_with('^') {
            negated = !negated;
        }
        let name = name.strip_prefix('^').unwrap_or(name);
        let name = match name {
            "Lu" | "Ll" | "Lt" if self.flags.i => "L&",
            _ => name,
        };
        let set = property_set(name)?;
        self.at += width;
        Ok(if negated { charset::negated(set) } else { set })
    }

    /// Read `\1` to `\9`.
    fn backreference(&mut self) -> Result<(), &'static str> {
        if self.byte(2).is_some_and(|d| d.is_ascii_digit()) {
            return Err(
                "a backslash and two or more digits, which PCRE2 reads as a \
                        backreference or an octal character by how many groups the pattern \
                        has: write \\g{n} or \\o{...}",
            );
        }
        let number = usize::from(self.byte(1).unwrap_or(b'1') - b'0');
        self.numbered_backreference(number, 2)
    }

    fn numbered_backreference(&mut self, number: usize, width: usize) -> Result<(), &'static str> {
        if self.flags.i {
            return Err(CASELESS_BACKREFERENCE);
        }
        if !self.closed.get(number - 1).copied().unwrap_or(false) {
            return Err("a backreference to a group that isn't closed before it");
        }
        self.need_backtracking(BACKREFERENCE);
        let text = format!(r"(?:\{number})");
        self.push(&text, width);
        Ok(())
    }

    fn named_backreference(
        &mut self,
        name: &str,
        width: usize,
    ) -> Result<Option<bool>, &'static str> {
        if self.flags.i {
            return Err(CASELESS_BACKREFERENCE);
        }
        let known = self
            .names
            .iter()
            .find(|(n, _)| *n == name)
            .map(|(_, number)| *number);
        if !known.is_some_and(|n| self.closed[n - 1]) {
            return Err("a backreference to a name no closed group has");
        }
        self.need_backtracking(BACKREFERENCE);
        let text = format!(r"(?:\k<{name}>)");
        self.push(&text, width);
        Ok(Some(true))
    }

    /// Read `\k<name>`, `\k'name'` and `\k{name}`.
    fn k_backreference(&mut self) -> Result<(), &'static str> {
        let close = match self.byte(2) {
            Some(b'<') => '>',
            Some(b'\'') => '\'',
            Some(b'{') => '}',
            _ => return Err("PCRE2's \\k needs a group name in <>, '' or {}"),
        };
        let (name, width) = group_name(&self.rest()[3..], close)?;
        self.named_backreference(name, 3 + width).map(|_| ())
    }

    /// Read `\g{n}`, `\g{-n}` and `\g{name}`.
    fn g_backreference(&mut self) -> Result<(), &'static str> {
        if self.byte(2) != Some(b'{') {
            return Err(
                "PCRE2's \\g outside the braced form \\g{n}, \\g{-n} or \\g{name} isn't \
                        read",
            );
        }
        let (inner, width) = group_name_loose(&self.rest()[3..])?;
        let width = 3 + width;
        if let Some(relative) = inner.strip_prefix('-') {
            let back: usize = relative.parse().map_err(|_| "a \\g{-n} with no number")?;
            let number = (self.closed.len() + 1)
                .checked_sub(back)
                .filter(|n| back > 0 && *n > 0)
                .ok_or("a relative backreference before the first group")?;
            return self.numbered_backreference(number, width);
        }
        if inner.bytes().all(|d| d.is_ascii_digit()) && !inner.is_empty() {
            let number: usize = inner.parse().map_err(|_| "a \\g{n} count too large")?;
            if number == 0 {
                return Err("a \\g{0}, which is a recursion in PCRE2");
            }
            return self.numbered_backreference(number, width);
        }
        self.named_backreference(inner, width).map(|_| ())
    }

    /// Read a class from its `[` to its `]`, or the word-start and word-end
    /// markers `[[:<:]]` and `[[:>:]]`. Returns whether a quantifier may
    /// follow.
    fn class(&mut self) -> Result<bool, &'static str> {
        if self.open.len() >= NEST_LIMIT {
            return Err(TOO_DEEP);
        }
        for (text, look) in [
            (
                "[[:<:]]",
                r"(?:(?<!(?-i:[0-9A-Za-z_]))(?=(?-i:[0-9A-Za-z_])))",
            ),
            (
                "[[:>:]]",
                r"(?:(?<=(?-i:[0-9A-Za-z_]))(?!(?-i:[0-9A-Za-z_])))",
            ),
        ] {
            if self.rest().starts_with(text) {
                self.need_backtracking(LOOKAROUND);
                self.push(look, text.len());
                return Ok(false);
            }
        }
        let start = self.at;
        self.at += 1;
        let negated = self.byte(0) == Some(b'^');
        if negated {
            self.at += 1;
        }
        let mut literal_part = Set::empty();
        let mut exact = Set::empty();
        let mut first = true;
        let mut after_set = false;
        loop {
            let Some(c) = self.rest().chars().next() else {
                return Err("a [ with no ] to close it");
            };
            if c == ']' && !first {
                self.at += 1;
                break;
            }
            first = false;
            let member = self.member(c)?;
            let hyphen = c == '-';
            match member {
                Member::None => {}
                Member::Set(set) => {
                    exact.union(&set);
                    after_set = true;
                    continue;
                }
                Member::Char(_) if hyphen && after_set && self.byte(0) != Some(b']') => {
                    return Err("a - after a class such as \\d or [:alpha:], which PCRE2 \
                                rejects as an invalid range: escape it as \\-");
                }
                Member::Char(a) => {
                    let end = self.range_end(a)?;
                    literal_part.union(&charset::set([(a, end)]));
                }
            }
            after_set = false;
        }
        let body = &self.src[start..self.at];
        if body.starts_with("[:") && body.ends_with(":]") && body.len() > 4 {
            return Err(
                "a POSIX class name outside a class, [:name:], which PCRE2 rejects: \
                        write [[:name:]]",
            );
        }
        if self.flags.i {
            literal_part = charset::folded(literal_part);
        }
        literal_part.union(&exact);
        let set = if negated {
            charset::negated(literal_part)
        } else {
            literal_part
        };
        self.push_set(&set);
        Ok(true)
    }

    /// The end of the range `a` starts when a `-` and a character follow,
    /// else `a` itself, which then stands for one character.
    fn range_end(&mut self, a: char) -> Result<char, &'static str> {
        if self.byte(0) != Some(b'-') || self.byte(1) == Some(b']') || self.byte(1).is_none() {
            return Ok(a);
        }
        self.at += 1;
        let Some(c) = self.rest().chars().next() else {
            return Err("a [ with no ] to close it");
        };
        match self.member(c)? {
            Member::Char(z) if z >= a => Ok(z),
            Member::Char(_) => Err("a class range whose end comes before its start"),
            Member::Set(_) | Member::None => Err("a range whose end is a class such as \\d or \
                                                   [:alpha:], which PCRE2 rejects"),
        }
    }

    /// Read one class member starting with `c` at the reader.
    fn member(&mut self, c: char) -> Result<Member, &'static str> {
        match c {
            '[' => self.posix_class(),
            '\\' => self.class_escape(),
            _ => {
                self.at += c.len_utf8();
                Ok(Member::Char(c))
            }
        }
    }

    /// Read `[:name:]` or `[:^name:]` at a `[` in a class, or the bracket.
    fn posix_class(&mut self) -> Result<Member, &'static str> {
        match self.byte(1) {
            Some(b'.' | b'=') => {
                return Err(
                    "a POSIX collating element or equivalence class, [.x.] or [=x=], \
                            which PCRE2 rejects",
                );
            }
            Some(b':') => {}
            _ => {
                self.at += 1;
                return Ok(Member::Char('['));
            }
        }
        let rest = &self.rest()[2..];
        let Some(close) = rest.find(":]") else {
            self.at += 1;
            return Ok(Member::Char('['));
        };
        let (negated, name) = rest[..close]
            .strip_prefix('^')
            .map_or_else(|| (false, &rest[..close]), |name| (true, name));
        if !name.bytes().all(|b| b.is_ascii_alphabetic()) {
            self.at += 1;
            return Ok(Member::Char('['));
        }
        let name = if self.flags.i && matches!(name, "upper" | "lower") {
            "alpha"
        } else {
            name
        };
        let set = charset::posix(name).ok_or(
            "a POSIX class name PCRE2 doesn't have, or \
                                               [[:<:]] and [[:>:]], which aren't read",
        )?;
        self.at += 2 + close + 2;
        Ok(Member::Set(if negated {
            charset::negated(set)
        } else {
            set
        }))
    }

    /// Read an escape in a class.
    fn class_escape(&mut self) -> Result<Member, &'static str> {
        let Some(letter) = self.byte(1) else {
            return Err("a pattern can't end in a backslash");
        };
        match letter {
            b'Q' => {
                let text = &self.src[self.at + 2..];
                let end = text.find("\\E").unwrap_or(text.len());
                let mut set = Set::empty();
                for c in text[..end].chars() {
                    set.union(&charset::single(c));
                }
                self.at += 2 + end + if end < text.len() { 2 } else { 0 };
                return Ok(if text[..end].is_empty() {
                    Member::None
                } else {
                    Member::Set(set)
                });
            }
            b'E' => {
                self.at += 2;
                return Ok(Member::None);
            }
            b'b' => {
                self.at += 2;
                return Ok(Member::Char('\u{8}'));
            }
            b'd' | b'D' | b'w' | b'W' | b's' | b'S' | b'h' | b'H' | b'v' | b'V' => {
                self.at += 2;
                return Ok(Member::Set(space_set(letter)));
            }
            b'p' | b'P' => return self.property().map(Member::Set),
            b'8' | b'9' => return Err("\\8 or \\9 in a class, which PCRE2 reads as text"),
            b'1'..=b'7' => return self.class_octal(),
            _ => {}
        }
        match escaped_char(self.rest())? {
            Some((c, width)) => {
                self.at += width;
                Ok(Member::Char(c))
            }
            None => Err(
                "an escape PCRE2 doesn't read in a class, such as \\B, \\R, \\X, \\N or \
                         a backreference",
            ),
        }
    }

    /// `\1` to `\377` in a class, each an octal character of up to three
    /// digits.
    fn class_octal(&mut self) -> Result<Member, &'static str> {
        let digits = self.rest().as_bytes()[1..]
            .iter()
            .take(3)
            .take_while(|d| (b'0'..=b'7').contains(*d))
            .count();
        let value = u32::from_str_radix(&self.rest()[1..=digits], 8).unwrap_or(0);
        let c = char::from_u32(value).ok_or("an octal escape that names no character")?;
        self.at += 1 + digits;
        Ok(Member::Char(c))
    }
}

/// The text PCRE2 says when a backreference sits under `(?i)`.
const CASELESS_BACKREFERENCE: &str = "a backreference under (?i), which PCRE2 compares by Unicode \
     case folding and the backtracking tier compares as written: drop the flag or the backreference";

/// The set a class escape letter stands for.
fn space_set(letter: u8) -> Set {
    let positive = match letter.to_ascii_lowercase() {
        b'd' => charset::digits(),
        b'w' => charset::word(),
        b's' => charset::set([('\t', '\r'), (' ', ' ')]),
        b'h' => charset::horizontal_space(),
        _ => charset::vertical_space(),
    };
    if letter.is_ascii_uppercase() {
        charset::negated(positive)
    } else {
        positive
    }
}

/// A group name closed by `close` at the start of `text`, and how many bytes
/// it and the closing character take.
fn group_name(text: &str, close: char) -> Result<(&str, usize), &'static str> {
    let len = text
        .bytes()
        .take_while(|b| b.is_ascii_alphanumeric() || *b == b'_')
        .count();
    let name = &text[..len];
    if name.is_empty()
        || name.len() > 32
        || name.as_bytes()[0].is_ascii_digit()
        || !text[len..].starts_with(close)
    {
        return Err(
            "a PCRE2 group name is ASCII letters, digits and _, not starting with a \
                    digit, up to 32 long, and closed by its bracket",
        );
    }
    Ok((name, len + 1))
}

/// The text of a `\g{...}`, a number, a relative number or a name.
fn group_name_loose(text: &str) -> Result<(&str, usize), &'static str> {
    let close = text.find('}').ok_or("a \\g{ with no }")?;
    Ok((&text[..close], close + 1))
}

/// The set for a PCRE2 property name, from the allowlist.
fn property_set(name: &str) -> Result<Set, &'static str> {
    let canonical = match name {
        "Any" => return Ok(charset::set([('\0', char::MAX)])),
        "L&" => {
            let mut set = charset::property("Lu").unwrap_or_else(Set::empty);
            set.union(&charset::property("Ll").unwrap_or_else(Set::empty));
            set.union(&charset::property("Lt").unwrap_or_else(Set::empty));
            return Ok(set);
        }
        _ if JAVA_CATEGORIES.contains(&name) && name != "Cs" => name.to_owned(),
        _ if JAVA_SCRIPTS.contains(&name) => format!("scx={name}"),
        _ => {
            return Err(
                "a \\p{...} name outside the general categories and scripts the PCRE2 \
                        dialect reads",
            );
        }
    };
    charset::property(&canonical).ok_or("a \\p{...} name the dialect can't read")
}

/// 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'o' => return braced_octal(text).map(Some),
        b'0' => return Ok(Some(octal_zero(b))),
        b'c' => {
            return match b.get(2) {
                Some(&x) if (0x20..0x7F).contains(&x) => {
                    Ok(Some((char::from(x.to_ascii_uppercase() ^ 0x40), 3)))
                }
                _ => Err("PCRE2's \\c needs a printable ASCII character after it"),
            };
        }
        b'u' | b'U' | b'l' | b'L' | b'F' => {
            return Err("PCRE2 has no \\u, \\U, \\l, \\L or \\F escape");
        }
        _ 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` with one or two hex digits, 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 {
        let n = b[2..]
            .iter()
            .take(2)
            .take_while(|d| d.is_ascii_hexdigit())
            .count();
        (&text[2..2 + n], 2 + n)
    };
    let valid = !digits.is_empty() && digits.bytes().all(|d| d.is_ascii_hexdigit());
    let c = valid
        .then(|| u32::from_str_radix(digits, 16).ok())
        .flatten()
        .and_then(char::from_u32)
        .ok_or("PCRE2's \\x needs hex digits naming a character")?;
    Ok((c, width))
}

/// `\o{o...o}`.
fn braced_octal(text: &str) -> Result<(char, usize), &'static str> {
    if text.as_bytes().get(2) != Some(&b'{') {
        return Err("PCRE2's \\o needs braces, \\o{...}");
    }
    let close = text[3..].find('}').ok_or("an \\o{ with no }")?;
    let digits = &text[3..3 + close];
    let valid = !digits.is_empty() && digits.bytes().all(|d| (b'0'..=b'7').contains(&d));
    let c = valid
        .then(|| u32::from_str_radix(digits, 8).ok())
        .flatten()
        .and_then(char::from_u32)
        .ok_or("PCRE2's \\o needs octal digits naming a character")?;
    Ok((c, 4 + close))
}

/// `\0`, `\0n` or `\0nn`: a character by octal code.
fn octal_zero(b: &[u8]) -> (char, usize) {
    let octal = |at: usize| b.get(at).filter(|d| (b'0'..=b'7').contains(*d)).copied();
    let mut value = 0_u32;
    let mut len = 0;
    for at in [2, 3] {
        let Some(d) = octal(at) else { break };
        value = value * 8 + u32::from(d - b'0');
        len += 1;
    }
    (char::from_u32(value).unwrap_or_default(), 2 + len)
}