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

//! The Python dialect: a pattern for `re` on a `str`, with the classes
//! Unicode by default and ASCII under `(?a)`. The pass reads an allowlist of
//! the grammar and writes the regex crate's syntax, or `fancy-regex`'s for
//! what only backtracking reads. Classes and case folding are written out
//! from the tables `CPython` generates, so the regex crate's own `\w` and `(?i)`
//! never stand in for Python's. Anything outside the list is refused with the
//! construct's name.

use std::collections::HashMap;
use std::sync::OnceLock;

use super::charset::{self, Set};
use super::dialect::{
    self, ATOMIC, BACKREFERENCE, LOOKAROUND, NEST_LIMIT, POSSESSIVE, Read, TOO_DEEP, literal,
};
use super::pcre::{check_empty_retry, proxy_of};
use super::python_tables as tables;

/// The most an interval's count may be here.
const INTERVAL_MAX: u32 = 1000;

/// Why a multi-line `$` needs the backtracking tier.
const MULTILINE: &str = "a multi-line $ runs only on the backtracking tier: turn on \
     StrMatcherBuilder::backtracking (the strmatch-backtracking feature)";

/// Why a Unicode `\b` needs the backtracking tier.
const WORD_BOUNDARY: &str = "a Unicode \\b or \\B is written as lookaround over Python's \\w, \
     which only the backtracking tier reads: turn on StrMatcherBuilder::backtracking (the \
     strmatch-backtracking feature), or use the a flag for ASCII";

/// Flags a pattern can switch with `(?...)`.
#[derive(Clone, Copy, Default)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "one switch per flag a pattern can set"
)]
struct Flags {
    i: bool,
    m: bool,
    x: bool,
    /// `re.ASCII`, set for the whole pattern.
    ascii: 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 group is a lookbehind, whose body has to be one width.
    behind: bool,
    /// Where the group's body starts in the output.
    start: usize,
    /// 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.
    Set(Set),
}

/// `pattern`, a Python `re` str pattern, in the regex crate's syntax.
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)
}

