regex-filtered 0.2.1

Efficiently check an input against a large number of patterns
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
#![doc = include_str!("../README.md")]
#![deny(unsafe_code)]
#![warn(missing_docs)]

use aho_corasick::AhoCorasick;

mod int_set;
pub mod mapper;
pub mod model;
pub use model::Error as ModelError;

/// Builder for the regexes set
pub struct Builder {
    regexes: Vec<regex::Regex>,
    mapper_builder: mapper::Builder,
}

/// Parser configuration, can be used to tune the regex parsing when
/// adding it to the [`Builder`]. Every option defaults to `false`
/// whether through [`Default`] or [`Options::new`].
///
/// The parser can also be configured via standard [`regex`] inline
/// flags.
#[derive(Default)]
pub struct Options {
    case_insensitive: bool,
    dot_matches_new_line: bool,
    ignore_whitespace: bool,
    multi_line: bool,
    crlf: bool,
}

impl Options {
    /// Create a new options object.
    pub fn new() -> Self {
        Self::default()
    }
    /// Configures case-insensitive matching for the entire pattern.
    pub fn case_insensitive(&mut self, yes: bool) -> &mut Self {
        self.case_insensitive = yes;
        self
    }
    /// Configures `.` to match newline characters, by default `.`
    /// matches everything *except* newline characters.
    pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut Self {
        self.dot_matches_new_line = yes;
        self
    }
    /// Configures ignoring whitespace inside patterns, as well as `#`
    /// line comments ("verbose" mode).
    ///
    /// Verbose mode is useful to break up complex regexes and improve
    /// their documentation.
    pub fn ignore_whitespace(&mut self, yes: bool) -> &mut Self {
        self.ignore_whitespace = yes;
        self
    }
    /// Configures multi-line mode. When enabled, `^` matches at every
    /// start of line and `$` at every end of line, by default they
    /// match only the start and end of the string respectively.ca
    pub fn multi_line(&mut self, yes: bool) -> &mut Self {
        self.multi_line = yes;
        self
    }
    /// Allows `\r` as a line terminator, by default only `\n` is a
    /// line terminator (relevant for [`Self::ignore_whitespace`] and
    /// [`Self::multi_line`]).
    pub fn crlf(&mut self, yes: bool) -> &mut Self {
        self.crlf = yes;
        self
    }
    fn to_regex(&self, pattern: &str) -> Result<regex::Regex, regex::Error> {
        regex::RegexBuilder::new(pattern)
            .case_insensitive(self.case_insensitive)
            .dot_matches_new_line(self.dot_matches_new_line)
            .ignore_whitespace(self.ignore_whitespace)
            .multi_line(self.multi_line)
            .crlf(self.crlf)
            .build()
    }
}
impl From<Options> for regex_syntax::Parser {
    fn from(opt: Options) -> Self {
        Self::from(&opt)
    }
}
impl From<&Options> for regex_syntax::Parser {
    fn from(
        Options {
            case_insensitive,
            dot_matches_new_line,
            ignore_whitespace,
            multi_line,
            crlf,
        }: &Options,
    ) -> Self {
        regex_syntax::ParserBuilder::new()
            .case_insensitive(*case_insensitive)
            .dot_matches_new_line(*dot_matches_new_line)
            .ignore_whitespace(*ignore_whitespace)
            .multi_line(*multi_line)
            .crlf(*crlf)
            .build()
    }
}

/// Parsing error when adding a new regex to the [`Builder`].
#[derive(Debug)]
pub enum ParseError {
    /// An error occurred while parsing the regex or translating it to
    /// HIR.
    SyntaxError(String),
    /// An error occurred while processing the regex for atom
    /// extraction.
    ProcessingError(ModelError),
    /// The regex was too large to compile to the NFA (within the
    /// default limits).
    RegexTooLarge(usize),
}
impl std::error::Error for ParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ParseError::ProcessingError(e) => Some(e),
            ParseError::SyntaxError(_) => None,
            ParseError::RegexTooLarge(_) => None,
        }
    }
}
impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}
impl From<regex_syntax::Error> for ParseError {
    fn from(value: regex_syntax::Error) -> Self {
        Self::SyntaxError(value.to_string())
    }
}
impl From<regex::Error> for ParseError {
    fn from(value: regex::Error) -> Self {
        match value {
            regex::Error::CompiledTooBig(v) => Self::RegexTooLarge(v),
            e => Self::SyntaxError(e.to_string()),
        }
    }
}
impl From<ModelError> for ParseError {
    fn from(value: ModelError) -> Self {
        Self::ProcessingError(value)
    }
}

