grippo 0.2.4

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
// Project:   grippo
// File:      src/ua/literals.rs
// Purpose:   ua-parser's pattern rewrite and each rule's required literals
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A rule's regex is read as ua-parser reads it, then walked for the
//! literals any match must contain, as RE2's `FilteredRE2` does: exact string
//! sets up to a size cap, else an AND/OR condition over atoms of at least a
//! minimum length. The condition becomes one literal clause per DNF term.

use std::collections::BTreeSet;

use regex_syntax::hir::{Class, Hir, HirKind};

/// Most strings an exact set holds before it becomes a condition.
const EXACT_CAP: usize = 16;
/// Widest class expanded into its characters.
const CLASS_CAP: u32 = 4;
/// Most DNF clauses one rule takes.
pub(super) const DNF_CAP: usize = 64;

/// `re` as ua-parser 0.2.2 reads it: `\d`, `\D`, `\w` and `\W` as their
/// ASCII sets, and `{0,N}` or `{1,N}` outside a class, with N of three
/// digits or more, as `*` or `+`.
pub(super) fn rewrite(re: &str) -> String {
    let chars: Vec<char> = re.chars().collect();
    let mut out = String::with_capacity(re.len());
    // Every unescaped bracket counts, as ua-parser counts them, so `[]` can
    // leave the depth below zero.
    let (mut i, mut escaped, mut class) = (0, false, 0_isize);
    while let Some(&c) = chars.get(i) {
        i += 1;
        if escaped {
            escaped = false;
            match c {
                'd' => out.push_str("[0-9]"),
                'D' => out.push_str("[^0-9]"),
                'w' => out.push_str("[A-Za-z0-9_]"),
                'W' => out.push_str("[^A-Za-z0-9_]"),
                _ => {
                    out.push('\\');
                    out.push(c);
                }
            }
            continue;
        }
        match c {
            '\\' => {
                escaped = true;
                continue;
            }
            '[' => class += 1,
            ']' => class -= 1,
            '{' if class == 0 && i > 1 => {
                if let Some((star, len)) = wide_range(&chars[i..]) {
                    out.push_str(star);
                    i += len;
                    continue;
                }
            }
            _ => {}
        }
        out.push(c);
    }
    if escaped {
        out.push('\\');
    }
    out
}

/// After a `{`: `0,N}` or `1,N}` with N of three digits or more, as the
/// repeat it reads as and the characters it spans.
fn wide_range(rest: &[char]) -> Option<(&'static str, usize)> {
    let star = match rest.first()? {
        '0' => "*",
        '1' => "+",
        _ => return None,
    };
    if rest.get(1) != Some(&',') {
        return None;
    }
    let digits = rest[2..].iter().take_while(|c| c.is_ascii_digit()).count();
    (digits >= 3 && rest.get(2 + digits) == Some(&'}')).then_some((star, digits + 3))
}

/// What a match must contain.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Cond {
    /// Nothing is required.
    All,
    Atom(Vec<u8>),
    And(Vec<Self>),
    Or(Vec<Self>),
}

/// A sub-expression's exact strings, when there are few enough, else what it
/// requires.
struct Info {
    exact: Option<BTreeSet<Vec<u8>>>,
    cond: Cond,
}

impl Info {
    fn exact(s: &[u8]) -> Self {
        Self {
            exact: Some(BTreeSet::from([s.to_vec()])),
            cond: Cond::All,
        }
    }

    const fn unknown() -> Self {
        Self {
            exact: None,
            cond: Cond::All,
        }
    }

    fn into_cond(self, min: usize) -> Cond {
        match self.exact {
            Some(set) => exact_cond(set, min),
            None => self.cond,
        }
    }
}

fn and(parts: Vec<Cond>) -> Cond {
    let mut out = BTreeSet::new();
    for p in parts {
        match p {
            Cond::All => {}
            Cond::And(inner) => out.extend(inner),
            other => {
                out.insert(other);
            }
        }
    }
    collapse(out, Cond::And)
}

fn or(parts: Vec<Cond>) -> Cond {
    let mut out = BTreeSet::new();
    for p in parts {
        match p {
            Cond::All => return Cond::All,
            Cond::Or(inner) => out.extend(inner),
            other => {
                out.insert(other);
            }
        }
    }
    collapse(out, Cond::Or)
}

