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

//! The JavaScript dialect: a `/source/flags` literal, or a bare source with no
//! flags. The pass reads an allowlist of the grammar, in `u` mode as the spec
//! reads it and without `u` as Annex B reads the escapes it keeps, 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 std::collections::HashMap;
use std::sync::OnceLock;

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

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

/// Why a multi-line `^` or `$` needs the backtracking tier.
const MULTILINE: &str = "a multi-line ^ or $ runs only on the backtracking tier, since \
     JavaScript's also hold at \\r, U+2028 and U+2029: turn on StrMatcherBuilder::backtracking \
     (the strmatch-backtracking feature)";

/// The line terminators JavaScript's `.`, `^` and `$` know.
const TERMINATORS: &str = r"\n\r\x{2028}\x{2029}";

/// The flags a literal carries.
#[derive(Clone, Copy, Default)]
#[allow(
    clippy::struct_excessive_bools,
    reason = "one switch per flag the literal can carry"
)]
struct Flags {
    i: bool,
    m: bool,
    s: bool,
    u: bool,
}

/// A capture group's place, for deciding whether a backreference to it reads
/// as JavaScript reads it.
struct Frame {
    /// Closed, with its `)` read.
    closed: bool,
    /// The groups open around it, and which `|` branch of each it sat in.
    around: Vec<(usize, usize)>,
    /// The `|` branches it has, counting the first.
    branches: usize,
    /// A quantifier after it that allows none, or a negative lookahead around.
    optional: bool,
    /// Whether it is a capture group.
    capture: bool,
}

/// `pattern`, a `/source/flags` literal or a bare source, in the regex
/// crate's syntax.
pub(super) fn syntax(pattern: &str) -> Result<Read, &'static str> {
    let (source, flags, literal_form) = split(pattern)?;
    let first = read(source, flags, literal_form, false)?;
    let read = if first.0.backtrack.is_some() && first.1 {
        read(source, flags, literal_form, true)?.0
    } else {
        first.0
    };
    check_empty_iteration(&read.text)?;
    Ok(read)
}

/// Why a repeated group that can match empty is refused.
const EMPTY_ITERATION: &str = "a group repeated more than once that can match empty, where \
     JavaScript rejects an iteration that matches nothing and backtracks into a longer one: \
     make the group need a character";

/// Refuse a pattern with a repeat that may run more than its minimum over a
/// body that can match empty.
fn check_empty_iteration(text: &str) -> Result<(), &'static str> {
    let proxy = super::pcre::proxy_of(text);
    let hir = regex_syntax::ParserBuilder::new()
        .utf8(false)
        .build()
        .parse(&proxy)
        .map_err(|_| EMPTY_ITERATION)?;
    if repeats_empty(&hir) {
        return Err(EMPTY_ITERATION);
    }
    Ok(())
}

fn repeats_empty(hir: &regex_syntax::hir::Hir) -> bool {
    use regex_syntax::hir::HirKind;
    match hir.kind() {
        HirKind::Repetition(r) => {
            let more = r.max.is_none_or(|m| m > r.min.max(1));
            (more && r.sub.properties().minimum_len().is_none_or(|n| n == 0))
                || repeats_empty(&r.sub)
        }
        HirKind::Capture(c) => repeats_empty(&c.sub),
        HirKind::Concat(parts) | HirKind::Alternation(parts) => parts.iter().any(repeats_empty),
        HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => false,
    }
}

/// The source, the flags and whether the text was a literal.
fn split(pattern: &str) -> Result<(&str, Flags, bool), &'static str> {
    let Some(rest) = pattern.strip_prefix('/') else {
        return Ok((pattern, Flags::default(), false));
    };
    let close = rest.rfind('/').ok_or(
        "a pattern starting with / must be a /source/flags literal: write \\/ for a \
                slash at the start",
    )?;
    let (source, letters) = (&rest[..close], &rest[close + 1..]);
    if source.is_empty() {
        return Err(
            "an empty /source/ is a comment in JavaScript: write (?:) for an empty \
                    pattern",
        );
    }
    let mut flags = Flags::default();
    let mut seen = String::new();
    for f in letters.chars() {
        if seen.contains(f) {
            return Err("a flag given twice, which JavaScript rejects");
        }
        seen.push(f);
        match f {
            'i' => flags.i = true,
            'm' => flags.m = true,
            's' => flags.s = true,
            'u' => flags.u = true,
            'g' | 'd' => {}
            'y' => {
                return Err(
                    "the y flag makes a match start where the last ended, which a \
                            search for every match doesn't read",
                );
            }
            'v' => {
                return Err(
                    "the v flag's class grammar, with nested classes and set operators, \
                            isn't read: use u",
                );
            }
            _ => return Err("a flag JavaScript doesn't have after the closing /"),
        }
    }
    Ok((source, flags, true))
}