/// Error while compiling the builder to a prefiltered set.
#[derive(Debug)]
pub enum BuildError {
    /// Error while building the prefilter.
    PrefilterError(aho_corasick::BuildError),
}
impl std::error::Error for BuildError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            BuildError::PrefilterError(p) => Some(p),
        }
    }
}
impl std::fmt::Display for BuildError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}
impl From<aho_corasick::BuildError> for BuildError {
    fn from(value: aho_corasick::BuildError) -> Self {
        Self::PrefilterError(value)
    }
}

impl Builder {
    /// Instantiate a builder with the default metadata configuration:
    ///
    /// - minimum atom length 3
    #[must_use]
    pub fn new() -> Self {
        Self::new_atom_len(3)
    }

    /// Instantiate a builder with a custom minimum atom length.
    /// Increasing the atom length decreases the size and cost of the
    /// prefilter, but may make more regexes impossible to prefilter,
    /// which can increase matching costs.
    #[must_use]
    pub fn new_atom_len(min_atom_len: usize) -> Self {
        Self {
            regexes: Vec::new(),
            mapper_builder: mapper::Builder::new(min_atom_len),
        }
    }

    /// Currently loaded regexes.
    pub fn regexes(&self) -> &[regex::Regex] {
        &self.regexes
    }

    /// Push a single regex into the builder, using the default
    /// parsing options.
    pub fn push(self, s: &str) -> Result<Self, ParseError> {
        self.push_opt(s, &Options::new())
    }

    /// Push a single regex into the builder, using custom parsing
    /// options.
    pub fn push_opt(mut self, regex: &str, opts: &Options) -> Result<Self, ParseError> {
        let hir = regex_syntax::Parser::from(opts).parse(regex)?;
        let pf = model::Model::new(&hir)?;
        self.mapper_builder.push(pf);
        self.regexes.push(opts.to_regex(regex)?);
        Ok(self)
    }

    /// Push a batch of regexes into the builder, using the default
    /// parsing options.
    pub fn push_all<T, I>(self, i: I) -> Result<Self, ParseError>
    where
        T: AsRef<str>,
        I: IntoIterator<Item = T>,
    {
        i.into_iter().try_fold(self, |b, s| b.push(s.as_ref()))
    }

    /// Build the regexes set from the current builder.
    ///
    /// Building a regexes set from no regexes is useless but not an
    /// error.
    pub fn build(self) -> Result<Regexes, BuildError> {
        let Self {
            regexes,
            mapper_builder,
        } = self;
        let (mapper, atoms) = mapper_builder.build();

        // Instead of returning a bunch of atoms for the user to
        // manage, since `regex` depends on aho-corasick by default we
        // can use that directly and not bother the user.
        let prefilter = AhoCorasick::builder()
            .ascii_case_insensitive(true)
            .prefilter(true)
            .build(atoms)?;

        Ok(Regexes {
            regexes,
            mapper,
            prefilter,
        })
    }
}

impl Default for Builder {
    fn default() -> Self {
        Self::new()
    }
}

/// Regexes set, allows testing inputs against a *large* number of
/// *non-trivial* regexes.
pub struct Regexes {
    regexes: Vec<regex::Regex>,
    mapper: mapper::Mapper,
    prefilter: AhoCorasick,
}

impl Regexes {
    // TODO:
    // - number of tokens (prefilter.patterns_len())
    // - number of regexes
    // - number of unfiltered regexes (from mapper)
    // - ratio of checked regexes to successes (cfg-gated)
    // - total / prefiltered (- unfiltered?) so atom size can be manipulated
    #[inline]
    fn prefilter<'a>(&'a self, haystack: &'a str) -> impl Iterator<Item = usize> + 'a {
        self.prefilter
            .find_overlapping_iter(haystack)
            .map(|m| m.pattern().as_usize())
    }

    #[inline]
    fn prefiltered(&self, haystack: &str) -> impl Iterator<Item = usize> + use<> {
        self.mapper.atom_to_re(self.prefilter(haystack)).into_iter()
    }

    /// Returns *whether* any regex in the set matches the haystack.
    pub fn is_match(&self, haystack: &str) -> bool {
        self.prefiltered(haystack)
            .any(|idx| self.regexes[idx].is_match(haystack))
    }