fn collapse(set: BTreeSet<Cond>, many: fn(Vec<Cond>) -> Cond) -> Cond {
    if set.len() > 1 {
        return many(set.into_iter().collect());
    }
    set.into_iter().next().unwrap_or(Cond::All)
}

/// An OR of the strings, or nothing required when one is shorter than `min`.
fn exact_cond(set: BTreeSet<Vec<u8>>, min: usize) -> Cond {
    if set.iter().any(|s| s.len() < min) {
        return Cond::All;
    }
    or(set.into_iter().map(Cond::Atom).collect())
}

fn class_set(
    ranges: impl Iterator<Item = (u32, u32)> + Clone,
    to: fn(u32) -> Option<Vec<u8>>,
) -> Info {
    let width: u32 = ranges.clone().map(|(a, b)| b - a + 1).sum();
    if width > CLASS_CAP {
        return Info::unknown();
    }
    let set = ranges.flat_map(|(a, b)| a..=b).filter_map(to).collect();
    Info {
        exact: Some(set),
        cond: Cond::All,
    }
}

fn info(h: &Hir, min: usize) -> Info {
    match h.kind() {
        HirKind::Empty | HirKind::Look(_) => Info::exact(b""),
        HirKind::Literal(l) => Info::exact(&l.0),
        HirKind::Class(Class::Unicode(c)) => class_set(
            c.ranges()
                .iter()
                .map(|r| (u32::from(r.start()), u32::from(r.end()))),
            |cp| char::from_u32(cp).map(|ch| ch.to_string().into_bytes()),
        ),
        HirKind::Class(Class::Bytes(c)) => class_set(
            c.ranges()
                .iter()
                .map(|r| (u32::from(r.start()), u32::from(r.end()))),
            |b| u8::try_from(b).ok().map(|b| vec![b]),
        ),
        HirKind::Repetition(r) => {
            if r.min == 0 {
                return Info::unknown();
            }
            let sub = info(&r.sub, min);
            if r.min == 1 && r.max == Some(1) {
                return sub;
            }
            Info {
                exact: None,
                cond: sub.into_cond(min),
            }
        }
        HirKind::Capture(c) => info(&c.sub, min),
        HirKind::Concat(parts) => concat(parts, min),
        HirKind::Alternation(parts) => {
            let infos: Vec<Info> = parts.iter().map(|p| info(p, min)).collect();
            let total: Option<usize> = infos
                .iter()
                .map(|i| i.exact.as_ref().map(BTreeSet::len))
                .sum();
            if total.is_some_and(|n| n <= EXACT_CAP) {
                return Info {
                    exact: Some(
                        infos
                            .into_iter()
                            .filter_map(|i| i.exact)
                            .flatten()
                            .collect(),
                    ),
                    cond: Cond::All,
                };
            }
            Info {
                exact: None,
                cond: or(infos.into_iter().map(|i| i.into_cond(min)).collect()),
            }
        }
    }
}

/// A concatenation: exact runs cross-multiplied while they stay small, each
/// run that grows too big or meets an inexact part closed into a condition.
fn concat(parts: &[Hir], min: usize) -> Info {
    let mut conds = Vec::new();
    let mut run: BTreeSet<Vec<u8>> = BTreeSet::from([Vec::new()]);
    for p in parts {
        let pi = info(p, min);
        match pi.exact {
            Some(e) if run.len() * e.len() <= EXACT_CAP => {
                let mut next = BTreeSet::new();
                for a in &run {
                    for b in &e {
                        let mut s = a.clone();
                        s.extend_from_slice(b);
                        next.insert(s);
                    }
                }
                run = next;
            }
            Some(e) => conds.push(exact_cond(std::mem::replace(&mut run, e), min)),
            None => {
                conds.push(exact_cond(
                    std::mem::replace(&mut run, BTreeSet::from([Vec::new()])),
                    min,
                ));
                conds.push(pi.cond);
            }
        }
    }
    if conds.is_empty() {
        return Info {
            exact: Some(run),
            cond: Cond::All,
        };
    }
    conds.push(exact_cond(run, min));
    Info {
        exact: None,
        cond: and(conds),
    }
}