/// `pattern` read once. `lookaround_boundary` writes an ASCII `\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 = Py {
        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 Py<'p> {
    /// Write an ASCII `\b` and `\B` as lookaround.
    lookaround_boundary: bool,
    /// An ASCII `\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> Py<'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;
    }

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

    fn in_lookbehind(&self) -> bool {
        self.open.iter().any(|o| o.behind)
    }

    /// Write one character, as a class of what it matches under `i`.
    fn push_char(&mut self, c: char) {
        match self.fold_char(c) {
            Some(set) => self.out.push_str(&charset::render(&set)),
            None => literal(c, &mut self.out),
        }
    }

    /// What `c` matches under the i flag, or `None` when it matches itself
    /// alone or the flag is off.
    fn fold_char(&self, c: char) -> Option<Set> {
        if !self.flags.i {
            return None;
        }
        if self.flags.ascii {
            return c.is_ascii_alphabetic().then(|| {
                let mut set = charset::single(c.to_ascii_lowercase());
                set.union(&charset::single(c.to_ascii_uppercase()));
                set
            });
        }
        fold_classes().get(&c).map(|class| {
            let mut set = Set::empty();
            for m in *class {
                set.union(&charset::single(*m));
            }
            set
        })
    }

    /// `set` with what each member matches under the i flag added.
    fn folded(&self, set: Set) -> Set {
        if !self.flags.i {
            return set;
        }
        let mut out = set.clone();
        if self.flags.ascii {
            for r in set.iter() {
                for (a, z) in [('a', 'z'), ('A', 'Z')] {
                    let (from, to) = (r.start().max(a), r.end().min(z));
                    if from <= to {
                        let flip = |c: char| char::from_u32(u32::from(c) ^ 0x20).unwrap_or(c);
                        out.union(&charset::set([(flip(from), flip(to))]));
                    }
                }
            }
            return out;
        }
        for class in tables::FOLD {
            if class.iter().any(|c| has(&set, *c)) {
                for m in *class {
                    out.union(&charset::single(*m));
                }
            }
        }
        out
    }

    /// The set a class escape letter stands for.
    fn class_set(&self, letter: u8) -> Set {
        let positive = match (letter.to_ascii_lowercase(), self.flags.ascii) {
            (b'd', true) => charset::digits(),
            (b'd', false) => table(tables::DIGIT),
            (b'w', true) => charset::word(),
            (b'w', false) => table(tables::WORD),
            (_, true) => charset::set([('\t', '\r'), (' ', ' ')]),
            (_, false) => table(tables::SPACE),
        };
        if letter.is_ascii_uppercase() {
            charset::negated(positive)
        } else {
            positive
        }
    }

    /// 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;
            }
            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'^' => {
                    if self.flags.m {
                        self.push("(?m:^)", 1);
                    } else {
                        self.push(r"\A", 1);
                    }
                    Some(false)
                }
                b'$' => {
                    if self.flags.m {
                        self.need_backtracking(MULTILINE);
                        self.push(r"(?=\n|\z)", 1);
                    } else {
                        self.push("(?-m:$)", 1);
                    }
                    Some(false)
                }
                b'*' | b'+' | b'?' if !atom => return Err(NOTHING_TO_REPEAT),
                b'*' | b'+' | b'?' => {
                    let q = &self.rest()[..1];
                    self.push(q, 1);
                    self.suffix();
                    Some(false)
                }
                b'{' => match self.interval()? {
                    Some(()) if !atom => return Err(NOTHING_TO_REPEAT),
                    Some(()) => Some(false),
                    None => {
                        self.push("\\x{7B}", 1);
                        Some(true)
                    }
                },
                _ => {
                    let c = self.rest().chars().next().unwrap_or_default();
                    self.push_char(c);
                    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) -> bool {
        match self.byte(0) {
            Some(b' ' | b'\t' | b'\n' | b'\r' | 0x0B | 0x0C) => {
                self.at += 1;
                true
            }
            Some(b'#') => {
                let end = self
                    .rest()
                    .find('\n')
                    .map_or_else(|| self.rest().len(), |n| n + 1);
                self.at += end;
                true
            }
            _ => false,
        }
    }

    /// 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,}`, `{,m}` or `{n,m}` and its suffix. `None` when the
    /// `{` opens no interval, which Python 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: Option<usize> = None;
        if rest.get(end) == Some(&b',') {
            let n = digits(end + 1);
            high = Some(n);
            end += 1 + n;
        }
        if rest.get(end) != Some(&b'}') || (low == 0 && high.is_none()) {
            return Ok(None);
        }
        if low == 0 && high == Some(0) {
            return Err(
                "an interval {,} with no count, which Python reads as a repeat from \
                        zero: write *",
            );
        }
        let number = |bytes: &[u8]| -> u32 {
            std::str::from_utf8(bytes)
                .ok()
                .and_then(|t| t.parse().ok())
                .unwrap_or(u32::MAX)
        };
        let n = if low == 0 { 0 } else { number(&rest[1..=low]) };
        let m = high.filter(|h| *h > 0).map(|h| number(&rest[end - h..end]));
        if n > INTERVAL_MAX || m.is_some_and(|m| m > INTERVAL_MAX) {
            return Err("an interval count past 1000, which this dialect doesn't build");
        }
        if m.is_some_and(|m| m < n) {
            return Err("an interval whose upper count is under its lower");
        }
        let text = if low == 0 {
            format!("{{0{}", &self.rest()[1..=end])
        } else {
            self.rest()[..=end].to_owned()
        };
        self.out.push_str(&text);
        self.at += end + 1;
        self.suffix();
        Ok(Some(()))
    }

    /// Read a group's opening and push its state.
    fn group(&mut self) -> Result<Option<bool>, &'static str> {
        if self.open.len() >= NEST_LIMIT {
            return Err(TOO_DEEP);
        }
        if self.byte(1) != Some(b'?') {
            let number = self.capture();
            self.open_group(false, false, number);
            self.push("(", 1);
            return Ok(Some(false));
        }
        let (a, b) = (self.byte(2), self.byte(3));
        let (text, width, look, behind, backtrack) = match (a, b) {
            (Some(b':'), _) => ("(?:", 3, false, false, None),
            (Some(b'='), _) => ("(?=", 3, true, false, Some(LOOKAROUND)),
            (Some(b'!'), _) => ("(?!", 3, true, false, Some(LOOKAROUND)),
            (Some(b'>'), _) => ("(?>", 3, false, false, Some(ATOMIC)),
            (Some(b'<'), Some(b'=')) => ("(?<=", 4, true, true, Some(LOOKAROUND)),
            (Some(b'<'), Some(b'!')) => ("(?<!", 4, true, true, Some(LOOKAROUND)),
            (Some(b'#'), _) => return self.comment(),
            (Some(b'P'), Some(b'<')) => return self.named(),
            (Some(b'P'), Some(b'=')) => return self.python_backreference(),
            (Some(b'P'), Some(b'>')) => {
                return Err("a (?P> group, which Python rejects");
            }
            (Some(b'('), _) => return Err("a conditional group, (?(...)...), which isn't read"),
            _ => return self.flags_group(),
        };
        if let Some(why) = backtrack {
            self.need_backtracking(why);
        }
        self.open_group(look, behind, 0);
        self.push(text, width);
        if let Some(open) = self.open.last_mut() {
            open.start = self.out.len();
        }
        Ok(Some(false))
    }

    /// Push the state of a group just opened.
    fn open_group(&mut self, look: bool, behind: bool, number: usize) {
        self.open.push(Open {
            outer: self.flags,
            look,
            behind,
            start: self.out.len() + 1,
            number,
        });
    }

    /// 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 `(?P<name>`.
    fn named(&mut self) -> Result<Option<bool>, &'static str> {
        let (name, width) = group_name(&self.rest()[4..], '>')?;
        if self.names.iter().any(|(n, _)| *n == name) {
            return Err("a group name used twice, which Python rejects");
        }
        let number = self.capture();
        self.names.push((name, number));
        if self.in_lookbehind() {
            return Err("a capture group in a lookbehind, which this dialect doesn't read");
        }
        self.open_group(false, false, number);
        let open = format!("(?<{name}>");
        self.push(&open, 4 + 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.check_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))
    }

    /// Refuse a backreference where this dialect can't read it.
    fn check_backreference(&self) -> Result<(), &'static str> {
        if self.flags.i {
            return Err(
                "a backreference under the i flag, which Python compares by case \
                        folding and the backtracking tier compares as written",
            );
        }
        if self.in_lookbehind() {
            return Err("a backreference in a lookbehind, which Python rejects");
        }
        Ok(())
    }

    /// Read a flag group: `(?aimsux)` at the start of the pattern, or
    /// `(?imsx-imsx:...)` anywhere.
    fn flags_group(&mut self) -> Result<Option<bool>, &'static str> {
        let rest = &self.rest()[2..];
        let end = rest
            .find([')', ':'])
            .ok_or("a (? construct Python doesn't have")?;
        let (on, off) = match rest[..end].split_once('-') {
            Some((on, off)) => (on, off),
            None => (&rest[..end], ""),
        };
        let closes = rest.as_bytes()[end] == b')';
        if on.is_empty() && off.is_empty() {
            return Err("a (? construct Python doesn't have");
        }
        let mut flags = self.flags;
        let mut regex_on = String::new();
        let mut regex_off = String::new();
        for (letters, set) in [(on, true), (off, false)] {
            for f in letters.chars() {
                match f {
                    'i' => flags.i = set,
                    'm' => flags.m = set,
                    'x' => flags.x = set,
                    's' if set => regex_on.push('s'),
                    's' => regex_off.push('s'),
                    'a' if set && closes => flags.ascii = true,
                    'u' if set && closes => {}
                    'a' | 'u' => {
                        return Err("a flag a or u inside a scoped flag group, which this \
                                    dialect doesn't read: set it for the whole pattern");
                    }
                    'L' => return Err("Python's L flag, which a str pattern rejects"),
                    _ => return Err("a flag Python's regex doesn't have"),
                }
            }
        }
        if on.contains('a') && on.contains('u') {
            return Err("the a and u flags together, which Python rejects");
        }
        if on.chars().any(|f| off.contains(f)) {
            return Err("a flag turned on and off in one group, which Python rejects");
        }
        if closes
            && (!self.out.is_empty()
                || !self.open.is_empty()
                || !off.is_empty()
                || rest.as_bytes()[..end].contains(&b'-'))
        {
            return Err(
                "a flag group in the middle of the pattern, or one that turns a flag \
                        off with no colon, which Python rejects: put the flags first, or \
                        scope them as (?i:...)",
            );
        }
        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 {
            self.flags = flags;
            if regex_on.is_empty() {
                text.clear();
            } else {
                text.push(')');
            }
            self.out.push_str(&text);
            self.at += width;
            return Ok(Some(false));
        }
        if self.open.len() >= NEST_LIMIT {
            return Err(TOO_DEEP);
        }
        if on.is_empty() && off.is_empty() {
            return Err("a (? construct Python doesn't have");
        }
        text.push(':');
        if regex_on.is_empty() && regex_off.is_empty() {
            text = String::from("(?:");
        }
        self.open_group(false, false, 0);
        self.flags = flags;
        self.out.push_str(&text);
        self.at += width;
        if let Some(open) = self.open.last_mut() {
            open.start = self.out.len();
        }
        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");
        };
        if open.behind {
            self.check_fixed_width(open.start)?;
        }
        self.flags = open.outer;
        if open.number > 0 {
            self.closed[open.number - 1] = true;
        }
        self.push(")", 1);
        Ok(Some(!open.look))
    }

    /// Refuse a lookbehind whose body isn't one width, as Python does.
    fn check_fixed_width(&self, start: usize) -> Result<(), &'static str> {
        let body = one_unit_each(&proxy_of(&self.out[start..]));
        let hir = regex_syntax::ParserBuilder::new()
            .utf8(false)
            .build()
            .parse(&body)
            .map_err(|_| FIXED_WIDTH)?;
        let props = hir.properties();
        if props.minimum_len() != props.maximum_len() {
            return Err(FIXED_WIDTH);
        }
        Ok(())
    }

    /// Read the escape at the reader, returning whether it is an atom a
    /// quantifier may follow.
    fn escape(&mut self) -> Result<Option<bool>, &'static str> {
        let Some(letter) = self.byte(1) else {
            return Err("a pattern can't end in a backslash");
        };
        match letter {
            b'd' | b'D' | b'w' | b'W' | b's' | b'S' => {
                let set = self.class_set(letter);
                self.out.push_str(&charset::render(&set));
                self.at += 2;
            }
            b'A' => {
                self.push(r"\A", 2);
                return Ok(Some(false));
            }
            b'Z' | b'z' => {
                self.push(r"\z", 2);
                return Ok(Some(false));
            }
            b'b' | b'B' => {
                self.word_boundary(letter == b'B');
                return Ok(Some(false));
            }
            b'1'..=b'9' => {
                if let Some((c, width)) = octal_escape(self.rest())? {
                    self.push_char(c);
                    self.at += width;
                } else {
                    self.backreference()?;
                }
            }
            b'N' => return Err("Python's \\N{name} named character isn't read"),
            _ => {
                let (c, width) = escaped_char(self.rest(), false)?;
                self.push_char(c);
                self.at += width;
            }
        }
        Ok(Some(true))
    }

    /// Write `\b`, or `\B` when `not`.
    fn word_boundary(&mut self, not: bool) {
        if self.flags.ascii {
            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);
            return;
        }
        self.need_backtracking(WORD_BOUNDARY);
        let w = charset::render(&table(tables::WORD));
        let text = if not {
            format!("(?:(?<={w})(?={w})|(?<!{w})(?!{w}))")
        } else {
            format!("(?:(?<={w})(?!{w})|(?<!{w})(?={w}))")
        };
        self.push(&text, 2);
    }

    /// 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 digits, which Python reads as a group number, \
                        an octal escape or an error by how many groups the pattern has: \
                        write (?P=name) or \\ooo",
            );
        }
        self.check_backreference()?;
        let number = usize::from(self.byte(1).unwrap_or(b'1') - b'0');
        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, 2);
        Ok(())
    }

    /// Read a class from its `[` to its `]`.
    fn class(&mut self) -> Result<bool, &'static str> {
        if self.open.len() >= NEST_LIMIT {
            return Err(TOO_DEEP);
        }
        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)?;
            match member {
                Member::Set(set) => {
                    exact.union(&set);
                    after_set = true;
                    continue;
                }
                Member::Char(_) if c == '-' && after_set && self.byte(0) != Some(b']') => {
                    return Err(
                        "a - after a class such as \\d, which Python rejects as a bad \
                                range: escape it as \\-",
                    );
                }
                Member::Char(a) => {
                    let end = self.range_end(a)?;
                    literal_part.union(&charset::set([(a, end)]));
                }
            }
            after_set = false;
        }
        let mut set = self.folded(literal_part);
        set.union(&exact);
        if negated {
            set.negate();
        }
        self.out.push_str(&charset::render(&set));
        Ok(true)
    }

    /// The end of the range `a` starts when a `-` and a character follow,
    /// else `a` itself.
    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(_) => Err("a range whose end is a class such as \\d, which Python \
                                   rejects"),
        }
    }

    /// Read one class member starting with `c` at the reader.
    fn member(&mut self, c: char) -> Result<Member, &'static str> {
        if c != '\\' {
            self.at += c.len_utf8();
            return Ok(Member::Char(c));
        }
        let Some(letter) = self.byte(1) else {
            return Err("a pattern can't end in a backslash");
        };
        match letter {
            b'd' | b'D' | b'w' | b'W' | b's' | b'S' => {
                self.at += 2;
                Ok(Member::Set(self.class_set(letter)))
            }
            b'b' => {
                self.at += 2;
                Ok(Member::Char('\u{8}'))
            }
            b'8' | b'9' => Err("\\8 or \\9 in a class, which Python rejects"),
            b'N' => Err("Python's \\N{name} named character isn't read"),
            _ => {
                let (c, width) = escaped_char(self.rest(), true)?;
                self.at += width;
                Ok(Member::Char(c))
            }
        }
    }
}

