1use regex_syntax::hir::{Class, ClassUnicode, ClassUnicodeRange, Hir, HirKind};
2
3use crate::optimize::{optimize, OptimizeOptions};
4use crate::to_hir::{parse_fragment, HirCtx};
5use crate::{Expr, LookAround, RegexOptions, Result};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
10pub struct ByteSet([u64; 4]);
11
12impl ByteSet {
13 pub fn insert(&mut self, byte: u8) {
15 self.0[(byte >> 6) as usize] |= 1u64 << (byte & 63);
16 }
17
18 pub fn is_empty(&self) -> bool {
20 self.0 == [0; 4]
21 }
22
23 #[inline]
25 pub fn contains(&self, byte: u8) -> bool {
26 self.0[(byte >> 6) as usize] & (1u64 << (byte & 63)) != 0
27 }
28
29 pub fn union(&mut self, other: &Self) {
31 for (a, b) in self.0.iter_mut().zip(&other.0) {
32 *a |= *b;
33 }
34 }
35
36 pub fn intersection(&mut self, other: &Self) {
38 for (a, b) in self.0.iter_mut().zip(&other.0) {
39 *a &= *b;
40 }
41 }
42
43 #[inline]
45 pub fn is_subset(&self, other: &Self) -> bool {
46 self.0
47 .iter()
48 .zip(other.0)
49 .all(|(self_word, other_word)| self_word & !other_word == 0)
50 }
51
52 pub fn iter(&self) -> impl Iterator<Item = u8> + '_ {
54 set_bits(&self.0).map(|i| i as u8)
55 }
56
57 pub fn words(&self) -> &[u64; 4] {
59 &self.0
60 }
61
62 pub const fn from_words(words: [u64; 4]) -> Self {
64 Self(words)
65 }
66}
67
68fn bits_of(mut bits: u64) -> impl Iterator<Item = usize> {
70 core::iter::from_fn(move || {
71 (bits != 0).then(|| {
72 let bit = bits.trailing_zeros() as usize;
73 bits &= bits - 1;
75 bit
76 })
77 })
78}
79
80fn set_bits(words: &[u64]) -> impl Iterator<Item = usize> + '_ {
82 words
83 .iter()
84 .enumerate()
85 .flat_map(|(i, &word)| bits_of(word).map(move |bit| i * 64 + bit))
86}
87
88#[derive(Debug, Clone, PartialEq, Eq)]
89enum Start {
90 Definite(ByteSet),
92 MaybeEmpty(ByteSet),
94 Bail,
96}
97
98impl Start {
99 fn concat(starts: impl Iterator<Item = Start>) -> Start {
100 let mut set = ByteSet::default();
101 for start in starts {
102 match start {
103 Start::Definite(mut s) => {
104 s.union(&set);
105 return Start::Definite(s);
106 }
107 Start::MaybeEmpty(s) => set.union(&s),
108 Start::Bail => return Start::Bail,
109 }
110 }
111 Start::MaybeEmpty(set)
112 }
113
114 fn alt(starts: impl Iterator<Item = Start>) -> Start {
115 let mut set = ByteSet::default();
116 let mut definite = None;
118 for start in starts {
119 match start {
120 Start::Definite(s) => {
121 set.union(&s);
122 definite.get_or_insert(true);
123 }
124 Start::MaybeEmpty(s) => {
125 set.union(&s);
126 definite = Some(false);
127 }
128 Start::Bail => return Start::Bail,
129 }
130 }
131 match definite {
132 Some(true) => Start::Definite(set),
133 _ => Start::MaybeEmpty(set),
134 }
135 }
136
137 fn optional(self) -> Start {
138 match self {
139 Start::Definite(set) | Start::MaybeEmpty(set) => Start::MaybeEmpty(set),
140 Start::Bail => Start::Bail,
141 }
142 }
143}
144
145#[inline]
146fn first_utf8_byte(c: char) -> u8 {
147 let mut buf = [0u8; 4];
148 c.encode_utf8(&mut buf).as_bytes()[0]
149}
150
151fn char_class(c: char) -> ClassUnicode {
152 ClassUnicode::new([ClassUnicodeRange::new(c, c)])
153}
154
155fn insert_class(set: &mut ByteSet, mut class: ClassUnicode, casei: bool) -> bool {
158 if casei && class.try_case_fold_simple().is_err() {
159 return false;
160 }
161 for range in class.ranges() {
162 for c in range.start()..=range.end() {
163 set.insert(first_utf8_byte(c));
164 }
165 }
166 true
167}
168
169fn regex_syntax_start(expr: &Hir, casei: bool) -> Start {
173 match expr.kind() {
174 HirKind::Empty | HirKind::Look(_) => Start::MaybeEmpty(ByteSet::default()),
176 HirKind::Literal(l) => {
177 let Some(&first) = l.0.first() else {
178 return Start::MaybeEmpty(ByteSet::default());
179 };
180 let mut set = ByteSet::default();
181 if casei {
182 let first_char = core::str::from_utf8(&l.0)
183 .ok()
184 .and_then(|s| s.chars().next());
185 let Some(c) = first_char else {
186 return Start::Bail;
187 };
188 if !insert_class(&mut set, char_class(c), true) {
189 return Start::Bail;
190 }
191 } else {
192 set.insert(first);
193 }
194 Start::Definite(set)
195 }
196 HirKind::Class(class) => {
197 let mut set = ByteSet::default();
198 match class {
199 Class::Unicode(cls) => {
200 let folded;
203 let cls = if casei {
204 let mut cls = cls.clone();
205 if cls.try_case_fold_simple().is_err() {
206 return Start::Bail;
207 }
208 folded = cls;
209 &folded
210 } else {
211 cls
212 };
213 let mut ascii = ClassUnicode::empty();
214 for r in cls.ranges() {
215 if r.start().is_ascii() {
216 ascii.push(ClassUnicodeRange::new(r.start(), r.end().min('\x7F')));
217 }
218 if !r.end().is_ascii() {
219 let start = first_utf8_byte(r.start().max('\u{80}'));
220 for b in start..=first_utf8_byte(r.end()) {
221 set.insert(b);
222 }
223 }
224 }
225 insert_class(&mut set, ascii, false);
226 }
227 Class::Bytes(cls) => {
228 for r in cls.ranges() {
229 for i in r.start()..=r.end() {
230 set.insert(i);
231 if casei && i.is_ascii_alphabetic() {
232 set.insert(i.to_ascii_uppercase());
233 set.insert(i.to_ascii_lowercase());
234 }
235 }
236 }
237 }
238 }
239
240 if set.is_empty() {
241 Start::Bail
242 } else {
243 Start::Definite(set)
244 }
245 }
246 HirKind::Capture(c) => regex_syntax_start(&c.sub, casei),
247 HirKind::Repetition(r) => {
248 let child = regex_syntax_start(&r.sub, casei);
249 if r.min == 0 {
250 child.optional()
251 } else {
252 child
253 }
254 }
255 HirKind::Concat(c) => Start::concat(c.iter().map(|e| regex_syntax_start(e, casei))),
256 HirKind::Alternation(c) => Start::alt(c.iter().map(|e| regex_syntax_start(e, casei))),
257 }
258}
259
260fn fancy_start(expr: &Expr, ctx: &mut HirCtx) -> Start {
261 match expr {
262 Expr::Empty | Expr::Assertion(_) | Expr::KeepOut | Expr::ContinueFromPreviousMatchEnd => {
263 Start::MaybeEmpty(ByteSet::default())
264 }
265 Expr::Literal { val, casei } => {
266 let Some(first) = val.chars().next() else {
267 return Start::MaybeEmpty(ByteSet::default());
268 };
269 if !ctx.utf8() && !first.is_ascii() {
272 return Start::Bail;
273 }
274 let mut set = ByteSet::default();
275 if !insert_class(&mut set, char_class(first), *casei) {
276 return Start::Bail;
277 }
278 Start::Definite(set)
279 }
280 Expr::Delegate { inner, casei } => match parse_fragment(inner, ctx) {
281 Some(hir) => regex_syntax_start(&hir, *casei),
282 None => Start::Bail,
283 },
284
285 Expr::Concat(exprs) => Start::concat(exprs.iter().map(|e| fancy_start(e, ctx))),
286 Expr::Alt(exprs) => Start::alt(exprs.iter().map(|e| fancy_start(e, ctx))),
287 Expr::Group(child) => fancy_start(child, ctx),
288 Expr::AtomicGroup(child) => fancy_start(child, ctx),
289 Expr::Repeat { child, lo, .. } => {
290 let child = fancy_start(child, ctx);
291 if *lo == 0 {
292 child.optional()
293 } else {
294 child
295 }
296 }
297 Expr::LookAround(expr, lookaround) => match lookaround {
298 LookAround::LookAhead => match fancy_start(expr, ctx) {
299 Start::Definite(set) => Start::Definite(set),
300 _ => Start::MaybeEmpty(ByteSet::default()),
301 },
302 _ => Start::MaybeEmpty(ByteSet::default()),
303 },
304 _ => Start::Bail,
305 }
306}
307
308pub(crate) fn byte_set_from_expr(expr: &Expr, options: &RegexOptions) -> Option<ByteSet> {
309 let mut hir_ctx = HirCtx::from(options);
310 match fancy_start(expr, &mut hir_ctx) {
311 Start::Definite(set) if !set.is_empty() => Some(set),
312 _ => None,
313 }
314}
315
316pub(crate) fn start_bytes(pattern: &str, options: &RegexOptions) -> Result<Option<ByteSet>> {
318 let mut tree = Expr::parse_tree_with_flags(pattern, options.compute_flags())?;
319 if options.should_optimize() {
326 optimize(
327 &mut tree,
328 OptimizeOptions {
329 find_not_empty: options.hard_regex_runtime_options.find_not_empty,
330 },
331 );
332 }
333 Ok(byte_set_from_expr(&tree.expr, options))
334}
335
336fn required_byte_set_from_expr(expr: &Expr) -> ByteSet {
337 let mut byte_set = ByteSet::default();
338
339 match expr {
340 Expr::Literal { val, casei } => {
341 for byte in val.bytes() {
342 if !casei || (byte.is_ascii() && !byte.is_ascii_alphabetic()) {
348 byte_set.insert(byte);
349 }
350 }
351 }
352 Expr::LiteralBytes { .. } => {
353 }
357 Expr::Concat(children) => {
358 for child in children {
359 byte_set.union(&required_byte_set_from_expr(child));
360 }
361 }
362 Expr::Alt(children) => {
363 if let Some((first, rest)) = children.split_first() {
364 byte_set = required_byte_set_from_expr(first);
365 for child in rest {
366 let other = required_byte_set_from_expr(child);
367 byte_set.intersection(&other);
368 }
369 }
370 }
371 Expr::Conditional {
372 condition,
373 true_branch,
374 false_branch,
375 } => {
376 byte_set = required_byte_set_from_expr(true_branch);
379 byte_set.union(&required_byte_set_from_expr(condition));
380 let other = required_byte_set_from_expr(false_branch);
381 byte_set.intersection(&other);
382 }
383 Expr::Group(child) => return required_byte_set_from_expr(child),
384 Expr::AtomicGroup(child)
385 | Expr::LookAround(child, LookAround::LookAhead | LookAround::LookBehind)
386 | Expr::Repeat { child, lo: 1.., .. } => return required_byte_set_from_expr(child),
387 Expr::Empty
388 | Expr::Assertion(_)
389 | Expr::DefineGroup { .. }
390 | Expr::KeepOut
391 | Expr::ContinueFromPreviousMatchEnd
392 | Expr::BackrefExistsCondition { .. }
393 | Expr::BacktrackingControlVerb(_)
394 | Expr::Any { .. }
395 | Expr::GeneralNewline { .. }
396 | Expr::Delegate { .. }
397 | Expr::Repeat { .. }
398 | Expr::LookAround(..)
399 | Expr::Absent(_)
400 | Expr::Backref { .. }
401 | Expr::BackrefWithRelativeRecursionLevel { .. }
402 | Expr::SubroutineCall(_)
403 | Expr::AstNode(..) => {}
404 }
405
406 byte_set
407}
408
409pub(crate) fn required_bytes(pattern: &str, options: &RegexOptions) -> Result<ByteSet> {
411 let mut tree = Expr::parse_tree_with_flags(pattern, options.compute_flags())?;
412 if options.should_optimize() {
417 optimize(
418 &mut tree,
419 OptimizeOptions {
420 find_not_empty: options.hard_regex_runtime_options.find_not_empty,
421 },
422 );
423 }
424 Ok(required_byte_set_from_expr(&tree.expr))
425}
426
427#[cfg(test)]
428mod tests {
429 use super::*;
430 use crate::{RegexInput, RegexOptionsBuilder};
431 use alloc::borrow::ToOwned;
432 use alloc::vec;
433 use alloc::vec::Vec;
434
435 fn get_byte_set_from_pattern(pattern: &str, options: &RegexOptions) -> Option<ByteSet> {
436 start_bytes(pattern, options).ok().flatten()
437 }
438
439 fn get_required_byte_set_from_pattern(pattern: &str) -> ByteSet {
440 let mut byte_set = ByteSet::default();
441 for b in pattern.bytes() {
442 byte_set.insert(b);
443 }
444 byte_set
445 }
446
447 fn first_bytes_of(pattern: &str) -> Option<Vec<u8>> {
448 let set = get_byte_set_from_pattern(pattern, &RegexOptions::default())?;
449 Some(set.iter().collect())
450 }
451
452 #[test]
453 fn can_extract_ascii_byteset_from_pattern() {
454 let inputs = vec![
455 (r"fn", Some(vec![b'f'])),
456 (r"::", Some(vec![b':'])),
457 (r"=>", Some(vec![b'='])),
458 (r"\{", Some(vec![b'{'])),
459 (r"fn|let|impl", Some(vec![b'f', b'i', b'l'])),
460 (r"(fn|let|impl)", Some(vec![b'f', b'i', b'l'])),
461 (r"(?:->|<-)", Some(vec![b'-', b'<'])),
462 (r"\bfn\b", Some(vec![b'f'])),
463 (r"^let", Some(vec![b'l'])),
464 (r"\Gx", Some(vec![b'x'])),
465 (r"(?<!\.)let", Some(vec![b'l'])),
466 (r"[abc]x", Some(vec![b'a', b'b', b'c'])),
467 (r"[a-d]", Some(vec![b'a', b'b', b'c', b'd'])),
468 (r"(?i)fn", Some(vec![b'F', b'f'])),
469 (r"(?i)[a-b]", Some(vec![b'A', b'B', b'a', b'b'])),
470 (r"&(?![&=])", Some(vec![b'&'])),
471 (r"(?x) fn # comment", Some(vec![b'f'])),
472 (r"(?=\[)", Some(vec![b'['])),
473 (r"(?=.*)x", Some(vec![b'x'])),
474 (r"(?=a?)x", Some(vec![b'x'])),
475 (r"(?!x)a", Some(vec![b'a'])),
476 (r#"(?=["'`])""#, Some(vec![b'"', b'\'', b'`'])),
477 (r#"(?=ab|xy)"#, Some(vec![b'a', b'x'])),
478 (r#"r?""#, Some(vec![b'"', b'r'])),
479 (r"a+", Some(vec![b'a'])),
480 (r"(?>fn)", Some(vec![b'f'])),
481 (r"\Kfn", Some(vec![b'f'])),
482 (r"über", Some(vec![0xC3])),
483 (r"[α-ω]x", Some(vec![0xCE, 0xCF])),
485 (r"a?", None),
486 (r"(?!x)", None),
487 (r".", None),
488 (r".*x", None),
489 (r"\R", None),
490 (r"(", None),
491 (r"(?i)sort", Some(vec![b'S', b's', 0xC5])),
494 (r"(?i)kind", Some(vec![b'K', b'k', 0xE2])),
496 (r"(?i)ſ", Some(vec![b'S', b's', 0xC5])),
498 (r"(?i)é", Some(vec![0xC3])),
500 (r"(?i)[k]", Some(vec![b'K', b'k', 0xE2])),
502 (r"(?i)[s-t]x", Some(vec![b'S', b'T', b's', b't', 0xC5])),
503 (r"(?i)[à-ÿ]", Some(vec![0xC3, 0xC5, 0xE2])),
506 (r"(?i)[α-ω]", Some(vec![0xC2, 0xCD, 0xCE, 0xCF, 0xE1, 0xE2])),
507 (r"(?i)[0-9_]", Some(b"0123456789_".to_vec())),
509 ];
510
511 for (input, expected) in inputs {
512 assert_eq!(first_bytes_of(input), expected, "pattern {input:?}");
513 }
514 }
515
516 #[test]
517 fn can_extract_byteset_from_unicode() {
518 let upper = first_bytes_of(r"\p{upper}!").unwrap();
519 assert!(upper.contains(&b'A') && upper.contains(&b'Z'));
520 assert!(!upper.contains(&b'a') && !upper.contains(&b'!'));
521 assert!(upper.contains(&0xC3));
523
524 let not_upper = first_bytes_of(r"\P{upper}!").unwrap();
525 assert!(not_upper.contains(&b'a') && not_upper.contains(&b'z'));
526 assert!(!not_upper.contains(&b'A') && not_upper.contains(&b'!'));
528 assert!(first_bytes_of(r"\P{typo}!").is_none());
530 }
531
532 #[test]
533 fn can_extract_byteset_from_negation() {
534 let b1 = first_bytes_of(r"[^a-c]x").unwrap();
535 assert!(!b1.contains(&b'a') && !b1.contains(&b'c'));
536 assert!(b1.contains(&b'd') && b1.contains(&b' ') && b1.contains(&0xC3));
537
538 let b2 = first_bytes_of(r"(?i)[^a]").unwrap();
539 assert!(b2.contains(&b'b') && b2.contains(&b'B') && b2.contains(&0xC3));
540
541 let b3 = first_bytes_of(r"[^[:alpha:]]").unwrap();
542 assert!(!b3.contains(&b'a') && !b3.contains(&b'Z'));
543 assert!(b3.contains(&b'0') && b3.contains(&b' ') && b3.contains(&0xC3));
544 }
545
546 #[test]
547 fn non_ascii_only_folds_to_k_and_s() {
548 let mut class = ClassUnicode::new([ClassUnicodeRange::new('\u{80}', '\u{10FFFF}')]);
549 class.try_case_fold_simple().unwrap();
550 let ascii: Vec<char> = class
551 .ranges()
552 .iter()
553 .flat_map(|r| r.start()..=r.end())
554 .filter(char::is_ascii)
555 .collect();
556 assert_eq!(ascii, vec!['K', 'S', 'k', 's']);
557 }
558
559 #[test]
560 fn can_extract_required_bytes() {
561 let inputs = vec![
562 ("a?b", "b"),
563 ("ab|ac", "a"),
564 ("a|b", ""),
565 ("(?=a)b", "ab"),
566 ("(?<=a)b", "ab"),
567 ("(?!a)b", "b"),
568 ("(?i)k!", "!"),
569 ("(?(DEFINE)(a))b", "b"),
570 ("(a){0}b", "b"),
571 ("é!", "é!"),
572 ("(?i)é!", "!"),
573 ("(?i:É)!", "!"),
574 ("(x)?(?(1)b!|c!)", "!"),
575 ("(x)(?(1)ab|ac)", "ax"),
576 ("(x)(?(1)ab)", "x"),
577 ("(?(a)b|ac)", "a"),
578 ("(?(a)b|zc)", ""),
579 ("(?(a)b|b)", "b"),
580 ];
581
582 for (pattern, bytes) in inputs {
583 assert_eq!(
584 required_bytes(pattern, &RegexOptions::default()).unwrap(),
585 get_required_byte_set_from_pattern(bytes),
586 "expected byte set for pattern {} doesn't match",
587 pattern
588 );
589 }
590 }
591
592 #[test]
593 fn required_bytes_match_match_result() {
594 let inputs = vec![
595 "a?b",
596 "ab|ac",
597 "a|b",
598 "(?=a)a",
599 "(?<=a)b",
600 "(?!a)b",
601 "(?i)k!",
602 "(?i)s",
603 "(?i:ABC)!",
604 r"a\Kb",
605 r"(a)\1",
606 "(a){0}b",
607 "(?x)a # ignored\n b",
608 "a*",
609 "^a$",
610 r"\Ga",
611 r"\Aa",
612 r"(?<x>a)(?(x)b|c)",
613 r"(x)?(?(1)b!|c!)",
614 r"(x)(?(1)ab|ac)",
615 r"(x)(?(1)ab)",
616 "(?i)é!",
617 "(?i:É)!",
618 "日!",
619 r"(?<x>a)\g<x>",
620 "é!",
621 ];
622
623 for pattern in inputs {
624 let re = RegexOptionsBuilder::default()
625 .build(pattern.to_owned())
626 .unwrap();
627
628 for text in [
631 "", "a", "b", "ab", "ac", "aa", "abc!", "ABC!", "K!", "ſ", "é!", "a\nb", "É!",
632 "日!", "x", "xb!", "xc!", "xab", "xac", "b!", "c!",
633 ] {
634 for pos in (0..=text.len()).filter(|&p| text.is_char_boundary(p)) {
635 let input = RegexInput::new(text).from_pos(pos).anchored(true);
636 if re.find_input(input).unwrap().is_some() {
637 assert!(required_bytes(pattern, &RegexOptions::default())
638 .unwrap()
639 .iter()
640 .all(|byte| get_required_byte_set_from_pattern(text).contains(byte)));
641 }
642 }
643 }
644 }
645 }
646
647 #[test]
648 fn can_do_set_operations() {
649 fn set(bytes: &[u8]) -> ByteSet {
650 let mut set = ByteSet::default();
651 for &b in bytes {
652 set.insert(b);
653 }
654 set
655 }
656
657 let empty = ByteSet::default();
658 let small = set(&[0, 70, 140]);
659 let big = set(&[0, 70, 140, 200, 255]);
660 let other = set(&[70, 140, 210]);
661
662 assert!(empty.is_subset(&small));
663 assert!(small.is_subset(&small));
664 assert!(small.is_subset(&big));
665 assert!(!big.is_subset(&small));
666 assert!(!other.is_subset(&big));
667
668 let mut intersection = big;
669 intersection.intersection(&other);
670 assert_eq!(intersection, set(&[70, 140]));
671
672 let mut union = small;
673 union.union(&other);
674 assert_eq!(union, set(&[0, 70, 140, 210]));
675 }
676}