mod class;
use alloc::{boxed::Box, vec, vec::Vec};
use class::Class;
const DUPMAX: usize = 255;
const GROUP_DEPTH_LIMIT: usize = 64;
const EXPANDED_SIZE_LIMIT: usize = 10_000;
const LAST_SIMPLE: char = '\u{7ff}';
const COLOR_LIMIT: usize = 16_000;
const ARCS_PER_ELEMENT: usize = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
pub enum RegexError {
#[error("the regular expression subset takes no class escape such as \\d")]
ClassEscape,
#[error("the regular expression subset takes no back reference")]
BackReference,
#[error("the regular expression subset takes no constraint escape such as \\y")]
ConstraintEscape,
#[error(
"the regular expression subset takes no escape but \\ before ASCII punctuation outside a bracket expression"
)]
OtherEscape,
#[error("the regular expression subset takes no lookahead or lookbehind constraint")]
Lookaround,
#[error("the regular expression subset takes no embedded option")]
EmbeddedOption,
#[error("the regular expression subset takes no comment")]
Comment,
#[error("the regular expression subset takes no director such as ***=")]
Director,
#[error("the regular expression subset takes no collating element or equivalence class")]
CollatingElement,
#[error("the regular expression subset takes no bracket expression of this form")]
BracketForm,
#[error("the regular expression subset takes no repetition count past 255")]
BoundPastDupmax,
#[error("the regular expression subset takes no bound of this form")]
BoundForm,
#[error("the regular expression subset takes no quantifier without an operand")]
QuantifierOperand,
#[error("the regular expression subset takes no unbalanced parenthesis, bracket or brace")]
Unbalanced,
#[error("the regular expression subset takes no groups nested past 64 deep")]
TooDeep,
#[error("the regular expression subset takes no pattern expanding past 10000 elements")]
TooLarge,
}
impl RegexError {
fn escape(escaped: Option<char>) -> Self {
match escaped {
Some('d' | 'D' | 's' | 'S' | 'w' | 'W') => Self::ClassEscape,
Some('1'..='9') => Self::BackReference,
Some('A' | 'Z' | 'm' | 'M' | 'y' | 'Y') => Self::ConstraintEscape,
_ => Self::OtherEscape,
}
}
fn bracket_escape(escaped: Option<char>) -> Self {
match escaped {
Some('d' | 'D' | 's' | 'S' | 'w' | 'W') => Self::ClassEscape,
_ => Self::OtherEscape,
}
}
}
#[derive(Debug)]
enum Node {
Char(char),
Any,
Set(usize),
Start,
End,
Concat(Vec<Node>),
Alternation(Vec<Node>),
Repeat {
node: Box<Node>,
min: usize,
max: Option<usize>,
},
}
impl Node {
fn expanded_size(&self, sets: &[Set], colors: Colors) -> usize {
match self {
Self::Char(character) => 1 + colors.char_arcs(*character) / ARCS_PER_ELEMENT,
Self::Any | Self::Start | Self::End => 1,
Self::Set(index) => {
let set = &sets[*index];
1 + set.ranges.len() + set.classes.len() + set.arcs(colors) / ARCS_PER_ELEMENT
}
Self::Concat(nodes) | Self::Alternation(nodes) => nodes.iter().fold(1, |size, node| {
size.saturating_add(node.expanded_size(sets, colors))
}),
Self::Repeat { node, min, max } => node
.expanded_size(sets, colors)
.saturating_mul(max.unwrap_or(*min) + 1),
}
}
}
#[derive(Debug, Clone, Copy)]
struct Colors {
total: usize,
high_columns: usize,
}
impl Colors {
fn char_arcs(self, character: char) -> usize {
if character <= LAST_SIMPLE {
1
} else {
self.high_columns
}
}
}
#[derive(Debug, Clone)]
struct Set {
negated: bool,
ranges: Vec<(char, char)>,
classes: Vec<Class>,
}
impl Set {
fn contains(&self, character: char) -> bool {
(self
.ranges
.iter()
.any(|(low, high)| (*low..=*high).contains(&character))
|| self.classes.iter().any(|class| class.contains(character)))
!= self.negated
}
fn arcs(&self, colors: Colors) -> usize {
if self.negated || !self.classes.is_empty() {
return colors.total;
}
self.ranges
.iter()
.map(|(low, high)| {
usize::try_from(u32::from(*high) - u32::from(*low))
.map_or(usize::MAX, |width| width.saturating_add(1))
})
.fold(0, usize::saturating_add)
.min(colors.total)
}
}
struct Parser<'pattern> {
rest: &'pattern str,
depth: usize,
sets: Vec<Set>,
low_flips: usize,
high_ranges: usize,
classes: Vec<Class>,
}
impl Parser<'_> {
fn new(pattern: &str) -> Parser<'_> {
Parser {
rest: pattern,
depth: 0,
sets: Vec::new(),
low_flips: 0,
high_ranges: 0,
classes: Vec::new(),
}
}
fn mention(&mut self, low: char, high: char) {
if low <= LAST_SIMPLE {
self.low_flips += 2;
}
if high > LAST_SIMPLE {
self.high_ranges += 1;
}
}
fn mention_class(&mut self, class: Class) {
if !self.classes.contains(&class) {
self.low_flips += class.flips_through(LAST_SIMPLE);
self.classes.push(class);
}
}
fn colors(&self) -> Colors {
let simple = usize::try_from(u32::from(LAST_SIMPLE)).map_or(usize::MAX, |last| last + 1);
let asking = self
.classes
.iter()
.filter(|class| class.asks_locale())
.count();
let high_columns = 1 << asking;
let high_rows = self.high_ranges.saturating_mul(2).saturating_add(1);
Colors {
total: (self.low_flips + 1)
.min(simple)
.saturating_add(high_rows.saturating_mul(high_columns)),
high_columns,
}
}
fn literal(&mut self, character: char) -> Node {
self.mention(character, character);
Node::Char(character)
}
fn peek(&self) -> Option<char> {
self.rest.chars().next()
}
fn peek_second(&self) -> Option<char> {
let mut ahead = self.rest.chars();
ahead.next();
ahead.next()
}
fn next(&mut self) -> Option<char> {
let next = self.peek()?;
self.rest = &self.rest[next.len_utf8()..];
Some(next)
}
fn eat(&mut self, expected: char) -> bool {
let eaten = self.peek() == Some(expected);
if eaten {
self.next();
}
eaten
}
fn at_quantifier(&self) -> bool {
matches!(self.peek(), Some('*' | '+' | '?' | '{'))
}
fn alternation(&mut self) -> Result<Node, RegexError> {
let mut branches = vec![self.branch()?];
while self.eat('|') {
branches.push(self.branch()?);
}
Ok(if branches.len() == 1 {
branches.swap_remove(0)
} else {
Node::Alternation(branches)
})
}
fn branch(&mut self) -> Result<Node, RegexError> {
let mut pieces = Vec::new();
while let Some(first) = self.peek() {
if first == '|' || first == ')' {
break;
}
self.next();
pieces.push(self.piece(first)?);
}
Ok(Node::Concat(pieces))
}
fn piece(&mut self, first: char) -> Result<Node, RegexError> {
let atom = self.atom(first)?;
if !self.at_quantifier() {
return Ok(atom);
}
if matches!(atom, Node::Start | Node::End) {
return Err(RegexError::QuantifierOperand);
}
let (min, max) = match self.next() {
Some('*') => (0, None),
Some('+') => (1, None),
Some('?') => (0, Some(1)),
_ => self.bound()?,
};
self.eat('?');
if self.at_quantifier() {
return Err(RegexError::QuantifierOperand);
}
Ok(Node::Repeat {
node: Box::new(atom),
min,
max,
})
}
fn atom(&mut self, first: char) -> Result<Node, RegexError> {
match first {
'(' => self.group(),
'.' => Ok(Node::Any),
'^' => Ok(Node::Start),
'$' => Ok(Node::End),
'[' => self.set(),
'\\' => match self.next() {
Some(escaped) if escaped.is_ascii_punctuation() => Ok(self.literal(escaped)),
escaped => Err(RegexError::escape(escaped)),
},
'*' | '+' | '?' | '{' => Err(RegexError::QuantifierOperand),
']' | '}' => Err(RegexError::Unbalanced),
literal => Ok(self.literal(literal)),
}
}
fn group(&mut self) -> Result<Node, RegexError> {
if self.peek() == Some('?') {
match self.peek_second() {
Some(':') => {
self.next();
self.next();
}
Some('=' | '!') => return Err(RegexError::Lookaround),
Some('<') => {
self.next();
self.next();
return Err(match self.peek() {
Some('=' | '!') => RegexError::Lookaround,
_ => RegexError::QuantifierOperand,
});
}
Some('#') => return Err(RegexError::Comment),
Some(letter) if letter.is_ascii_alphabetic() => {
return Err(RegexError::EmbeddedOption);
}
_ => return Err(RegexError::QuantifierOperand),
}
}
if self.depth == GROUP_DEPTH_LIMIT {
return Err(RegexError::TooDeep);
}
self.depth += 1;
let group = self.alternation()?;
self.depth -= 1;
if self.eat(')') {
Ok(group)
} else {
Err(RegexError::Unbalanced)
}
}
fn set(&mut self) -> Result<Node, RegexError> {
let mut set = Set {
negated: self.eat('^'),
ranges: Vec::new(),
classes: Vec::new(),
};
if self.eat('-') {
self.mention('-', '-');
set.ranges.push(('-', '-'));
}
loop {
let low = match self.next() {
None => return Err(RegexError::Unbalanced),
Some(']') if !set.ranges.is_empty() || !set.classes.is_empty() => break,
Some('-') if self.eat(']') => {
self.mention('-', '-');
set.ranges.push(('-', '-'));
break;
}
Some(']' | '-') => return Err(RegexError::BracketForm),
Some('[') => match self.bracket_class()? {
Some(class) => {
self.mention_class(class);
set.classes.push(class);
continue;
}
None => '[',
},
Some('\\') => return Err(RegexError::bracket_escape(self.next())),
Some(low) => low,
};
let high = match self.peek_second() {
Some(high) if self.peek() == Some('-') && high != ']' => {
self.next();
self.next();
match high {
'[' => match self.bracket_class()? {
Some(_) => return Err(RegexError::BracketForm),
None => '[',
},
'\\' => return Err(RegexError::bracket_escape(self.next())),
'-' => return Err(RegexError::BracketForm),
high => high,
}
}
_ => low,
};
if high < low {
return Err(RegexError::BracketForm);
}
self.mention(low, high);
set.ranges.push((low, high));
}
self.sets.push(set);
Ok(Node::Set(self.sets.len() - 1))
}
fn bracket_class(&mut self) -> Result<Option<Class>, RegexError> {
match self.peek() {
Some(':') => {
let (name, rest) = self.rest[1..]
.split_once(":]")
.ok_or(RegexError::Unbalanced)?;
self.rest = rest;
Class::named(name).map(Some).ok_or(RegexError::BracketForm)
}
Some('.' | '=') => Err(RegexError::CollatingElement),
_ => Ok(None),
}
}
fn bound(&mut self) -> Result<(usize, Option<usize>), RegexError> {
let min = self.count()?;
let max = if self.eat(',') {
if self.peek() == Some('}') {
None
} else {
Some(self.count()?)
}
} else {
Some(min)
};
if !self.eat('}') || max.is_some_and(|max| max < min) {
return Err(RegexError::BoundForm);
}
Ok((min, max))
}
fn count(&mut self) -> Result<usize, RegexError> {
let mut count = None;
while let Some(digit) = self.peek().and_then(|next| next.to_digit(10)) {
self.next();
let value = count.unwrap_or(0) * 10 + usize::try_from(digit).unwrap_or(usize::MAX);
if value > DUPMAX {
return Err(RegexError::BoundPastDupmax);
}
count = Some(value);
}
count.ok_or(RegexError::BoundForm)
}
}
#[derive(Debug, Clone, Copy)]
enum Step {
Char(char),
Any,
Set(usize),
Start,
End,
Split(usize, usize),
Jump(usize),
Match,
}
#[derive(Debug, Clone)]
pub struct PgRegex {
steps: Vec<Step>,
sets: Vec<Set>,
}
impl PgRegex {
pub fn new(pattern: &str) -> Result<Self, RegexError> {
if pattern.starts_with("***") {
return Err(RegexError::Director);
}
let mut parser = Parser::new(pattern);
let node = parser.alternation()?;
if !parser.rest.is_empty() {
return Err(RegexError::Unbalanced);
}
let colors = parser.colors();
if colors.total > COLOR_LIMIT
|| node.expanded_size(&parser.sets, colors) > EXPANDED_SIZE_LIMIT
{
return Err(RegexError::TooLarge);
}
let mut regex = Self {
steps: Vec::new(),
sets: parser.sets,
};
regex.compile(&node);
regex.steps.push(Step::Match);
Ok(regex)
}
fn compile(&mut self, node: &Node) {
match node {
Node::Char(character) => self.steps.push(Step::Char(*character)),
Node::Any => self.steps.push(Step::Any),
Node::Set(index) => self.steps.push(Step::Set(*index)),
Node::Start => self.steps.push(Step::Start),
Node::End => self.steps.push(Step::End),
Node::Concat(nodes) => {
for node in nodes {
self.compile(node);
}
}
Node::Alternation(branches) => {
let mut exits = Vec::with_capacity(branches.len());
for (position, branch) in branches.iter().enumerate() {
if position + 1 == branches.len() {
self.compile(branch);
break;
}
let split = self.steps.len();
self.steps.push(Step::Split(split + 1, 0));
self.compile(branch);
exits.push(self.steps.len());
self.steps.push(Step::Jump(0));
self.steps[split] = Step::Split(split + 1, self.steps.len());
}
let end = self.steps.len();
for exit in exits {
self.steps[exit] = Step::Jump(end);
}
}
Node::Repeat { node, min, max } => {
for _ in 0..*min {
self.compile(node);
}
if let Some(max) = max {
let mut exits = Vec::with_capacity(max - min);
for _ in *min..*max {
exits.push(self.steps.len());
self.steps.push(Step::Split(self.steps.len() + 1, 0));
self.compile(node);
}
let end = self.steps.len();
for exit in exits {
self.steps[exit] = Step::Split(exit + 1, end);
}
} else {
let split = self.steps.len();
self.steps.push(Step::Split(split + 1, 0));
self.compile(node);
self.steps.push(Step::Jump(split));
self.steps[split] = Step::Split(split + 1, self.steps.len());
}
}
}
}
#[must_use]
pub fn is_match(&self, text: &str) -> bool {
let mut reached = vec![usize::MAX; self.steps.len()];
let mut consuming = Vec::new();
let mut seeds = Vec::new();
let mut pending = Vec::new();
let mut characters = text.chars();
let mut position = 0;
loop {
let character = characters.next();
consuming.clear();
pending.append(&mut seeds);
pending.push(0);
while let Some(index) = pending.pop() {
if reached[index] == position {
continue;
}
reached[index] = position;
match self.steps[index] {
Step::Match => return true,
Step::Split(first, second) => pending.extend([second, first]),
Step::Jump(target) => pending.push(target),
Step::Start if position == 0 => pending.push(index + 1),
Step::End if character.is_none() => pending.push(index + 1),
Step::Start | Step::End => {}
Step::Char(_) | Step::Any | Step::Set(_) => consuming.push(index),
}
}
let Some(character) = character else {
return false;
};
for &index in &consuming {
let consumed = match self.steps[index] {
Step::Char(expected) => expected == character,
Step::Set(set) => self.sets[set].contains(character),
_ => true,
};
if consumed {
seeds.push(index + 1);
}
}
position += 1;
}
}
}
#[cfg(test)]
mod tests {
use alloc::{format, string::String};
use super::{PgRegex, RegexError};
#[test]
fn matches_as_postgresql_does() {
let list = "^[a-z_][a-z0-9_]*:(read|insert|update|delete)(,[a-z_][a-z0-9_]*:(read|insert|update|delete))*$";
for (pattern, text, expected) in [
("", "x", true),
("()", "x", true),
("a|", "x", true),
("|a", "x", true),
("[a^]", "^", true),
("a$", "a\n", false),
("^.$", "\n", true),
("^[^a]$", "\n", true),
("a^b", "ab", false),
("^a{0}b$", "b", true),
("^ab?c$", "ac", true),
("^ab?c$", "abbc", false),
("^a{1,2}?a$", "aaa", true),
("[-a]", "-", true),
("[a-]", "-", true),
("a\\.", "a.", true),
("a\\.", "ab", false),
("^[a-z]$", "é", false),
("^[à-ÿ]$", "é", true),
("a{255}", "a", false),
("^(ab|cd)*$", "abcdab", true),
("^(ab|cd)*$", "abc", false),
("^(a*)*$", "aaa", true),
("^(?:a|b)+c$", "abbac", true),
("b{2,}", "abbbc", true),
("b{2,}", "abc", false),
("^x{2,3}$", "xxxx", false),
(list, "resources:read,team_members:delete", true),
(list, "resources:read,", false),
("^https://[^[:space:]/?#]+$", "https://example.com", true),
("^https://[^[:space:]/?#]+$", "https://exa mple.com", false),
(
"^https://[^[:space:]/?#]+$",
"https://exa\u{2000}mple.com",
false,
),
(
"^https://[^[:space:]/?#]+$",
"https://exa\u{a0}mple.com",
true,
),
("^[^[:space:]]$", "\n", false),
("^[[:alpha:]]+$", "Ωmega", true),
("^[[:alpha:]]+$", "a1", false),
("^[[:alnum:]_]+$", "a1_", true),
("^[[:upper:]][[:lower:]]+$", "Élan", true),
("^[[:digit:]]$", "٣", false),
("^[[:punct:]]$", "¿", true),
("^[[:word:]-]+$", "a-b_c", true),
("^[-[:xdigit:]]+$", "-fF0", true),
("^[[:blank:][:cntrl:]]+$", "\t \u{7f}\u{85}", true),
("^[[:ascii:]]+$", "é", false),
("^[[:graph:]]$", " ", false),
("^[[:print:]]$", " ", true),
("[[]", "[", true),
("[a[]", "[", true),
("^[A-[]$", "Z", true),
("^[[-a]$", "_", true),
("^[[[:digit:]]+$", "[1", true),
("^[[:digit:][]+$", "1[", true),
("^[[:alpha:]:]$", ":", true),
] {
let regex = PgRegex::new(pattern).unwrap_or_else(|error| panic!("{pattern}: {error}"));
assert_eq!(regex.is_match(text), expected, "{text:?} ~ {pattern:?}");
}
}
#[test]
fn names_the_first_construct_outside_the_subset() {
let deep = format!("{}a{}", "(".repeat(65), ")".repeat(65));
let nested = format!("{}a{}", "(".repeat(64), ")".repeat(64));
let complement: String = ('\u{100}'..='\u{2f3}').collect();
let complement = format!("{complement}([^a]{{255}}){{17}}");
let high: String = ('\u{4e00}'..'\u{4ec8}').collect();
let high = format!(
"{high}[[:alpha:]][[:punct:]][[:space:]][[:upper:]][[:lower:]][[:print:]][[:graph:]][[:word:]][[:alnum:]]"
);
assert!(PgRegex::new(&nested).is_ok());
for (pattern, expected) in [
(r"\d", RegexError::ClassEscape),
(r"a\W", RegexError::ClassEscape),
(r"[\d]", RegexError::ClassEscape),
(r"(a)\1", RegexError::BackReference),
(r"\y", RegexError::ConstraintEscape),
(r"\A", RegexError::ConstraintEscape),
(r"\n", RegexError::OtherEscape),
(r"\x41", RegexError::OtherEscape),
(r"\é", RegexError::OtherEscape),
("a\\", RegexError::OtherEscape),
(r"[\.]", RegexError::OtherEscape),
(r"[a-\]]", RegexError::OtherEscape),
("(?=a)", RegexError::Lookaround),
("(?!a)", RegexError::Lookaround),
("(?<=a)", RegexError::Lookaround),
("(?<!a)", RegexError::Lookaround),
("(?<a)", RegexError::QuantifierOperand),
("(?)", RegexError::QuantifierOperand),
("(?i)a", RegexError::EmbeddedOption),
("(?#x)a", RegexError::Comment),
("***=a", RegexError::Director),
("***:a", RegexError::Director),
("[[.a.]]", RegexError::CollatingElement),
("[[=a=]]", RegexError::CollatingElement),
("[a-[.z.]]", RegexError::CollatingElement),
("[[:foo:]]", RegexError::BracketForm),
("[[:ALPHA:]]", RegexError::BracketForm),
("[[::]]", RegexError::BracketForm),
("[[:a]b:]]", RegexError::BracketForm),
("[[:alpha:]-z]", RegexError::BracketForm),
("[a-[:alpha:]]", RegexError::BracketForm),
("[[:digit:]--]", RegexError::BracketForm),
("[a-[]", RegexError::BracketForm),
("[[:alpha]]", RegexError::Unbalanced),
("[[:]]", RegexError::Unbalanced),
("[[:alpha:]", RegexError::Unbalanced),
("[[", RegexError::Unbalanced),
("[[:space:]\\s]", RegexError::ClassEscape),
("[]a]", RegexError::BracketForm),
("[^]a]", RegexError::BracketForm),
("[a-c-e]", RegexError::BracketForm),
("[a--]", RegexError::BracketForm),
("[z-a]", RegexError::BracketForm),
("a{256}", RegexError::BoundPastDupmax),
("a{1,300}", RegexError::BoundPastDupmax),
("a{3,2}", RegexError::BoundForm),
("a{", RegexError::BoundForm),
("a{,2}", RegexError::BoundForm),
("a{2", RegexError::BoundForm),
("a**", RegexError::QuantifierOperand),
("a*?+", RegexError::QuantifierOperand),
("*a", RegexError::QuantifierOperand),
("^*a", RegexError::QuantifierOperand),
("a$+", RegexError::QuantifierOperand),
("a|*", RegexError::QuantifierOperand),
("(+a)", RegexError::QuantifierOperand),
("(a", RegexError::Unbalanced),
("a)", RegexError::Unbalanced),
("[a", RegexError::Unbalanced),
("]", RegexError::Unbalanced),
("a}", RegexError::Unbalanced),
(deep.as_str(), RegexError::TooDeep),
("((a{100}){100}){100}", RegexError::TooLarge),
(complement.as_str(), RegexError::TooLarge),
(high.as_str(), RegexError::TooLarge),
] {
assert_eq!(PgRegex::new(pattern).err(), Some(expected), "{pattern}");
}
}
}