grippo 0.1.3

Parse, match and scrub data at scale.
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
// Project:   grippo
// File:      src/strmatch/ops.rs
// Purpose:   Captures, replace and split on a compiled StrMatcher
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Captures, replace and split. The plan finds each match on its cheapest
//! engine, and a capture engine runs only on a hit, only when a group past
//! group 0 is asked for.

use std::borrow::Cow;
use std::cell::Cell;

use regex_automata::util::captures::{Captures as Slots, GroupInfo};
use regex_automata::util::interpolate;
use regex_automata::util::iter::Searcher;
use regex_automata::util::primitives::{NonMaxUsize, PatternID};
use regex_automata::{Anchored, Input, meta};

use super::dialect::{self, final_terminator};
use super::plan::{JavaEnd, Plan, resume};
use super::{Match, StrMatcher};

/// The groups of one match. Make one with [`StrMatcher::create_captures`] and
/// reuse it, so a search allocates nothing.
#[derive(Debug, Clone)]
pub struct Captures {
    slots: Slots,
    /// Groups the pattern has, counting group 0. `slots` can hold one more,
    /// which the engine that reads `$` as Java's writes and the user never
    /// sees.
    len: usize,
}

impl Captures {
    /// `true` when the last search matched.
    #[must_use]
    pub fn is_match(&self) -> bool {
        self.slots.is_match()
    }

    /// The span of group `index`, 0 being the whole match. `None` for a
    /// group that took no part, or no match.
    #[must_use]
    pub fn get(&self, index: usize) -> Option<Match> {
        if index >= self.len {
            return None;
        }
        self.slots.get_group(index).map(|s| Match {
            start: s.start,
            end: s.end,
        })
    }

    /// The span of the group called `name`.
    #[must_use]
    pub fn name(&self, name: &str) -> Option<Match> {
        self.slots.get_group_by_name(name).map(|s| Match {
            start: s.start,
            end: s.end,
        })
    }

    /// Groups in the pattern, counting group 0.
    #[must_use]
    pub const fn group_len(&self) -> usize {
        self.len
    }

    /// Append `rep` to `dst` with each group it names copied from `hay`, as
    /// `replace` writes a match: `$2-$1` after `(\d+)-(\d+)` matched `10-20`
    /// appends `20-10`. A group that took no part, or that `hay` doesn't
    /// reach, writes nothing. Read `rep` with the matcher these groups came
    /// from, and pass the haystack it searched.
    pub fn expand(&self, hay: &[u8], rep: &Replacement, dst: &mut Vec<u8>) {
        rep.write(hay, |i| self.get(i), self.slots.group_info(), dst);
    }
}

/// How a replacement string reads `$` and `\`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReplaceSyntax {
    /// Written out as given: `$` and `\` are text.
    Literal,
    /// The regex crate's: `$N` and `$name` take the longest run of letters,
    /// digits and `_`, `${N}` and `${name}` are braced, `$$` is a dollar.
    #[default]
    Rust,
    /// Java's `Matcher.replaceAll`: `$N` takes further digits only while the
    /// number still names a group, so `$1_x` is group 1 then `_x`. `${name}`
    /// is a named group, and `\` writes the next character as text.
    Java,
}

/// A replacement read once against one matcher's groups.
#[derive(Debug, Clone)]
pub struct Replacement {
    /// In the regex crate's syntax, or the text to write for `Expand::None`.
    text: Box<[u8]>,
    expand: Expand,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Expand {
    None,
    WholeMatch,
    Groups,
}

impl Replacement {
    fn bind(text: Vec<u8>) -> Self {
        if memchr::memchr(b'$', &text).is_none() {
            return Self {
                text: text.into_boxed_slice(),
                expand: Expand::None,
            };
        }
        let (whole, groups) = (Cell::new(false), Cell::new(false));
        let mut plain: Vec<u8> = Vec::with_capacity(text.len());
        interpolate::bytes(
            &text,
            |index, _| {
                if index == 0 {
                    whole.set(true);
                } else {
                    groups.set(true);
                }
            },
            |_| {
                groups.set(true);
                None
            },
            &mut plain,
        );
        let (text, expand) = match (whole.get(), groups.get()) {
            (_, true) => (text, Expand::Groups),
            (true, false) => (text, Expand::WholeMatch),
            (false, false) => (plain, Expand::None),
        };
        Self {
            text: text.into_boxed_slice(),
            expand,
        }
    }