/// One AND of literals and one OR of literals implied by `c`, weaker than
/// `c` where it nests deeper.
fn flat(c: &Cond) -> (BTreeSet<Vec<u8>>, Option<BTreeSet<Vec<u8>>>) {
    match c {
        Cond::All => (BTreeSet::new(), None),
        Cond::Atom(a) => (BTreeSet::from([a.clone()]), None),
        Cond::And(parts) => {
            let mut all = BTreeSet::new();
            let mut best: Option<BTreeSet<Vec<u8>>> = None;
            let score = |s: &BTreeSet<Vec<u8>>| {
                (
                    s.iter().map(Vec::len).min().unwrap_or(0),
                    usize::MAX - s.len(),
                )
            };
            for p in parts {
                let (a, any) = flat(p);
                all.extend(a);
                if let Some(any) = any
                    && best.as_ref().is_none_or(|b| score(&any) > score(b))
                {
                    best = Some(any);
                }
            }
            (all, best)
        }
        Cond::Or(parts) => {
            let mut any = BTreeSet::new();
            for p in parts {
                let (a, sub) = flat(p);
                if let Some(longest) = a.iter().max_by_key(|l| l.len()) {
                    any.insert(longest.clone());
                } else if let Some(sub) = sub {
                    any.extend(sub);
                } else {
                    return (BTreeSet::new(), None);
                }
            }
            (BTreeSet::new(), Some(any))
        }
    }
}

/// `c` as an OR of AND clauses. An AND that would pass `cap` clauses drops
/// that conjunct, which only weakens the filter. `None` when an OR alone
/// passes `cap`.
fn dnf(c: &Cond, cap: usize) -> Option<Vec<BTreeSet<Vec<u8>>>> {
    match c {
        Cond::All => Some(vec![BTreeSet::new()]),
        Cond::Atom(a) => Some(vec![BTreeSet::from([a.clone()])]),
        Cond::Or(parts) => {
            let mut out = Vec::new();
            for p in parts {
                let d = dnf(p, cap)?;
                if d.iter().any(BTreeSet::is_empty) {
                    return Some(vec![BTreeSet::new()]);
                }
                out.extend(d);
                if out.len() > cap {
                    return None;
                }
            }
            Some(out)
        }
        Cond::And(parts) => {
            let mut out = vec![BTreeSet::new()];
            for p in parts {
                let Some(d) = dnf(p, cap) else { continue };
                if d.len() * out.len() > cap {
                    continue;
                }
                let mut next = Vec::with_capacity(d.len() * out.len());
                for a in &out {
                    for b in &d {
                        let mut s = a.clone();
                        s.extend(b.iter().cloned());
                        next.push(s);
                    }
                }
                out = next;
            }
            Some(out)
        }
    }
}

/// What a rule's matches must contain.
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Required {
    /// Nothing: the rule is tried on every string.
    Nothing,
    /// One `all_of` set per clause, any of which may hold.
    Clauses(Vec<Vec<Vec<u8>>>),
    /// One `all_of` set and one `any_of` set, past [`DNF_CAP`] clauses.
    Flat {
        all_of: Vec<Vec<u8>>,
        any_of: Vec<Vec<u8>>,
    },
}

/// The literals a match of `hir` must contain, as atoms of at least `min`
/// bytes.
pub(super) fn required(hir: &Hir, min: usize) -> Required {
    let cond = info(hir, min).into_cond(min);
    if let Some(clauses) = dnf(&cond, DNF_CAP) {
        if clauses.iter().any(BTreeSet::is_empty) {
            return Required::Nothing;
        }
        return Required::Clauses(
            clauses
                .into_iter()
                .map(|c| c.into_iter().collect())
                .collect(),
        );
    }
    let (all, any) = flat(&cond);
    let (all_of, any_of): (Vec<Vec<u8>>, Vec<Vec<u8>>) = (
        all.into_iter().collect(),
        any.unwrap_or_default().into_iter().collect(),
    );
    if all_of.is_empty() && any_of.is_empty() {
        return Required::Nothing;
    }
    Required::Flat { all_of, any_of }
}