Skip to main content

agent86_ui/runtime/
regex.rs

1//! The A2UI regex dialect (the specification's "The `regex` function"): a
2//! portable subset of ECMAScript patterns in Unicode mode, a static safety check
3//! before anything runs, and search semantics.
4//!
5//! Patterns come from the agent's model, so they are untrusted. A pattern is
6//! parsed here, in full; refused if it uses a construct outside the dialect
7//! (backreferences, lookbehind, named groups, `\p{...}`, `\cX`, legacy octal,
8//! inline flags) or could backtrack badly (the four safety rules); and only then
9//! translated into `fancy-regex` syntax with the dialect's meanings made
10//! explicit (`.`, `\d`, `\w`, `\s`, `\b`, `^`, `$`). `fancy-regex` adds a
11//! backtracking limit on top, as a last line of defense.
12
13use std::fmt::Write as _;
14
15/// The longest pattern, in code points.
16pub const MAX_PATTERN_CODE_POINTS: usize = 256;
17/// The longest value matched, in code points; a longer one does not match.
18pub const MAX_VALUE_CODE_POINTS: usize = 4_096;
19
20/// Why a pattern was refused, with the specification's reason names.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum Refusal {
23    /// It does not parse in the dialect, or uses a construct the dialect
24    /// leaves out.
25    UnsupportedSyntax,
26    /// Longer than [`MAX_PATTERN_CODE_POINTS`] (safety rule 1).
27    PatternTooLong,
28    /// A repeated subexpression contains an unbounded quantifier (rule 2).
29    NestedQuantifier,
30    /// An unbounded repetition of alternatives that can start alike (rule 3).
31    OverlappingAlternation,
32    /// Adjacent unbounded atoms that can match the same character (rule 4).
33    AdjacentOverlap,
34}
35
36impl Refusal {
37    /// The reason as the specification's suites name it.
38    pub fn as_str(self) -> &'static str {
39        match self {
40            Refusal::UnsupportedSyntax => "UNSUPPORTED_SYNTAX",
41            Refusal::PatternTooLong => "PATTERN_TOO_LONG",
42            Refusal::NestedQuantifier => "NESTED_QUANTIFIER",
43            Refusal::OverlappingAlternation => "OVERLAPPING_ALTERNATION",
44            Refusal::AdjacentOverlap => "ADJACENT_OVERLAP",
45        }
46    }
47}
48
49/// A set of code points as sorted, disjoint, inclusive ranges.
50#[derive(Debug, Clone, PartialEq, Eq, Default)]
51struct Set(Vec<(u32, u32)>);
52
53const MAX_CODE_POINT: u32 = 0x10FFFF;
54
55impl Set {
56    fn of(ranges: &[(u32, u32)]) -> Self {
57        let mut set = Set(ranges.to_vec());
58        set.normalize();
59        set
60    }
61
62    fn char(c: u32) -> Self {
63        Set(vec![(c, c)])
64    }
65
66    fn normalize(&mut self) {
67        self.0.sort_unstable();
68        let mut merged: Vec<(u32, u32)> = Vec::new();
69        for &(lo, hi) in &self.0 {
70            match merged.last_mut() {
71                Some(last) if lo <= last.1.saturating_add(1) => last.1 = last.1.max(hi),
72                _ => merged.push((lo, hi)),
73            }
74        }
75        self.0 = merged;
76    }
77
78    fn union(&mut self, other: &Set) {
79        self.0.extend_from_slice(&other.0);
80        self.normalize();
81    }
82
83    fn negate(&self) -> Set {
84        let mut out = Vec::new();
85        let mut next = 0u32;
86        for &(lo, hi) in &self.0 {
87            if lo > next {
88                out.push((next, lo - 1));
89            }
90            next = hi.saturating_add(1);
91        }
92        if next <= MAX_CODE_POINT {
93            out.push((next, MAX_CODE_POINT));
94        }
95        Set(out)
96    }
97
98    fn overlaps(&self, other: &Set) -> bool {
99        let (mut i, mut j) = (0, 0);
100        while i < self.0.len() && j < other.0.len() {
101            let (a, b) = (self.0[i], other.0[j]);
102            if a.1 < b.0 {
103                i += 1;
104            } else if b.1 < a.0 {
105                j += 1;
106            } else {
107                return true;
108            }
109        }
110        false
111    }
112
113    fn digit() -> Set {
114        Set::of(&[(0x30, 0x39)])
115    }
116
117    fn word() -> Set {
118        Set::of(&[(0x30, 0x39), (0x41, 0x5A), (0x5F, 0x5F), (0x61, 0x7A)])
119    }
120
121    /// ECMAScript WhiteSpace and LineTerminator.
122    fn space() -> Set {
123        Set::of(&[
124            (0x09, 0x0D),
125            (0x20, 0x20),
126            (0xA0, 0xA0),
127            (0x1680, 0x1680),
128            (0x2000, 0x200A),
129            (0x2028, 0x2029),
130            (0x202F, 0x202F),
131            (0x205F, 0x205F),
132            (0x3000, 0x3000),
133            (0xFEFF, 0xFEFF),
134        ])
135    }
136
137    /// `.`: anything but the line terminators.
138    fn dot() -> Set {
139        Set::of(&[(0x0A, 0x0A), (0x0D, 0x0D), (0x2028, 0x2029)]).negate()
140    }
141}
142
143#[derive(Debug, Clone, PartialEq)]
144enum Node {
145    Empty,
146    Set(Set),
147    Start,
148    End,
149    Boundary {
150        negated: bool,
151    },
152    Look {
153        negated: bool,
154        body: Box<Node>,
155    },
156    Group {
157        capturing: bool,
158        body: Box<Node>,
159    },
160    Concat(Vec<Node>),
161    Alt(Vec<Node>),
162    Repeat {
163        body: Box<Node>,
164        min: u32,
165        max: Option<u32>,
166        lazy: bool,
167    },
168}
169
170type Parsed<T> = Result<T, Refusal>;
171
172const SYNTAX: &str = "^$\\.*+?()[]{}|/";
173
174struct Parser {
175    chars: Vec<char>,
176    pos: usize,
177}
178
179impl Parser {
180    fn peek(&self) -> Option<char> {
181        self.chars.get(self.pos).copied()
182    }
183
184    fn peek_at(&self, offset: usize) -> Option<char> {
185        self.chars.get(self.pos + offset).copied()
186    }
187
188    fn next(&mut self) -> Option<char> {
189        let c = self.peek();
190        self.pos += 1;
191        c
192    }
193
194    fn eat(&mut self, c: char) -> bool {
195        if self.peek() == Some(c) {
196            self.pos += 1;
197            true
198        } else {
199            false
200        }
201    }
202
203    fn alternation(&mut self) -> Parsed<Node> {
204        let mut branches = vec![self.concat()?];
205        while self.eat('|') {
206            branches.push(self.concat()?);
207        }
208        Ok(if branches.len() == 1 {
209            branches.pop().unwrap_or(Node::Empty)
210        } else {
211            Node::Alt(branches)
212        })
213    }
214
215    fn concat(&mut self) -> Parsed<Node> {
216        let mut items = Vec::new();
217        while let Some(c) = self.peek() {
218            if c == '|' || c == ')' {
219                break;
220            }
221            items.push(self.term()?);
222        }
223        Ok(match items.len() {
224            0 => Node::Empty,
225            1 => items.pop().unwrap_or(Node::Empty),
226            _ => Node::Concat(items),
227        })
228    }
229
230    fn term(&mut self) -> Parsed<Node> {
231        let atom = self.atom()?;
232        let Some((min, max)) = self.quantifier()? else {
233            return Ok(atom);
234        };
235        // Unicode mode: assertions and lookaheads cannot be repeated.
236        if matches!(
237            atom,
238            Node::Start | Node::End | Node::Boundary { .. } | Node::Look { .. }
239        ) {
240            return Err(Refusal::UnsupportedSyntax);
241        }
242        let lazy = self.eat('?');
243        Ok(Node::Repeat {
244            body: Box::new(atom),
245            min,
246            max,
247            lazy,
248        })
249    }
250
251    /// A quantifier, if one follows: `*`, `+`, `?`, `{n}`, `{n,}`, `{n,m}`.
252    fn quantifier(&mut self) -> Parsed<Option<(u32, Option<u32>)>> {
253        match self.peek() {
254            Some('*') => {
255                self.pos += 1;
256                Ok(Some((0, None)))
257            }
258            Some('+') => {
259                self.pos += 1;
260                Ok(Some((1, None)))
261            }
262            Some('?') => {
263                self.pos += 1;
264                Ok(Some((0, Some(1))))
265            }
266            Some('{') => {
267                let start = self.pos;
268                self.pos += 1;
269                let min = self.digits().ok_or(Refusal::UnsupportedSyntax)?;
270                let max = if self.eat(',') {
271                    if self.peek() == Some('}') {
272                        None
273                    } else {
274                        Some(self.digits().ok_or(Refusal::UnsupportedSyntax)?)
275                    }
276                } else {
277                    Some(min)
278                };
279                if !self.eat('}') {
280                    self.pos = start;
281                    return Err(Refusal::UnsupportedSyntax);
282                }
283                if max.is_some_and(|max| max < min) {
284                    return Err(Refusal::UnsupportedSyntax);
285                }
286                Ok(Some((min, max)))
287            }
288            _ => Ok(None),
289        }
290    }
291
292    fn digits(&mut self) -> Option<u32> {
293        let start = self.pos;
294        while self.peek().is_some_and(|c| c.is_ascii_digit()) {
295            self.pos += 1;
296        }
297        if self.pos == start {
298            return None;
299        }
300        let text: String = self.chars[start..self.pos].iter().collect();
301        Some(text.parse().unwrap_or(u32::MAX))
302    }
303
304    fn atom(&mut self) -> Parsed<Node> {
305        let c = self.next().ok_or(Refusal::UnsupportedSyntax)?;
306        match c {
307            '^' => Ok(Node::Start),
308            '$' => Ok(Node::End),
309            '.' => Ok(Node::Set(Set::dot())),
310            '(' => self.group(),
311            '[' => self.class().map(Node::Set),
312            '\\' => self.escape(),
313            ')' | ']' | '{' | '}' | '*' | '+' | '?' => Err(Refusal::UnsupportedSyntax),
314            other => Ok(Node::Set(Set::char(other as u32))),
315        }
316    }
317
318    fn group(&mut self) -> Parsed<Node> {
319        let (capturing, look) = if self.eat('?') {
320            match self.next() {
321                Some(':') => (false, None),
322                Some('=') => (false, Some(false)),
323                Some('!') => (false, Some(true)),
324                // Lookbehind `(?<=`/`(?<!`, named groups `(?<name>`, and inline
325                // flags `(?i)` are all outside the dialect.
326                _ => return Err(Refusal::UnsupportedSyntax),
327            }
328        } else {
329            (true, None)
330        };
331        let body = self.alternation()?;
332        if !self.eat(')') {
333            return Err(Refusal::UnsupportedSyntax);
334        }
335        Ok(match look {
336            Some(negated) => Node::Look {
337                negated,
338                body: Box::new(body),
339            },
340            None => Node::Group {
341                capturing,
342                body: Box::new(body),
343            },
344        })
345    }
346
347    /// An escape outside a class.
348    fn escape(&mut self) -> Parsed<Node> {
349        let c = self.next().ok_or(Refusal::UnsupportedSyntax)?;
350        Ok(match c {
351            'b' => Node::Boundary { negated: false },
352            'B' => Node::Boundary { negated: true },
353            '-' => return Err(Refusal::UnsupportedSyntax),
354            _ => Node::Set(self.escape_set(c, false)?),
355        })
356    }
357
358    /// The set an escape stands for (`c` is the character after `\`).
359    fn escape_set(&mut self, c: char, in_class: bool) -> Parsed<Set> {
360        Ok(match c {
361            'd' => Set::digit(),
362            'D' => Set::digit().negate(),
363            'w' => Set::word(),
364            'W' => Set::word().negate(),
365            's' => Set::space(),
366            'S' => Set::space().negate(),
367            't' => Set::char(0x09),
368            'n' => Set::char(0x0A),
369            'v' => Set::char(0x0B),
370            'f' => Set::char(0x0C),
371            'r' => Set::char(0x0D),
372            'b' if in_class => Set::char(0x08),
373            '-' if in_class => Set::char('-' as u32),
374            '0' => {
375                if self.peek().is_some_and(|d| d.is_ascii_digit()) {
376                    // Legacy octal.
377                    return Err(Refusal::UnsupportedSyntax);
378                }
379                Set::char(0)
380            }
381            'x' => Set::char(self.hex(2)?),
382            'u' => self.unicode_escape()?,
383            c if SYNTAX.contains(c) => Set::char(c as u32),
384            // Backreferences `\1`-`\9` and `\k<name>`, `\p{...}`, `\cX`, and
385            // every other identity escape are outside the dialect.
386            _ => return Err(Refusal::UnsupportedSyntax),
387        })
388    }
389
390    fn hex(&mut self, count: usize) -> Parsed<u32> {
391        let mut value = 0u32;
392        for _ in 0..count {
393            let digit = self
394                .next()
395                .and_then(|c| c.to_digit(16))
396                .ok_or(Refusal::UnsupportedSyntax)?;
397            value = value * 16 + digit;
398        }
399        Ok(value)
400    }
401
402    /// `\uHHHH` (a surrogate pair written as two escapes is one code point),
403    /// or `\u{H...}`.
404    fn unicode_escape(&mut self) -> Parsed<Set> {
405        let code = if self.eat('{') {
406            let start = self.pos;
407            while self.peek().is_some_and(|c| c.is_ascii_hexdigit()) {
408                self.pos += 1;
409            }
410            let text: String = self.chars[start..self.pos].iter().collect();
411            if text.is_empty() || !self.eat('}') {
412                return Err(Refusal::UnsupportedSyntax);
413            }
414            let value = u32::from_str_radix(&text, 16).map_err(|_| Refusal::UnsupportedSyntax)?;
415            if value > MAX_CODE_POINT {
416                return Err(Refusal::UnsupportedSyntax);
417            }
418            value
419        } else {
420            let high = self.hex(4)?;
421            if (0xD800..=0xDBFF).contains(&high)
422                && self.peek() == Some('\\')
423                && self.peek_at(1) == Some('u')
424            {
425                let save = self.pos;
426                self.pos += 2;
427                match self.hex(4) {
428                    Ok(low) if (0xDC00..=0xDFFF).contains(&low) => {
429                        0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00)
430                    }
431                    _ => {
432                        self.pos = save;
433                        high
434                    }
435                }
436            } else {
437                high
438            }
439        };
440        // A lone surrogate: no Rust string holds one, so it matches nothing.
441        if (0xD800..=0xDFFF).contains(&code) {
442            return Ok(Set::default());
443        }
444        Ok(Set::char(code))
445    }
446
447    /// A character class, after its `[`.
448    fn class(&mut self) -> Parsed<Set> {
449        let negated = self.eat('^');
450        let mut set = Set::default();
451        loop {
452            let first = match self.next() {
453                None => return Err(Refusal::UnsupportedSyntax),
454                Some(']') => break,
455                Some(c) => self.class_atom(c)?,
456            };
457            if self.peek() == Some('-') && self.peek_at(1).is_some_and(|c| c != ']') {
458                self.pos += 1;
459                let c = self.next().ok_or(Refusal::UnsupportedSyntax)?;
460                let second = self.class_atom(c)?;
461                match (single(&first), single(&second)) {
462                    (Some(lo), Some(hi)) if lo <= hi => set.union(&Set::of(&[(lo, hi)])),
463                    _ => return Err(Refusal::UnsupportedSyntax),
464                }
465            } else {
466                set.union(&first);
467            }
468        }
469        Ok(if negated { set.negate() } else { set })
470    }
471
472    fn class_atom(&mut self, c: char) -> Parsed<Set> {
473        if c != '\\' {
474            return Ok(Set::char(c as u32));
475        }
476        let escaped = self.next().ok_or(Refusal::UnsupportedSyntax)?;
477        if escaped == 'B' {
478            return Err(Refusal::UnsupportedSyntax);
479        }
480        self.escape_set(escaped, true)
481    }
482}
483
484/// The one code point a set holds, if it holds exactly one.
485fn single(set: &Set) -> Option<u32> {
486    match set.0.as_slice() {
487        [(lo, hi)] if lo == hi => Some(*lo),
488        _ => None,
489    }
490}
491
492fn unbounded(node: &Node) -> bool {
493    match node {
494        Node::Repeat { body, max, .. } => max.is_none() || unbounded(body),
495        Node::Look { body, .. } | Node::Group { body, .. } => unbounded(body),
496        Node::Concat(items) | Node::Alt(items) => items.iter().any(unbounded),
497        _ => false,
498    }
499}
500
501fn nullable(node: &Node) -> bool {
502    match node {
503        Node::Empty | Node::Start | Node::End | Node::Boundary { .. } | Node::Look { .. } => true,
504        Node::Set(_) => false,
505        Node::Group { body, .. } => nullable(body),
506        Node::Repeat { body, min, .. } => *min == 0 || nullable(body),
507        Node::Concat(items) => items.iter().all(nullable),
508        Node::Alt(items) => items.iter().any(nullable),
509    }
510}
511
512/// The characters a node's match can start with.
513fn first(node: &Node) -> Set {
514    match node {
515        Node::Set(set) => set.clone(),
516        Node::Group { body, .. } | Node::Repeat { body, .. } => first(body),
517        Node::Concat(items) => {
518            let mut set = Set::default();
519            for item in items {
520                set.union(&first(item));
521                if !nullable(item) {
522                    break;
523                }
524            }
525            set
526        }
527        Node::Alt(items) => {
528            let mut set = Set::default();
529            for item in items {
530                set.union(&first(item));
531            }
532            set
533        }
534        _ => Set::default(),
535    }
536}
537
538fn unwrap_groups(mut node: &Node) -> &Node {
539    while let Node::Group { body, .. } = node {
540        node = body;
541    }
542    node
543}
544
545/// The character set of an unbounded-repeated atom, for rule 4: a repeated
546/// single-character atom, or a group whose only content is one (a group
547/// holding just `\d+` counts as `\d+`).
548fn unbounded_atom(node: &Node) -> Option<&Set> {
549    let node = unwrap_groups(node);
550    match node {
551        Node::Repeat {
552            body, max: None, ..
553        } => match unwrap_groups(body) {
554            Node::Set(set) => Some(set),
555            _ => None,
556        },
557        _ => None,
558    }
559}
560
561fn check(node: &Node) -> Result<(), Refusal> {
562    match node {
563        Node::Repeat { body, max, .. } => {
564            if max.is_none_or(|max| max > 1) && unbounded(body) {
565                return Err(Refusal::NestedQuantifier);
566            }
567            if max.is_none() {
568                if let Node::Alt(branches) = unwrap_groups(body) {
569                    let firsts: Vec<Set> = branches.iter().map(first).collect();
570                    for (i, a) in firsts.iter().enumerate() {
571                        if firsts[i + 1..].iter().any(|b| a.overlaps(b)) {
572                            return Err(Refusal::OverlappingAlternation);
573                        }
574                    }
575                }
576            }
577            check(body)
578        }
579        Node::Concat(items) => {
580            for (i, item) in items.iter().enumerate() {
581                let Some(set) = unbounded_atom(item) else {
582                    continue;
583                };
584                for later in &items[i + 1..] {
585                    if let Some(other) = unbounded_atom(later) {
586                        if set.overlaps(other) {
587                            return Err(Refusal::AdjacentOverlap);
588                        }
589                    }
590                    if !nullable(later) {
591                        break;
592                    }
593                }
594            }
595            items.iter().try_for_each(check)
596        }
597        Node::Alt(items) => items.iter().try_for_each(check),
598        Node::Look { body, .. } | Node::Group { body, .. } => check(body),
599        _ => Ok(()),
600    }
601}
602
603fn emit_set(set: &Set, out: &mut String) {
604    if set.0.is_empty() {
605        // Matches nothing.
606        out.push_str("(?!)");
607        return;
608    }
609    out.push('[');
610    for &(lo, hi) in &set.0 {
611        let _ = write!(out, "\\x{{{lo:X}}}");
612        if hi != lo {
613            let _ = write!(out, "-\\x{{{hi:X}}}");
614        }
615    }
616    out.push(']');
617}
618
619const WORD: &str = "[0-9A-Za-z_]";
620
621fn emit(node: &Node, out: &mut String) {
622    match node {
623        Node::Empty => {}
624        Node::Set(set) => emit_set(set, out),
625        Node::Start => out.push_str("\\A"),
626        Node::End => out.push_str("\\z"),
627        // `\b` and `\B` are ASCII-only in the dialect, so spell them out.
628        Node::Boundary { negated: false } => {
629            let _ = write!(out, "(?:(?<={WORD})(?!{WORD})|(?<!{WORD})(?={WORD}))");
630        }
631        Node::Boundary { negated: true } => {
632            let _ = write!(out, "(?:(?<={WORD})(?={WORD})|(?<!{WORD})(?!{WORD}))");
633        }
634        Node::Look { negated, body } => {
635            out.push_str(if *negated { "(?!" } else { "(?=" });
636            emit(body, out);
637            out.push(')');
638        }
639        Node::Group { capturing, body } => {
640            out.push_str(if *capturing { "(" } else { "(?:" });
641            emit(body, out);
642            out.push(')');
643        }
644        Node::Concat(items) => items.iter().for_each(|item| emit(item, out)),
645        Node::Alt(items) => {
646            out.push_str("(?:");
647            for (i, item) in items.iter().enumerate() {
648                if i > 0 {
649                    out.push('|');
650                }
651                emit(item, out);
652            }
653            out.push(')');
654        }
655        Node::Repeat {
656            body,
657            min,
658            max,
659            lazy,
660        } => {
661            out.push_str("(?:");
662            emit(body, out);
663            out.push(')');
664            match max {
665                None => {
666                    let _ = write!(out, "{{{min},}}");
667                }
668                Some(max) => {
669                    let _ = write!(out, "{{{min},{max}}}");
670                }
671            }
672            if *lazy {
673                out.push('?');
674            }
675        }
676    }
677}
678
679/// A pattern that passed the dialect's checks.
680#[derive(Debug)]
681pub struct Pattern {
682    regex: fancy_regex::Regex,
683}
684
685impl Pattern {
686    /// Parse and check `pattern`, refusing it with the specification's reason
687    /// when it is outside the dialect or unsafe.
688    pub fn compile(pattern: &str) -> Result<Pattern, Refusal> {
689        if pattern.chars().count() > MAX_PATTERN_CODE_POINTS {
690            return Err(Refusal::PatternTooLong);
691        }
692        let mut parser = Parser {
693            chars: pattern.chars().collect(),
694            pos: 0,
695        };
696        let node = parser.alternation()?;
697        if parser.pos < parser.chars.len() {
698            // A `)` with no group open.
699            return Err(Refusal::UnsupportedSyntax);
700        }
701        check(&node)?;
702        let mut translated = String::new();
703        emit(&node, &mut translated);
704        let regex = fancy_regex::RegexBuilder::new(&translated)
705            .backtrack_limit(100_000)
706            .build()
707            .map_err(|_| Refusal::UnsupportedSyntax)?;
708        Ok(Pattern { regex })
709    }
710
711    /// Whether the pattern matches anywhere in `value` (`RegExp.test`). A
712    /// value longer than [`MAX_VALUE_CODE_POINTS`] does not match; neither
713    /// does one that exhausts the backtracking limit.
714    pub fn test(&self, value: &str) -> bool {
715        if value.chars().count() > MAX_VALUE_CODE_POINTS {
716            return false;
717        }
718        self.regex.is_match(value).unwrap_or(false)
719    }
720}
721
722#[cfg(test)]
723mod tests {
724    use super::*;
725
726    fn refusal(pattern: &str) -> Option<Refusal> {
727        Pattern::compile(pattern).err()
728    }
729
730    #[test]
731    fn the_specifications_examples() {
732        for accepted in [r"^[a-z]+@[a-z]+\.com$", r"^(?=.*\d).{8,}$", r"\w+\s+\w+"] {
733            assert_eq!(refusal(accepted), None, "{accepted}");
734        }
735        assert_eq!(refusal("(a+)+$"), Some(Refusal::NestedQuantifier));
736        assert_eq!(refusal("(a|ab)*c"), Some(Refusal::OverlappingAlternation));
737        assert_eq!(refusal(r"\d+\s*\d+"), Some(Refusal::AdjacentOverlap));
738        assert_eq!(refusal(r"(\w)\1"), Some(Refusal::UnsupportedSyntax));
739    }
740
741    #[test]
742    fn unicode_mode_refuses_what_legacy_mode_allows() {
743        for refused in [
744            r"\a", "a{", "]", "}", r"\-", "[a-\\d]", r"\c1", r"\01", "(?i)a", "(?<n>a)",
745        ] {
746            assert_eq!(
747                refusal(refused),
748                Some(Refusal::UnsupportedSyntax),
749                "{refused}"
750            );
751        }
752        assert_eq!(refusal(r"[\-a]"), None);
753        assert_eq!(refusal(r"[\b]"), None);
754        assert!(Pattern::compile("^$").unwrap().test(""));
755    }
756
757    #[test]
758    fn matching_follows_the_dialect() {
759        let test = |pattern: &str, value: &str| Pattern::compile(pattern).unwrap().test(value);
760        assert!(test("abc", "xxabcxx"));
761        assert!(!test("^abc$", "abc\n"));
762        assert!(!test(r"^\d+$", "١٢٣"));
763        assert!(!test(r"^\w+$", "café"));
764        assert!(!test("^a.b$", "a\nb"));
765        assert!(!test(r"\b", "é"));
766        assert!(test("^.$", "😀"));
767        assert!(test(r"^\u{1F600}+$", "😀😀"));
768        assert!(test(r"^😀$", "😀"));
769        assert!(test("[^]", "x"));
770        assert!(!test("[]", "x"));
771        assert!(test("a{2}", "xaa"));
772        assert!(!test("^a{2}$", "aaa"));
773    }
774}