fn read(
    source: &str,
    flags: Flags,
    literal_form: bool,
    lookaround_boundary: bool,
) -> Result<(Read, bool), &'static str> {
    let mut p = Js {
        src: source,
        at: 0,
        out: String::with_capacity(source.len() + 16),
        flags,
        literal_form,
        lookaround_boundary,
        boundary: false,
        total: count_groups(source),
        open: Vec::new(),
        frames: Vec::new(),
        names: Vec::new(),
        last_closed: None,
        backtrack: None,
    };
    if flags.i && flags.u {
        p.out.push_str("(?i)");
    }
    // The whole pattern is the first group open, so a `|` outside every
    // group counts as a branch.
    p.open_frame(false, Look::No);
    p.sequence()?;
    if p.open.len() != 1 {
        return Err("a ( with no ) to close it");
    }
    Ok((
        Read {
            text: p.out,
            backtrack: p.backtrack,
        },
        p.boundary,
    ))
}

/// How many capture groups `src` has, counting through the whole pattern.
fn count_groups(src: &str) -> usize {
    let b = src.as_bytes();
    let (mut i, mut n, mut in_class) = (0, 0, false);
    while i < b.len() {
        match b[i] {
            b'\\' => i += 1,
            b'[' => in_class = true,
            b']' => in_class = false,
            b'(' if !in_class => {
                let named = b.get(i + 1) == Some(&b'?')
                    && b.get(i + 2) == Some(&b'<')
                    && !matches!(b.get(i + 3), Some(b'=' | b'!'));
                if b.get(i + 1) != Some(&b'?') || named {
                    n += 1;
                }
            }
            _ => {}
        }
        i += 1;
    }
    n
}

/// A class member, read one at a time.
enum Member {
    Char(char),
    /// A set, and whether the `i` flag folds it: a property does, and a
    /// class escape such as `\d`, which is closed under folding already,
    /// doesn't.
    Set(Set, bool),
}

struct Js<'p> {
    src: &'p str,
    at: usize,
    out: String,
    flags: Flags,
    /// The source came in a `/.../` literal, where a bare `/` can't appear.
    literal_form: bool,
    lookaround_boundary: bool,
    boundary: bool,
    /// The capture groups in the whole pattern.
    total: usize,
    /// For each group open, its index in `frames`, the `|` branch the reader
    /// is in, and whether it is lookaround.
    open: Vec<Open>,
    frames: Vec<Frame>,
    /// A name and its group's number, for each named group opened.
    names: Vec<(&'p str, usize)>,
    /// The frame the last `)` closed.
    last_closed: Option<usize>,
    backtrack: Option<&'static str>,
}

struct Open {
    frame: usize,
    branch: usize,
    look: Look,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Look {
    No,
    Ahead,
    Behind,
}

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