/// Why a quantifier with nothing to repeat is refused.
const NOTHING_TO_REPEAT: &str = "a quantifier with nothing before it to repeat, or after an \
     anchor, a flag group or another quantifier";

/// Why a lookbehind of no fixed width is refused.
const FIXED_WIDTH: &str = "a lookbehind whose body isn't one width, which Python rejects";

/// `text`, the proxy of what the reader wrote, with each class, `\x{..}` escape,
/// dot and non-ASCII character as one `a`, so a regex length in bytes counts
/// the characters Python counts.
fn one_unit_each(text: &str) -> String {
    let b = text.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            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('a');
                i = j + 1;
            }
            b'\\' if b.get(i + 1) == Some(&b'x') && b.get(i + 2) == Some(&b'{') => {
                out.push('a');
                i += text[i..].find('}').map_or(b.len() - i, |n| n + 1);
            }
            b'\\' => {
                out.push_str(&text[i..(i + 2).min(b.len())]);
                i += 2;
            }
            b'.' => {
                out.push('a');
                i += 1;
            }
            _ => {
                let c = text[i..].chars().next().unwrap_or_default();
                out.push(if c.is_ascii() { c } else { 'a' });
                i += c.len_utf8();
            }
        }
    }
    out
}

/// `ranges` as a set.
fn table(ranges: &[(char, char)]) -> Set {
    charset::from_ranges(ranges)
}

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

