mod matcher;
mod parser;
pub use matcher::{Anchoring, Captures, Match};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Flags {
pub global: bool,
pub ignore_case: bool,
pub multiline: bool,
pub dot_all: bool,
pub sticky: bool,
pub unicode: bool,
pub has_indices: bool,
pub unicode_sets: bool,
}
impl Flags {
pub fn parse(text: &str) -> Option<Flags> {
let mut flags = Flags::default();
let mut seen = [false; 8];
for c in text.chars() {
let (slot, target) = match c {
'g' => (0, &mut flags.global),
'i' => (1, &mut flags.ignore_case),
'm' => (2, &mut flags.multiline),
's' => (3, &mut flags.dot_all),
'y' => (4, &mut flags.sticky),
'u' => (5, &mut flags.unicode),
'd' => (6, &mut flags.has_indices),
'v' => (7, &mut flags.unicode_sets),
_ => return None,
};
if seen[slot] {
return None;
}
seen[slot] = true;
*target = true;
}
if flags.unicode && flags.unicode_sets {
return None;
}
Some(flags)
}
pub fn as_flag_string(self) -> String {
let mut out = String::new();
for (present, letter) in [
(self.has_indices, 'd'),
(self.global, 'g'),
(self.ignore_case, 'i'),
(self.multiline, 'm'),
(self.dot_all, 's'),
(self.unicode, 'u'),
(self.unicode_sets, 'v'),
(self.sticky, 'y'),
] {
if present {
out.push(letter);
}
}
out
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropertyKind {
Lower,
Upper,
}
impl PropertyKind {
pub fn holds(self, c: char) -> bool {
match self {
PropertyKind::Lower => c.is_lowercase(),
PropertyKind::Upper => c.is_uppercase(),
}
}
pub fn from_name(name: &str) -> Option<PropertyKind> {
match name {
"Lower" | "Lowercase" | "Lowercase_Letter" | "Ll" => Some(PropertyKind::Lower),
"Upper" | "Uppercase" | "Uppercase_Letter" | "Lu" => Some(PropertyKind::Upper),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub enum Node {
Empty,
Char(char),
Any,
Class(bool, Vec<(char, char)>),
Set(Box<ClassSet>),
Property {
kind: PropertyKind,
negated: bool,
},
Start,
End,
WordBoundary(bool),
Group {
index: Option<usize>,
node: Box<Node>,
},
Concat(Vec<Node>),
Alt(Vec<Node>),
Repeat {
node: Box<Node>,
min: u32,
max: Option<u32>,
greedy: bool,
},
Backref(usize),
Look {
node: Box<Node>,
ahead: bool,
negated: bool,
},
}
impl Node {
pub fn nullable(&self) -> bool {
match self {
Node::Empty | Node::Start | Node::End | Node::WordBoundary(_) | Node::Look { .. } => {
true
}
Node::Char(_)
| Node::Any
| Node::Class(..)
| Node::Property { .. }
| Node::Set(_)
| Node::Backref(_) => false,
Node::Group { node, .. } => node.nullable(),
Node::Concat(nodes) => nodes.iter().all(Node::nullable),
Node::Alt(branches) => branches.iter().any(Node::nullable),
Node::Repeat { min, node, .. } => *min == 0 || node.nullable(),
}
}
}
#[derive(Debug, Clone)]
pub enum ClassSet {
Char(char),
Range(char, char),
Property {
kind: PropertyKind,
negated: bool,
},
Predefined {
negated: bool,
ranges: Vec<(char, char)>,
},
Strings(Vec<Vec<char>>),
Union(Vec<ClassSet>),
Intersection(Vec<ClassSet>),
Difference(Box<ClassSet>, Box<ClassSet>),
Negated(Box<ClassSet>),
}
pub struct Regex {
pub source: String,
pub flags: Flags,
pub node: Node,
pub groups: usize,
pub nullable: bool,
}
impl Regex {
pub fn compile(source: &str, flags: Flags) -> Result<Regex, parser::PatternError> {
let parsed = parser::parse(source, flags)?;
Ok(Regex {
source: source.to_string(),
flags,
node: parsed.node,
groups: parsed.groups,
nullable: parsed.nullable,
})
}
pub fn exec_at(&self, input: &[char], from: usize) -> Option<Match> {
let anchoring = if self.flags.sticky {
Anchoring::At(from)
} else {
Anchoring::Search
};
matcher::exec(&self.node, self.groups, self.flags, input, from, anchoring)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn find(pattern: &str, flags: &str, text: &str) -> Option<String> {
let regex = Regex::compile(pattern, Flags::parse(flags).expect("flags")).expect("pattern");
let input: Vec<char> = text.chars().collect();
regex
.exec_at(&input, 0)
.map(|m| input[m.start..m.end].iter().collect())
}
#[test]
fn literals_and_dot() {
assert_eq!(find("abc", "", "xxabcxx").as_deref(), Some("abc"));
assert_eq!(find("a.c", "", "abc").as_deref(), Some("abc"));
assert_eq!(find("a.c", "", "a\nc"), None);
assert_eq!(find("a.c", "s", "a\nc").as_deref(), Some("a\nc"));
assert_eq!(find("zzz", "", "abc"), None);
}
#[test]
fn anchors() {
assert_eq!(find("^abc", "", "abc").as_deref(), Some("abc"));
assert_eq!(find("^bc", "", "abc"), None);
assert_eq!(find("bc$", "", "abc").as_deref(), Some("bc"));
assert_eq!(find("^abc", "m", "x\nabc").as_deref(), Some("abc"));
assert_eq!(find("abc$", "m", "abc\nx").as_deref(), Some("abc"));
assert_eq!(find("^abc$", "", "abc").as_deref(), Some("abc"));
}
#[test]
fn classes_and_escapes() {
assert_eq!(find("[a-c]+", "", "xxabcxx").as_deref(), Some("abc"));
assert_eq!(find("[^a-c]+", "", "abcxyz").as_deref(), Some("xyz"));
assert_eq!(find("\\d+", "", "ab123cd").as_deref(), Some("123"));
assert_eq!(find("\\w+", "", " foo_1 ").as_deref(), Some("foo_1"));
assert_eq!(find("\\s+", "", "a \t b").as_deref(), Some(" \t "));
assert_eq!(find("[\\d]+", "", "a12").as_deref(), Some("12"));
assert_eq!(find("\\x41", "", "zA").as_deref(), Some("A"));
assert_eq!(find("\\u0041", "", "zA").as_deref(), Some("A"));
assert_eq!(find("[]]", "", "x]").as_deref(), Some("]"));
assert_eq!(find("[a-]", "", "x-").as_deref(), Some("-"));
}
#[test]
fn quantifiers_are_greedy_unless_asked_otherwise() {
assert_eq!(find("<.+>", "", "<a><b>").as_deref(), Some("<a><b>"));
assert_eq!(find("<.+?>", "", "<a><b>").as_deref(), Some("<a>"));
assert_eq!(find("ab*", "", "abbbc").as_deref(), Some("abbb"));
assert_eq!(find("ab+", "", "ac"), None);
assert_eq!(find("colou?r", "", "color").as_deref(), Some("color"));
assert_eq!(find("a{2,3}", "", "aaaa").as_deref(), Some("aaa"));
assert_eq!(find("a{2}", "", "a"), None);
assert_eq!(find("a{2,}", "", "aaaa").as_deref(), Some("aaaa"));
assert_eq!(find("a{x}", "", "a{x}").as_deref(), Some("a{x}"));
}
#[test]
fn alternation_and_groups() {
assert_eq!(find("cat|dog", "", "a dog").as_deref(), Some("dog"));
assert_eq!(find("(?:ab)+", "", "ababx").as_deref(), Some("abab"));
let regex = Regex::compile("(a)(b)?", Flags::default()).expect("pattern");
let input: Vec<char> = "a".chars().collect();
let found = regex.exec_at(&input, 0).expect("match");
assert_eq!(found.captures[1], Some((0, 1)));
assert_eq!(found.captures[2], None);
}
#[test]
fn backreferences_and_boundaries() {
assert_eq!(find("(a+)-\\1", "", "aa-aa").as_deref(), Some("aa-aa"));
assert_eq!(
find("\\bword\\b", "", "a word here").as_deref(),
Some("word")
);
assert_eq!(find("\\bword\\b", "", "swordfish"), None);
}
#[test]
fn lookahead() {
assert_eq!(find("foo(?=bar)", "", "foobar").as_deref(), Some("foo"));
assert_eq!(find("foo(?!bar)", "", "foobaz").as_deref(), Some("foo"));
assert_eq!(find("foo(?!bar)", "", "foobar"), None);
}
#[test]
fn ignore_case_and_sticky() {
assert_eq!(find("abc", "i", "xABC").as_deref(), Some("ABC"));
assert_eq!(find("[a-z]+", "i", "ABC").as_deref(), Some("ABC"));
let regex = Regex::compile("b", Flags::parse("y").expect("flags")).expect("pattern");
let input: Vec<char> = "abc".chars().collect();
assert!(regex.exec_at(&input, 1).is_some());
assert!(regex.exec_at(&input, 0).is_none());
}
#[test]
fn unsupported_syntax_is_reported() {
assert!(Regex::compile("(?<=a)b", Flags::default()).is_err());
assert!(Regex::compile("(?<name>a)", Flags::default()).is_err());
assert!(Regex::compile("(a", Flags::default()).is_err());
assert!(Regex::compile("a)", Flags::default()).is_err());
assert!(Regex::compile("*a", Flags::default()).is_err());
assert!(Regex::compile("[z-a]", Flags::default()).is_err());
}
#[test]
fn empty_matches_do_not_loop() {
let regex = Regex::compile("(?:)", Flags::default()).expect("pattern");
assert!(regex.nullable);
let input: Vec<char> = "ab".chars().collect();
assert_eq!(
regex.exec_at(&input, 0).map(|m| (m.start, m.end)),
Some((0, 0))
);
}
}