    /// Write one character outside a class. Without the `u` flag JavaScript
    /// reads a character past U+FFFF as two units, which a quantifier after
    /// it would repeat the second of.
    fn push_char(&mut self, c: char, quantified: bool) -> Result<(), &'static str> {
        if !self.flags.u && u32::from(c) > 0xFFFF && quantified {
            return Err(ASTRAL_QUANTIFIED);
        }
        if self.flags.i && !self.flags.u && fold_index().contains_key(&c) {
            self.out
                .push_str(&charset::render(&upper_folded(charset::single(c))));
        } else {
            literal(c, &mut self.out);
        }
        Ok(())
    }

    /// Write `set`, folded as the flags say when `fold`, as a class.
    fn push_set(&mut self, set: Set, fold: bool) {
        let set = if fold { self.folded(set) } else { set };
        if self.flags.i && self.flags.u {
            self.out.push_str(&charset::render_exact(&set));
        } else {
            self.out.push_str(&charset::render(&set));
        }
    }

    /// `set` with its case folded as JavaScript's `i` flag does.
    fn folded(&self, set: Set) -> Set {
        if !self.flags.i {
            set
        } else if self.flags.u {
            charset::folded(set)
        } else {
            upper_folded(set)
        }
    }

    /// 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) {
            let now = match b {
                b'\\' => self.escape()?,
                b'[' => {
                    self.class()?;
                    Some(true)
                }
                b'(' => self.group()?,
                b')' => self.close_group()?,
                b'.' => {
                    if self.flags.s {
                        self.push("(?s:.)", 1);
                    } else {
                        self.push(&format!("[^{TERMINATORS}]"), 1);
                    }
                    Some(true)
                }
                b'|' => {
                    if let Some(open) = self.open.last_mut() {
                        open.branch += 1;
                        let frame = open.frame;
                        self.frames[frame].branches += 1;
                    }
                    self.push("|", 1);
                    Some(false)
                }
                b'^' => {
                    if self.flags.m {
                        self.need_backtracking(MULTILINE);
                        self.push(&format!(r"(?:\A|(?<=[{TERMINATORS}]))"), 1);
                    } else {
                        self.push(r"\A", 1);
                    }
                    Some(false)
                }
                b'$' => {
                    if self.flags.m {
                        self.need_backtracking(MULTILINE);
                        self.push(&format!(r"(?:\z|(?=[{TERMINATORS}]))"), 1);
                    } else {
                        self.push(r"\z", 1);
                    }
                    Some(false)
                }
                b'/' if self.literal_form => {
                    return Err(
                        "a / outside a class in a /source/flags literal, which ends \
                                the literal: write \\/",
                    );
                }
                b'*' | b'+' | b'?' if !atom => {
                    return Err(
                        "a quantifier with nothing before it to repeat, or after an \
                                anchor, lookaround or another quantifier",
                    );
                }
                b'*' | b'+' | b'?' => {
                    self.quantifier(1);
                    Some(false)
                }
                b'{' => match self.interval()? {
                    Some(()) if !atom => {
                        return Err("a quantifier with nothing before it to repeat, or after \
                                    an anchor, lookaround or another quantifier");
                    }
                    Some(()) => Some(false),
                    None if self.flags.u => {
                        return Err("a lone { or } in a u-flag pattern, which JavaScript \
                                    rejects: write \\{");
                    }
                    None => {
                        self.push("\\x{7B}", 1);
                        Some(true)
                    }
                },
                b'}' | b']' if self.flags.u => {
                    return Err("a lone { or } or ] in a u-flag pattern, which JavaScript \
                                rejects: write the escape");
                }
                _ => {
                    let c = self.rest().chars().next().unwrap_or_default();
                    let width = c.len_utf8();
                    let quantified = matches!(
                        self.src.as_bytes().get(self.at + width),
                        Some(b'*' | b'+' | b'?' | b'{')
                    );
                    self.push_char(c, quantified)?;
                    self.at += width;
                    Some(true)
                }
            };
            if let Some(now) = now {
                atom = now;
            }
        }
        Ok(())
    }

    /// Read a `* + ?` quantifier of `width` bytes and the lazy `?` after it.
    fn quantifier(&mut self, width: usize) {
        let min0 = !matches!(self.byte(0), Some(b'+'));
        self.note_quantified(min0);
        let q = &self.rest()[..width];
        self.push(q, width);
        if self.byte(0) == Some(b'?') {
            self.push("?", 1);
        }
    }

    /// Record that the group the last `)` closed is repeated, and whether
    /// zero repeats are allowed.
    fn note_quantified(&mut self, min0: bool) {
        if let Some(frame) = self.last_closed.take() {
            self.frames[frame].optional |= min0;
        }
    }

    /// Read `{n}`, `{n,}` or `{n,m}` and its lazy suffix. `None` when the `{`
    /// opens no interval, which JavaScript reads as the brace without `u`.
    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<&[u8]> = None;
        if low > 0 && rest.get(end) == Some(&b',') {
            let n = digits(end + 1);
            high = Some(&rest[end + 1..end + 1 + n]);
            end += 1 + n;
        }
        if low == 0 || rest.get(end) != Some(&b'}') {
            return Ok(None);
        }
        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) {
            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");
        }
        self.note_quantified(n == 0);
        let interval = &self.rest()[..=end];
        self.push(interval, end + 1);
        if self.byte(0) == Some(b'?') {
            self.push("?", 1);
        }
        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);
        }
        let capture = self.byte(1) != Some(b'?')
            || (self.byte(2) == Some(b'<') && self.byte(3).is_some_and(|b| b != b'=' && b != b'!'));
        if self.in_lookbehind() && capture {
            return Err("a capture group in a lookbehind, which JavaScript matches backwards");
        }
        if self.byte(1) != Some(b'?') {
            self.open_frame(true, Look::No);
            self.push("(", 1);
            return Ok(Some(false));
        }
        let (a, b) = (self.byte(2), self.byte(3));
        let (text, width, look, why) = match (a, b) {
            (Some(b':'), _) => ("(?:", 3, Look::No, None),
            (Some(b'='), _) => ("(?=", 3, Look::Ahead, Some(LOOKAROUND)),
            (Some(b'!'), _) => ("(?!", 3, Look::Ahead, Some(LOOKAROUND)),
            (Some(b'<'), Some(b'=')) => ("(?<=", 4, Look::Behind, Some(LOOKAROUND)),
            (Some(b'<'), Some(b'!')) => ("(?<!", 4, Look::Behind, Some(LOOKAROUND)),
            (Some(b'<'), _) => return self.named(),
            _ => {
                return Err("a (? construct JavaScript's regex doesn't have, or a flag \
                            modifier (?i:...), which isn't read");
            }
        };
        if let Some(why) = why {
            self.need_backtracking(why);
        }
        let negative = text.ends_with('!');
        self.open_frame(false, look);
        if negative && let Some(open) = self.open.last() {
            self.frames[open.frame].optional = true;
        }
        self.push(text, width);
        Ok(Some(false))
    }

    /// Push a frame for a group just opened.
    fn open_frame(&mut self, capture: bool, look: Look) -> usize {
        let around = self.open.iter().map(|o| (o.frame, o.branch)).collect();
        let inside_negative = self
            .open
            .iter()
            .any(|o| self.frames[o.frame].optional && o.look == Look::Ahead);
        self.frames.push(Frame {
            closed: false,
            around,
            branches: 1,
            optional: inside_negative,
            capture,
        });
        let frame = self.frames.len() - 1;
        self.open.push(Open {
            frame,
            branch: 0,
            look,
        });
        frame
    }

    /// Read `(?<name>`.
    fn named(&mut self) -> Result<Option<bool>, &'static str> {
        let text = &self.rest()[3..];
        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.as_bytes().get(len) != Some(&b'>')
        {
            return Err(
                "a JavaScript group name here is ASCII letters, digits and _, not \
                        starting with a digit, closed by >",
            );
        }
        if self.names.iter().any(|(n, _)| *n == name) {
            return Err(
                "a group name used twice, which JavaScript allows only in separate \
                        alternatives of newer engines",
            );
        }
        let frame = self.open_frame(true, Look::No);
        self.names.push((name, frame));
        let open = format!("(?<{name}>");
        self.push(&open, 4 + len);
        Ok(Some(false))
    }

    /// Read a group's `)`.
    fn close_group(&mut self) -> Result<Option<bool>, &'static str> {
        if self.open.len() <= 1 {
            return Err("a ) with no ( before it");
        }
        let Some(open) = self.open.pop() else {
            return Err("a ) with no ( before it");
        };
        self.frames[open.frame].closed = true;
        self.last_closed = Some(open.frame);
        self.push(")", 1);
        // Lookaround takes no quantifier here, so the next one is refused.
        Ok(Some(open.look == Look::No))
    }

    /// Whether the reader sits inside a lookbehind.
    fn in_lookbehind(&self) -> bool {
        self.open.iter().any(|o| o.look == Look::Behind)
    }

    /// 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.push_set(set, false);
                self.at += 2;
            }
            b'b' | b'B' => {
                self.word_boundary(letter == b'B')?;
                return Ok(Some(false));
            }
            b'p' | b'P' if self.flags.u => {
                let set = self.property()?;
                self.push_set(set, true);
            }
            b'1'..=b'9' => self.backreference()?,
            b'k' => self.named_backreference()?,
            _ => {
                let (c, width) = self.escaped_char(false)?;
                let quantified = matches!(
                    self.src.as_bytes().get(self.at + width),
                    Some(b'*' | b'+' | b'?' | b'{')
                );
                self.push_char(c, quantified)?;
                self.at += width;
            }
        }
        Ok(Some(true))
    }

    /// The set a class escape letter stands for, in the flags' reading.
    fn class_set(&self, letter: u8) -> Set {
        let mut positive = match letter.to_ascii_lowercase() {
            b'd' => charset::digits(),
            b'w' => charset::word(),
            _ => js_space(),
        };
        if letter.eq_ignore_ascii_case(&b'w') && self.flags.i && self.flags.u {
            positive.union(&charset::set([
                ('\u{17F}', '\u{17F}'),
                ('\u{212A}', '\u{212A}'),
            ]));
        }
        if letter.is_ascii_uppercase() {
            charset::negated(positive)
        } else {
            positive
        }
    }

    fn word_boundary(&mut self, not: bool) -> Result<(), &'static str> {
        if self.flags.i && self.flags.u {
            return Err(
                "\\b or \\B under the i and u flags, where the word characters also \
                        include U+017F and U+212A: drop one of the flags",
            );
        }
        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);
        Ok(())
    }

    /// Read `\p{name}` or `\P{name}`, in u mode.
    fn property(&mut self) -> Result<Set, &'static str> {
        let negated = self.byte(1) == Some(b'P');
        if self.byte(2) != Some(b'{') {
            return Err("a \\p with no braced name, which a u-flag pattern rejects");
        }
        let close = self.rest()[3..].find('}').ok_or("a \\p{ with no }")?;
        let name = &self.rest()[3..3 + close];
        let set = property_set(name)?;
        self.at += 4 + close;
        Ok(if negated { charset::negated(set) } else { set })
    }

    /// Read `\1` to `\99`.
    fn backreference(&mut self) -> Result<(), &'static str> {
        let digits = self.rest().as_bytes()[1..]
            .iter()
            .take_while(|d| d.is_ascii_digit())
            .count();
        let number: usize = self.rest()[1..=digits].parse().unwrap_or(usize::MAX);
        if number > self.total {
            return Err(
                "a backslash and digits that name no group, which JavaScript reads as \
                        an octal escape without the u flag and rejects with it",
            );
        }
        self.reference(number - 1, 1 + digits)
    }

    /// Read `\k<name>`.
    fn named_backreference(&mut self) -> Result<(), &'static str> {
        if self.names.is_empty() {
            return Err(
                "a \\k with no named group in the pattern, which JavaScript reads as \
                        the letter k without the u flag and rejects with it",
            );
        }
        if self.byte(2) != Some(b'<') {
            return Err("a \\k needs a group name in <>");
        }
        let text = &self.rest()[3..];
        let close = text.find('>').ok_or("a \\k< with no >")?;
        let name = &text[..close];
        let Some(&(_, frame)) = self.names.iter().find(|(n, _)| *n == name) else {
            return Err("a \\k<name> that names no group opened before it");
        };
        self.reference_text(frame, &format!(r"(?:\k<{name}>)"), 3 + close + 1)
    }

    /// Write the backreference to the capture group whose index among the
    /// pattern's capture groups is `index`.
    fn reference(&mut self, index: usize, width: usize) -> Result<(), &'static str> {
        let Some(frame) = self
            .frames
            .iter()
            .enumerate()
            .filter(|(_, f)| f.capture)
            .nth(index)
            .map(|(i, _)| i)
        else {
            return Err("a backreference to a group that isn't opened before it");
        };
        let number = index + 1;
        self.reference_text(frame, &format!(r"(?:\{number})"), width)
    }

    fn reference_text(
        &mut self,
        frame: usize,
        text: &str,
        width: usize,
    ) -> Result<(), &'static str> {
        if self.flags.i {
            return Err(
                "a backreference under the i flag, which JavaScript compares by case \
                        folding and the backtracking tier compares as written",
            );
        }
        if self.in_lookbehind() || !self.certain(frame) {
            return Err(
                "a backreference to a group that may not have taken part, or inside a \
                        lookbehind, where JavaScript matches the empty string and the \
                        backtracking tier fails",
            );
        }
        self.need_backtracking(BACKREFERENCE);
        self.push(text, width);
        Ok(())
    }

    /// Whether the capture group in `frame` has always taken part by the
    /// reader's place.
    fn certain(&self, frame: usize) -> bool {
        let f = &self.frames[frame];
        if !f.closed || f.optional {
            return false;
        }
        f.around.iter().all(|&(id, branch)| {
            let around = &self.frames[id];
            self.open
                .iter()
                .find(|o| o.frame == id)
                .map_or(around.branches == 1 && !around.optional, |open| {
                    open.branch == branch
                })
        })
    }

    /// The one character the escape at the reader stands for, in or out of
    /// a class, and the escape's length.
    fn escaped_char(&self, in_class: bool) -> Result<(char, usize), &'static str> {
        let text = self.rest();
        let b = text.as_bytes();
        let letter = b[1];
        let simple = match letter {
            b't' => '\t',
            b'n' => '\n',
            b'r' => '\r',
            b'f' => '\u{c}',
            b'v' => '\u{b}',
            b'0' if !b.get(2).is_some_and(u8::is_ascii_digit) => '\0',
            b'0'..=b'9' => {
                return Err(
                    "a legacy octal escape or a backslash and a digit, which a u-flag \
                            pattern rejects: write \\x.. or \\u....",
                );
            }
            b'c' => {
                return match b.get(2) {
                    Some(&x) if x.is_ascii_alphabetic() => Ok((char::from(x % 32), 3)),
                    _ => Err("JavaScript's \\c needs a letter after it"),
                };
            }
            b'x' => return self.hex2(),
            b'u' => return self.unicode_escape(),
            _ if letter.is_ascii_alphanumeric() => {
                return Err(
                    "a backslash before a letter JavaScript has no escape for, which \
                            it reads as the letter without the u flag and rejects with it",
                );
            }
            _ => {
                let c = text[1..].chars().next().unwrap_or_default();
                let syntax = "^$\\.*+?()[]{}|/".contains(c) || (in_class && c == '-');
                if self.flags.u && !syntax {
                    return Err(
                        "a backslash before a character a u-flag pattern doesn't allow \
                                escaped",
                    );
                }
                return Ok((c, 1 + c.len_utf8()));
            }
        };
        Ok((simple, 2))
    }

    /// `\xhh`.
    fn hex2(&self) -> Result<(char, usize), &'static str> {
        let digits = self.rest().get(2..4).unwrap_or_default();
        if digits.len() == 2 && digits.bytes().all(|d| d.is_ascii_hexdigit()) {
            let value = u32::from_str_radix(digits, 16).unwrap_or(0);
            return Ok((char::from_u32(value).unwrap_or_default(), 4));
        }
        Err("JavaScript's \\x needs two hex digits, and reads the letter x without them")
    }

    /// `\uhhhh`, `\u{h...h}` in u mode, and a surrogate pair in u mode.
    fn unicode_escape(&self) -> Result<(char, usize), &'static str> {
        let text = self.rest();
        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())
        };
        if text.as_bytes().get(2) == Some(&b'{') {
            if !self.flags.u {
                return Err("\\u{...} without the u flag, which JavaScript reads as u repeated");
            }
            let close = text[3..].find('}').ok_or("a \\u{ with no }")?;
            let digits = &text[3..3 + close];
            let value = (!digits.is_empty() && digits.bytes().all(|d| d.is_ascii_hexdigit()))
                .then(|| u32::from_str_radix(digits, 16).ok())
                .flatten()
                .and_then(char::from_u32)
                .ok_or("a \\u{...} that names no character")?;
            return Ok((value, 4 + close));
        }
        let first = unit(2).ok_or("JavaScript's \\u needs four hex digits")?;
        if let Some(c) = char::from_u32(first) {
            return Ok((c, 6));
        }
        let low = (self.flags.u && text.get(6..8) == Some("\\u"))
            .then(|| unit(8))
            .flatten()
            .filter(|low| (0xDC00..=0xDFFF).contains(low) && (0xD800..=0xDBFF).contains(&first));
        match low {
            Some(low) => {
                let c = char::from_u32(0x10000 + ((first - 0xD800) << 10) + (low - 0xDC00))
                    .ok_or("a \\u surrogate pair that names no character")?;
                Ok((c, 12))
            }
            None => Err(
                "a \\u surrogate escape, which no UTF-8 text holds alone and which is \
                         read as one character only in a u-flag pattern",
            ),
        }
    }

    /// Read a class from its `[` to its `]`.
    fn class(&mut self) -> Result<(), &'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 members = Set::empty();
        let mut exact = Set::empty();
        let mut after_set = false;
        loop {
            let Some(c) = self.rest().chars().next() else {
                return Err("a [ with no ] to close it");
            };
            if c == ']' {
                self.at += 1;
                break;
            }
            let member = self.member(c)?;
            match member {
                Member::Set(set, true) => {
                    members.union(&set);
                    after_set = true;
                }
                Member::Set(set, false) => {
                    exact.union(&set);
                    after_set = true;
                }
                Member::Char(_) if c == '-' && after_set && self.byte(0) != Some(b']') => {
                    return Err("a - after a class such as \\d, which a u-flag pattern \
                                rejects and Annex B reads as a hyphen: escape it as \\-");
                }
                Member::Char(a) => {
                    let end = self.range_end(a)?;
                    members.union(&charset::set([(a, end)]));
                    after_set = false;
                }
            }
        }
        let mut set = self.folded(members);
        set.union(&exact);
        if negated {
            set.negate();
        }
        if self.flags.i && self.flags.u {
            self.out.push_str(&charset::render_exact(&set));
        } else {
            self.out.push_str(&charset::render(&set));
        }
        Ok(())
    }

    /// 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 a u-flag \
                                   pattern rejects and Annex B reads as a hyphen"),
        }
    }

    /// Read one class member starting with `c` at the reader.
    fn member(&mut self, c: char) -> Result<Member, &'static str> {
        if c != '\\' {
            if !self.flags.u && u32::from(c) > 0xFFFF {
                return Err(ASTRAL_IN_CLASS);
            }
            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), false))
            }
            b'b' => {
                self.at += 2;
                Ok(Member::Char('\u{8}'))
            }
            b'-' if self.flags.u => {
                self.at += 2;
                Ok(Member::Char('-'))
            }
            b'p' | b'P' if self.flags.u => self.property().map(|set| Member::Set(set, true)),
            b'B' | b'k' | b'1'..=b'9' => Err("a \\B, \\k or backreference in a class, which a \
                                              u-flag pattern rejects and Annex B reads \
                                              differently"),
            _ => {
                let (c, width) = self.escaped_char(true)?;
                if !self.flags.u && u32::from(c) > 0xFFFF {
                    return Err(ASTRAL_IN_CLASS);
                }
                self.at += width;
                Ok(Member::Char(c))
            }
        }
    }
}