/// Each cased character and the class it matches under the i flag.
fn fold_classes() -> &'static HashMap<char, &'static [char]> {
    static CLASSES: OnceLock<HashMap<char, &'static [char]>> = OnceLock::new();
    CLASSES.get_or_init(|| {
        tables::FOLD
            .iter()
            .flat_map(|class| class.iter().map(move |c| (*c, *class)))
            .collect()
    })
}

/// 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.as_bytes()[0].is_ascii_digit() || !text[len..].starts_with(close) {
        return Err(
            "a Python group name here is ASCII letters, digits and _, not starting \
                    with a digit, closed by its bracket",
        );
    }
    Ok((name, len + 1))
}

/// `\ooo` at the start of `text`, where the first digit is 1 to 9: an octal
/// escape when three octal digits follow the backslash, else `None`.
fn octal_escape(text: &str) -> Result<Option<(char, usize)>, &'static str> {
    let b = text.as_bytes();
    let octal = |at: usize| b.get(at).is_some_and(|d| (b'0'..=b'7').contains(d));
    if !(octal(1) && octal(2) && octal(3)) {
        return Ok(None);
    }
    let value = u32::from_str_radix(&text[1..4], 8).unwrap_or(0);
    if value > 0o377 {
        return Err("an octal escape past \\377, which Python rejects");
    }
    Ok(Some((char::from_u32(value).unwrap_or_default(), 4)))
}