    fn write(
        &self,
        hay: &[u8],
        group: impl Fn(usize) -> Option<Match>,
        info: &GroupInfo,
        dst: &mut Vec<u8>,
    ) {
        if self.expand == Expand::None {
            dst.extend_from_slice(&self.text);
            return;
        }
        interpolate::bytes(
            &self.text,
            |index, dst| {
                if let Some(text) = group(index).and_then(|m| hay.get(m.start..m.end)) {
                    dst.extend_from_slice(text);
                }
            },
            |name| info.to_index(PatternID::ZERO, name),
            dst,
        );
    }
}

impl StrMatcher {
    /// Capture groups in the pattern, counting group 0.
    #[must_use]
    pub fn group_len(&self) -> usize {
        self.groups.info.group_len(PatternID::ZERO)
    }

    /// Each group's name in group order, `None` for an unnamed group.
    pub fn group_names(&self) -> impl Iterator<Item = Option<&str>> + '_ {
        self.groups.info.pattern_names(PatternID::ZERO)
    }

    /// The index of the group called `name`.
    #[must_use]
    pub fn group_index(&self, name: &str) -> Option<usize> {
        self.groups.info.to_index(PatternID::ZERO, name)
    }

    /// Room for this matcher's groups, to pass to [`Self::captures_into`].
    #[must_use]
    pub fn create_captures(&self) -> Captures {
        let layout = self.plan.layout().unwrap_or(&self.groups.info);
        Captures {
            slots: Slots::all(layout.clone()),
            len: self.group_len(),
        }
    }

    /// The groups of the first match, allocating their room.
    #[must_use]
    pub fn captures(&self, hay: &[u8]) -> Option<Captures> {
        let mut caps = self.create_captures();
        self.captures_into(hay, &mut caps).then_some(caps)
    }

    /// Write the groups of the first match into `caps` and say whether there
    /// was one. `caps` from another matcher with a different group count is
    /// replaced.
    pub fn captures_into(&self, hay: &[u8], caps: &mut Captures) -> bool {
        self.fit(caps);
        if !self.captures_from(&self.plan, hay, 0, caps) {
            caps.slots.set_pattern(None);
        }
        caps.slots.is_match()
    }

    /// Write the groups of the leftmost match starting at `from` or later
    /// into `caps`. Returns `false` when the backtracking tier passed its
    /// limit.
    fn captures_from(&self, plan: &Plan, hay: &[u8], from: usize, caps: &mut Captures) -> bool {
        let input = Input::new(hay).span(from.min(hay.len())..hay.len());
        match plan {
            Plan::Meta(r) => r.search_captures(&input, &mut caps.slots),
            #[cfg(feature = "strmatch-backtracking")]
            Plan::Backtrack(r) => match r.captures_from_pos(hay, from) {
                Ok(Some(found)) => fill_backtrack(&found, &self.groups.info, caps),
                Ok(None) => caps.slots.set_pattern(None),
                Err(_) => return false,
            },
            Plan::LineEnd(le) => match (final_terminator(hay), &le.java) {
                (None, _) => return self.captures_from(&le.inner, hay, from, caps),
                (Some(_), JavaEnd::Regex { find, groups, .. }) => {
                    java_captures(groups.as_ref().unwrap_or(find), &input, caps);
                }
                (Some(t), JavaEnd::Literals { .. }) => match le.find_at(hay, t, from) {
                    Some(m) => self.read_groups(&hay[..m.end], m, caps),
                    None => caps.slots.set_pattern(None),
                },
            },
            plan => match plan.find_from(hay, from) {
                Ok(Some(m)) => self.read_groups(hay, m, caps),
                Ok(None) => caps.slots.set_pattern(None),
                Err(_) => return false,
            },
        }
        true
    }

    /// The groups of every non-overlapping match, in order.
    #[must_use]
    pub fn captures_iter(&self, hay: &[u8]) -> std::vec::IntoIter<Captures> {
        let mut out: Vec<Captures> = Vec::new();
        let mut caps = self.create_captures();
        if !self.each_captures(hay, 0, &mut caps, |c| {
            out.push(c.clone());
            true
        }) {
            out.clear();
        }
        out.into_iter()
    }

    /// Read `text` as a replacement for this matcher's groups.
    #[must_use]
    pub fn replacement(&self, text: impl AsRef<[u8]>, syntax: ReplaceSyntax) -> Replacement {
        let text = text.as_ref();
        match syntax {
            ReplaceSyntax::Literal => Replacement {
                text: text.into(),
                expand: Expand::None,
            },
            ReplaceSyntax::Rust => Replacement::bind(text.to_vec()),
            ReplaceSyntax::Java => {
                Replacement::bind(dialect::java_replacement(text, self.group_len()))
            }
        }
    }