/// Why an astral character before a quantifier is refused without `u`.
const ASTRAL_QUANTIFIED: &str = "a character past U+FFFF before a quantifier without the u \
     flag, which JavaScript reads as two units and repeats the second: add the u flag";

/// Why an astral character in a class is refused without `u`.
const ASTRAL_IN_CLASS: &str = "a character past U+FFFF in a class without the u flag, which \
     JavaScript reads as two units: add the u flag";

/// What JavaScript's `Canonicalize` makes of `c` without the `u` flag: its
/// one-character upper case, unless the upper case is several characters or
/// takes a non-ASCII character to ASCII.
fn canonical(c: char) -> char {
    let mut up = c.to_uppercase();
    let (Some(u), None) = (up.next(), up.next()) else {
        return c;
    };
    if !c.is_ascii() && u.is_ascii() { c } else { u }
}

/// The characters of the BMP that share a canonical form with another, each
/// with the group it belongs to.
fn fold_index() -> &'static HashMap<char, usize> {
    &fold_groups().0
}

fn fold_groups() -> &'static (HashMap<char, usize>, Vec<Vec<char>>) {
    static GROUPS: OnceLock<(HashMap<char, usize>, Vec<Vec<char>>)> = OnceLock::new();
    GROUPS.get_or_init(|| {
        let mut by_canonical: HashMap<char, Vec<char>> = HashMap::new();
        for c in '\0'..='\u{FFFF}' {
            by_canonical.entry(canonical(c)).or_default().push(c);
        }
        let mut groups: Vec<Vec<char>> = by_canonical
            .into_values()
            .filter(|members| members.len() > 1)
            .collect();
        groups.sort();
        let index = groups
            .iter()
            .enumerate()
            .flat_map(|(i, members)| members.iter().map(move |c| (*c, i)))
            .collect();
        (index, groups)
    })
}