/// The one character the escape at the start of `text` stands for and the
/// escape's length.
fn escaped_char(text: &str, in_class: bool) -> Result<(char, usize), &'static str> {
    let b = text.as_bytes();
    let letter = b[1];
    let simple = match letter {
        b'a' => '\u{7}',
        b'f' => '\u{c}',
        b'n' => '\n',
        b'r' => '\r',
        b't' => '\t',
        b'v' => '\u{b}',
        b'x' => return hex_escape(text, 2),
        b'u' => return hex_escape(text, 4),
        b'U' => return hex_escape(text, 8),
        b'0' => return octal_run(b),
        b'1'..=b'7' if in_class => return octal_run(b),
        _ if letter.is_ascii_alphanumeric() => {
            return Err(
                "a backslash before a letter or digit Python has no escape for, or one \
                        this dialect doesn't read",
            );
        }
        _ => {
            let c = text[1..].chars().next().unwrap_or_default();
            return Ok((c, 1 + c.len_utf8()));
        }
    };
    Ok((simple, 2))
}

/// An octal escape of up to three digits after the backslash, the first of
/// which is known to be one.
fn octal_run(b: &[u8]) -> Result<(char, usize), &'static str> {
    let len = b[1..]
        .iter()
        .take(3)
        .take_while(|d| (b'0'..=b'7').contains(*d))
        .count();
    let value = b[1..=len]
        .iter()
        .fold(0_u32, |v, d| v * 8 + u32::from(d - b'0'));
    if value > 0o377 {
        return Err("an octal escape past \\377, which Python rejects");
    }
    Ok((char::from_u32(value).unwrap_or_default(), 1 + len))
}

/// `\x`, `\u` or `\U` and exactly `digits` hex digits.
fn hex_escape(text: &str, digits: usize) -> Result<(char, usize), &'static str> {
    let run = text.get(2..2 + digits).unwrap_or_default();
    let value = (run.len() == digits && run.bytes().all(|d| d.is_ascii_hexdigit()))
        .then(|| u32::from_str_radix(run, 16).ok())
        .flatten()
        .and_then(char::from_u32)
        .ok_or(
            "a Python \\x, \\u or \\U escape needs its hex digits and names a character a \
                UTF-8 text can hold",
        )?;
    Ok((value, 2 + digits))
}