regex_syntax/hir/literal.rs
1/*!
2Provides literal extraction from `Hir` expressions.
3
4An [`Extractor`] pulls literals out of [`Hir`] expressions and returns a
5[`Seq`] of [`Literal`]s.
6
7The purpose of literal extraction is generally to provide avenues for
8optimizing regex searches. The main idea is that substring searches can be an
9order of magnitude faster than a regex search. Therefore, if one can execute
10a substring search to find candidate match locations and only run the regex
11search at those locations, then it is possible for huge improvements in
12performance to be realized.
13
14With that said, literal optimizations are generally a black art because even
15though substring search is generally faster, if the number of candidates
16produced is high, then it can create a lot of overhead by ping-ponging between
17the substring search and the regex search.
18
19Here are some heuristics that might be used to help increase the chances of
20effective literal optimizations:
21
22* Stick to small [`Seq`]s. If you search for too many literals, it's likely
23to lead to substring search that is only a little faster than a regex search,
24and thus the overhead of using literal optimizations in the first place might
25make things slower overall.
26* The literals in your [`Seq`] shouldn't be too short. In general, longer is
27better. A sequence corresponding to single bytes that occur frequently in the
28haystack, for example, is probably a bad literal optimization because it's
29likely to produce many false positive candidates. Longer literals are less
30likely to match, and thus probably produce fewer false positives.
31* If it's possible to estimate the approximate frequency of each byte according
32to some pre-computed background distribution, it is possible to compute a score
33of how "good" a `Seq` is. If a `Seq` isn't good enough, you might consider
34skipping the literal optimization and just use the regex engine.
35
36(It should be noted that there are always pathological cases that can make
37any kind of literal optimization be a net slower result. This is why it
38might be a good idea to be conservative, or to even provide a means for
39literal optimizations to be dynamically disabled if they are determined to be
40ineffective according to some measure.)
41
42You're encouraged to explore the methods on [`Seq`], which permit shrinking
43the size of sequences in a preference-order preserving fashion.
44
45Finally, note that it isn't strictly necessary to use an [`Extractor`]. Namely,
46an `Extractor` only uses public APIs of the [`Seq`] and [`Literal`] types,
47so it is possible to implement your own extractor. For example, for n-grams
48or "inner" literals (i.e., not prefix or suffix literals). The `Extractor`
49is mostly responsible for the case analysis over `Hir` expressions. Much of
50the "trickier" parts are how to combine literal sequences, and that is all
51implemented on [`Seq`].
52*/
53
54use core::{cmp, mem, num::NonZeroUsize};
55
56use alloc::{vec, vec::Vec};
57
58use crate::hir::{self, Hir};
59
60/// Extracts prefix or suffix literal sequences from [`Hir`] expressions.
61///
62/// Literal extraction is based on the following observations:
63///
64/// * Many regexes start with one or a small number of literals.
65/// * Substring search for literals is often much faster (sometimes by an order
66/// of magnitude) than a regex search.
67///
68/// Thus, in many cases, one can search for literals to find candidate starting
69/// locations of a match, and then only run the full regex engine at each such
70/// location instead of over the full haystack.
71///
72/// The main downside of literal extraction is that it can wind up causing a
73/// search to be slower overall. For example, if there are many matches or if
74/// there are many candidates that don't ultimately lead to a match, then a
75/// lot of overhead will be spent in shuffling back-and-forth between substring
76/// search and the regex engine. This is the fundamental reason why literal
77/// optimizations for regex patterns is sometimes considered a "black art."
78///
79/// # Look-around assertions
80///
81/// Literal extraction treats all look-around assertions as-if they match every
82/// empty string. So for example, the regex `\bquux\b` will yield a sequence
83/// containing a single exact literal `quux`. However, not all occurrences
84/// of `quux` correspond to a match a of the regex. For example, `\bquux\b`
85/// does not match `ZquuxZ` anywhere because `quux` does not fall on a word
86/// boundary.
87///
88/// In effect, if your regex contains look-around assertions, then a match of
89/// an exact literal does not necessarily mean the regex overall matches. So
90/// you may still need to run the regex engine in such cases to confirm the
91/// match.
92///
93/// The precise guarantee you get from a literal sequence is: if every literal
94/// in the sequence is exact and the original regex contains zero look-around
95/// assertions, then a preference-order multi-substring search of those
96/// literals will precisely match a preference-order search of the original
97/// regex.
98///
99/// # Example
100///
101/// This shows how to extract prefixes:
102///
103/// ```
104/// use regex_syntax::{hir::literal::{Extractor, Literal, Seq}, parse};
105///
106/// let hir = parse(r"(a|b|c)(x|y|z)[A-Z]+foo")?;
107/// let got = Extractor::new().extract(&hir);
108/// // All literals returned are "inexact" because none of them reach the
109/// // match state.
110/// let expected = Seq::from_iter([
111/// Literal::inexact("ax"),
112/// Literal::inexact("ay"),
113/// Literal::inexact("az"),
114/// Literal::inexact("bx"),
115/// Literal::inexact("by"),
116/// Literal::inexact("bz"),
117/// Literal::inexact("cx"),
118/// Literal::inexact("cy"),
119/// Literal::inexact("cz"),
120/// ]);
121/// assert_eq!(expected, got);
122///
123/// # Ok::<(), Box<dyn std::error::Error>>(())
124/// ```
125///
126/// This shows how to extract suffixes:
127///
128/// ```
129/// use regex_syntax::{
130/// hir::literal::{Extractor, ExtractKind, Literal, Seq},
131/// parse,
132/// };
133///
134/// let hir = parse(r"foo|[A-Z]+bar")?;
135/// let got = Extractor::new().kind(ExtractKind::Suffix).extract(&hir);
136/// // Since 'foo' gets to a match state, it is considered exact. But 'bar'
137/// // does not because of the '[A-Z]+', and thus is marked inexact.
138/// let expected = Seq::from_iter([
139/// Literal::exact("foo"),
140/// Literal::inexact("bar"),
141/// ]);
142/// assert_eq!(expected, got);
143///
144/// # Ok::<(), Box<dyn std::error::Error>>(())
145/// ```
146#[derive(Clone, Debug)]
147pub struct Extractor {
148 kind: ExtractKind,
149 limit_class: usize,
150 limit_repeat: usize,
151 limit_literal_len: usize,
152 limit_total: usize,
153}
154
155impl Extractor {
156 /// Create a new extractor with a default configuration.
157 ///
158 /// The extractor can be optionally configured before calling
159 /// [`Extractor::extract`] to get a literal sequence.
160 pub fn new() -> Extractor {
161 Extractor {
162 kind: ExtractKind::Prefix,
163 limit_class: 10,
164 limit_repeat: 10,
165 limit_literal_len: 100,
166 limit_total: 250,
167 }
168 }
169
170 /// Execute the extractor and return a sequence of literals.
171 pub fn extract(&self, hir: &Hir) -> Seq {
172 use crate::hir::HirKind::*;
173
174 match *hir.kind() {
175 Empty | Look(_) => Seq::singleton(self::Literal::exact(vec![])),
176 Literal(hir::Literal(ref bytes)) => {
177 let mut seq =
178 Seq::singleton(self::Literal::exact(bytes.to_vec()));
179 self.enforce_literal_len(&mut seq);
180 seq
181 }
182 Class(hir::Class::Unicode(ref cls)) => {
183 self.extract_class_unicode(cls)
184 }
185 Class(hir::Class::Bytes(ref cls)) => self.extract_class_bytes(cls),
186 Repetition(ref rep) => self.extract_repetition(rep),
187 Capture(hir::Capture { ref sub, .. }) => self.extract(sub),
188 Concat(ref hirs) => match self.kind {
189 ExtractKind::Prefix => self.extract_concat(hirs.iter()),
190 ExtractKind::Suffix => self.extract_concat(hirs.iter().rev()),
191 },
192 Alternation(ref hirs) => {
193 // Unlike concat, we always union starting from the beginning,
194 // since the beginning corresponds to the highest preference,
195 // which doesn't change based on forwards vs reverse.
196 self.extract_alternation(hirs.iter())
197 }
198 }
199 }
200
201 /// Set the kind of literal sequence to extract from an [`Hir`] expression.
202 ///
203 /// The default is to extract prefixes, but suffixes can be selected
204 /// instead. The contract for prefixes is that every match of the
205 /// corresponding `Hir` must start with one of the literals in the sequence
206 /// returned. Moreover, the _order_ of the sequence returned corresponds to
207 /// the preference order.
208 ///
209 /// Suffixes satisfy a similar contract in that every match of the
210 /// corresponding `Hir` must end with one of the literals in the sequence
211 /// returned. However, there is no guarantee that the literals are in
212 /// preference order.
213 ///
214 /// Remember that a sequence can be infinite. For example, unless the
215 /// limits are configured to be impractically large, attempting to extract
216 /// prefixes (or suffixes) for the pattern `[A-Z]` will return an infinite
217 /// sequence. Generally speaking, if the sequence returned is infinite,
218 /// then it is presumed to be unwise to do prefix (or suffix) optimizations
219 /// for the pattern.
220 pub fn kind(&mut self, kind: ExtractKind) -> &mut Extractor {
221 self.kind = kind;
222 self
223 }
224
225 /// Configure a limit on the length of the sequence that is permitted for
226 /// a character class. If a character class exceeds this limit, then the
227 /// sequence returned for it is infinite.
228 ///
229 /// This prevents classes like `[A-Z]` or `\pL` from getting turned into
230 /// huge and likely unproductive sequences of literals.
231 ///
232 /// # Example
233 ///
234 /// This example shows how this limit can be lowered to decrease the tolerance
235 /// for character classes being turned into literal sequences.
236 ///
237 /// ```
238 /// use regex_syntax::{hir::literal::{Extractor, Seq}, parse};
239 ///
240 /// let hir = parse(r"[0-9]")?;
241 ///
242 /// let got = Extractor::new().extract(&hir);
243 /// let expected = Seq::new([
244 /// "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
245 /// ]);
246 /// assert_eq!(expected, got);
247 ///
248 /// // Now let's shrink the limit and see how that changes things.
249 /// let got = Extractor::new().limit_class(4).extract(&hir);
250 /// let expected = Seq::infinite();
251 /// assert_eq!(expected, got);
252 ///
253 /// # Ok::<(), Box<dyn std::error::Error>>(())
254 /// ```
255 pub fn limit_class(&mut self, limit: usize) -> &mut Extractor {
256 self.limit_class = limit;
257 self
258 }
259
260 /// Configure a limit on the total number of repetitions that is permitted
261 /// before literal extraction is stopped.
262 ///
263 /// This is useful for limiting things like `(abcde){50}`, or more
264 /// insidiously, `(?:){1000000000}`. This limit prevents any one single
265 /// repetition from adding too much to a literal sequence.
266 ///
267 /// With this limit set, repetitions that exceed it will be stopped and any
268 /// literals extracted up to that point will be made inexact.
269 ///
270 /// # Example
271 ///
272 /// This shows how to decrease the limit and compares it with the default.
273 ///
274 /// ```
275 /// use regex_syntax::{hir::literal::{Extractor, Literal, Seq}, parse};
276 ///
277 /// let hir = parse(r"(abc){8}")?;
278 ///
279 /// let got = Extractor::new().extract(&hir);
280 /// let expected = Seq::new(["abcabcabcabcabcabcabcabc"]);
281 /// assert_eq!(expected, got);
282 ///
283 /// // Now let's shrink the limit and see how that changes things.
284 /// let got = Extractor::new().limit_repeat(4).extract(&hir);
285 /// let expected = Seq::from_iter([
286 /// Literal::inexact("abcabcabcabc"),
287 /// ]);
288 /// assert_eq!(expected, got);
289 ///
290 /// # Ok::<(), Box<dyn std::error::Error>>(())
291 /// ```
292 pub fn limit_repeat(&mut self, limit: usize) -> &mut Extractor {
293 self.limit_repeat = limit;
294 self
295 }
296
297 /// Configure a limit on the maximum length of any literal in a sequence.
298 ///
299 /// This is useful for limiting things like `(abcde){5}{5}{5}{5}`. While
300 /// each repetition or literal in that regex is small, when all the
301 /// repetitions are applied, one ends up with a literal of length `5^4 =
302 /// 625`.
303 ///
304 /// With this limit set, literals that exceed it will be made inexact and
305 /// thus prevented from growing.
306 ///
307 /// # Example
308 ///
309 /// This shows how to decrease the limit and compares it with the default.
310 ///
311 /// ```
312 /// use regex_syntax::{hir::literal::{Extractor, Literal, Seq}, parse};
313 ///
314 /// let hir = parse(r"(abc){2}{2}{2}")?;
315 ///
316 /// let got = Extractor::new().extract(&hir);
317 /// let expected = Seq::new(["abcabcabcabcabcabcabcabc"]);
318 /// assert_eq!(expected, got);
319 ///
320 /// // Now let's shrink the limit and see how that changes things.
321 /// let got = Extractor::new().limit_literal_len(14).extract(&hir);
322 /// let expected = Seq::from_iter([
323 /// Literal::inexact("abcabcabcabcab"),
324 /// ]);
325 /// assert_eq!(expected, got);
326 ///
327 /// # Ok::<(), Box<dyn std::error::Error>>(())
328 /// ```
329 pub fn limit_literal_len(&mut self, limit: usize) -> &mut Extractor {
330 self.limit_literal_len = limit;
331 self
332 }
333
334 /// Configure a limit on the total number of literals that will be
335 /// returned.
336 ///
337 /// This is useful as a practical measure for avoiding the creation of
338 /// large sequences of literals. While the extractor will automatically
339 /// handle local creations of large sequences (for example, `[A-Z]` yields
340 /// an infinite sequence by default), large sequences can be created
341 /// through non-local means as well.
342 ///
343 /// For example, `[ab]{3}{3}` would yield a sequence of length `512 = 2^9`
344 /// despite each of the repetitions being small on their own. This limit
345 /// thus represents a "catch all" for avoiding locally small sequences from
346 /// combining into large sequences.
347 ///
348 /// # Example
349 ///
350 /// This example shows how reducing the limit will change the literal
351 /// sequence returned.
352 ///
353 /// ```
354 /// use regex_syntax::{hir::literal::{Extractor, Literal, Seq}, parse};
355 ///
356 /// let hir = parse(r"[ab]{2}{2}")?;
357 ///
358 /// let got = Extractor::new().extract(&hir);
359 /// let expected = Seq::new([
360 /// "aaaa", "aaab", "aaba", "aabb",
361 /// "abaa", "abab", "abba", "abbb",
362 /// "baaa", "baab", "baba", "babb",
363 /// "bbaa", "bbab", "bbba", "bbbb",
364 /// ]);
365 /// assert_eq!(expected, got);
366 ///
367 /// // The default limit is not too big, but big enough to extract all
368 /// // literals from '[ab]{2}{2}'. If we shrink the limit to less than 16,
369 /// // then we'll get a truncated set. Notice that it returns a sequence of
370 /// // length 4 even though our limit was 10. This is because the sequence
371 /// // is difficult to increase without blowing the limit. Notice also
372 /// // that every literal in the sequence is now inexact because they were
373 /// // stripped of some suffix.
374 /// let got = Extractor::new().limit_total(10).extract(&hir);
375 /// let expected = Seq::from_iter([
376 /// Literal::inexact("aa"),
377 /// Literal::inexact("ab"),
378 /// Literal::inexact("ba"),
379 /// Literal::inexact("bb"),
380 /// ]);
381 /// assert_eq!(expected, got);
382 ///
383 /// # Ok::<(), Box<dyn std::error::Error>>(())
384 /// ```
385 pub fn limit_total(&mut self, limit: usize) -> &mut Extractor {
386 self.limit_total = limit;
387 self
388 }
389
390 /// Extract a sequence from the given concatenation. Sequences from each of
391 /// the child HIR expressions are combined via cross product.
392 ///
393 /// This short circuits once the cross product turns into a sequence
394 /// containing only inexact literals.
395 fn extract_concat<'a, I: Iterator<Item = &'a Hir>>(&self, it: I) -> Seq {
396 let mut seq = Seq::singleton(self::Literal::exact(vec![]));
397 for hir in it {
398 // If every element in the sequence is inexact, then a cross
399 // product will always be a no-op. Thus, there is nothing else we
400 // can add to it and can quit early. Note that this also includes
401 // infinite sequences.
402 if seq.is_inexact() {
403 break;
404 }
405 // Note that 'cross' also dispatches based on whether we're
406 // extracting prefixes or suffixes.
407 seq = self.cross(seq, &mut self.extract(hir));
408 }
409 seq
410 }
411
412 /// Extract a sequence from the given alternation.
413 ///
414 /// This short circuits once the union turns into an infinite sequence.
415 fn extract_alternation<'a, I: Iterator<Item = &'a Hir>>(
416 &self,
417 it: I,
418 ) -> Seq {
419 let mut seq = Seq::empty();
420 for hir in it {
421 // Once our 'seq' is infinite, every subsequent union
422 // operation on it will itself always result in an
423 // infinite sequence. Thus, it can never change and we can
424 // short-circuit.
425 if !seq.is_finite() {
426 break;
427 }
428 seq = self.union(seq, &mut self.extract(hir));
429 }
430 seq
431 }
432
433 /// Extract a sequence of literals from the given repetition. We do our
434 /// best, Some examples:
435 ///
436 /// 'a*' => [inexact(a), exact("")]
437 /// 'a*?' => [exact(""), inexact(a)]
438 /// 'a+' => [inexact(a)]
439 /// 'a{3}' => [exact(aaa)]
440 /// 'a{3,5} => [inexact(aaa)]
441 ///
442 /// The key here really is making sure we get the 'inexact' vs 'exact'
443 /// attributes correct on each of the literals we add. For example, the
444 /// fact that 'a*' gives us an inexact 'a' and an exact empty string means
445 /// that a regex like 'ab*c' will result in [inexact(ab), exact(ac)]
446 /// literals being extracted, which might actually be a better prefilter
447 /// than just 'a'.
448 fn extract_repetition(&self, rep: &hir::Repetition) -> Seq {
449 let mut subseq = self.extract(&rep.sub);
450 match *rep {
451 hir::Repetition { min: 0, max, greedy, .. } => {
452 // When 'max=1', we can retain exactness, since 'a?' is
453 // equivalent to 'a|'. Similarly below, 'a??' is equivalent to
454 // '|a'.
455 if max != Some(1) {
456 subseq.make_inexact();
457 }
458 let mut empty = Seq::singleton(Literal::exact(vec![]));
459 if !greedy {
460 mem::swap(&mut subseq, &mut empty);
461 }
462 self.union(subseq, &mut empty)
463 }
464 hir::Repetition { min, max: Some(max), .. } if min == max => {
465 assert!(min > 0); // handled above
466 let limit =
467 u32::try_from(self.limit_repeat).unwrap_or(u32::MAX);
468 let mut seq = Seq::singleton(Literal::exact(vec![]));
469 for _ in 0..cmp::min(min, limit) {
470 if seq.is_inexact() {
471 break;
472 }
473 seq = self.cross(seq, &mut subseq.clone());
474 }
475 if usize::try_from(min).is_err() || min > limit {
476 seq.make_inexact();
477 }
478 seq
479 }
480 hir::Repetition { min, .. } => {
481 assert!(min > 0); // handled above
482 let limit =
483 u32::try_from(self.limit_repeat).unwrap_or(u32::MAX);
484 let mut seq = Seq::singleton(Literal::exact(vec![]));
485 for _ in 0..cmp::min(min, limit) {
486 if seq.is_inexact() {
487 break;
488 }
489 seq = self.cross(seq, &mut subseq.clone());
490 }
491 seq.make_inexact();
492 seq
493 }
494 }
495 }
496
497 /// Convert the given Unicode class into a sequence of literals if the
498 /// class is small enough. If the class is too big, return an infinite
499 /// sequence.
500 fn extract_class_unicode(&self, cls: &hir::ClassUnicode) -> Seq {
501 if self.class_over_limit_unicode(cls) {
502 return Seq::infinite();
503 }
504 let mut seq = Seq::empty();
505 for r in cls.iter() {
506 for ch in r.start()..=r.end() {
507 seq.push(Literal::from(ch));
508 }
509 }
510 self.enforce_literal_len(&mut seq);
511 seq
512 }
513
514 /// Convert the given byte class into a sequence of literals if the class
515 /// is small enough. If the class is too big, return an infinite sequence.
516 fn extract_class_bytes(&self, cls: &hir::ClassBytes) -> Seq {
517 if self.class_over_limit_bytes(cls) {
518 return Seq::infinite();
519 }
520 let mut seq = Seq::empty();
521 for r in cls.iter() {
522 for b in r.start()..=r.end() {
523 seq.push(Literal::from(b));
524 }
525 }
526 self.enforce_literal_len(&mut seq);
527 seq
528 }
529
530 /// Returns true if the given Unicode class exceeds the configured limits
531 /// on this extractor.
532 fn class_over_limit_unicode(&self, cls: &hir::ClassUnicode) -> bool {
533 let mut count = 0;
534 for r in cls.iter() {
535 if count > self.limit_class {
536 return true;
537 }
538 count += r.len();
539 }
540 count > self.limit_class
541 }
542
543 /// Returns true if the given byte class exceeds the configured limits on
544 /// this extractor.
545 fn class_over_limit_bytes(&self, cls: &hir::ClassBytes) -> bool {
546 let mut count = 0;
547 for r in cls.iter() {
548 if count > self.limit_class {
549 return true;
550 }
551 count += r.len();
552 }
553 count > self.limit_class
554 }
555
556 /// Compute the cross product of the two sequences if the result would be
557 /// within configured limits. Otherwise, make `seq2` infinite and cross the
558 /// infinite sequence with `seq1`.
559 fn cross(&self, mut seq1: Seq, seq2: &mut Seq) -> Seq {
560 if seq1.max_cross_len(seq2).map_or(false, |len| len > self.limit_total)
561 {
562 seq2.make_infinite();
563 }
564 if let ExtractKind::Suffix = self.kind {
565 seq1.cross_reverse(seq2);
566 } else {
567 seq1.cross_forward(seq2);
568 }
569 assert!(seq1.len().map_or(true, |x| x <= self.limit_total));
570 self.enforce_literal_len(&mut seq1);
571 seq1
572 }
573
574 /// Union the two sequences if the result would be within configured
575 /// limits. Otherwise, make `seq2` infinite and union the infinite sequence
576 /// with `seq1`.
577 fn union(&self, mut seq1: Seq, seq2: &mut Seq) -> Seq {
578 if seq1.max_union_len(seq2).map_or(false, |len| len > self.limit_total)
579 {
580 // We try to trim our literal sequences to see if we can make
581 // room for more literals. The idea is that we'd rather trim down
582 // literals already in our sequence if it means we can add a few
583 // more and retain a finite sequence. Otherwise, we'll union with
584 // an infinite sequence and that infects everything and effectively
585 // stops literal extraction in its tracks.
586 //
587 // We do we keep 4 bytes here? Well, it's a bit of an abstraction
588 // leakage. Downstream, the literals may wind up getting fed to
589 // the Teddy algorithm, which supports searching literals up to
590 // length 4. So that's why we pick that number here. Arguably this
591 // should be a tunable parameter, but it seems a little tricky to
592 // describe. And I'm still unsure if this is the right way to go
593 // about culling literal sequences.
594 match self.kind {
595 ExtractKind::Prefix => {
596 seq1.keep_first_bytes(4);
597 seq2.keep_first_bytes(4);
598 }
599 ExtractKind::Suffix => {
600 seq1.keep_last_bytes(4);
601 seq2.keep_last_bytes(4);
602 }
603 }
604 seq1.dedup();
605 seq2.dedup();
606 if seq1
607 .max_union_len(seq2)
608 .map_or(false, |len| len > self.limit_total)
609 {
610 seq2.make_infinite();
611 }
612 }
613 seq1.union(seq2);
614 assert!(seq1.len().map_or(true, |x| x <= self.limit_total));
615 seq1
616 }
617
618 /// Applies the literal length limit to the given sequence. If none of the
619 /// literals in the sequence exceed the limit, then this is a no-op.
620 fn enforce_literal_len(&self, seq: &mut Seq) {
621 let len = self.limit_literal_len;
622 match self.kind {
623 ExtractKind::Prefix => seq.keep_first_bytes(len),
624 ExtractKind::Suffix => seq.keep_last_bytes(len),
625 }
626 }
627}
628
629impl Default for Extractor {
630 fn default() -> Extractor {
631 Extractor::new()
632 }
633}
634
635/// The kind of literals to extract from an [`Hir`] expression.
636///
637/// The default extraction kind is `Prefix`.
638#[non_exhaustive]
639#[derive(Clone, Debug, Default)]
640pub enum ExtractKind {
641 /// Extracts only prefix literals from a regex.
642 #[default]
643 Prefix,
644 /// Extracts only suffix literals from a regex.
645 ///
646 /// Note that the sequence returned by suffix literals currently may
647 /// not correctly represent leftmost-first or "preference" order match
648 /// semantics.
649 Suffix,
650}
651
652impl ExtractKind {
653 /// Returns true if this kind is the `Prefix` variant.
654 pub fn is_prefix(&self) -> bool {
655 matches!(*self, ExtractKind::Prefix)
656 }
657
658 /// Returns true if this kind is the `Suffix` variant.
659 pub fn is_suffix(&self) -> bool {
660 matches!(*self, ExtractKind::Suffix)
661 }
662}
663
664/// A sequence of literals.
665///
666/// A `Seq` is very much like a set in that it represents a union of its
667/// members. That is, it corresponds to a set of literals where at least one
668/// must match in order for a particular [`Hir`] expression to match. (Whether
669/// this corresponds to the entire `Hir` expression, a prefix of it or a suffix
670/// of it depends on how the `Seq` was extracted from the `Hir`.)
671///
672/// It is also unlike a set in that multiple identical literals may appear,
673/// and that the order of the literals in the `Seq` matters. For example, if
674/// the sequence is `[sam, samwise]` and leftmost-first matching is used, then
675/// `samwise` can never match and the sequence is equivalent to `[sam]`.
676///
677/// # States of a sequence
678///
679/// A `Seq` has a few different logical states to consider:
680///
681/// * The sequence can represent "any" literal. When this happens, the set does
682/// not have a finite size. The purpose of this state is to inhibit callers
683/// from making assumptions about what literals are required in order to match
684/// a particular [`Hir`] expression. Generally speaking, when a set is in this
685/// state, literal optimizations are inhibited. A good example of a regex that
686/// will cause this sort of set to appear is `[A-Za-z]`. The character class
687/// is just too big (and also too narrow) to be usefully expanded into 52
688/// different literals. (Note that the decision for when a seq should become
689/// infinite is determined by the caller. A seq itself has no hard-coded
690/// limits.)
691/// * The sequence can be empty, in which case, it is an affirmative statement
692/// that there are no literals that can match the corresponding `Hir`.
693/// Consequently, the `Hir` never matches any input. For example, `[a&&b]`.
694/// * The sequence can be non-empty, in which case, at least one of the
695/// literals must match in order for the corresponding `Hir` to match.
696///
697/// # Example
698///
699/// This example shows how literal sequences can be simplified by stripping
700/// suffixes and minimizing while maintaining preference order.
701///
702/// ```
703/// use regex_syntax::hir::literal::{Literal, Seq};
704///
705/// let mut seq = Seq::new(&[
706/// "farm",
707/// "appliance",
708/// "faraway",
709/// "apple",
710/// "fare",
711/// "gap",
712/// "applicant",
713/// "applaud",
714/// ]);
715/// seq.keep_first_bytes(3);
716/// seq.minimize_by_preference();
717/// // Notice that 'far' comes before 'app', which matches the order in the
718/// // original sequence. This guarantees that leftmost-first semantics are
719/// // not altered by simplifying the set.
720/// let expected = Seq::from_iter([
721/// Literal::inexact("far"),
722/// Literal::inexact("app"),
723/// Literal::exact("gap"),
724/// ]);
725/// assert_eq!(expected, seq);
726/// ```
727#[derive(Clone, Eq, PartialEq)]
728pub struct Seq {
729 /// The members of this seq.
730 ///
731 /// When `None`, the seq represents all possible literals. That is, it
732 /// prevents one from making assumptions about specific literals in the
733 /// seq, and forces one to treat it as if any literal might be in the seq.
734 ///
735 /// Note that `Some(vec![])` is valid and corresponds to the empty seq of
736 /// literals, i.e., a regex that can never match. For example, `[a&&b]`.
737 /// It is distinct from `Some(vec![""])`, which corresponds to the seq
738 /// containing an empty string, which matches at every position.
739 literals: Option<Vec<Literal>>,
740}
741
742impl Seq {
743 /// Returns an empty sequence.
744 ///
745 /// An empty sequence matches zero literals, and thus corresponds to a
746 /// regex that itself can never match.
747 #[inline]
748 pub fn empty() -> Seq {
749 Seq { literals: Some(vec![]) }
750 }
751
752 /// Returns a sequence of literals without a finite size and may contain
753 /// any literal.
754 ///
755 /// A sequence without finite size does not reveal anything about the
756 /// characteristics of the literals in its set. There are no fixed prefixes
757 /// or suffixes, nor are lower or upper bounds on the length of the literals
758 /// in the set known.
759 ///
760 /// This is useful to represent constructs in a regex that are "too big"
761 /// to useful represent as a sequence of literals. For example, `[A-Za-z]`.
762 /// When sequences get too big, they lose their discriminating nature and
763 /// are more likely to produce false positives, which in turn makes them
764 /// less likely to speed up searches.
765 ///
766 /// More pragmatically, for many regexes, enumerating all possible literals
767 /// is itself not possible or might otherwise use too many resources. So
768 /// constraining the size of sets during extraction is a practical trade
769 /// off to make.
770 #[inline]
771 pub fn infinite() -> Seq {
772 Seq { literals: None }
773 }
774
775 /// Returns a sequence containing a single literal.
776 #[inline]
777 pub fn singleton(lit: Literal) -> Seq {
778 Seq { literals: Some(vec![lit]) }
779 }
780
781 /// Returns a sequence of exact literals from the given byte strings.
782 #[inline]
783 pub fn new<I, B>(it: I) -> Seq
784 where
785 I: IntoIterator<Item = B>,
786 B: AsRef<[u8]>,
787 {
788 it.into_iter().map(|b| Literal::exact(b.as_ref())).collect()
789 }
790
791 /// If this is a finite sequence, return its members as a slice of
792 /// literals.
793 ///
794 /// The slice returned may be empty, in which case, there are no literals
795 /// that can match this sequence.
796 #[inline]
797 pub fn literals(&self) -> Option<&[Literal]> {
798 self.literals.as_deref()
799 }
800
801 /// Push a literal to the end of this sequence.
802 ///
803 /// If this sequence is not finite, then this is a no-op.
804 ///
805 /// Similarly, if the most recently added item of this sequence is
806 /// equivalent to the literal given, then it is not added. This reflects
807 /// a `Seq`'s "set like" behavior, and represents a practical trade off.
808 /// Namely, there is never any need to have two adjacent and equivalent
809 /// literals in the same sequence, _and_ it is easy to detect in some
810 /// cases.
811 #[inline]
812 pub fn push(&mut self, lit: Literal) {
813 let lits = match self.literals {
814 None => return,
815 Some(ref mut lits) => lits,
816 };
817 if lits.last().map_or(false, |m| m == &lit) {
818 return;
819 }
820 lits.push(lit);
821 }
822
823 /// Make all of the literals in this sequence inexact.
824 ///
825 /// This is a no-op if this sequence is not finite.
826 #[inline]
827 pub fn make_inexact(&mut self) {
828 let lits = match self.literals {
829 None => return,
830 Some(ref mut lits) => lits,
831 };
832 for lit in lits.iter_mut() {
833 lit.make_inexact();
834 }
835 }
836
837 /// Converts this sequence to an infinite sequence.
838 ///
839 /// This is a no-op if the sequence is already infinite.
840 #[inline]
841 pub fn make_infinite(&mut self) {
842 self.literals = None;
843 }
844
845 /// Modify this sequence to contain the cross product between it and the
846 /// sequence given.
847 ///
848 /// The cross product only considers literals in this sequence that are
849 /// exact. That is, inexact literals are not extended.
850 ///
851 /// The literals are always drained from `other`, even if none are used.
852 /// This permits callers to reuse the sequence allocation elsewhere.
853 ///
854 /// If this sequence is infinite, then this is a no-op, regardless of what
855 /// `other` contains (and in this case, the literals are still drained from
856 /// `other`). If `other` is infinite and this sequence is finite, then this
857 /// is a no-op, unless this sequence contains a zero-length literal. In
858 /// which case, the infiniteness of `other` infects this sequence, and this
859 /// sequence is itself made infinite.
860 ///
861 /// Like [`Seq::union`], this may attempt to deduplicate literals. See
862 /// [`Seq::dedup`] for how deduplication deals with exact and inexact
863 /// literals.
864 ///
865 /// # Example
866 ///
867 /// This example shows basic usage and how exact and inexact literals
868 /// interact.
869 ///
870 /// ```
871 /// use regex_syntax::hir::literal::{Literal, Seq};
872 ///
873 /// let mut seq1 = Seq::from_iter([
874 /// Literal::exact("foo"),
875 /// Literal::inexact("bar"),
876 /// ]);
877 /// let mut seq2 = Seq::from_iter([
878 /// Literal::inexact("quux"),
879 /// Literal::exact("baz"),
880 /// ]);
881 /// seq1.cross_forward(&mut seq2);
882 ///
883 /// // The literals are pulled out of seq2.
884 /// assert_eq!(Some(0), seq2.len());
885 ///
886 /// let expected = Seq::from_iter([
887 /// Literal::inexact("fooquux"),
888 /// Literal::exact("foobaz"),
889 /// Literal::inexact("bar"),
890 /// ]);
891 /// assert_eq!(expected, seq1);
892 /// ```
893 ///
894 /// This example shows the behavior of when `other` is an infinite
895 /// sequence.
896 ///
897 /// ```
898 /// use regex_syntax::hir::literal::{Literal, Seq};
899 ///
900 /// let mut seq1 = Seq::from_iter([
901 /// Literal::exact("foo"),
902 /// Literal::inexact("bar"),
903 /// ]);
904 /// let mut seq2 = Seq::infinite();
905 /// seq1.cross_forward(&mut seq2);
906 ///
907 /// // When seq2 is infinite, cross product doesn't add anything, but
908 /// // ensures all members of seq1 are inexact.
909 /// let expected = Seq::from_iter([
910 /// Literal::inexact("foo"),
911 /// Literal::inexact("bar"),
912 /// ]);
913 /// assert_eq!(expected, seq1);
914 /// ```
915 ///
916 /// This example is like the one above, but shows what happens when this
917 /// sequence contains an empty string. In this case, an infinite `other`
918 /// sequence infects this sequence (because the empty string means that
919 /// there are no finite prefixes):
920 ///
921 /// ```
922 /// use regex_syntax::hir::literal::{Literal, Seq};
923 ///
924 /// let mut seq1 = Seq::from_iter([
925 /// Literal::exact("foo"),
926 /// Literal::exact(""), // inexact provokes same behavior
927 /// Literal::inexact("bar"),
928 /// ]);
929 /// let mut seq2 = Seq::infinite();
930 /// seq1.cross_forward(&mut seq2);
931 ///
932 /// // seq1 is now infinite!
933 /// assert!(!seq1.is_finite());
934 /// ```
935 ///
936 /// This example shows the behavior of this sequence is infinite.
937 ///
938 /// ```
939 /// use regex_syntax::hir::literal::{Literal, Seq};
940 ///
941 /// let mut seq1 = Seq::infinite();
942 /// let mut seq2 = Seq::from_iter([
943 /// Literal::exact("foo"),
944 /// Literal::inexact("bar"),
945 /// ]);
946 /// seq1.cross_forward(&mut seq2);
947 ///
948 /// // seq1 remains unchanged.
949 /// assert!(!seq1.is_finite());
950 /// // Even though the literals in seq2 weren't used, it was still drained.
951 /// assert_eq!(Some(0), seq2.len());
952 /// ```
953 #[inline]
954 pub fn cross_forward(&mut self, other: &mut Seq) {
955 let (lits1, lits2) = match self.cross_preamble(other) {
956 None => return,
957 Some((lits1, lits2)) => (lits1, lits2),
958 };
959 let newcap = lits1.len().saturating_mul(lits2.len());
960 for selflit in mem::replace(lits1, Vec::with_capacity(newcap)) {
961 if !selflit.is_exact() {
962 lits1.push(selflit);
963 continue;
964 }
965 for otherlit in lits2.iter() {
966 let mut newlit = Literal::exact(Vec::with_capacity(
967 selflit.len() + otherlit.len(),
968 ));
969 newlit.extend(&selflit);
970 newlit.extend(&otherlit);
971 if !otherlit.is_exact() {
972 newlit.make_inexact();
973 }
974 lits1.push(newlit);
975 }
976 }
977 lits2.drain(..);
978 self.dedup();
979 }
980
981 /// Modify this sequence to contain the cross product between it and
982 /// the sequence given, where the sequences are treated as suffixes
983 /// instead of prefixes. Namely, the sequence `other` is *prepended*
984 /// to `self` (as opposed to `other` being *appended* to `self` in
985 /// [`Seq::cross_forward`]).
986 ///
987 /// The cross product only considers literals in this sequence that are
988 /// exact. That is, inexact literals are not extended.
989 ///
990 /// The literals are always drained from `other`, even if none are used.
991 /// This permits callers to reuse the sequence allocation elsewhere.
992 ///
993 /// If this sequence is infinite, then this is a no-op, regardless of what
994 /// `other` contains (and in this case, the literals are still drained from
995 /// `other`). If `other` is infinite and this sequence is finite, then this
996 /// is a no-op, unless this sequence contains a zero-length literal. In
997 /// which case, the infiniteness of `other` infects this sequence, and this
998 /// sequence is itself made infinite.
999 ///
1000 /// Like [`Seq::union`], this may attempt to deduplicate literals. See
1001 /// [`Seq::dedup`] for how deduplication deals with exact and inexact
1002 /// literals.
1003 ///
1004 /// # Example
1005 ///
1006 /// This example shows basic usage and how exact and inexact literals
1007 /// interact.
1008 ///
1009 /// ```
1010 /// use regex_syntax::hir::literal::{Literal, Seq};
1011 ///
1012 /// let mut seq1 = Seq::from_iter([
1013 /// Literal::exact("foo"),
1014 /// Literal::inexact("bar"),
1015 /// ]);
1016 /// let mut seq2 = Seq::from_iter([
1017 /// Literal::inexact("quux"),
1018 /// Literal::exact("baz"),
1019 /// ]);
1020 /// seq1.cross_reverse(&mut seq2);
1021 ///
1022 /// // The literals are pulled out of seq2.
1023 /// assert_eq!(Some(0), seq2.len());
1024 ///
1025 /// let expected = Seq::from_iter([
1026 /// Literal::inexact("quuxfoo"),
1027 /// Literal::inexact("bar"),
1028 /// Literal::exact("bazfoo"),
1029 /// ]);
1030 /// assert_eq!(expected, seq1);
1031 /// ```
1032 ///
1033 /// This example shows the behavior of when `other` is an infinite
1034 /// sequence.
1035 ///
1036 /// ```
1037 /// use regex_syntax::hir::literal::{Literal, Seq};
1038 ///
1039 /// let mut seq1 = Seq::from_iter([
1040 /// Literal::exact("foo"),
1041 /// Literal::inexact("bar"),
1042 /// ]);
1043 /// let mut seq2 = Seq::infinite();
1044 /// seq1.cross_reverse(&mut seq2);
1045 ///
1046 /// // When seq2 is infinite, cross product doesn't add anything, but
1047 /// // ensures all members of seq1 are inexact.
1048 /// let expected = Seq::from_iter([
1049 /// Literal::inexact("foo"),
1050 /// Literal::inexact("bar"),
1051 /// ]);
1052 /// assert_eq!(expected, seq1);
1053 /// ```
1054 ///
1055 /// This example is like the one above, but shows what happens when this
1056 /// sequence contains an empty string. In this case, an infinite `other`
1057 /// sequence infects this sequence (because the empty string means that
1058 /// there are no finite suffixes):
1059 ///
1060 /// ```
1061 /// use regex_syntax::hir::literal::{Literal, Seq};
1062 ///
1063 /// let mut seq1 = Seq::from_iter([
1064 /// Literal::exact("foo"),
1065 /// Literal::exact(""), // inexact provokes same behavior
1066 /// Literal::inexact("bar"),
1067 /// ]);
1068 /// let mut seq2 = Seq::infinite();
1069 /// seq1.cross_reverse(&mut seq2);
1070 ///
1071 /// // seq1 is now infinite!
1072 /// assert!(!seq1.is_finite());
1073 /// ```
1074 ///
1075 /// This example shows the behavior when this sequence is infinite.
1076 ///
1077 /// ```
1078 /// use regex_syntax::hir::literal::{Literal, Seq};
1079 ///
1080 /// let mut seq1 = Seq::infinite();
1081 /// let mut seq2 = Seq::from_iter([
1082 /// Literal::exact("foo"),
1083 /// Literal::inexact("bar"),
1084 /// ]);
1085 /// seq1.cross_reverse(&mut seq2);
1086 ///
1087 /// // seq1 remains unchanged.
1088 /// assert!(!seq1.is_finite());
1089 /// // Even though the literals in seq2 weren't used, it was still drained.
1090 /// assert_eq!(Some(0), seq2.len());
1091 /// ```
1092 #[inline]
1093 pub fn cross_reverse(&mut self, other: &mut Seq) {
1094 let (lits1, lits2) = match self.cross_preamble(other) {
1095 None => return,
1096 Some((lits1, lits2)) => (lits1, lits2),
1097 };
1098 // We basically proceed as we do in 'cross_forward' at this point,
1099 // except that the outer loop is now 'other' and the inner loop is now
1100 // 'self'. That's because 'self' corresponds to suffixes and 'other'
1101 // corresponds to the sequence we want to *prepend* to the suffixes.
1102 let newcap = lits1.len().saturating_mul(lits2.len());
1103 let selflits = mem::replace(lits1, Vec::with_capacity(newcap));
1104 for (i, otherlit) in lits2.drain(..).enumerate() {
1105 for selflit in selflits.iter() {
1106 if !selflit.is_exact() {
1107 // If the suffix isn't exact, then we can't prepend
1108 // anything to it. However, we still want to keep it. But
1109 // we only want to keep one of them, to avoid duplication.
1110 // (The duplication is okay from a correctness perspective,
1111 // but wasteful.)
1112 if i == 0 {
1113 lits1.push(selflit.clone());
1114 }
1115 continue;
1116 }
1117 let mut newlit = Literal::exact(Vec::with_capacity(
1118 otherlit.len() + selflit.len(),
1119 ));
1120 newlit.extend(&otherlit);
1121 newlit.extend(&selflit);
1122 if !otherlit.is_exact() {
1123 newlit.make_inexact();
1124 }
1125 lits1.push(newlit);
1126 }
1127 }
1128 self.dedup();
1129 }
1130
1131 /// A helper function the corresponds to the subtle preamble for both
1132 /// `cross_forward` and `cross_reverse`. In effect, it handles the cases
1133 /// of infinite sequences for both `self` and `other`, as well as ensuring
1134 /// that literals from `other` are drained even if they aren't used.
1135 fn cross_preamble<'a>(
1136 &'a mut self,
1137 other: &'a mut Seq,
1138 ) -> Option<(&'a mut Vec<Literal>, &'a mut Vec<Literal>)> {
1139 let lits2 = match other.literals {
1140 None => {
1141 // If our current seq contains the empty string and the seq
1142 // we're adding matches any literal, then it follows that the
1143 // current seq must now also match any literal.
1144 //
1145 // Otherwise, we just have to make sure everything in this
1146 // sequence is inexact.
1147 if self.min_literal_len() == Some(0) {
1148 *self = Seq::infinite();
1149 } else {
1150 self.make_inexact();
1151 }
1152 return None;
1153 }
1154 Some(ref mut lits) => lits,
1155 };
1156 let lits1 = match self.literals {
1157 None => {
1158 // If we aren't going to make it to the end of this routine
1159 // where lits2 is drained, then we need to do it now.
1160 lits2.drain(..);
1161 return None;
1162 }
1163 Some(ref mut lits) => lits,
1164 };
1165 Some((lits1, lits2))
1166 }
1167
1168 /// Unions the `other` sequence into this one.
1169 ///
1170 /// The literals are always drained out of the given `other` sequence,
1171 /// even if they are being unioned into an infinite sequence. This permits
1172 /// the caller to reuse the `other` sequence in another context.
1173 ///
1174 /// Some literal deduping may be performed. If any deduping happens,
1175 /// any leftmost-first or "preference" order match semantics will be
1176 /// preserved.
1177 ///
1178 /// # Example
1179 ///
1180 /// This example shows basic usage.
1181 ///
1182 /// ```
1183 /// use regex_syntax::hir::literal::Seq;
1184 ///
1185 /// let mut seq1 = Seq::new(&["foo", "bar"]);
1186 /// let mut seq2 = Seq::new(&["bar", "quux", "foo"]);
1187 /// seq1.union(&mut seq2);
1188 ///
1189 /// // The literals are pulled out of seq2.
1190 /// assert_eq!(Some(0), seq2.len());
1191 ///
1192 /// // Adjacent literals are deduped, but non-adjacent literals may not be.
1193 /// assert_eq!(Seq::new(&["foo", "bar", "quux", "foo"]), seq1);
1194 /// ```
1195 ///
1196 /// This example shows that literals are drained from `other` even when
1197 /// they aren't necessarily used.
1198 ///
1199 /// ```
1200 /// use regex_syntax::hir::literal::Seq;
1201 ///
1202 /// let mut seq1 = Seq::infinite();
1203 /// // Infinite sequences have no finite length.
1204 /// assert_eq!(None, seq1.len());
1205 ///
1206 /// let mut seq2 = Seq::new(&["bar", "quux", "foo"]);
1207 /// seq1.union(&mut seq2);
1208 ///
1209 /// // seq1 is still infinite and seq2 has been drained.
1210 /// assert_eq!(None, seq1.len());
1211 /// assert_eq!(Some(0), seq2.len());
1212 /// ```
1213 #[inline]
1214 pub fn union(&mut self, other: &mut Seq) {
1215 let lits2 = match other.literals {
1216 None => {
1217 // Unioning with an infinite sequence always results in an
1218 // infinite sequence.
1219 self.make_infinite();
1220 return;
1221 }
1222 Some(ref mut lits) => lits.drain(..),
1223 };
1224 let lits1 = match self.literals {
1225 None => return,
1226 Some(ref mut lits) => lits,
1227 };
1228 lits1.extend(lits2);
1229 self.dedup();
1230 }
1231
1232 /// Unions the `other` sequence into this one by splice the `other`
1233 /// sequence at the position of the first zero-length literal.
1234 ///
1235 /// This is useful for preserving preference order semantics when combining
1236 /// two literal sequences. For example, in the regex `(a||f)+foo`, the
1237 /// correct preference order prefix sequence is `[a, foo, f]`.
1238 ///
1239 /// The literals are always drained out of the given `other` sequence,
1240 /// even if they are being unioned into an infinite sequence. This permits
1241 /// the caller to reuse the `other` sequence in another context. Note that
1242 /// the literals are drained even if no union is performed as well, i.e.,
1243 /// when this sequence does not contain a zero-length literal.
1244 ///
1245 /// Some literal deduping may be performed. If any deduping happens,
1246 /// any leftmost-first or "preference" order match semantics will be
1247 /// preserved.
1248 ///
1249 /// # Example
1250 ///
1251 /// This example shows basic usage.
1252 ///
1253 /// ```
1254 /// use regex_syntax::hir::literal::Seq;
1255 ///
1256 /// let mut seq1 = Seq::new(&["a", "", "f", ""]);
1257 /// let mut seq2 = Seq::new(&["foo"]);
1258 /// seq1.union_into_empty(&mut seq2);
1259 ///
1260 /// // The literals are pulled out of seq2.
1261 /// assert_eq!(Some(0), seq2.len());
1262 /// // 'foo' gets spliced into seq1 where the first empty string occurs.
1263 /// assert_eq!(Seq::new(&["a", "foo", "f"]), seq1);
1264 /// ```
1265 ///
1266 /// This example shows that literals are drained from `other` even when
1267 /// they aren't necessarily used.
1268 ///
1269 /// ```
1270 /// use regex_syntax::hir::literal::Seq;
1271 ///
1272 /// let mut seq1 = Seq::new(&["foo", "bar"]);
1273 /// let mut seq2 = Seq::new(&["bar", "quux", "foo"]);
1274 /// seq1.union_into_empty(&mut seq2);
1275 ///
1276 /// // seq1 has no zero length literals, so no splicing happens.
1277 /// assert_eq!(Seq::new(&["foo", "bar"]), seq1);
1278 /// // Even though no splicing happens, seq2 is still drained.
1279 /// assert_eq!(Some(0), seq2.len());
1280 /// ```
1281 #[inline]
1282 pub fn union_into_empty(&mut self, other: &mut Seq) {
1283 let lits2 = other.literals.as_mut().map(|lits| lits.drain(..));
1284 let lits1 = match self.literals {
1285 None => return,
1286 Some(ref mut lits) => lits,
1287 };
1288 let first_empty = match lits1.iter().position(|m| m.is_empty()) {
1289 None => return,
1290 Some(i) => i,
1291 };
1292 let lits2 = match lits2 {
1293 None => {
1294 // Note that we are only here if we've found an empty literal,
1295 // which implies that an infinite sequence infects this seq and
1296 // also turns it into an infinite sequence.
1297 self.literals = None;
1298 return;
1299 }
1300 Some(lits) => lits,
1301 };
1302 // Clearing out the empties needs to come before the splice because
1303 // the splice might add more empties that we don't want to get rid
1304 // of. Since we're splicing into the position of the first empty, the
1305 // 'first_empty' position computed above is still correct.
1306 lits1.retain(|m| !m.is_empty());
1307 lits1.splice(first_empty..first_empty, lits2);
1308 self.dedup();
1309 }
1310
1311 /// Deduplicate adjacent equivalent literals in this sequence.
1312 ///
1313 /// If adjacent literals are equivalent strings but one is exact and the
1314 /// other inexact, the inexact literal is kept and the exact one is
1315 /// removed.
1316 ///
1317 /// Deduping an infinite sequence is a no-op.
1318 ///
1319 /// # Example
1320 ///
1321 /// This example shows how literals that are duplicate byte strings but
1322 /// are not equivalent with respect to exactness are resolved.
1323 ///
1324 /// ```
1325 /// use regex_syntax::hir::literal::{Literal, Seq};
1326 ///
1327 /// let mut seq = Seq::from_iter([
1328 /// Literal::exact("foo"),
1329 /// Literal::inexact("foo"),
1330 /// ]);
1331 /// seq.dedup();
1332 ///
1333 /// assert_eq!(Seq::from_iter([Literal::inexact("foo")]), seq);
1334 /// ```
1335 #[inline]
1336 pub fn dedup(&mut self) {
1337 if let Some(ref mut lits) = self.literals {
1338 lits.dedup_by(|lit1, lit2| {
1339 if lit1.as_bytes() != lit2.as_bytes() {
1340 return false;
1341 }
1342 if lit1.is_exact() != lit2.is_exact() {
1343 lit1.make_inexact();
1344 lit2.make_inexact();
1345 }
1346 true
1347 });
1348 }
1349 }
1350
1351 /// Sorts this sequence of literals lexicographically.
1352 ///
1353 /// Note that if, before sorting, if a literal that is a prefix of another
1354 /// literal appears after it, then after sorting, the sequence will not
1355 /// represent the same preference order match semantics. For example,
1356 /// sorting the sequence `[samwise, sam]` yields the sequence `[sam,
1357 /// samwise]`. Under preference order semantics, the latter sequence will
1358 /// never match `samwise` where as the first sequence can.
1359 ///
1360 /// # Example
1361 ///
1362 /// This example shows basic usage.
1363 ///
1364 /// ```
1365 /// use regex_syntax::hir::literal::Seq;
1366 ///
1367 /// let mut seq = Seq::new(&["foo", "quux", "bar"]);
1368 /// seq.sort();
1369 ///
1370 /// assert_eq!(Seq::new(&["bar", "foo", "quux"]), seq);
1371 /// ```
1372 #[inline]
1373 pub fn sort(&mut self) {
1374 if let Some(ref mut lits) = self.literals {
1375 lits.sort();
1376 }
1377 }
1378
1379 /// Reverses all of the literals in this sequence.
1380 ///
1381 /// The order of the sequence itself is preserved.
1382 ///
1383 /// # Example
1384 ///
1385 /// This example shows basic usage.
1386 ///
1387 /// ```
1388 /// use regex_syntax::hir::literal::Seq;
1389 ///
1390 /// let mut seq = Seq::new(&["oof", "rab"]);
1391 /// seq.reverse_literals();
1392 /// assert_eq!(Seq::new(&["foo", "bar"]), seq);
1393 /// ```
1394 #[inline]
1395 pub fn reverse_literals(&mut self) {
1396 if let Some(ref mut lits) = self.literals {
1397 for lit in lits.iter_mut() {
1398 lit.reverse();
1399 }
1400 }
1401 }
1402
1403 /// Shrinks this seq to its minimal size while respecting the preference
1404 /// order of its literals.
1405 ///
1406 /// While this routine will remove duplicate literals from this seq, it
1407 /// will also remove literals that can never match in a leftmost-first or
1408 /// "preference order" search. Similar to [`Seq::dedup`], if a literal is
1409 /// deduped, then the one that remains is made inexact.
1410 ///
1411 /// This is a no-op on seqs that are empty or not finite.
1412 ///
1413 /// # Example
1414 ///
1415 /// This example shows the difference between `{sam, samwise}` and
1416 /// `{samwise, sam}`.
1417 ///
1418 /// ```
1419 /// use regex_syntax::hir::literal::{Literal, Seq};
1420 ///
1421 /// // If 'sam' comes before 'samwise' and a preference order search is
1422 /// // executed, then 'samwise' can never match.
1423 /// let mut seq = Seq::new(&["sam", "samwise"]);
1424 /// seq.minimize_by_preference();
1425 /// assert_eq!(Seq::from_iter([Literal::inexact("sam")]), seq);
1426 ///
1427 /// // But if they are reversed, then it's possible for 'samwise' to match
1428 /// // since it is given higher preference.
1429 /// let mut seq = Seq::new(&["samwise", "sam"]);
1430 /// seq.minimize_by_preference();
1431 /// assert_eq!(Seq::new(&["samwise", "sam"]), seq);
1432 /// ```
1433 ///
1434 /// This example shows that if an empty string is in this seq, then
1435 /// anything that comes after it can never match.
1436 ///
1437 /// ```
1438 /// use regex_syntax::hir::literal::{Literal, Seq};
1439 ///
1440 /// // An empty string is a prefix of all strings, so it automatically
1441 /// // inhibits any subsequent strings from matching.
1442 /// let mut seq = Seq::new(&["foo", "bar", "", "quux", "fox"]);
1443 /// seq.minimize_by_preference();
1444 /// let expected = Seq::from_iter([
1445 /// Literal::exact("foo"),
1446 /// Literal::exact("bar"),
1447 /// Literal::inexact(""),
1448 /// ]);
1449 /// assert_eq!(expected, seq);
1450 ///
1451 /// // And of course, if it's at the beginning, then it makes it impossible
1452 /// // for anything else to match.
1453 /// let mut seq = Seq::new(&["", "foo", "quux", "fox"]);
1454 /// seq.minimize_by_preference();
1455 /// assert_eq!(Seq::from_iter([Literal::inexact("")]), seq);
1456 /// ```
1457 #[inline]
1458 pub fn minimize_by_preference(&mut self) {
1459 if let Some(ref mut lits) = self.literals {
1460 PreferenceTrie::minimize(lits, false);
1461 }
1462 }
1463
1464 /// Trims all literals in this seq such that only the first `len` bytes
1465 /// remain. If a literal has less than or equal to `len` bytes, then it
1466 /// remains unchanged. Otherwise, it is trimmed and made inexact.
1467 ///
1468 /// # Example
1469 ///
1470 /// ```
1471 /// use regex_syntax::hir::literal::{Literal, Seq};
1472 ///
1473 /// let mut seq = Seq::new(&["a", "foo", "quux"]);
1474 /// seq.keep_first_bytes(2);
1475 ///
1476 /// let expected = Seq::from_iter([
1477 /// Literal::exact("a"),
1478 /// Literal::inexact("fo"),
1479 /// Literal::inexact("qu"),
1480 /// ]);
1481 /// assert_eq!(expected, seq);
1482 /// ```
1483 #[inline]
1484 pub fn keep_first_bytes(&mut self, len: usize) {
1485 if let Some(ref mut lits) = self.literals {
1486 for m in lits.iter_mut() {
1487 m.keep_first_bytes(len);
1488 }
1489 }
1490 }
1491
1492 /// Trims all literals in this seq such that only the last `len` bytes
1493 /// remain. If a literal has less than or equal to `len` bytes, then it
1494 /// remains unchanged. Otherwise, it is trimmed and made inexact.
1495 ///
1496 /// # Example
1497 ///
1498 /// ```
1499 /// use regex_syntax::hir::literal::{Literal, Seq};
1500 ///
1501 /// let mut seq = Seq::new(&["a", "foo", "quux"]);
1502 /// seq.keep_last_bytes(2);
1503 ///
1504 /// let expected = Seq::from_iter([
1505 /// Literal::exact("a"),
1506 /// Literal::inexact("oo"),
1507 /// Literal::inexact("ux"),
1508 /// ]);
1509 /// assert_eq!(expected, seq);
1510 /// ```
1511 #[inline]
1512 pub fn keep_last_bytes(&mut self, len: usize) {
1513 if let Some(ref mut lits) = self.literals {
1514 for m in lits.iter_mut() {
1515 m.keep_last_bytes(len);
1516 }
1517 }
1518 }
1519
1520 /// Returns true if this sequence is finite.
1521 ///
1522 /// When false, this sequence is infinite and must be treated as if it
1523 /// contains every possible literal.
1524 #[inline]
1525 pub fn is_finite(&self) -> bool {
1526 self.literals.is_some()
1527 }
1528
1529 /// Returns true if and only if this sequence is finite and empty.
1530 ///
1531 /// An empty sequence never matches anything. It can only be produced by
1532 /// literal extraction when the corresponding regex itself cannot match.
1533 #[inline]
1534 pub fn is_empty(&self) -> bool {
1535 self.len() == Some(0)
1536 }
1537
1538 /// Returns the number of literals in this sequence if the sequence is
1539 /// finite. If the sequence is infinite, then `None` is returned.
1540 #[inline]
1541 pub fn len(&self) -> Option<usize> {
1542 self.literals.as_ref().map(|lits| lits.len())
1543 }
1544
1545 /// Returns true if and only if all literals in this sequence are exact.
1546 ///
1547 /// This returns false if the sequence is infinite.
1548 #[inline]
1549 pub fn is_exact(&self) -> bool {
1550 self.literals().map_or(false, |lits| lits.iter().all(|x| x.is_exact()))
1551 }
1552
1553 /// Returns true if and only if all literals in this sequence are inexact.
1554 ///
1555 /// This returns true if the sequence is infinite.
1556 #[inline]
1557 pub fn is_inexact(&self) -> bool {
1558 self.literals().map_or(true, |lits| lits.iter().all(|x| !x.is_exact()))
1559 }
1560
1561 /// Return the maximum length of the sequence that would result from
1562 /// unioning `self` with `other`. If either set is infinite, then this
1563 /// returns `None`.
1564 #[inline]
1565 pub fn max_union_len(&self, other: &Seq) -> Option<usize> {
1566 let len1 = self.len()?;
1567 let len2 = other.len()?;
1568 Some(len1.saturating_add(len2))
1569 }
1570
1571 /// Return the maximum length of the sequence that would result from the
1572 /// cross product of `self` with `other`. If either set is infinite, then
1573 /// this returns `None`.
1574 #[inline]
1575 pub fn max_cross_len(&self, other: &Seq) -> Option<usize> {
1576 let len1 = self.len()?;
1577 let len2 = other.len()?;
1578 Some(len1.saturating_mul(len2))
1579 }
1580
1581 /// Returns the length of the shortest literal in this sequence.
1582 ///
1583 /// If the sequence is infinite or empty, then this returns `None`.
1584 #[inline]
1585 pub fn min_literal_len(&self) -> Option<usize> {
1586 self.literals.as_ref()?.iter().map(|x| x.len()).min()
1587 }
1588
1589 /// Returns the length of the longest literal in this sequence.
1590 ///
1591 /// If the sequence is infinite or empty, then this returns `None`.
1592 #[inline]
1593 pub fn max_literal_len(&self) -> Option<usize> {
1594 self.literals.as_ref()?.iter().map(|x| x.len()).max()
1595 }
1596
1597 /// Returns the longest common prefix from this seq.
1598 ///
1599 /// If the seq matches any literal or other contains no literals, then
1600 /// there is no meaningful prefix and this returns `None`.
1601 ///
1602 /// # Example
1603 ///
1604 /// This shows some example seqs and their longest common prefix.
1605 ///
1606 /// ```
1607 /// use regex_syntax::hir::literal::Seq;
1608 ///
1609 /// let seq = Seq::new(&["foo", "foobar", "fo"]);
1610 /// assert_eq!(Some(&b"fo"[..]), seq.longest_common_prefix());
1611 /// let seq = Seq::new(&["foo", "foo"]);
1612 /// assert_eq!(Some(&b"foo"[..]), seq.longest_common_prefix());
1613 /// let seq = Seq::new(&["foo", "bar"]);
1614 /// assert_eq!(Some(&b""[..]), seq.longest_common_prefix());
1615 /// let seq = Seq::new(&[""]);
1616 /// assert_eq!(Some(&b""[..]), seq.longest_common_prefix());
1617 ///
1618 /// let seq = Seq::infinite();
1619 /// assert_eq!(None, seq.longest_common_prefix());
1620 /// let seq = Seq::empty();
1621 /// assert_eq!(None, seq.longest_common_prefix());
1622 /// ```
1623 #[inline]
1624 pub fn longest_common_prefix(&self) -> Option<&[u8]> {
1625 // If we match everything or match nothing, then there's no meaningful
1626 // longest common prefix.
1627 let lits = match self.literals {
1628 None => return None,
1629 Some(ref lits) => lits,
1630 };
1631 if lits.len() == 0 {
1632 return None;
1633 }
1634 let base = lits[0].as_bytes();
1635 let mut len = base.len();
1636 for m in lits.iter().skip(1) {
1637 len = m
1638 .as_bytes()
1639 .iter()
1640 .zip(base[..len].iter())
1641 .take_while(|&(a, b)| a == b)
1642 .count();
1643 if len == 0 {
1644 return Some(&[]);
1645 }
1646 }
1647 Some(&base[..len])
1648 }
1649
1650 /// Returns the longest common suffix from this seq.
1651 ///
1652 /// If the seq matches any literal or other contains no literals, then
1653 /// there is no meaningful suffix and this returns `None`.
1654 ///
1655 /// # Example
1656 ///
1657 /// This shows some example seqs and their longest common suffix.
1658 ///
1659 /// ```
1660 /// use regex_syntax::hir::literal::Seq;
1661 ///
1662 /// let seq = Seq::new(&["oof", "raboof", "of"]);
1663 /// assert_eq!(Some(&b"of"[..]), seq.longest_common_suffix());
1664 /// let seq = Seq::new(&["foo", "foo"]);
1665 /// assert_eq!(Some(&b"foo"[..]), seq.longest_common_suffix());
1666 /// let seq = Seq::new(&["foo", "bar"]);
1667 /// assert_eq!(Some(&b""[..]), seq.longest_common_suffix());
1668 /// let seq = Seq::new(&[""]);
1669 /// assert_eq!(Some(&b""[..]), seq.longest_common_suffix());
1670 ///
1671 /// let seq = Seq::infinite();
1672 /// assert_eq!(None, seq.longest_common_suffix());
1673 /// let seq = Seq::empty();
1674 /// assert_eq!(None, seq.longest_common_suffix());
1675 /// ```
1676 #[inline]
1677 pub fn longest_common_suffix(&self) -> Option<&[u8]> {
1678 // If we match everything or match nothing, then there's no meaningful
1679 // longest common suffix.
1680 let lits = match self.literals {
1681 None => return None,
1682 Some(ref lits) => lits,
1683 };
1684 if lits.len() == 0 {
1685 return None;
1686 }
1687 let base = lits[0].as_bytes();
1688 let mut len = base.len();
1689 for m in lits.iter().skip(1) {
1690 len = m
1691 .as_bytes()
1692 .iter()
1693 .rev()
1694 .zip(base[base.len() - len..].iter().rev())
1695 .take_while(|&(a, b)| a == b)
1696 .count();
1697 if len == 0 {
1698 return Some(&[]);
1699 }
1700 }
1701 Some(&base[base.len() - len..])
1702 }
1703
1704 /// Optimizes this seq while treating its literals as prefixes and
1705 /// respecting the preference order of its literals.
1706 ///
1707 /// The specific way "optimization" works is meant to be an implementation
1708 /// detail, as it essentially represents a set of heuristics. The goal
1709 /// that optimization tries to accomplish is to make the literals in this
1710 /// set reflect inputs that will result in a more effective prefilter.
1711 /// Principally by reducing the false positive rate of candidates found by
1712 /// the literals in this sequence. That is, when a match of a literal is
1713 /// found, we would like it to be a strong predictor of the overall match
1714 /// of the regex. If it isn't, then much time will be spent starting and
1715 /// stopping the prefilter search and attempting to confirm the match only
1716 /// to have it fail.
1717 ///
1718 /// Some of those heuristics might be:
1719 ///
1720 /// * Identifying a common prefix from a larger sequence of literals, and
1721 /// shrinking the sequence down to that single common prefix.
1722 /// * Rejecting the sequence entirely if it is believed to result in very
1723 /// high false positive rate. When this happens, the sequence is made
1724 /// infinite.
1725 /// * Shrinking the sequence to a smaller number of literals representing
1726 /// prefixes, but not shrinking it so much as to make literals too short.
1727 /// (A sequence with very short literals, of 1 or 2 bytes, will typically
1728 /// result in a higher false positive rate.)
1729 ///
1730 /// Optimization should only be run once extraction is complete. Namely,
1731 /// optimization may make assumptions that do not compose with other
1732 /// operations in the middle of extraction. For example, optimization will
1733 /// reduce `[E(sam), E(samwise)]` to `[E(sam)]`, but such a transformation
1734 /// is only valid if no other extraction will occur. If other extraction
1735 /// may occur, then the correct transformation would be to `[I(sam)]`.
1736 ///
1737 /// The [`Seq::optimize_for_suffix_by_preference`] does the same thing, but
1738 /// for suffixes.
1739 ///
1740 /// # Example
1741 ///
1742 /// This shows how optimization might transform a sequence. Note that
1743 /// the specific behavior is not a documented guarantee. The heuristics
1744 /// used are an implementation detail and may change over time in semver
1745 /// compatible releases.
1746 ///
1747 /// ```
1748 /// use regex_syntax::hir::literal::{Seq, Literal};
1749 ///
1750 /// let mut seq = Seq::new(&[
1751 /// "samantha",
1752 /// "sam",
1753 /// "samwise",
1754 /// "frodo",
1755 /// ]);
1756 /// seq.optimize_for_prefix_by_preference();
1757 /// assert_eq!(Seq::from_iter([
1758 /// Literal::exact("samantha"),
1759 /// // Kept exact even though 'samwise' got pruned
1760 /// // because optimization assumes literal extraction
1761 /// // has finished.
1762 /// Literal::exact("sam"),
1763 /// Literal::exact("frodo"),
1764 /// ]), seq);
1765 /// ```
1766 ///
1767 /// # Example: optimization may make the sequence infinite
1768 ///
1769 /// If the heuristics deem that the sequence could cause a very high false
1770 /// positive rate, then it may make the sequence infinite, effectively
1771 /// disabling its use as a prefilter.
1772 ///
1773 /// ```
1774 /// use regex_syntax::hir::literal::{Seq, Literal};
1775 ///
1776 /// let mut seq = Seq::new(&[
1777 /// "samantha",
1778 /// // An empty string matches at every position,
1779 /// // thus rendering the prefilter completely
1780 /// // ineffective.
1781 /// "",
1782 /// "sam",
1783 /// "samwise",
1784 /// "frodo",
1785 /// ]);
1786 /// seq.optimize_for_prefix_by_preference();
1787 /// assert!(!seq.is_finite());
1788 /// ```
1789 ///
1790 /// Do note that just because there is a `" "` in the sequence, that
1791 /// doesn't mean the sequence will always be made infinite after it is
1792 /// optimized. Namely, if the sequence is considered exact (any match
1793 /// corresponds to an overall match of the original regex), then any match
1794 /// is an overall match, and so the false positive rate is always `0`.
1795 ///
1796 /// To demonstrate this, we remove `samwise` from our sequence. This
1797 /// results in no optimization happening and all literals remain exact.
1798 /// Thus the entire sequence is exact, and it is kept as-is, even though
1799 /// one is an ASCII space:
1800 ///
1801 /// ```
1802 /// use regex_syntax::hir::literal::{Seq, Literal};
1803 ///
1804 /// let mut seq = Seq::new(&[
1805 /// "samantha",
1806 /// " ",
1807 /// "sam",
1808 /// "frodo",
1809 /// ]);
1810 /// seq.optimize_for_prefix_by_preference();
1811 /// assert!(seq.is_finite());
1812 /// ```
1813 #[inline]
1814 pub fn optimize_for_prefix_by_preference(&mut self) {
1815 self.optimize_by_preference(true);
1816 }
1817
1818 /// Optimizes this seq while treating its literals as suffixes and
1819 /// respecting the preference order of its literals.
1820 ///
1821 /// Optimization should only be run once extraction is complete.
1822 ///
1823 /// The [`Seq::optimize_for_prefix_by_preference`] does the same thing, but
1824 /// for prefixes. See its documentation for more explanation.
1825 #[inline]
1826 pub fn optimize_for_suffix_by_preference(&mut self) {
1827 self.optimize_by_preference(false);
1828 }
1829
1830 fn optimize_by_preference(&mut self, prefix: bool) {
1831 let origlen = match self.len() {
1832 None => return,
1833 Some(len) => len,
1834 };
1835 // Just give up now if our sequence contains an empty string.
1836 if self.min_literal_len().map_or(false, |len| len == 0) {
1837 // We squash the sequence so that nobody else gets any bright
1838 // ideas to try and use it. An empty string implies a match at
1839 // every position. A prefilter cannot help you here.
1840 self.make_infinite();
1841 return;
1842 }
1843 // Make sure we start with the smallest sequence possible. We use a
1844 // special version of preference minimization that retains exactness.
1845 // This is legal because optimization is only expected to occur once
1846 // extraction is complete.
1847 if prefix {
1848 if let Some(ref mut lits) = self.literals {
1849 PreferenceTrie::minimize(lits, true);
1850 }
1851 }
1852
1853 // Look for a common prefix (or suffix). If we found one of those and
1854 // it's long enough, then it's a good bet that it will be our fastest
1855 // possible prefilter since single-substring search is so fast.
1856 let fix = if prefix {
1857 self.longest_common_prefix()
1858 } else {
1859 self.longest_common_suffix()
1860 };
1861 if let Some(fix) = fix {
1862 // As a special case, if we have a common prefix and the leading
1863 // byte of that prefix is one that we think probably occurs rarely,
1864 // then strip everything down to just that single byte. This should
1865 // promote the use of memchr.
1866 //
1867 // ... we only do this though if our sequence has more than one
1868 // literal. Otherwise, we'd rather just stick with a single literal
1869 // scan. That is, using memchr is probably better than looking
1870 // for 2 or more literals, but probably not as good as a straight
1871 // memmem search.
1872 //
1873 // ... and also only do this when the prefix is short and probably
1874 // not too discriminatory anyway. If it's longer, then it's
1875 // probably quite discriminatory and thus is likely to have a low
1876 // false positive rate.
1877 if prefix
1878 && origlen > 1
1879 && fix.len() >= 1
1880 && fix.len() <= 3
1881 && rank(fix[0]) < 200
1882 {
1883 self.keep_first_bytes(1);
1884 self.dedup();
1885 return;
1886 }
1887 // We only strip down to the common prefix/suffix if we think
1888 // the existing set of literals isn't great, or if the common
1889 // prefix/suffix is expected to be particularly discriminatory.
1890 let isfast =
1891 self.is_exact() && self.len().map_or(false, |len| len <= 16);
1892 let usefix = fix.len() > 4 || (fix.len() > 1 && !isfast);
1893 if usefix {
1894 // If we keep exactly the number of bytes equal to the length
1895 // of the prefix (or suffix), then by the definition of a
1896 // prefix, every literal in the sequence will be equivalent.
1897 // Thus, 'dedup' will leave us with one literal.
1898 //
1899 // We do it this way to avoid an alloc, but also to make sure
1900 // the exactness of literals is kept (or not).
1901 if prefix {
1902 self.keep_first_bytes(fix.len());
1903 } else {
1904 self.keep_last_bytes(fix.len());
1905 }
1906 self.dedup();
1907 assert_eq!(Some(1), self.len());
1908 // We still fall through here. In particular, we want our
1909 // longest common prefix to be subject to the poison check.
1910 }
1911 }
1912 // If we have an exact sequence, we *probably* just want to keep it
1913 // as-is. But there are some cases where we don't. So we save a copy of
1914 // the exact sequence now, and then try to do some more optimizations
1915 // below. If those don't work out, we go back to this exact sequence.
1916 //
1917 // The specific motivation for this is that we sometimes wind up with
1918 // an exact sequence with a hefty number of literals. Say, 100. If we
1919 // stuck with that, it would be too big for Teddy and would result in
1920 // using Aho-Corasick. Which is fine... but the lazy DFA is plenty
1921 // suitable in such cases. The real issue is that we will wind up not
1922 // using a fast prefilter at all. So in cases like this, even though
1923 // we have an exact sequence, it would be better to try and shrink the
1924 // sequence (which we do below) and use it as a prefilter that can
1925 // produce false positive matches.
1926 //
1927 // But if the shrinking below results in a sequence that "sucks," then
1928 // we don't want to use that because we already have an exact sequence
1929 // in hand.
1930 let exact: Option<Seq> =
1931 if self.is_exact() { Some(self.clone()) } else { None };
1932 // Now we attempt to shorten the sequence. The idea here is that we
1933 // don't want to look for too many literals, but we want to shorten
1934 // our sequence enough to improve our odds of using better algorithms
1935 // downstream (such as Teddy).
1936 //
1937 // The pair of numbers in this list corresponds to the maximal prefix
1938 // (in bytes) to keep for all literals and the length of the sequence
1939 // at which to do it.
1940 //
1941 // So for example, the pair (3, 500) would mean, "if we have more than
1942 // 500 literals in our sequence, then truncate all of our literals
1943 // such that they are at most 3 bytes in length and the minimize the
1944 // sequence."
1945 const ATTEMPTS: [(usize, usize); 5] =
1946 [(5, 10), (4, 10), (3, 64), (2, 64), (1, 10)];
1947 for (keep, limit) in ATTEMPTS {
1948 let len = match self.len() {
1949 None => break,
1950 Some(len) => len,
1951 };
1952 if len <= limit {
1953 break;
1954 }
1955 if prefix {
1956 self.keep_first_bytes(keep);
1957 } else {
1958 self.keep_last_bytes(keep);
1959 }
1960 if prefix {
1961 if let Some(ref mut lits) = self.literals {
1962 PreferenceTrie::minimize(lits, true);
1963 }
1964 }
1965 }
1966 // Check for a poison literal. A poison literal is one that is short
1967 // and is believed to have a very high match count. These poisons
1968 // generally lead to a prefilter with a very high false positive rate,
1969 // and thus overall worse performance.
1970 //
1971 // We do this last because we could have gone from a non-poisonous
1972 // sequence to a poisonous one. Perhaps we should add some code to
1973 // prevent such transitions in the first place, but then again, we
1974 // likely only made the transition in the first place if the sequence
1975 // was itself huge. And huge sequences are themselves poisonous. So...
1976 if let Some(lits) = self.literals() {
1977 if lits.iter().any(|lit| lit.is_poisonous()) {
1978 self.make_infinite();
1979 }
1980 }
1981 // OK, if we had an exact sequence before attempting more optimizations
1982 // above and our post-optimized sequence sucks for some reason or
1983 // another, then we go back to the exact sequence.
1984 if let Some(exact) = exact {
1985 // If optimizing resulted in dropping our literals, then certainly
1986 // backup and use the exact sequence that we had.
1987 if !self.is_finite() {
1988 *self = exact;
1989 return;
1990 }
1991 // If our optimized sequence contains a short literal, then it's
1992 // *probably* not so great. So throw it away and revert to the
1993 // exact sequence.
1994 if self.min_literal_len().map_or(true, |len| len <= 2) {
1995 *self = exact;
1996 return;
1997 }
1998 // Finally, if our optimized sequence is "big" (i.e., can't use
1999 // Teddy), then also don't use it and rely on the exact sequence.
2000 if self.len().map_or(true, |len| len > 64) {
2001 *self = exact;
2002 return;
2003 }
2004 }
2005 }
2006}
2007
2008impl core::fmt::Debug for Seq {
2009 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2010 write!(f, "Seq")?;
2011 if let Some(lits) = self.literals() {
2012 f.debug_list().entries(lits.iter()).finish()
2013 } else {
2014 write!(f, "[∞]")
2015 }
2016 }
2017}
2018
2019impl FromIterator<Literal> for Seq {
2020 fn from_iter<T: IntoIterator<Item = Literal>>(it: T) -> Seq {
2021 let mut seq = Seq::empty();
2022 for literal in it {
2023 seq.push(literal);
2024 }
2025 seq
2026 }
2027}
2028
2029/// A single literal extracted from an [`Hir`] expression.
2030///
2031/// A literal is composed of two things:
2032///
2033/// * A sequence of bytes. No guarantees with respect to UTF-8 are provided.
2034/// In particular, even if the regex a literal is extracted from is UTF-8, the
2035/// literal extracted may not be valid UTF-8. (For example, if an [`Extractor`]
2036/// limit resulted in trimming a literal in a way that splits a codepoint.)
2037/// * Whether the literal is "exact" or not. An "exact" literal means that it
2038/// has not been trimmed, and may continue to be extended. If a literal is
2039/// "exact" after visiting the entire `Hir` expression, then this implies that
2040/// the literal leads to a match state. (Although it doesn't necessarily imply
2041/// all occurrences of the literal correspond to a match of the regex, since
2042/// literal extraction ignores look-around assertions.)
2043#[derive(Clone, Eq, PartialEq, PartialOrd, Ord)]
2044pub struct Literal {
2045 bytes: Vec<u8>,
2046 exact: bool,
2047}
2048
2049impl Literal {
2050 /// Returns a new exact literal containing the bytes given.
2051 #[inline]
2052 pub fn exact<B: Into<Vec<u8>>>(bytes: B) -> Literal {
2053 Literal { bytes: bytes.into(), exact: true }
2054 }
2055
2056 /// Returns a new inexact literal containing the bytes given.
2057 #[inline]
2058 pub fn inexact<B: Into<Vec<u8>>>(bytes: B) -> Literal {
2059 Literal { bytes: bytes.into(), exact: false }
2060 }
2061
2062 /// Returns the bytes in this literal.
2063 #[inline]
2064 pub fn as_bytes(&self) -> &[u8] {
2065 &self.bytes
2066 }
2067
2068 /// Yields ownership of the bytes inside this literal.
2069 ///
2070 /// Note that this throws away whether the literal is "exact" or not.
2071 #[inline]
2072 pub fn into_bytes(self) -> Vec<u8> {
2073 self.bytes
2074 }
2075
2076 /// Returns the length of this literal in bytes.
2077 #[inline]
2078 pub fn len(&self) -> usize {
2079 self.as_bytes().len()
2080 }
2081
2082 /// Returns true if and only if this literal has zero bytes.
2083 #[inline]
2084 pub fn is_empty(&self) -> bool {
2085 self.len() == 0
2086 }
2087
2088 /// Returns true if and only if this literal is exact.
2089 #[inline]
2090 pub fn is_exact(&self) -> bool {
2091 self.exact
2092 }
2093
2094 /// Marks this literal as inexact.
2095 ///
2096 /// Inexact literals can never be extended. For example,
2097 /// [`Seq::cross_forward`] will not extend inexact literals.
2098 #[inline]
2099 pub fn make_inexact(&mut self) {
2100 self.exact = false;
2101 }
2102
2103 /// Reverse the bytes in this literal.
2104 #[inline]
2105 pub fn reverse(&mut self) {
2106 self.bytes.reverse();
2107 }
2108
2109 /// Extend this literal with the literal given.
2110 ///
2111 /// If this literal is inexact, then this is a no-op.
2112 #[inline]
2113 pub fn extend(&mut self, lit: &Literal) {
2114 if !self.is_exact() {
2115 return;
2116 }
2117 self.bytes.extend_from_slice(&lit.bytes);
2118 }
2119
2120 /// Trims this literal such that only the first `len` bytes remain. If
2121 /// this literal has fewer than `len` bytes, then it remains unchanged.
2122 /// Otherwise, the literal is marked as inexact.
2123 #[inline]
2124 pub fn keep_first_bytes(&mut self, len: usize) {
2125 if len >= self.len() {
2126 return;
2127 }
2128 self.make_inexact();
2129 self.bytes.truncate(len);
2130 }
2131
2132 /// Trims this literal such that only the last `len` bytes remain. If this
2133 /// literal has fewer than `len` bytes, then it remains unchanged.
2134 /// Otherwise, the literal is marked as inexact.
2135 #[inline]
2136 pub fn keep_last_bytes(&mut self, len: usize) {
2137 if len >= self.len() {
2138 return;
2139 }
2140 self.make_inexact();
2141 self.bytes.drain(..self.len() - len);
2142 }
2143
2144 /// Returns true if it is believe that this literal is likely to match very
2145 /// frequently, and is thus not a good candidate for a prefilter.
2146 fn is_poisonous(&self) -> bool {
2147 self.is_empty() || (self.len() == 1 && rank(self.as_bytes()[0]) >= 250)
2148 }
2149}
2150
2151impl From<u8> for Literal {
2152 fn from(byte: u8) -> Literal {
2153 Literal::exact(vec![byte])
2154 }
2155}
2156
2157impl From<char> for Literal {
2158 fn from(ch: char) -> Literal {
2159 use alloc::string::ToString;
2160 Literal::exact(ch.encode_utf8(&mut [0; 4]).to_string())
2161 }
2162}
2163
2164impl AsRef<[u8]> for Literal {
2165 fn as_ref(&self) -> &[u8] {
2166 self.as_bytes()
2167 }
2168}
2169
2170impl core::fmt::Debug for Literal {
2171 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2172 let tag = if self.exact { "E" } else { "I" };
2173 f.debug_tuple(tag)
2174 .field(&crate::debug::Bytes(self.as_bytes()))
2175 .finish()
2176 }
2177}
2178
2179/// A "preference" trie that rejects literals that will never match when
2180/// executing a leftmost first or "preference" search.
2181///
2182/// For example, if 'sam' is inserted, then trying to insert 'samwise' will be
2183/// rejected because 'samwise' can never match since 'sam' will always take
2184/// priority. However, if 'samwise' is inserted first, then inserting 'sam'
2185/// after it is accepted. In this case, either 'samwise' or 'sam' can match in
2186/// a "preference" search.
2187///
2188/// Note that we only use this trie as a "set." That is, given a sequence of
2189/// literals, we insert each one in order. An `insert` will reject a literal
2190/// if a prefix of that literal already exists in the trie. Thus, to rebuild
2191/// the "minimal" sequence, we simply only keep literals that were successfully
2192/// inserted. (Since we don't need traversal, one wonders whether we can make
2193/// some simplifications here, but I haven't given it a ton of thought and I've
2194/// never seen this show up on a profile. Because of the heuristic limits
2195/// imposed on literal extractions, the size of the inputs here is usually
2196/// very small.)
2197#[derive(Debug)]
2198struct PreferenceTrie {
2199 /// The states in this trie. The index of a state in this vector is its ID.
2200 states: Vec<State>,
2201 /// This vec indicates which states are match states. It always has
2202 /// the same length as `states` and is indexed by the same state ID.
2203 /// A state with identifier `sid` is a match state if and only if
2204 /// `matches[sid].is_some()`. The option contains the index of the literal
2205 /// corresponding to the match. The index is offset by 1 so that it fits in
2206 /// a NonZeroUsize.
2207 matches: Vec<Option<NonZeroUsize>>,
2208 /// The index to allocate to the next literal added to this trie. Starts at
2209 /// 1 and increments by 1 for every literal successfully added to the trie.
2210 next_literal_index: usize,
2211}
2212
2213/// A single state in a trie. Uses a sparse representation for its transitions.
2214#[derive(Debug, Default)]
2215struct State {
2216 /// Sparse representation of the transitions out of this state. Transitions
2217 /// are sorted by byte. There is at most one such transition for any
2218 /// particular byte.
2219 trans: Vec<(u8, usize)>,
2220}
2221
2222impl PreferenceTrie {
2223 /// Minimizes the given sequence of literals while preserving preference
2224 /// order semantics.
2225 ///
2226 /// When `keep_exact` is true, the exactness of every literal retained is
2227 /// kept. This is useful when dealing with a fully extracted `Seq` that
2228 /// only contains exact literals. In that case, we can keep all retained
2229 /// literals as exact because we know we'll never need to match anything
2230 /// after them and because any removed literals are guaranteed to never
2231 /// match.
2232 fn minimize(literals: &mut Vec<Literal>, keep_exact: bool) {
2233 let mut trie = PreferenceTrie {
2234 states: vec![],
2235 matches: vec![],
2236 next_literal_index: 1,
2237 };
2238 let mut make_inexact = vec![];
2239 literals.retain_mut(|lit| match trie.insert(lit.as_bytes()) {
2240 Ok(_) => true,
2241 Err(i) => {
2242 if !keep_exact {
2243 make_inexact.push(i.checked_sub(1).unwrap());
2244 }
2245 false
2246 }
2247 });
2248 for i in make_inexact {
2249 literals[i].make_inexact();
2250 }
2251 }
2252
2253 /// Returns `Ok` if the given byte string is accepted into this trie and
2254 /// `Err` otherwise. The index for the success case corresponds to the
2255 /// index of the literal added. The index for the error case corresponds to
2256 /// the index of the literal already in the trie that prevented the given
2257 /// byte string from being added. (Which implies it is a prefix of the one
2258 /// given.)
2259 ///
2260 /// In short, the byte string given is accepted into the trie if and only
2261 /// if it is possible for it to match when executing a preference order
2262 /// search.
2263 fn insert(&mut self, bytes: &[u8]) -> Result<usize, usize> {
2264 let mut prev = self.root();
2265 if let Some(idx) = self.matches[prev] {
2266 return Err(idx.get());
2267 }
2268 for &b in bytes.iter() {
2269 match self.states[prev].trans.binary_search_by_key(&b, |t| t.0) {
2270 Ok(i) => {
2271 prev = self.states[prev].trans[i].1;
2272 if let Some(idx) = self.matches[prev] {
2273 return Err(idx.get());
2274 }
2275 }
2276 Err(i) => {
2277 let next = self.create_state();
2278 self.states[prev].trans.insert(i, (b, next));
2279 prev = next;
2280 }
2281 }
2282 }
2283 let idx = self.next_literal_index;
2284 self.next_literal_index += 1;
2285 self.matches[prev] = NonZeroUsize::new(idx);
2286 Ok(idx)
2287 }
2288
2289 /// Returns the root state ID, and if it doesn't exist, creates it.
2290 fn root(&mut self) -> usize {
2291 if !self.states.is_empty() {
2292 0
2293 } else {
2294 self.create_state()
2295 }
2296 }
2297
2298 /// Creates a new empty state and returns its ID.
2299 fn create_state(&mut self) -> usize {
2300 let id = self.states.len();
2301 self.states.push(State::default());
2302 self.matches.push(None);
2303 id
2304 }
2305}
2306
2307/// Returns the "rank" of the given byte.
2308///
2309/// The minimum rank value is `0` and the maximum rank value is `255`.
2310///
2311/// The rank of a byte is derived from a heuristic background distribution of
2312/// relative frequencies of bytes. The heuristic says that lower the rank of a
2313/// byte, the less likely that byte is to appear in any arbitrary haystack.
2314pub fn rank(byte: u8) -> u8 {
2315 crate::rank::BYTE_FREQUENCIES[usize::from(byte)]
2316}
2317
2318#[cfg(test)]
2319mod tests {
2320 use super::*;
2321
2322 fn parse(pattern: &str) -> Hir {
2323 crate::ParserBuilder::new().utf8(false).build().parse(pattern).unwrap()
2324 }
2325
2326 fn prefixes(pattern: &str) -> Seq {
2327 Extractor::new().kind(ExtractKind::Prefix).extract(&parse(pattern))
2328 }
2329
2330 fn suffixes(pattern: &str) -> Seq {
2331 Extractor::new().kind(ExtractKind::Suffix).extract(&parse(pattern))
2332 }
2333
2334 fn e(pattern: &str) -> (Seq, Seq) {
2335 (prefixes(pattern), suffixes(pattern))
2336 }
2337
2338 #[allow(non_snake_case)]
2339 fn E(x: &str) -> Literal {
2340 Literal::exact(x.as_bytes())
2341 }
2342
2343 #[allow(non_snake_case)]
2344 fn I(x: &str) -> Literal {
2345 Literal::inexact(x.as_bytes())
2346 }
2347
2348 fn seq<I: IntoIterator<Item = Literal>>(it: I) -> Seq {
2349 Seq::from_iter(it)
2350 }
2351
2352 fn infinite() -> (Seq, Seq) {
2353 (Seq::infinite(), Seq::infinite())
2354 }
2355
2356 fn inexact<I1, I2>(it1: I1, it2: I2) -> (Seq, Seq)
2357 where
2358 I1: IntoIterator<Item = Literal>,
2359 I2: IntoIterator<Item = Literal>,
2360 {
2361 (Seq::from_iter(it1), Seq::from_iter(it2))
2362 }
2363
2364 fn exact<B: AsRef<[u8]>, I: IntoIterator<Item = B>>(it: I) -> (Seq, Seq) {
2365 let s1 = Seq::new(it);
2366 let s2 = s1.clone();
2367 (s1, s2)
2368 }
2369
2370 fn opt<B: AsRef<[u8]>, I: IntoIterator<Item = B>>(it: I) -> (Seq, Seq) {
2371 let (mut p, mut s) = exact(it);
2372 p.optimize_for_prefix_by_preference();
2373 s.optimize_for_suffix_by_preference();
2374 (p, s)
2375 }
2376
2377 #[test]
2378 fn literal() {
2379 assert_eq!(exact(["a"]), e("a"));
2380 assert_eq!(exact(["aaaaa"]), e("aaaaa"));
2381 assert_eq!(exact(["A", "a"]), e("(?i-u)a"));
2382 assert_eq!(exact(["AB", "Ab", "aB", "ab"]), e("(?i-u)ab"));
2383 assert_eq!(exact(["abC", "abc"]), e("ab(?i-u)c"));
2384
2385 assert_eq!(exact([b"\xFF"]), e(r"(?-u:\xFF)"));
2386
2387 #[cfg(feature = "unicode-case")]
2388 {
2389 assert_eq!(exact(["☃"]), e("☃"));
2390 assert_eq!(exact(["☃"]), e("(?i)☃"));
2391 assert_eq!(exact(["☃☃☃☃☃"]), e("☃☃☃☃☃"));
2392
2393 assert_eq!(exact(["Δ"]), e("Δ"));
2394 assert_eq!(exact(["δ"]), e("δ"));
2395 assert_eq!(exact(["Δ", "δ"]), e("(?i)Δ"));
2396 assert_eq!(exact(["Δ", "δ"]), e("(?i)δ"));
2397
2398 assert_eq!(exact(["S", "s", "ſ"]), e("(?i)S"));
2399 assert_eq!(exact(["S", "s", "ſ"]), e("(?i)s"));
2400 assert_eq!(exact(["S", "s", "ſ"]), e("(?i)ſ"));
2401 }
2402
2403 let letters = "ͱͳͷΐάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋ";
2404 assert_eq!(exact([letters]), e(letters));
2405 }
2406
2407 #[test]
2408 fn class() {
2409 assert_eq!(exact(["a", "b", "c"]), e("[abc]"));
2410 assert_eq!(exact(["a1b", "a2b", "a3b"]), e("a[123]b"));
2411 assert_eq!(exact(["δ", "ε"]), e("[εδ]"));
2412 #[cfg(feature = "unicode-case")]
2413 {
2414 assert_eq!(exact(["Δ", "Ε", "δ", "ε", "ϵ"]), e(r"(?i)[εδ]"));
2415 }
2416 }
2417
2418 #[test]
2419 fn look() {
2420 assert_eq!(exact(["ab"]), e(r"a\Ab"));
2421 assert_eq!(exact(["ab"]), e(r"a\zb"));
2422 assert_eq!(exact(["ab"]), e(r"a(?m:^)b"));
2423 assert_eq!(exact(["ab"]), e(r"a(?m:$)b"));
2424 assert_eq!(exact(["ab"]), e(r"a\bb"));
2425 assert_eq!(exact(["ab"]), e(r"a\Bb"));
2426 assert_eq!(exact(["ab"]), e(r"a(?-u:\b)b"));
2427 assert_eq!(exact(["ab"]), e(r"a(?-u:\B)b"));
2428
2429 assert_eq!(exact(["ab"]), e(r"^ab"));
2430 assert_eq!(exact(["ab"]), e(r"$ab"));
2431 assert_eq!(exact(["ab"]), e(r"(?m:^)ab"));
2432 assert_eq!(exact(["ab"]), e(r"(?m:$)ab"));
2433 assert_eq!(exact(["ab"]), e(r"\bab"));
2434 assert_eq!(exact(["ab"]), e(r"\Bab"));
2435 assert_eq!(exact(["ab"]), e(r"(?-u:\b)ab"));
2436 assert_eq!(exact(["ab"]), e(r"(?-u:\B)ab"));
2437
2438 assert_eq!(exact(["ab"]), e(r"ab^"));
2439 assert_eq!(exact(["ab"]), e(r"ab$"));
2440 assert_eq!(exact(["ab"]), e(r"ab(?m:^)"));
2441 assert_eq!(exact(["ab"]), e(r"ab(?m:$)"));
2442 assert_eq!(exact(["ab"]), e(r"ab\b"));
2443 assert_eq!(exact(["ab"]), e(r"ab\B"));
2444 assert_eq!(exact(["ab"]), e(r"ab(?-u:\b)"));
2445 assert_eq!(exact(["ab"]), e(r"ab(?-u:\B)"));
2446
2447 let expected = (seq([I("aZ"), E("ab")]), seq([I("Zb"), E("ab")]));
2448 assert_eq!(expected, e(r"^aZ*b"));
2449 }
2450
2451 #[test]
2452 fn repetition() {
2453 assert_eq!(exact(["a", ""]), e(r"a?"));
2454 assert_eq!(exact(["", "a"]), e(r"a??"));
2455 assert_eq!(inexact([I("a"), E("")], [I("a"), E("")]), e(r"a*"));
2456 assert_eq!(inexact([E(""), I("a")], [E(""), I("a")]), e(r"a*?"));
2457 assert_eq!(inexact([I("a")], [I("a")]), e(r"a+"));
2458 assert_eq!(inexact([I("a")], [I("a")]), e(r"(a+)+"));
2459
2460 assert_eq!(exact(["ab"]), e(r"aZ{0}b"));
2461 assert_eq!(exact(["aZb", "ab"]), e(r"aZ?b"));
2462 assert_eq!(exact(["ab", "aZb"]), e(r"aZ??b"));
2463 assert_eq!(
2464 inexact([I("aZ"), E("ab")], [I("Zb"), E("ab")]),
2465 e(r"aZ*b")
2466 );
2467 assert_eq!(
2468 inexact([E("ab"), I("aZ")], [E("ab"), I("Zb")]),
2469 e(r"aZ*?b")
2470 );
2471 assert_eq!(inexact([I("aZ")], [I("Zb")]), e(r"aZ+b"));
2472 assert_eq!(inexact([I("aZ")], [I("Zb")]), e(r"aZ+?b"));
2473
2474 assert_eq!(exact(["aZZb"]), e(r"aZ{2}b"));
2475 assert_eq!(inexact([I("aZZ")], [I("ZZb")]), e(r"aZ{2,3}b"));
2476
2477 assert_eq!(exact(["abc", ""]), e(r"(abc)?"));
2478 assert_eq!(exact(["", "abc"]), e(r"(abc)??"));
2479
2480 assert_eq!(inexact([I("a"), E("b")], [I("ab"), E("b")]), e(r"a*b"));
2481 assert_eq!(inexact([E("b"), I("a")], [E("b"), I("ab")]), e(r"a*?b"));
2482 assert_eq!(inexact([I("ab")], [I("b")]), e(r"ab+"));
2483 assert_eq!(inexact([I("a"), I("b")], [I("b")]), e(r"a*b+"));
2484
2485 // FIXME: The suffixes for this don't look quite right to me. I think
2486 // the right suffixes would be: [I(ac), I(bc), E(c)]. The main issue I
2487 // think is that suffixes are computed by iterating over concatenations
2488 // in reverse, and then [bc, ac, c] ordering is indeed correct from
2489 // that perspective. We also test a few more equivalent regexes, and
2490 // we get the same result, so it is consistent at least I suppose.
2491 //
2492 // The reason why this isn't an issue is that it only messes up
2493 // preference order, and currently, suffixes are never used in a
2494 // context where preference order matters. For prefixes it matters
2495 // because we sometimes want to use prefilters without confirmation
2496 // when all of the literals are exact (and there's no look-around). But
2497 // we never do that for suffixes. Any time we use suffixes, we always
2498 // include a confirmation step. If that ever changes, then it's likely
2499 // this bug will need to be fixed, but last time I looked, it appears
2500 // hard to do so.
2501 assert_eq!(
2502 inexact([I("a"), I("b"), E("c")], [I("bc"), I("ac"), E("c")]),
2503 e(r"a*b*c")
2504 );
2505 assert_eq!(
2506 inexact([I("a"), I("b"), E("c")], [I("bc"), I("ac"), E("c")]),
2507 e(r"(a+)?(b+)?c")
2508 );
2509 assert_eq!(
2510 inexact([I("a"), I("b"), E("c")], [I("bc"), I("ac"), E("c")]),
2511 e(r"(a+|)(b+|)c")
2512 );
2513 // A few more similarish but not identical regexes. These may have a
2514 // similar problem as above.
2515 assert_eq!(
2516 inexact(
2517 [I("a"), I("b"), I("c"), E("")],
2518 [I("c"), I("b"), I("a"), E("")]
2519 ),
2520 e(r"a*b*c*")
2521 );
2522 assert_eq!(inexact([I("a"), I("b"), I("c")], [I("c")]), e(r"a*b*c+"));
2523 assert_eq!(inexact([I("a"), I("b")], [I("bc")]), e(r"a*b+c"));
2524 assert_eq!(inexact([I("a"), I("b")], [I("c"), I("b")]), e(r"a*b+c*"));
2525 assert_eq!(inexact([I("ab"), E("a")], [I("b"), E("a")]), e(r"ab*"));
2526 assert_eq!(
2527 inexact([I("ab"), E("ac")], [I("bc"), E("ac")]),
2528 e(r"ab*c")
2529 );
2530 assert_eq!(inexact([I("ab")], [I("b")]), e(r"ab+"));
2531 assert_eq!(inexact([I("ab")], [I("bc")]), e(r"ab+c"));
2532
2533 assert_eq!(
2534 inexact([I("z"), E("azb")], [I("zazb"), E("azb")]),
2535 e(r"z*azb")
2536 );
2537
2538 let expected =
2539 exact(["aaa", "aab", "aba", "abb", "baa", "bab", "bba", "bbb"]);
2540 assert_eq!(expected, e(r"[ab]{3}"));
2541 let expected = inexact(
2542 [
2543 I("aaa"),
2544 I("aab"),
2545 I("aba"),
2546 I("abb"),
2547 I("baa"),
2548 I("bab"),
2549 I("bba"),
2550 I("bbb"),
2551 ],
2552 [
2553 I("aaa"),
2554 I("aab"),
2555 I("aba"),
2556 I("abb"),
2557 I("baa"),
2558 I("bab"),
2559 I("bba"),
2560 I("bbb"),
2561 ],
2562 );
2563 assert_eq!(expected, e(r"[ab]{3,4}"));
2564 }
2565
2566 #[test]
2567 fn concat() {
2568 let empty: [&str; 0] = [];
2569
2570 assert_eq!(exact(["abcxyz"]), e(r"abc()xyz"));
2571 assert_eq!(exact(["abcxyz"]), e(r"(abc)(xyz)"));
2572 assert_eq!(exact(["abcmnoxyz"]), e(r"abc()mno()xyz"));
2573 assert_eq!(exact(empty), e(r"abc[a&&b]xyz"));
2574 assert_eq!(exact(["abcxyz"]), e(r"abc[a&&b]*xyz"));
2575 }
2576
2577 #[test]
2578 fn alternation() {
2579 assert_eq!(exact(["abc", "mno", "xyz"]), e(r"abc|mno|xyz"));
2580 assert_eq!(
2581 inexact(
2582 [E("abc"), I("mZ"), E("mo"), E("xyz")],
2583 [E("abc"), I("Zo"), E("mo"), E("xyz")]
2584 ),
2585 e(r"abc|mZ*o|xyz")
2586 );
2587 assert_eq!(exact(["abc", "xyz"]), e(r"abc|M[a&&b]N|xyz"));
2588 assert_eq!(exact(["abc", "MN", "xyz"]), e(r"abc|M[a&&b]*N|xyz"));
2589
2590 assert_eq!(exact(["aaa", "aaaaa"]), e(r"(?:|aa)aaa"));
2591 assert_eq!(
2592 inexact(
2593 [I("aaa"), E(""), I("aaaaa"), E("aa")],
2594 [I("aaa"), E(""), E("aa")]
2595 ),
2596 e(r"(?:|aa)(?:aaa)*")
2597 );
2598 assert_eq!(
2599 inexact(
2600 [E(""), I("aaa"), E("aa"), I("aaaaa")],
2601 [E(""), I("aaa"), E("aa")]
2602 ),
2603 e(r"(?:|aa)(?:aaa)*?")
2604 );
2605
2606 assert_eq!(
2607 inexact([E("a"), I("b"), E("")], [E("a"), I("b"), E("")]),
2608 e(r"a|b*")
2609 );
2610 assert_eq!(inexact([E("a"), I("b")], [E("a"), I("b")]), e(r"a|b+"));
2611
2612 assert_eq!(
2613 inexact([I("a"), E("b"), E("c")], [I("ab"), E("b"), E("c")]),
2614 e(r"a*b|c")
2615 );
2616
2617 assert_eq!(
2618 inexact(
2619 [E("a"), E("b"), I("c"), E("")],
2620 [E("a"), E("b"), I("c"), E("")]
2621 ),
2622 e(r"a|(?:b|c*)")
2623 );
2624
2625 assert_eq!(
2626 inexact(
2627 [I("a"), I("b"), E("c"), I("a"), I("ab"), E("c")],
2628 [I("ac"), I("bc"), E("c"), I("ac"), I("abc"), E("c")],
2629 ),
2630 e(r"(a|b)*c|(a|ab)*c")
2631 );
2632
2633 assert_eq!(
2634 exact(["abef", "abgh", "cdef", "cdgh"]),
2635 e(r"(ab|cd)(ef|gh)")
2636 );
2637 assert_eq!(
2638 exact([
2639 "abefij", "abefkl", "abghij", "abghkl", "cdefij", "cdefkl",
2640 "cdghij", "cdghkl",
2641 ]),
2642 e(r"(ab|cd)(ef|gh)(ij|kl)")
2643 );
2644
2645 assert_eq!(inexact([E("abab")], [E("abab")]), e(r"(ab){2}"));
2646
2647 assert_eq!(inexact([I("abab")], [I("abab")]), e(r"(ab){2,3}"));
2648
2649 assert_eq!(inexact([I("abab")], [I("abab")]), e(r"(ab){2,}"));
2650 }
2651
2652 #[test]
2653 fn impossible() {
2654 let empty: [&str; 0] = [];
2655
2656 assert_eq!(exact(empty), e(r"[a&&b]"));
2657 assert_eq!(exact(empty), e(r"a[a&&b]"));
2658 assert_eq!(exact(empty), e(r"[a&&b]b"));
2659 assert_eq!(exact(empty), e(r"a[a&&b]b"));
2660 assert_eq!(exact(["a", "b"]), e(r"a|[a&&b]|b"));
2661 assert_eq!(exact(["a", "b"]), e(r"a|c[a&&b]|b"));
2662 assert_eq!(exact(["a", "b"]), e(r"a|[a&&b]d|b"));
2663 assert_eq!(exact(["a", "b"]), e(r"a|c[a&&b]d|b"));
2664 assert_eq!(exact([""]), e(r"[a&&b]*"));
2665 assert_eq!(exact(["MN"]), e(r"M[a&&b]*N"));
2666 }
2667
2668 // This tests patterns that contain something that defeats literal
2669 // detection, usually because it would blow some limit on the total number
2670 // of literals that can be returned.
2671 //
2672 // The main idea is that when literal extraction sees something that
2673 // it knows will blow a limit, it replaces it with a marker that says
2674 // "any literal will match here." While not necessarily true, the
2675 // over-estimation is just fine for the purposes of literal extraction,
2676 // because the imprecision doesn't matter: too big is too big.
2677 //
2678 // This is one of the trickier parts of literal extraction, since we need
2679 // to make sure all of our literal extraction operations correctly compose
2680 // with the markers.
2681 #[test]
2682 fn anything() {
2683 assert_eq!(infinite(), e(r"."));
2684 assert_eq!(infinite(), e(r"(?s)."));
2685 assert_eq!(infinite(), e(r"[A-Za-z]"));
2686 assert_eq!(infinite(), e(r"[A-Z]"));
2687 assert_eq!(exact([""]), e(r"[A-Z]{0}"));
2688 assert_eq!(infinite(), e(r"[A-Z]?"));
2689 assert_eq!(infinite(), e(r"[A-Z]*"));
2690 assert_eq!(infinite(), e(r"[A-Z]+"));
2691 assert_eq!((seq([I("1")]), Seq::infinite()), e(r"1[A-Z]"));
2692 assert_eq!((seq([I("1")]), seq([I("2")])), e(r"1[A-Z]2"));
2693 assert_eq!((Seq::infinite(), seq([I("123")])), e(r"[A-Z]+123"));
2694 assert_eq!(infinite(), e(r"[A-Z]+123[A-Z]+"));
2695 assert_eq!(infinite(), e(r"1|[A-Z]|3"));
2696 assert_eq!(
2697 (seq([E("1"), I("2"), E("3")]), Seq::infinite()),
2698 e(r"1|2[A-Z]|3"),
2699 );
2700 assert_eq!(
2701 (Seq::infinite(), seq([E("1"), I("2"), E("3")])),
2702 e(r"1|[A-Z]2|3"),
2703 );
2704 assert_eq!(
2705 (seq([E("1"), I("2"), E("4")]), seq([E("1"), I("3"), E("4")])),
2706 e(r"1|2[A-Z]3|4"),
2707 );
2708 assert_eq!((Seq::infinite(), seq([I("2")])), e(r"(?:|1)[A-Z]2"));
2709 assert_eq!(inexact([I("a")], [I("z")]), e(r"a.z"));
2710 }
2711
2712 // Like the 'anything' test, but it uses smaller limits in order to test
2713 // the logic for effectively aborting literal extraction when the seqs get
2714 // too big.
2715 #[test]
2716 fn anything_small_limits() {
2717 fn prefixes(pattern: &str) -> Seq {
2718 Extractor::new()
2719 .kind(ExtractKind::Prefix)
2720 .limit_total(10)
2721 .extract(&parse(pattern))
2722 }
2723
2724 fn suffixes(pattern: &str) -> Seq {
2725 Extractor::new()
2726 .kind(ExtractKind::Suffix)
2727 .limit_total(10)
2728 .extract(&parse(pattern))
2729 }
2730
2731 fn e(pattern: &str) -> (Seq, Seq) {
2732 (prefixes(pattern), suffixes(pattern))
2733 }
2734
2735 assert_eq!(
2736 (
2737 seq([
2738 I("aaa"),
2739 I("aab"),
2740 I("aba"),
2741 I("abb"),
2742 I("baa"),
2743 I("bab"),
2744 I("bba"),
2745 I("bbb")
2746 ]),
2747 seq([
2748 I("aaa"),
2749 I("aab"),
2750 I("aba"),
2751 I("abb"),
2752 I("baa"),
2753 I("bab"),
2754 I("bba"),
2755 I("bbb")
2756 ])
2757 ),
2758 e(r"[ab]{3}{3}")
2759 );
2760
2761 assert_eq!(infinite(), e(r"ab|cd|ef|gh|ij|kl|mn|op|qr|st|uv|wx|yz"));
2762 }
2763
2764 #[test]
2765 fn empty() {
2766 assert_eq!(exact([""]), e(r""));
2767 assert_eq!(exact([""]), e(r"^"));
2768 assert_eq!(exact([""]), e(r"$"));
2769 assert_eq!(exact([""]), e(r"(?m:^)"));
2770 assert_eq!(exact([""]), e(r"(?m:$)"));
2771 assert_eq!(exact([""]), e(r"\b"));
2772 assert_eq!(exact([""]), e(r"\B"));
2773 assert_eq!(exact([""]), e(r"(?-u:\b)"));
2774 assert_eq!(exact([""]), e(r"(?-u:\B)"));
2775 }
2776
2777 #[test]
2778 fn odds_and_ends() {
2779 assert_eq!((Seq::infinite(), seq([I("a")])), e(r".a"));
2780 assert_eq!((seq([I("a")]), Seq::infinite()), e(r"a."));
2781 assert_eq!(infinite(), e(r"a|."));
2782 assert_eq!(infinite(), e(r".|a"));
2783
2784 let pat = r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]";
2785 let expected = inexact(
2786 ["Mo'am", "Moam", "Mu'am", "Muam"].map(I),
2787 [
2788 "ddafi", "ddafy", "dhafi", "dhafy", "dzafi", "dzafy", "dafi",
2789 "dafy", "tdafi", "tdafy", "thafi", "thafy", "tzafi", "tzafy",
2790 "tafi", "tafy", "zdafi", "zdafy", "zhafi", "zhafy", "zzafi",
2791 "zzafy", "zafi", "zafy",
2792 ]
2793 .map(I),
2794 );
2795 assert_eq!(expected, e(pat));
2796
2797 assert_eq!(
2798 (seq(["fn is_", "fn as_"].map(I)), Seq::infinite()),
2799 e(r"fn is_([A-Z]+)|fn as_([A-Z]+)"),
2800 );
2801 assert_eq!(
2802 inexact([I("foo")], [I("quux")]),
2803 e(r"foo[A-Z]+bar[A-Z]+quux")
2804 );
2805 assert_eq!(infinite(), e(r"[A-Z]+bar[A-Z]+"));
2806 assert_eq!(
2807 exact(["Sherlock Holmes"]),
2808 e(r"(?m)^Sherlock Holmes|Sherlock Holmes$")
2809 );
2810
2811 assert_eq!(exact(["sa", "sb"]), e(r"\bs(?:[ab])"));
2812 }
2813
2814 // This tests a specific regex along with some heuristic steps to reduce
2815 // the sequences extracted. This is meant to roughly correspond to the
2816 // types of heuristics used to shrink literal sets in practice. (Shrinking
2817 // is done because you want to balance "spend too much work looking for
2818 // too many literals" and "spend too much work processing false positive
2819 // matches from short literals.")
2820 #[test]
2821 #[cfg(feature = "unicode-case")]
2822 fn holmes() {
2823 let expected = inexact(
2824 ["HOL", "HOl", "HoL", "Hol", "hOL", "hOl", "hoL", "hol"].map(I),
2825 [
2826 "MES", "MEs", "Eſ", "MeS", "Mes", "eſ", "mES", "mEs", "meS",
2827 "mes",
2828 ]
2829 .map(I),
2830 );
2831 let (mut prefixes, mut suffixes) = e(r"(?i)Holmes");
2832 prefixes.keep_first_bytes(3);
2833 suffixes.keep_last_bytes(3);
2834 prefixes.minimize_by_preference();
2835 suffixes.minimize_by_preference();
2836 assert_eq!(expected, (prefixes, suffixes));
2837 }
2838
2839 // This tests that we get some kind of literals extracted for a beefier
2840 // alternation with case insensitive mode enabled. At one point during
2841 // development, this returned nothing, and motivated some special case
2842 // code in Extractor::union to try and trim down the literal sequences
2843 // if the union would blow the limits set.
2844 #[test]
2845 #[cfg(feature = "unicode-case")]
2846 fn holmes_alt() {
2847 let mut pre =
2848 prefixes(r"(?i)Sherlock|Holmes|Watson|Irene|Adler|John|Baker");
2849 assert!(pre.len().unwrap() > 0);
2850 pre.optimize_for_prefix_by_preference();
2851 assert!(pre.len().unwrap() > 0);
2852 }
2853
2854 // See: https://github.com/rust-lang/regex/security/advisories/GHSA-m5pq-gvj9-9vr8
2855 // See: CVE-2022-24713
2856 //
2857 // We test this here to ensure literal extraction completes in reasonable
2858 // time and isn't materially impacted by these sorts of pathological
2859 // repeats.
2860 #[test]
2861 fn crazy_repeats() {
2862 assert_eq!(inexact([E("")], [E("")]), e(r"(?:){4294967295}"));
2863 assert_eq!(
2864 inexact([E("")], [E("")]),
2865 e(r"(?:){64}{64}{64}{64}{64}{64}")
2866 );
2867 assert_eq!(inexact([E("")], [E("")]), e(r"x{0}{4294967295}"));
2868 assert_eq!(inexact([E("")], [E("")]), e(r"(?:|){4294967295}"));
2869
2870 assert_eq!(
2871 inexact([E("")], [E("")]),
2872 e(r"(?:){8}{8}{8}{8}{8}{8}{8}{8}{8}{8}{8}{8}{8}{8}")
2873 );
2874 let repa = "a".repeat(100);
2875 assert_eq!(
2876 inexact([I(&repa)], [I(&repa)]),
2877 e(r"a{8}{8}{8}{8}{8}{8}{8}{8}{8}{8}{8}{8}{8}{8}")
2878 );
2879 }
2880
2881 #[test]
2882 fn huge() {
2883 let pat = r#"(?-u)
2884 2(?:
2885 [45]\d{3}|
2886 7(?:
2887 1[0-267]|
2888 2[0-289]|
2889 3[0-29]|
2890 4[01]|
2891 5[1-3]|
2892 6[013]|
2893 7[0178]|
2894 91
2895 )|
2896 8(?:
2897 0[125]|
2898 [139][1-6]|
2899 2[0157-9]|
2900 41|
2901 6[1-35]|
2902 7[1-5]|
2903 8[1-8]|
2904 90
2905 )|
2906 9(?:
2907 0[0-2]|
2908 1[0-4]|
2909 2[568]|
2910 3[3-6]|
2911 5[5-7]|
2912 6[0167]|
2913 7[15]|
2914 8[0146-9]
2915 )
2916 )\d{4}|
2917 3(?:
2918 12?[5-7]\d{2}|
2919 0(?:
2920 2(?:
2921 [025-79]\d|
2922 [348]\d{1,2}
2923 )|
2924 3(?:
2925 [2-4]\d|
2926 [56]\d?
2927 )
2928 )|
2929 2(?:
2930 1\d{2}|
2931 2(?:
2932 [12]\d|
2933 [35]\d{1,2}|
2934 4\d?
2935 )
2936 )|
2937 3(?:
2938 1\d{2}|
2939 2(?:
2940 [2356]\d|
2941 4\d{1,2}
2942 )
2943 )|
2944 4(?:
2945 1\d{2}|
2946 2(?:
2947 2\d{1,2}|
2948 [47]|
2949 5\d{2}
2950 )
2951 )|
2952 5(?:
2953 1\d{2}|
2954 29
2955 )|
2956 [67]1\d{2}|
2957 8(?:
2958 1\d{2}|
2959 2(?:
2960 2\d{2}|
2961 3|
2962 4\d
2963 )
2964 )
2965 )\d{3}|
2966 4(?:
2967 0(?:
2968 2(?:
2969 [09]\d|
2970 7
2971 )|
2972 33\d{2}
2973 )|
2974 1\d{3}|
2975 2(?:
2976 1\d{2}|
2977 2(?:
2978 [25]\d?|
2979 [348]\d|
2980 [67]\d{1,2}
2981 )
2982 )|
2983 3(?:
2984 1\d{2}(?:
2985 \d{2}
2986 )?|
2987 2(?:
2988 [045]\d|
2989 [236-9]\d{1,2}
2990 )|
2991 32\d{2}
2992 )|
2993 4(?:
2994 [18]\d{2}|
2995 2(?:
2996 [2-46]\d{2}|
2997 3
2998 )|
2999 5[25]\d{2}
3000 )|
3001 5(?:
3002 1\d{2}|
3003 2(?:
3004 3\d|
3005 5
3006 )
3007 )|
3008 6(?:
3009 [18]\d{2}|
3010 2(?:
3011 3(?:
3012 \d{2}
3013 )?|
3014 [46]\d{1,2}|
3015 5\d{2}|
3016 7\d
3017 )|
3018 5(?:
3019 3\d?|
3020 4\d|
3021 [57]\d{1,2}|
3022 6\d{2}|
3023 8
3024 )
3025 )|
3026 71\d{2}|
3027 8(?:
3028 [18]\d{2}|
3029 23\d{2}|
3030 54\d{2}
3031 )|
3032 9(?:
3033 [18]\d{2}|
3034 2[2-5]\d{2}|
3035 53\d{1,2}
3036 )
3037 )\d{3}|
3038 5(?:
3039 02[03489]\d{2}|
3040 1\d{2}|
3041 2(?:
3042 1\d{2}|
3043 2(?:
3044 2(?:
3045 \d{2}
3046 )?|
3047 [457]\d{2}
3048 )
3049 )|
3050 3(?:
3051 1\d{2}|
3052 2(?:
3053 [37](?:
3054 \d{2}
3055 )?|
3056 [569]\d{2}
3057 )
3058 )|
3059 4(?:
3060 1\d{2}|
3061 2[46]\d{2}
3062 )|
3063 5(?:
3064 1\d{2}|
3065 26\d{1,2}
3066 )|
3067 6(?:
3068 [18]\d{2}|
3069 2|
3070 53\d{2}
3071 )|
3072 7(?:
3073 1|
3074 24
3075 )\d{2}|
3076 8(?:
3077 1|
3078 26
3079 )\d{2}|
3080 91\d{2}
3081 )\d{3}|
3082 6(?:
3083 0(?:
3084 1\d{2}|
3085 2(?:
3086 3\d{2}|
3087 4\d{1,2}
3088 )
3089 )|
3090 2(?:
3091 2[2-5]\d{2}|
3092 5(?:
3093 [3-5]\d{2}|
3094 7
3095 )|
3096 8\d{2}
3097 )|
3098 3(?:
3099 1|
3100 2[3478]
3101 )\d{2}|
3102 4(?:
3103 1|
3104 2[34]
3105 )\d{2}|
3106 5(?:
3107 1|
3108 2[47]
3109 )\d{2}|
3110 6(?:
3111 [18]\d{2}|
3112 6(?:
3113 2(?:
3114 2\d|
3115 [34]\d{2}
3116 )|
3117 5(?:
3118 [24]\d{2}|
3119 3\d|
3120 5\d{1,2}
3121 )
3122 )
3123 )|
3124 72[2-5]\d{2}|
3125 8(?:
3126 1\d{2}|
3127 2[2-5]\d{2}
3128 )|
3129 9(?:
3130 1\d{2}|
3131 2[2-6]\d{2}
3132 )
3133 )\d{3}|
3134 7(?:
3135 (?:
3136 02|
3137 [3-589]1|
3138 6[12]|
3139 72[24]
3140 )\d{2}|
3141 21\d{3}|
3142 32
3143 )\d{3}|
3144 8(?:
3145 (?:
3146 4[12]|
3147 [5-7]2|
3148 1\d?
3149 )|
3150 (?:
3151 0|
3152 3[12]|
3153 [5-7]1|
3154 217
3155 )\d
3156 )\d{4}|
3157 9(?:
3158 [35]1|
3159 (?:
3160 [024]2|
3161 81
3162 )\d|
3163 (?:
3164 1|
3165 [24]1
3166 )\d{2}
3167 )\d{3}
3168 "#;
3169 // TODO: This is a good candidate of a seq of literals that could be
3170 // shrunk quite a bit and still be very productive with respect to
3171 // literal optimizations.
3172 let (prefixes, suffixes) = e(pat);
3173 assert!(!suffixes.is_finite());
3174 assert_eq!(Some(243), prefixes.len());
3175 }
3176
3177 #[test]
3178 fn optimize() {
3179 // This gets a common prefix that isn't too short.
3180 let (p, s) =
3181 opt(["foobarfoobar", "foobar", "foobarzfoobar", "foobarfoobar"]);
3182 assert_eq!(seq([I("foobar")]), p);
3183 assert_eq!(seq([I("foobar")]), s);
3184
3185 // This also finds a common prefix, but since it's only one byte, it
3186 // prefers the multiple literals.
3187 let (p, s) = opt(["abba", "akka", "abccba"]);
3188 assert_eq!(exact(["abba", "akka", "abccba"]), (p, s));
3189
3190 let (p, s) = opt(["sam", "samwise"]);
3191 assert_eq!((seq([E("sam")]), seq([E("sam"), E("samwise")])), (p, s));
3192
3193 // The empty string is poisonous, so our seq becomes infinite, even
3194 // though all literals are exact.
3195 let (p, s) = opt(["foobarfoo", "foo", "", "foozfoo", "foofoo"]);
3196 assert!(!p.is_finite());
3197 assert!(!s.is_finite());
3198
3199 // A space is also poisonous, so our seq becomes infinite. But this
3200 // only gets triggered when we don't have a completely exact sequence.
3201 // When the sequence is exact, spaces are okay, since we presume that
3202 // any prefilter will match a space more quickly than the regex engine.
3203 // (When the sequence is exact, there's a chance of the prefilter being
3204 // used without needing the regex engine at all.)
3205 let mut p = seq([E("foobarfoo"), I("foo"), E(" "), E("foofoo")]);
3206 p.optimize_for_prefix_by_preference();
3207 assert!(!p.is_finite());
3208 }
3209}