/// `set` with every character that shares a canonical form with a member
/// added, as a class matches without the `u` flag under `i`.
fn upper_folded(mut set: Set) -> Set {
    let has = |c: char| {
        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()
    };
    let extra: Vec<char> = fold_groups()
        .1
        .iter()
        .filter(|members| members.iter().any(|c| has(*c)))
        .flatten()
        .copied()
        .collect();
    for c in extra {
        set.union(&charset::single(c));
    }
    set
}

/// JavaScript's `\s`: white space and line terminators.
fn js_space() -> Set {
    charset::set([
        ('\t', '\r'),
        (' ', ' '),
        ('\u{A0}', '\u{A0}'),
        ('\u{1680}', '\u{1680}'),
        ('\u{2000}', '\u{200A}'),
        ('\u{2028}', '\u{2029}'),
        ('\u{202F}', '\u{202F}'),
        ('\u{205F}', '\u{205F}'),
        ('\u{3000}', '\u{3000}'),
        ('\u{FEFF}', '\u{FEFF}'),
    ])
}

/// The set for a property name in a u-flag pattern, from the allowlist.
fn property_set(name: &str) -> Result<Set, &'static str> {
    let unread = "a \\p{...} name outside the general categories, scripts and few binary \
                  properties the JavaScript dialect reads";
    let canonical = match name.split_once('=') {
        Some(("General_Category" | "gc", value)) if category(value) => value.to_owned(),
        Some(("Script" | "sc", value)) if script(value) => format!("sc={value}"),
        Some(("Script_Extensions" | "scx", value)) if script(value) => format!("scx={value}"),
        Some(_) => return Err(unread),
        None if category(name) => name.to_owned(),
        None => match name {
            "Any" => return Ok(charset::set([('\0', char::MAX)])),
            "ASCII" => return Ok(charset::set([('\0', '\x7F')])),
            "Alphabetic" | "Lowercase" | "Uppercase" | "White_Space" => name.to_owned(),
            _ => return Err(unread),
        },
    };
    charset::property(&canonical).ok_or(unread)
}

