grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
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
// Project:   grippo
// File:      src/strmatch/dialect.rs
// Purpose:   Pattern and replacement readings other regex dialects expect
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

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

use std::borrow::Cow;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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