    /// Replace the first match. Borrows `hay` when nothing matches.
    #[must_use]
    pub fn replace<'h>(&self, hay: &'h [u8], rep: &Replacement) -> Cow<'h, [u8]> {
        self.replacen(hay, 1, rep)
    }

    /// Replace every non-overlapping match. Borrows `hay` when nothing
    /// matches.
    #[must_use]
    pub fn replace_all<'h>(&self, hay: &'h [u8], rep: &Replacement) -> Cow<'h, [u8]> {
        self.replacen(hay, 0, rep)
    }

    /// Replace the first `limit` matches, every one when `limit` is 0.
    /// Borrows `hay` when nothing matches, or when the backtracking tier
    /// passes its limit.
    #[must_use]
    pub fn replacen<'h>(&self, hay: &'h [u8], limit: usize, rep: &Replacement) -> Cow<'h, [u8]> {
        let mut out: Option<Vec<u8>> = None;
        let mut last = 0;
        let mut done = 0;
        let info = &self.groups.info;
        let mut put = |m: Match, write: &dyn Fn(&mut Vec<u8>)| {
            let dst = out.get_or_insert_with(|| Vec::with_capacity(hay.len()));
            dst.extend_from_slice(&hay[last..m.start]);
            write(dst);
            last = m.end;
            done += 1;
            limit == 0 || done < limit
        };
        let complete = if rep.expand == Expand::Groups {
            let Some(first) = self.plan.find(hay) else {
                return Cow::Borrowed(hay);
            };
            let mut caps = self.create_captures();
            self.each_captures(hay, first.start, &mut caps, |c| {
                let Some(m) = c.get(0) else { return true };
                put(m, &|dst| rep.write(hay, |i| c.get(i), info, dst))
            })
        } else {
            self.each_match(hay, |m| {
                put(m, &|dst| {
                    rep.write(hay, |i| (i == 0).then_some(m), info, dst);
                })
            })
        };
        match out {
            Some(mut dst) if complete => {
                dst.extend_from_slice(&hay[last..]);
                Cow::Owned(dst)
            }
            _ => Cow::Borrowed(hay),
        }
    }

    /// The pieces between every match.
    #[must_use]
    pub fn split<'h>(&self, hay: &'h [u8]) -> std::vec::IntoIter<&'h [u8]> {
        self.splitn(hay, usize::MAX)
    }

    /// At most `limit` pieces: the last one holds the rest of `hay` unsplit,
    /// and a `limit` of 0 gives none. When the backtracking tier passes its
    /// limit, `hay` is the one piece.
    #[must_use]
    pub fn splitn<'h>(&self, hay: &'h [u8], limit: usize) -> std::vec::IntoIter<&'h [u8]> {
        let mut out: Vec<&'h [u8]> = Vec::new();
        if limit == 0 {
            return out.into_iter();
        }
        let mut last = 0;
        let complete = self.each_match(hay, |m| {
            if out.len() + 1 >= limit {
                return false;
            }
            out.push(&hay[last..m.start]);
            last = m.end;
            true
        });
        if !complete {
            return vec![hay].into_iter();
        }
        out.push(&hay[last..]);
        out.into_iter()
    }

    fn fit(&self, caps: &mut Captures) {
        let layout = self.plan.layout().unwrap_or(&self.groups.info);
        if caps.slots.group_info().slot_len() != layout.slot_len() || caps.len != self.group_len() {
            *caps = self.create_captures();
        }
    }

    /// The groups of a hit a literal plan found at `m`. For a hit that ends
    /// before a final line terminator, pass `hay` cut there, so its `$` holds.
    fn read_groups(&self, hay: &[u8], m: Match, caps: &mut Captures) {
        if let Some(r) = &self.groups.anchored {
            let input = Input::new(hay).span(m.start..m.end).anchored(Anchored::Yes);
            r.search_captures(&input, &mut caps.slots);
            if caps.slots.is_match() {
                return;
            }
        }
        set_whole(m, &self.groups.info, caps);
    }

    /// Call `f` on the groups of each match from `from` on, until it returns
    /// `false`. `from` must be at or before the first match. Returns `false`
    /// when the backtracking tier passed its limit.
    fn each_captures(
        &self,
        hay: &[u8],
        from: usize,
        caps: &mut Captures,
        f: impl FnMut(&Captures) -> bool,
    ) -> bool {
        self.fit(caps);
        if self.java_empty {
            self.each_captures_java(hay, from, caps, f)
        } else {
            self.each_captures_on(&self.plan, hay, from, caps, f)
        }
    }

    /// As [`Self::each_captures`], with Java's rule for empty matches.
    fn each_captures_java(
        &self,
        hay: &[u8],
        from: usize,
        caps: &mut Captures,
        mut f: impl FnMut(&Captures) -> bool,
    ) -> bool {
        let mut at = from;
        while at <= hay.len() {
            if !self.captures_from(&self.plan, hay, at, caps) {
                return false;
            }
            let Some(m) = caps.get(0) else { break };
            if !f(caps) {
                break;
            }
            at = resume(hay, m);
        }
        true
    }

    fn each_captures_on(
        &self,
        plan: &Plan,
        hay: &[u8],
        from: usize,
        caps: &mut Captures,
        mut f: impl FnMut(&Captures) -> bool,
    ) -> bool {
        match plan {
            Plan::Meta(r) => {
                each_search(
                    hay,
                    from,
                    caps,
                    |input, caps| {
                        r.search_captures(input, &mut caps.slots);
                    },
                    f,
                );
                true
            }
            #[cfg(feature = "strmatch-backtracking")]
            Plan::Backtrack(r) => {
                for found in r.captures_iter(hay) {
                    let Ok(found) = found else { return false };
                    fill_backtrack(&found, &self.groups.info, caps);
                    if !f(caps) {
                        break;
                    }
                }
                true
            }
            Plan::LineEnd(le) => match (final_terminator(hay), &le.java) {
                (None, _) => self.each_captures_on(&le.inner, hay, from, caps, f),
                (Some(_), JavaEnd::Regex { find, groups, .. }) => {
                    let re = groups.as_ref().unwrap_or(find);
                    each_search(
                        hay,
                        from,
                        caps,
                        |input, caps| java_captures(re, input, caps),
                        f,
                    );
                    true
                }
                (Some(t), JavaEnd::Literals { .. }) => {
                    le.each_at(hay, t, &mut |m| {
                        self.read_groups(&hay[..m.end], m, caps);
                        f(caps)
                    });
                    true
                }
            },
            plan => plan.for_each_match(hay, |m| {
                self.read_groups(hay, m, caps);
                f(caps)
            }),
        }
    }
}