fn category(name: &str) -> bool {
    (JAVA_CATEGORIES.contains(&name) && name != "Cs") || LONG_CATEGORIES.contains(&name)
}

/// The long names of the general categories, which JavaScript reads as it
/// reads the two-letter ones.
const LONG_CATEGORIES: &[&str] = &[
    "Letter",
    "Cased_Letter",
    "Uppercase_Letter",
    "Lowercase_Letter",
    "Titlecase_Letter",
    "Modifier_Letter",
    "Other_Letter",
    "Mark",
    "Nonspacing_Mark",
    "Spacing_Mark",
    "Enclosing_Mark",
    "Number",
    "Decimal_Number",
    "Letter_Number",
    "Other_Number",
    "Punctuation",
    "Connector_Punctuation",
    "Dash_Punctuation",
    "Open_Punctuation",
    "Close_Punctuation",
    "Initial_Punctuation",
    "Final_Punctuation",
    "Other_Punctuation",
    "Symbol",
    "Math_Symbol",
    "Currency_Symbol",
    "Modifier_Symbol",
    "Other_Symbol",
    "Separator",
    "Space_Separator",
    "Line_Separator",
    "Paragraph_Separator",
    "Other",
    "Control",
    "Format",
    "Private_Use",
    "Unassigned",
];

fn script(name: &str) -> bool {
    JAVA_SCRIPTS.contains(&name)
}