Skip to main content

sql_values/postgres/
regex.rs

1//! The subset of PostgreSQL 18's advanced regular expressions whose `textregexeq` matches without
2//! flags are decided here.
3//!
4//! A pattern of the subset holds literal characters, `\` before an ASCII punctuation character,
5//! `.`, bracket expressions of characters, ranges and character classes such as `[:space:]`, `^`,
6//! `$`, capturing and `(?:` groups, alternation, and the quantifiers `*`, `+`, `?` and `{m}`,
7//! `{m,}`, `{m,n}`, greedy or not. It holds no back reference, lookaround, escape letter,
8//! collating element, equivalence class, director or embedded option, so PostgreSQL matches it
9//! through the search DFA alone and runs no recursion that may outgrow the stack.
10
11mod class;
12
13use alloc::{boxed::Box, vec, vec::Vec};
14
15use class::Class;
16
17const DUPMAX: usize = 255;
18
19const GROUP_DEPTH_LIMIT: usize = 64;
20
21const EXPANDED_SIZE_LIMIT: usize = 10_000;
22
23/// PostgreSQL's `MAX_SIMPLE_CHR`, past which a character takes its colour from a map whose rows
24/// are the ranges the pattern mentions and whose columns are the combinations of the classes
25/// asking the locale.
26const LAST_SIMPLE: char = '\u{7ff}';
27
28const COLOR_LIMIT: usize = 16_000;
29
30const ARCS_PER_ELEMENT: usize = 32;
31
32/// Why [`PgRegex::new`] refuses a pattern, naming its first construct outside the subset, which
33/// PostgreSQL may take or refuse.
34///
35/// ```
36/// use sql_values::postgres::{PgRegex, RegexError};
37///
38/// assert_eq!(PgRegex::new(r"\d+").unwrap_err(), RegexError::ClassEscape);
39/// assert_eq!(PgRegex::new("(?=a)").unwrap_err(), RegexError::Lookaround);
40/// assert_eq!(PgRegex::new("a{256}").unwrap_err(), RegexError::BoundPastDupmax);
41/// assert_eq!(
42///     PgRegex::new(r"(a)\1").unwrap_err().to_string(),
43///     "the regular expression subset takes no back reference",
44/// );
45/// ```
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
47pub enum RegexError {
48    /// `\d`, `\s`, `\w` or their uppercase negations, in or out of a bracket expression.
49    #[error("the regular expression subset takes no class escape such as \\d")]
50    ClassEscape,
51    /// `\` and a nonzero digit outside a bracket expression.
52    #[error("the regular expression subset takes no back reference")]
53    BackReference,
54    /// `\A`, `\Z`, `\m`, `\M`, `\y` or `\Y` outside a bracket expression.
55    #[error("the regular expression subset takes no constraint escape such as \\y")]
56    ConstraintEscape,
57    /// Any other `\`, such as a character-entry escape like `\n` or `\x41`, an escape inside a
58    /// bracket expression, an escape PostgreSQL refuses, or a `\` ending the pattern.
59    #[error(
60        "the regular expression subset takes no escape but \\ before ASCII punctuation outside a bracket expression"
61    )]
62    OtherEscape,
63    /// `(?=`, `(?!`, `(?<=` or `(?<!`.
64    #[error("the regular expression subset takes no lookahead or lookbehind constraint")]
65    Lookaround,
66    /// `(?` and a letter, such as `(?i)`.
67    #[error("the regular expression subset takes no embedded option")]
68    EmbeddedOption,
69    /// `(?#`.
70    #[error("the regular expression subset takes no comment")]
71    Comment,
72    /// `***` opening the pattern, such as `***=`.
73    #[error("the regular expression subset takes no director such as ***=")]
74    Director,
75    /// A collating element such as `[.a.]` or an equivalence class such as `[=a=]` inside a
76    /// bracket expression.
77    #[error("the regular expression subset takes no collating element or equivalence class")]
78    CollatingElement,
79    /// A bracket expression opening with `]`, holding a `-` that is neither first, last nor
80    /// between the ends of a range, holding a range whose end precedes its start or is a
81    /// character class, or naming a character class PostgreSQL does not know.
82    #[error("the regular expression subset takes no bracket expression of this form")]
83    BracketForm,
84    /// A count in a bound past 255, PostgreSQL's `DUPMAX`.
85    #[error("the regular expression subset takes no repetition count past 255")]
86    BoundPastDupmax,
87    /// A `{` opening no `{m}`, `{m,}` or `{m,n}` closed by `}`, or a bound whose `n` is below its
88    /// `m`.
89    #[error("the regular expression subset takes no bound of this form")]
90    BoundForm,
91    /// A quantifier after nothing, after `(` or `|`, after an anchor, or after another
92    /// quantifier and its optional non-greedy `?`.
93    #[error("the regular expression subset takes no quantifier without an operand")]
94    QuantifierOperand,
95    /// A `(` without its `)`, a bracket expression without its `]`, or a `)`, `]` or `}` without
96    /// its opener.
97    #[error("the regular expression subset takes no unbalanced parenthesis, bracket or brace")]
98    Unbalanced,
99    /// Groups nested past 64 deep.
100    #[error("the regular expression subset takes no groups nested past 64 deep")]
101    TooDeep,
102    /// A pattern past 10000 elements once its bounded repetitions are copied out, as
103    /// PostgreSQL's compiler copies them, an element weighing more for every 32 arcs its
104    /// colours may draw, or a pattern that may split the characters into more than 16000
105    /// colours.
106    #[error("the regular expression subset takes no pattern expanding past 10000 elements")]
107    TooLarge,
108}
109
110impl RegexError {
111    /// The error for the escape `\` and `escaped` outside a bracket expression, `escaped` being
112    /// no ASCII punctuation.
113    fn escape(escaped: Option<char>) -> Self {
114        match escaped {
115            Some('d' | 'D' | 's' | 'S' | 'w' | 'W') => Self::ClassEscape,
116            Some('1'..='9') => Self::BackReference,
117            Some('A' | 'Z' | 'm' | 'M' | 'y' | 'Y') => Self::ConstraintEscape,
118            _ => Self::OtherEscape,
119        }
120    }
121
122    /// The error for the escape `\` and `escaped` inside a bracket expression.
123    fn bracket_escape(escaped: Option<char>) -> Self {
124        match escaped {
125            Some('d' | 'D' | 's' | 'S' | 'w' | 'W') => Self::ClassEscape,
126            _ => Self::OtherEscape,
127        }
128    }
129}
130
131/// A parsed pattern of the subset.
132#[derive(Debug)]
133enum Node {
134    Char(char),
135    Any,
136    /// The bracket expression at this index of the parser's sets.
137    Set(usize),
138    Start,
139    End,
140    Concat(Vec<Node>),
141    Alternation(Vec<Node>),
142    Repeat {
143        node: Box<Node>,
144        min: usize,
145        max: Option<usize>,
146    },
147}
148
149impl Node {
150    /// The size of the pattern with its bounded repetitions copied out, as PostgreSQL's compiler
151    /// copies them, each element weighing one more for every [`ARCS_PER_ELEMENT`] arcs its
152    /// colours may draw.
153    fn expanded_size(&self, sets: &[Set], colors: Colors) -> usize {
154        match self {
155            Self::Char(character) => 1 + colors.char_arcs(*character) / ARCS_PER_ELEMENT,
156            Self::Any | Self::Start | Self::End => 1,
157            Self::Set(index) => {
158                let set = &sets[*index];
159                1 + set.ranges.len() + set.classes.len() + set.arcs(colors) / ARCS_PER_ELEMENT
160            }
161            Self::Concat(nodes) | Self::Alternation(nodes) => nodes.iter().fold(1, |size, node| {
162                size.saturating_add(node.expanded_size(sets, colors))
163            }),
164            Self::Repeat { node, min, max } => node
165                .expanded_size(sets, colors)
166                .saturating_mul(max.unwrap_or(*min) + 1),
167        }
168    }
169}
170
171/// Bounds on the colours PostgreSQL's compiler splits the characters into for a pattern, a
172/// character or bracket expression drawing one arc of the automaton per colour it covers.
173#[derive(Debug, Clone, Copy)]
174struct Colors {
175    total: usize,
176    /// The columns of the colour map past [`LAST_SIMPLE`].
177    high_columns: usize,
178}
179
180impl Colors {
181    fn char_arcs(self, character: char) -> usize {
182        if character <= LAST_SIMPLE {
183            1
184        } else {
185            self.high_columns
186        }
187    }
188}
189
190/// A bracket expression.
191#[derive(Debug, Clone)]
192struct Set {
193    negated: bool,
194    ranges: Vec<(char, char)>,
195    classes: Vec<Class>,
196}
197
198impl Set {
199    fn contains(&self, character: char) -> bool {
200        (self
201            .ranges
202            .iter()
203            .any(|(low, high)| (*low..=*high).contains(&character))
204            || self.classes.iter().any(|class| class.contains(character)))
205            != self.negated
206    }
207
208    /// A bound on the arcs the set draws, one per colour it covers.
209    fn arcs(&self, colors: Colors) -> usize {
210        if self.negated || !self.classes.is_empty() {
211            return colors.total;
212        }
213        self.ranges
214            .iter()
215            .map(|(low, high)| {
216                usize::try_from(u32::from(*high) - u32::from(*low))
217                    .map_or(usize::MAX, |width| width.saturating_add(1))
218            })
219            .fold(0, usize::saturating_add)
220            .min(colors.total)
221    }
222}
223
224struct Parser<'pattern> {
225    rest: &'pattern str,
226    depth: usize,
227    sets: Vec<Set>,
228    /// A bound on the times the characters up to [`LAST_SIMPLE`] the pattern mentions start or
229    /// stop a run of one colour.
230    low_flips: usize,
231    /// The characters and ranges past [`LAST_SIMPLE`] the pattern mentions.
232    high_ranges: usize,
233    /// The distinct classes the pattern mentions.
234    classes: Vec<Class>,
235}
236
237impl Parser<'_> {
238    fn new(pattern: &str) -> Parser<'_> {
239        Parser {
240            rest: pattern,
241            depth: 0,
242            sets: Vec::new(),
243            low_flips: 0,
244            high_ranges: 0,
245            classes: Vec::new(),
246        }
247    }
248
249    /// Count the characters `low` through `high` towards the pattern's colours.
250    fn mention(&mut self, low: char, high: char) {
251        if low <= LAST_SIMPLE {
252            self.low_flips += 2;
253        }
254        if high > LAST_SIMPLE {
255            self.high_ranges += 1;
256        }
257    }
258
259    /// Count `class` towards the pattern's colours.
260    fn mention_class(&mut self, class: Class) {
261        if !self.classes.contains(&class) {
262            self.low_flips += class.flips_through(LAST_SIMPLE);
263            self.classes.push(class);
264        }
265    }
266
267    fn colors(&self) -> Colors {
268        let simple = usize::try_from(u32::from(LAST_SIMPLE)).map_or(usize::MAX, |last| last + 1);
269        let asking = self
270            .classes
271            .iter()
272            .filter(|class| class.asks_locale())
273            .count();
274        let high_columns = 1 << asking;
275        let high_rows = self.high_ranges.saturating_mul(2).saturating_add(1);
276        Colors {
277            total: (self.low_flips + 1)
278                .min(simple)
279                .saturating_add(high_rows.saturating_mul(high_columns)),
280            high_columns,
281        }
282    }
283
284    /// The literal `character`, counted towards the pattern's colours.
285    fn literal(&mut self, character: char) -> Node {
286        self.mention(character, character);
287        Node::Char(character)
288    }
289
290    fn peek(&self) -> Option<char> {
291        self.rest.chars().next()
292    }
293
294    /// The character after the next one.
295    fn peek_second(&self) -> Option<char> {
296        let mut ahead = self.rest.chars();
297        ahead.next();
298        ahead.next()
299    }
300
301    fn next(&mut self) -> Option<char> {
302        let next = self.peek()?;
303        self.rest = &self.rest[next.len_utf8()..];
304        Some(next)
305    }
306
307    fn eat(&mut self, expected: char) -> bool {
308        let eaten = self.peek() == Some(expected);
309        if eaten {
310            self.next();
311        }
312        eaten
313    }
314
315    fn at_quantifier(&self) -> bool {
316        matches!(self.peek(), Some('*' | '+' | '?' | '{'))
317    }
318
319    fn alternation(&mut self) -> Result<Node, RegexError> {
320        let mut branches = vec![self.branch()?];
321        while self.eat('|') {
322            branches.push(self.branch()?);
323        }
324        Ok(if branches.len() == 1 {
325            branches.swap_remove(0)
326        } else {
327            Node::Alternation(branches)
328        })
329    }
330
331    fn branch(&mut self) -> Result<Node, RegexError> {
332        let mut pieces = Vec::new();
333        while let Some(first) = self.peek() {
334            if first == '|' || first == ')' {
335                break;
336            }
337            self.next();
338            pieces.push(self.piece(first)?);
339        }
340        Ok(Node::Concat(pieces))
341    }
342
343    /// The atom opening with `first` and its quantifier.
344    fn piece(&mut self, first: char) -> Result<Node, RegexError> {
345        let atom = self.atom(first)?;
346        if !self.at_quantifier() {
347            return Ok(atom);
348        }
349        if matches!(atom, Node::Start | Node::End) {
350            return Err(RegexError::QuantifierOperand);
351        }
352        let (min, max) = match self.next() {
353            Some('*') => (0, None),
354            Some('+') => (1, None),
355            Some('?') => (0, Some(1)),
356            _ => self.bound()?,
357        };
358        // Greediness decides which match is reported, never whether one is.
359        self.eat('?');
360        if self.at_quantifier() {
361            return Err(RegexError::QuantifierOperand);
362        }
363        Ok(Node::Repeat {
364            node: Box::new(atom),
365            min,
366            max,
367        })
368    }
369
370    /// The atom opening with `first`.
371    fn atom(&mut self, first: char) -> Result<Node, RegexError> {
372        match first {
373            '(' => self.group(),
374            '.' => Ok(Node::Any),
375            '^' => Ok(Node::Start),
376            '$' => Ok(Node::End),
377            '[' => self.set(),
378            '\\' => match self.next() {
379                Some(escaped) if escaped.is_ascii_punctuation() => Ok(self.literal(escaped)),
380                escaped => Err(RegexError::escape(escaped)),
381            },
382            '*' | '+' | '?' | '{' => Err(RegexError::QuantifierOperand),
383            ']' | '}' => Err(RegexError::Unbalanced),
384            literal => Ok(self.literal(literal)),
385        }
386    }
387
388    /// The group after its `(`.
389    fn group(&mut self) -> Result<Node, RegexError> {
390        if self.peek() == Some('?') {
391            match self.peek_second() {
392                Some(':') => {
393                    self.next();
394                    self.next();
395                }
396                Some('=' | '!') => return Err(RegexError::Lookaround),
397                Some('<') => {
398                    self.next();
399                    self.next();
400                    return Err(match self.peek() {
401                        Some('=' | '!') => RegexError::Lookaround,
402                        _ => RegexError::QuantifierOperand,
403                    });
404                }
405                Some('#') => return Err(RegexError::Comment),
406                Some(letter) if letter.is_ascii_alphabetic() => {
407                    return Err(RegexError::EmbeddedOption);
408                }
409                _ => return Err(RegexError::QuantifierOperand),
410            }
411        }
412        if self.depth == GROUP_DEPTH_LIMIT {
413            return Err(RegexError::TooDeep);
414        }
415        self.depth += 1;
416        let group = self.alternation()?;
417        self.depth -= 1;
418        if self.eat(')') {
419            Ok(group)
420        } else {
421            Err(RegexError::Unbalanced)
422        }
423    }
424
425    /// The bracket expression after its `[`.
426    fn set(&mut self) -> Result<Node, RegexError> {
427        let mut set = Set {
428            negated: self.eat('^'),
429            ranges: Vec::new(),
430            classes: Vec::new(),
431        };
432        if self.eat('-') {
433            self.mention('-', '-');
434            set.ranges.push(('-', '-'));
435        }
436        loop {
437            let low = match self.next() {
438                None => return Err(RegexError::Unbalanced),
439                Some(']') if !set.ranges.is_empty() || !set.classes.is_empty() => break,
440                Some('-') if self.eat(']') => {
441                    self.mention('-', '-');
442                    set.ranges.push(('-', '-'));
443                    break;
444                }
445                Some(']' | '-') => return Err(RegexError::BracketForm),
446                Some('[') => match self.bracket_class()? {
447                    Some(class) => {
448                        self.mention_class(class);
449                        set.classes.push(class);
450                        continue;
451                    }
452                    None => '[',
453                },
454                Some('\\') => return Err(RegexError::bracket_escape(self.next())),
455                Some(low) => low,
456            };
457            let high = match self.peek_second() {
458                Some(high) if self.peek() == Some('-') && high != ']' => {
459                    self.next();
460                    self.next();
461                    match high {
462                        '[' => match self.bracket_class()? {
463                            Some(_) => return Err(RegexError::BracketForm),
464                            None => '[',
465                        },
466                        '\\' => return Err(RegexError::bracket_escape(self.next())),
467                        '-' => return Err(RegexError::BracketForm),
468                        high => high,
469                    }
470                }
471                _ => low,
472            };
473            if high < low {
474                return Err(RegexError::BracketForm);
475            }
476            self.mention(low, high);
477            set.ranges.push((low, high));
478        }
479        self.sets.push(set);
480        Ok(Node::Set(self.sets.len() - 1))
481    }
482
483    /// The class a `[` inside a bracket expression opens, or `None` when it stands for itself.
484    fn bracket_class(&mut self) -> Result<Option<Class>, RegexError> {
485        match self.peek() {
486            Some(':') => {
487                let (name, rest) = self.rest[1..]
488                    .split_once(":]")
489                    .ok_or(RegexError::Unbalanced)?;
490                self.rest = rest;
491                Class::named(name).map(Some).ok_or(RegexError::BracketForm)
492            }
493            Some('.' | '=') => Err(RegexError::CollatingElement),
494            _ => Ok(None),
495        }
496    }
497
498    /// The bounds of a `{m}`, `{m,}` or `{m,n}` quantifier after its `{`.
499    fn bound(&mut self) -> Result<(usize, Option<usize>), RegexError> {
500        let min = self.count()?;
501        let max = if self.eat(',') {
502            if self.peek() == Some('}') {
503                None
504            } else {
505                Some(self.count()?)
506            }
507        } else {
508            Some(min)
509        };
510        if !self.eat('}') || max.is_some_and(|max| max < min) {
511            return Err(RegexError::BoundForm);
512        }
513        Ok((min, max))
514    }
515
516    fn count(&mut self) -> Result<usize, RegexError> {
517        let mut count = None;
518        while let Some(digit) = self.peek().and_then(|next| next.to_digit(10)) {
519            self.next();
520            // A digit fits any `usize`, and the count stops past `DUPMAX` before it can overflow.
521            let value = count.unwrap_or(0) * 10 + usize::try_from(digit).unwrap_or(usize::MAX);
522            if value > DUPMAX {
523                return Err(RegexError::BoundPastDupmax);
524            }
525            count = Some(value);
526        }
527        count.ok_or(RegexError::BoundForm)
528    }
529}
530
531/// A step of the matching automaton.
532#[derive(Debug, Clone, Copy)]
533enum Step {
534    Char(char),
535    Any,
536    Set(usize),
537    Start,
538    End,
539    Split(usize, usize),
540    Jump(usize),
541    Match,
542}
543
544/// A pattern of a subset of PostgreSQL 18's advanced regular expressions, compiled once to an
545/// automaton that answers `text ~ pattern` without flags for any text.
546///
547/// The subset holds literal characters, `\` before an ASCII punctuation character, `.`, bracket
548/// expressions of characters, ranges and character classes, `^`, `$`, capturing and `(?:`
549/// groups, alternation, and `*`, `+`, `?`, `{m}`, `{m,}` and `{m,n}`, greedy or not. PostgreSQL
550/// compiles every pattern of the subset, and a pattern holding anything else is refused with the
551/// [`RegexError`] naming its first construct the subset does not take.
552///
553/// The classes `[:alnum:]`, `[:alpha:]`, `[:ascii:]`, `[:blank:]`, `[:cntrl:]`, `[:digit:]`,
554/// `[:graph:]`, `[:lower:]`, `[:print:]`, `[:punct:]`, `[:space:]`, `[:upper:]`, `[:word:]` and
555/// `[:xdigit:]` match as in a UTF-8 database whose `LC_CTYPE` is glibc 2.41's `en_US.utf8`, the
556/// locale of the `postgres:18.6` Docker image, so `[:space:]` holds U+3000 and not U+00A0.
557///
558/// ```
559/// use sql_values::postgres::{PgRegex, RegexError};
560///
561/// let list = PgRegex::new(
562///     r"^[a-z_][a-z0-9_]*:(read|insert|update|delete)(,[a-z_][a-z0-9_]*:(read|insert|update|delete))*$",
563/// )
564/// .unwrap();
565/// assert!(list.is_match("resources:read,notes:insert"));
566/// assert!(!list.is_match("resources:read,"));
567///
568/// let url = PgRegex::new("^https://[^[:space:]/?#]+").unwrap();
569/// assert!(url.is_match("https://example.com/notes"));
570/// assert!(!url.is_match("https://\u{3000}example.com"));
571/// assert!(url.is_match("https://\u{a0}example.com"));
572///
573/// assert_eq!(PgRegex::new(r"\d+").unwrap_err(), RegexError::ClassEscape);
574/// assert_eq!(PgRegex::new("(?=a)").unwrap_err(), RegexError::Lookaround);
575/// assert_eq!(PgRegex::new("***=a").unwrap_err(), RegexError::Director);
576/// ```
577#[derive(Debug, Clone)]
578pub struct PgRegex {
579    steps: Vec<Step>,
580    sets: Vec<Set>,
581}
582
583impl PgRegex {
584    /// Compile `pattern`.
585    ///
586    /// # Errors
587    ///
588    /// The [`RegexError`] naming the first construct of `pattern` outside the subset, or
589    /// [`RegexError::TooLarge`] for a pattern past the subset's size limit.
590    pub fn new(pattern: &str) -> Result<Self, RegexError> {
591        if pattern.starts_with("***") {
592            return Err(RegexError::Director);
593        }
594        let mut parser = Parser::new(pattern);
595        let node = parser.alternation()?;
596        if !parser.rest.is_empty() {
597            return Err(RegexError::Unbalanced);
598        }
599        let colors = parser.colors();
600        if colors.total > COLOR_LIMIT
601            || node.expanded_size(&parser.sets, colors) > EXPANDED_SIZE_LIMIT
602        {
603            return Err(RegexError::TooLarge);
604        }
605        let mut regex = Self {
606            steps: Vec::new(),
607            sets: parser.sets,
608        };
609        regex.compile(&node);
610        regex.steps.push(Step::Match);
611        Ok(regex)
612    }
613
614    fn compile(&mut self, node: &Node) {
615        match node {
616            Node::Char(character) => self.steps.push(Step::Char(*character)),
617            Node::Any => self.steps.push(Step::Any),
618            Node::Set(index) => self.steps.push(Step::Set(*index)),
619            Node::Start => self.steps.push(Step::Start),
620            Node::End => self.steps.push(Step::End),
621            Node::Concat(nodes) => {
622                for node in nodes {
623                    self.compile(node);
624                }
625            }
626            Node::Alternation(branches) => {
627                let mut exits = Vec::with_capacity(branches.len());
628                for (position, branch) in branches.iter().enumerate() {
629                    if position + 1 == branches.len() {
630                        self.compile(branch);
631                        break;
632                    }
633                    let split = self.steps.len();
634                    self.steps.push(Step::Split(split + 1, 0));
635                    self.compile(branch);
636                    exits.push(self.steps.len());
637                    self.steps.push(Step::Jump(0));
638                    self.steps[split] = Step::Split(split + 1, self.steps.len());
639                }
640                let end = self.steps.len();
641                for exit in exits {
642                    self.steps[exit] = Step::Jump(end);
643                }
644            }
645            Node::Repeat { node, min, max } => {
646                for _ in 0..*min {
647                    self.compile(node);
648                }
649                if let Some(max) = max {
650                    let mut exits = Vec::with_capacity(max - min);
651                    for _ in *min..*max {
652                        exits.push(self.steps.len());
653                        self.steps.push(Step::Split(self.steps.len() + 1, 0));
654                        self.compile(node);
655                    }
656                    let end = self.steps.len();
657                    for exit in exits {
658                        self.steps[exit] = Step::Split(exit + 1, end);
659                    }
660                } else {
661                    let split = self.steps.len();
662                    self.steps.push(Step::Split(split + 1, 0));
663                    self.compile(node);
664                    self.steps.push(Step::Jump(split));
665                    self.steps[split] = Step::Split(split + 1, self.steps.len());
666                }
667            }
668        }
669    }
670
671    /// Whether `text ~ pattern` holds, as `textregexeq` without flags answers, a match anywhere
672    /// in `text`, `^` and `$` anchoring at its ends alone, and `.` and a negated bracket
673    /// expression matching a newline.
674    #[must_use]
675    pub fn is_match(&self, text: &str) -> bool {
676        // The position each step was last reached at, to visit it once per position.
677        let mut reached = vec![usize::MAX; self.steps.len()];
678        let mut consuming = Vec::new();
679        let mut seeds = Vec::new();
680        let mut pending = Vec::new();
681        let mut characters = text.chars();
682        let mut position = 0;
683        loop {
684            let character = characters.next();
685            consuming.clear();
686            pending.append(&mut seeds);
687            // A match may start at every position.
688            pending.push(0);
689            while let Some(index) = pending.pop() {
690                if reached[index] == position {
691                    continue;
692                }
693                reached[index] = position;
694                match self.steps[index] {
695                    Step::Match => return true,
696                    Step::Split(first, second) => pending.extend([second, first]),
697                    Step::Jump(target) => pending.push(target),
698                    Step::Start if position == 0 => pending.push(index + 1),
699                    Step::End if character.is_none() => pending.push(index + 1),
700                    Step::Start | Step::End => {}
701                    Step::Char(_) | Step::Any | Step::Set(_) => consuming.push(index),
702                }
703            }
704            let Some(character) = character else {
705                return false;
706            };
707            for &index in &consuming {
708                let consumed = match self.steps[index] {
709                    Step::Char(expected) => expected == character,
710                    Step::Set(set) => self.sets[set].contains(character),
711                    _ => true,
712                };
713                if consumed {
714                    seeds.push(index + 1);
715                }
716            }
717            position += 1;
718        }
719    }
720}
721
722#[cfg(test)]
723mod tests {
724    use alloc::{format, string::String};
725
726    use super::{PgRegex, RegexError};
727
728    /// Patterns PostgreSQL 18 compiles, with texts and whether each matches, as
729    /// `SELECT text ~ pattern` answers.
730    #[test]
731    fn matches_as_postgresql_does() {
732        let list = "^[a-z_][a-z0-9_]*:(read|insert|update|delete)(,[a-z_][a-z0-9_]*:(read|insert|update|delete))*$";
733        for (pattern, text, expected) in [
734            ("", "x", true),
735            ("()", "x", true),
736            ("a|", "x", true),
737            ("|a", "x", true),
738            ("[a^]", "^", true),
739            ("a$", "a\n", false),
740            ("^.$", "\n", true),
741            ("^[^a]$", "\n", true),
742            ("a^b", "ab", false),
743            ("^a{0}b$", "b", true),
744            ("^ab?c$", "ac", true),
745            ("^ab?c$", "abbc", false),
746            ("^a{1,2}?a$", "aaa", true),
747            ("[-a]", "-", true),
748            ("[a-]", "-", true),
749            ("a\\.", "a.", true),
750            ("a\\.", "ab", false),
751            ("^[a-z]$", "é", false),
752            ("^[à-ÿ]$", "é", true),
753            ("a{255}", "a", false),
754            ("^(ab|cd)*$", "abcdab", true),
755            ("^(ab|cd)*$", "abc", false),
756            ("^(a*)*$", "aaa", true),
757            ("^(?:a|b)+c$", "abbac", true),
758            ("b{2,}", "abbbc", true),
759            ("b{2,}", "abc", false),
760            ("^x{2,3}$", "xxxx", false),
761            (list, "resources:read,team_members:delete", true),
762            (list, "resources:read,", false),
763            ("^https://[^[:space:]/?#]+$", "https://example.com", true),
764            ("^https://[^[:space:]/?#]+$", "https://exa mple.com", false),
765            (
766                "^https://[^[:space:]/?#]+$",
767                "https://exa\u{2000}mple.com",
768                false,
769            ),
770            (
771                "^https://[^[:space:]/?#]+$",
772                "https://exa\u{a0}mple.com",
773                true,
774            ),
775            ("^[^[:space:]]$", "\n", false),
776            ("^[[:alpha:]]+$", "Ωmega", true),
777            ("^[[:alpha:]]+$", "a1", false),
778            ("^[[:alnum:]_]+$", "a1_", true),
779            ("^[[:upper:]][[:lower:]]+$", "Élan", true),
780            ("^[[:digit:]]$", "٣", false),
781            ("^[[:punct:]]$", "¿", true),
782            ("^[[:word:]-]+$", "a-b_c", true),
783            ("^[-[:xdigit:]]+$", "-fF0", true),
784            ("^[[:blank:][:cntrl:]]+$", "\t \u{7f}\u{85}", true),
785            ("^[[:ascii:]]+$", "é", false),
786            ("^[[:graph:]]$", " ", false),
787            ("^[[:print:]]$", " ", true),
788            ("[[]", "[", true),
789            ("[a[]", "[", true),
790            ("^[A-[]$", "Z", true),
791            ("^[[-a]$", "_", true),
792            ("^[[[:digit:]]+$", "[1", true),
793            ("^[[:digit:][]+$", "1[", true),
794            ("^[[:alpha:]:]$", ":", true),
795        ] {
796            let regex = PgRegex::new(pattern).unwrap_or_else(|error| panic!("{pattern}: {error}"));
797            assert_eq!(regex.is_match(text), expected, "{text:?} ~ {pattern:?}");
798        }
799    }
800
801    /// Patterns PostgreSQL refuses, and patterns it compiles holding what the subset leaves out,
802    /// each refused with its first construct outside the subset.
803    #[test]
804    fn names_the_first_construct_outside_the_subset() {
805        let deep = format!("{}a{}", "(".repeat(65), ")".repeat(65));
806        let nested = format!("{}a{}", "(".repeat(64), ")".repeat(64));
807        let complement: String = ('\u{100}'..='\u{2f3}').collect();
808        let complement = format!("{complement}([^a]{{255}}){{17}}");
809        let high: String = ('\u{4e00}'..'\u{4ec8}').collect();
810        let high = format!(
811            "{high}[[:alpha:]][[:punct:]][[:space:]][[:upper:]][[:lower:]][[:print:]][[:graph:]][[:word:]][[:alnum:]]"
812        );
813        assert!(PgRegex::new(&nested).is_ok());
814        for (pattern, expected) in [
815            (r"\d", RegexError::ClassEscape),
816            (r"a\W", RegexError::ClassEscape),
817            (r"[\d]", RegexError::ClassEscape),
818            (r"(a)\1", RegexError::BackReference),
819            (r"\y", RegexError::ConstraintEscape),
820            (r"\A", RegexError::ConstraintEscape),
821            (r"\n", RegexError::OtherEscape),
822            (r"\x41", RegexError::OtherEscape),
823            (r"\é", RegexError::OtherEscape),
824            ("a\\", RegexError::OtherEscape),
825            (r"[\.]", RegexError::OtherEscape),
826            (r"[a-\]]", RegexError::OtherEscape),
827            ("(?=a)", RegexError::Lookaround),
828            ("(?!a)", RegexError::Lookaround),
829            ("(?<=a)", RegexError::Lookaround),
830            ("(?<!a)", RegexError::Lookaround),
831            ("(?<a)", RegexError::QuantifierOperand),
832            ("(?)", RegexError::QuantifierOperand),
833            ("(?i)a", RegexError::EmbeddedOption),
834            ("(?#x)a", RegexError::Comment),
835            ("***=a", RegexError::Director),
836            ("***:a", RegexError::Director),
837            ("[[.a.]]", RegexError::CollatingElement),
838            ("[[=a=]]", RegexError::CollatingElement),
839            ("[a-[.z.]]", RegexError::CollatingElement),
840            ("[[:foo:]]", RegexError::BracketForm),
841            ("[[:ALPHA:]]", RegexError::BracketForm),
842            ("[[::]]", RegexError::BracketForm),
843            ("[[:a]b:]]", RegexError::BracketForm),
844            ("[[:alpha:]-z]", RegexError::BracketForm),
845            ("[a-[:alpha:]]", RegexError::BracketForm),
846            ("[[:digit:]--]", RegexError::BracketForm),
847            ("[a-[]", RegexError::BracketForm),
848            ("[[:alpha]]", RegexError::Unbalanced),
849            ("[[:]]", RegexError::Unbalanced),
850            ("[[:alpha:]", RegexError::Unbalanced),
851            ("[[", RegexError::Unbalanced),
852            ("[[:space:]\\s]", RegexError::ClassEscape),
853            ("[]a]", RegexError::BracketForm),
854            ("[^]a]", RegexError::BracketForm),
855            ("[a-c-e]", RegexError::BracketForm),
856            ("[a--]", RegexError::BracketForm),
857            ("[z-a]", RegexError::BracketForm),
858            ("a{256}", RegexError::BoundPastDupmax),
859            ("a{1,300}", RegexError::BoundPastDupmax),
860            ("a{3,2}", RegexError::BoundForm),
861            ("a{", RegexError::BoundForm),
862            ("a{,2}", RegexError::BoundForm),
863            ("a{2", RegexError::BoundForm),
864            ("a**", RegexError::QuantifierOperand),
865            ("a*?+", RegexError::QuantifierOperand),
866            ("*a", RegexError::QuantifierOperand),
867            ("^*a", RegexError::QuantifierOperand),
868            ("a$+", RegexError::QuantifierOperand),
869            ("a|*", RegexError::QuantifierOperand),
870            ("(+a)", RegexError::QuantifierOperand),
871            ("(a", RegexError::Unbalanced),
872            ("a)", RegexError::Unbalanced),
873            ("[a", RegexError::Unbalanced),
874            ("]", RegexError::Unbalanced),
875            ("a}", RegexError::Unbalanced),
876            (deep.as_str(), RegexError::TooDeep),
877            ("((a{100}){100}){100}", RegexError::TooLarge),
878            (complement.as_str(), RegexError::TooLarge),
879            (high.as_str(), RegexError::TooLarge),
880        ] {
881            assert_eq!(PgRegex::new(pattern).err(), Some(expected), "{pattern}");
882        }
883    }
884}