/// Call `f` on the groups of each match `search` writes into `caps`, from
/// `from` on, until it returns `false`, with the regex crate's rule for empty
/// matches.
fn each_search(
    hay: &[u8],
    from: usize,
    caps: &mut Captures,
    search: impl Fn(&Input<'_>, &mut Captures),
    mut f: impl FnMut(&Captures) -> bool,
) {
    let mut it = Searcher::new(Input::new(hay).span(from..hay.len()));
    loop {
        let found = it.advance(|input| {
            search(input, caps);
            Ok(caps.slots.get_match())
        });
        if found.is_none() || !f(caps) {
            return;
        }
    }
}

/// A search on a regex [`JavaEnd::Regex`] built, which marks in its hidden
/// last group a terminator a `$` stepped over. The match and each group bound
/// at the end move back to where that terminator starts, where Java's `$`
/// stood.
fn java_captures(re: &meta::Regex, input: &Input<'_>, caps: &mut Captures) {
    // The marker must read as unset unless this search set it.
    if let [.., start, end] = caps.slots.slots_mut() {
        (*start, *end) = (None, None);
    }
    re.search_captures(input, &mut caps.slots);
    if !caps.slots.is_match() {
        return;
    }
    let end = input.haystack().len();
    let [groups @ .., start, marker_end] = caps.slots.slots_mut() else {
        return;
    };
    let Some(at) = start.take() else { return };
    *marker_end = None;
    for slot in groups
        .iter_mut()
        .filter(|s| s.is_some_and(|s| s.get() == end))
    {
        *slot = Some(at);
    }
}

/// Group 0 at `m` and every other group unset.
fn set_whole(m: Match, info: &GroupInfo, caps: &mut Captures) {
    caps.slots.set_pattern(Some(PatternID::ZERO));
    let slots = caps.slots.slots_mut();
    slots.fill(None);
    if let Some((start, end)) = info.slots(PatternID::ZERO, 0) {
        slots[start] = NonMaxUsize::new(m.start);
        slots[end] = NonMaxUsize::new(m.end);
    }
}

#[cfg(feature = "strmatch-backtracking")]
fn fill_backtrack(found: &fancy_regex::Captures<'_, [u8]>, info: &GroupInfo, caps: &mut Captures) {
    caps.slots.set_pattern(Some(PatternID::ZERO));
    let slots = caps.slots.slots_mut();
    slots.fill(None);
    for index in 0..info.group_len(PatternID::ZERO) {
        if let (Some((start, end)), Some(m)) =
            (info.slots(PatternID::ZERO, index), found.get(index))
        {
            slots[start] = NonMaxUsize::new(m.start());
            slots[end] = NonMaxUsize::new(m.end());
        }
    }
}