    /// Yields the regexes matching the haystack along with their
    /// index.
    ///
    /// The results are guaranteed to be returned in ascending order.
    pub fn matching<'a>(
        &'a self,
        haystack: &'a str,
    ) -> impl Iterator<Item = (usize, &'a regex::Regex)> + 'a {
        self.prefiltered(haystack).filter_map(move |idx| {
            let r = &self.regexes[idx];
            r.is_match(haystack).then_some((idx, r))
        })
    }

    /// Returns a reference to all the regexes in the set.
    pub fn regexes(&self) -> &[regex::Regex] {
        &self.regexes
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use itertools::Itertools;

    #[test]
    fn empty_filter() {
        let f = Builder::new().build().unwrap();
        assert_eq!(f.prefilter("0123").collect_vec(), vec![]);

        assert_eq!(f.matching("foo").count(), 0);
    }

    #[test]
    fn empty_pattern() {
        let f = Builder::new().push("").unwrap().build().unwrap();

        assert_eq!(f.prefilter("0123").collect_vec(), vec![]);

        assert_eq!(
            f.matching("0123").map(|(idx, _)| idx).collect_vec(),
            vec![0]
        );
    }

    #[test]
    fn small_or_test() {
        let f = Builder::new_atom_len(4)
            .push("(foo|bar)")
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(f.prefilter("lemurs bar").collect_vec(), vec![]);

        assert_eq!(
            f.matching("lemurs bar").map(|(idx, _)| idx).collect_vec(),
            vec![0],
        );

        let f = Builder::new().push("(foo|bar)").unwrap().build().unwrap();

        assert_eq!(f.prefilter("lemurs bar").collect_vec(), vec![1]);

        assert_eq!(
            f.matching("lemurs bar").map(|(idx, _)| idx).collect_vec(),
            vec![0],
        );
    }

    #[test]
    fn basic_matches() {
        let f = Builder::new()
            .push("(abc123|abc|defxyz|ghi789|abc1234|xyz).*[x-z]+")
            .unwrap()
            .push("abcd..yyy..yyyzzz")
            .unwrap()
            .push("mnmnpp[a-z]+PPP")
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(
            f.matching("abc121212xyz").map(|(idx, _)| idx).collect_vec(),
            vec![0],
        );

        assert_eq!(
            f.matching("abc12312yyyzzz")
                .map(|(idx, _)| idx)
                .collect_vec(),
            vec![0],
        );

        assert_eq!(
            f.matching("abcd12yyy32yyyzzz")
                .map(|(idx, _)| idx)
                .collect_vec(),
            vec![0, 1],
        );
    }

    #[test]
    fn basics() {
        // In re2 this is the `MoveSemantics` test, which is... so not
        // necessary for us. But it's a pair of extra regexes we can
        // test

        let f = Builder::new().push("foo\\d+").unwrap().build().unwrap();

        assert_eq!(
            f.matching("abc foo1 xyz").map(|(idx, _)| idx).collect_vec(),
            vec![0],
        );
        assert_eq!(
            f.matching("abc bar2 xyz").map(|(idx, _)| idx).collect_vec(),
            vec![],
        );

        let f = Builder::new().push("bar\\d+").unwrap().build().unwrap();

        assert_eq!(
            f.matching("abc foo1 xyz").map(|(idx, _)| idx).collect_vec(),
            vec![],
        );
        assert_eq!(
            f.matching("abc bar2 xyz").map(|(idx, _)| idx).collect_vec(),
            vec![0],
        );
    }

    #[test]
    fn bulk_api() {
        use std::io::BufRead as _;

        Builder::new().push_all(["a", "b"]).unwrap();

        Builder::new()
            .push_all(vec!["a".to_string(), "b".to_string()])
            .unwrap();

        Builder::new().push_all("a\nb\nc\nd\n".lines()).unwrap();

        Builder::new()
            .push_all(b"a\nb\nc\nd\n".lines().map(|l| l.unwrap()))
            .unwrap();
    }

    #[test]
    fn alternate() {
        let f = Builder::new().push("abc|").unwrap().build().unwrap();
        assert_eq!(
            f.matching("abcde").map(|(idx, _)| idx).collect_vec(),
            vec![0],
        );
        assert_eq!(f.matching("xyz").map(|(idx, _)| idx).collect_vec(), vec![0],);
    }

    #[test]
    fn non_ascii() {
        let f = Builder::new().push("ΛΜΝΟΠ").unwrap().build().unwrap();
        assert_eq!(
            f.matching("ΛΜΝΟΠ").map(|(idx, _)| idx).collect_vec(),
            vec![0],
        );
        assert_eq!(
            f.matching("λμνοπ").map(|(idx, _)| idx).collect_vec(),
            vec![],
        );
        assert_eq!(
            f.matching("Λμνοπ").map(|(idx, _)| idx).collect_vec(),
            vec![],
        );
        let f = Builder::new().push("(?i)ΛΜΝΟΠ").unwrap().build().unwrap();
        assert_eq!(
            f.matching("ΛΜΝΟΠ").map(|(idx, _)| idx).collect_vec(),
            vec![0],
        );
        assert_eq!(
            f.matching("λμνοπ").map(|(idx, _)| idx).collect_vec(),
            vec![0],
        );
        assert_eq!(
            f.matching("Λμνοπ").map(|(idx, _)| idx).collect_vec(),
            vec![0],
        );
    }
}