1mod matcher;
21mod parser;
22
23pub use matcher::{Anchoring, Captures, Match};
24
25#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
27pub struct Flags {
28 pub global: bool,
30 pub ignore_case: bool,
32 pub multiline: bool,
34 pub dot_all: bool,
36 pub sticky: bool,
38 pub unicode: bool,
40 pub has_indices: bool,
43 pub unicode_sets: bool,
48}
49
50impl Flags {
51 pub fn parse(text: &str) -> Option<Flags> {
55 let mut flags = Flags::default();
56 let mut seen = [false; 8];
57 for c in text.chars() {
58 let (slot, target) = match c {
59 'g' => (0, &mut flags.global),
60 'i' => (1, &mut flags.ignore_case),
61 'm' => (2, &mut flags.multiline),
62 's' => (3, &mut flags.dot_all),
63 'y' => (4, &mut flags.sticky),
64 'u' => (5, &mut flags.unicode),
65 'd' => (6, &mut flags.has_indices),
66 'v' => (7, &mut flags.unicode_sets),
67 _ => return None,
68 };
69 if seen[slot] {
70 return None;
71 }
72 seen[slot] = true;
73 *target = true;
74 }
75 if flags.unicode && flags.unicode_sets {
78 return None;
79 }
80 Some(flags)
81 }
82
83 pub fn as_flag_string(self) -> String {
85 let mut out = String::new();
86 for (present, letter) in [
87 (self.has_indices, 'd'),
88 (self.global, 'g'),
89 (self.ignore_case, 'i'),
90 (self.multiline, 'm'),
91 (self.dot_all, 's'),
92 (self.unicode, 'u'),
93 (self.unicode_sets, 'v'),
94 (self.sticky, 'y'),
95 ] {
96 if present {
97 out.push(letter);
98 }
99 }
100 out
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum PropertyKind {
113 Lower,
115 Upper,
117}
118
119impl PropertyKind {
120 pub fn holds(self, c: char) -> bool {
122 match self {
123 PropertyKind::Lower => c.is_lowercase(),
124 PropertyKind::Upper => c.is_uppercase(),
125 }
126 }
127
128 pub fn from_name(name: &str) -> Option<PropertyKind> {
133 match name {
134 "Lower" | "Lowercase" | "Lowercase_Letter" | "Ll" => Some(PropertyKind::Lower),
135 "Upper" | "Uppercase" | "Uppercase_Letter" | "Lu" => Some(PropertyKind::Upper),
136 _ => None,
137 }
138 }
139}
140
141#[derive(Debug, Clone)]
143pub enum Node {
144 Empty,
146 Char(char),
148 Any,
150 Class(bool, Vec<(char, char)>),
152 Set(Box<ClassSet>),
154 Property {
161 kind: PropertyKind,
163 negated: bool,
165 },
166 Start,
168 End,
170 WordBoundary(bool),
172 Group {
174 index: Option<usize>,
176 node: Box<Node>,
178 },
179 Concat(Vec<Node>),
181 Alt(Vec<Node>),
183 Repeat {
185 node: Box<Node>,
187 min: u32,
189 max: Option<u32>,
191 greedy: bool,
193 },
194 Backref(usize),
196 Look {
198 node: Box<Node>,
200 ahead: bool,
202 negated: bool,
204 },
205}
206
207impl Node {
208 pub fn nullable(&self) -> bool {
213 match self {
214 Node::Empty | Node::Start | Node::End | Node::WordBoundary(_) | Node::Look { .. } => {
215 true
216 }
217 Node::Char(_)
218 | Node::Any
219 | Node::Class(..)
220 | Node::Property { .. }
221 | Node::Set(_)
222 | Node::Backref(_) => false,
223 Node::Group { node, .. } => node.nullable(),
224 Node::Concat(nodes) => nodes.iter().all(Node::nullable),
225 Node::Alt(branches) => branches.iter().any(Node::nullable),
226 Node::Repeat { min, node, .. } => *min == 0 || node.nullable(),
227 }
228 }
229}
230
231#[derive(Debug, Clone)]
239pub enum ClassSet {
240 Char(char),
242 Range(char, char),
244 Property {
246 kind: PropertyKind,
248 negated: bool,
250 },
251 Predefined {
253 negated: bool,
255 ranges: Vec<(char, char)>,
257 },
258 Strings(Vec<Vec<char>>),
260 Union(Vec<ClassSet>),
262 Intersection(Vec<ClassSet>),
264 Difference(Box<ClassSet>, Box<ClassSet>),
266 Negated(Box<ClassSet>),
268}
269
270pub struct Regex {
272 pub source: String,
274 pub flags: Flags,
276 pub node: Node,
278 pub groups: usize,
280 pub nullable: bool,
282}
283
284impl Regex {
285 pub fn compile(source: &str, flags: Flags) -> Result<Regex, parser::PatternError> {
287 let parsed = parser::parse(source, flags)?;
288 Ok(Regex {
289 source: source.to_string(),
290 flags,
291 node: parsed.node,
292 groups: parsed.groups,
293 nullable: parsed.nullable,
294 })
295 }
296
297 pub fn exec_at(&self, input: &[char], from: usize) -> Option<Match> {
299 let anchoring = if self.flags.sticky {
300 Anchoring::At(from)
301 } else {
302 Anchoring::Search
303 };
304 matcher::exec(&self.node, self.groups, self.flags, input, from, anchoring)
305 }
306}
307
308#[cfg(test)]
309mod tests {
310 use super::*;
311
312 fn find(pattern: &str, flags: &str, text: &str) -> Option<String> {
314 let regex = Regex::compile(pattern, Flags::parse(flags).expect("flags")).expect("pattern");
315 let input: Vec<char> = text.chars().collect();
316 regex
317 .exec_at(&input, 0)
318 .map(|m| input[m.start..m.end].iter().collect())
319 }
320
321 #[test]
322 fn literals_and_dot() {
323 assert_eq!(find("abc", "", "xxabcxx").as_deref(), Some("abc"));
324 assert_eq!(find("a.c", "", "abc").as_deref(), Some("abc"));
325 assert_eq!(find("a.c", "", "a\nc"), None);
326 assert_eq!(find("a.c", "s", "a\nc").as_deref(), Some("a\nc"));
327 assert_eq!(find("zzz", "", "abc"), None);
328 }
329
330 #[test]
331 fn anchors() {
332 assert_eq!(find("^abc", "", "abc").as_deref(), Some("abc"));
333 assert_eq!(find("^bc", "", "abc"), None);
334 assert_eq!(find("bc$", "", "abc").as_deref(), Some("bc"));
335 assert_eq!(find("^abc", "m", "x\nabc").as_deref(), Some("abc"));
336 assert_eq!(find("abc$", "m", "abc\nx").as_deref(), Some("abc"));
337 assert_eq!(find("^abc$", "", "abc").as_deref(), Some("abc"));
338 }
339
340 #[test]
341 fn classes_and_escapes() {
342 assert_eq!(find("[a-c]+", "", "xxabcxx").as_deref(), Some("abc"));
343 assert_eq!(find("[^a-c]+", "", "abcxyz").as_deref(), Some("xyz"));
344 assert_eq!(find("\\d+", "", "ab123cd").as_deref(), Some("123"));
345 assert_eq!(find("\\w+", "", " foo_1 ").as_deref(), Some("foo_1"));
346 assert_eq!(find("\\s+", "", "a \t b").as_deref(), Some(" \t "));
347 assert_eq!(find("[\\d]+", "", "a12").as_deref(), Some("12"));
348 assert_eq!(find("\\x41", "", "zA").as_deref(), Some("A"));
349 assert_eq!(find("\\u0041", "", "zA").as_deref(), Some("A"));
350 assert_eq!(find("[]]", "", "x]").as_deref(), Some("]"));
352 assert_eq!(find("[a-]", "", "x-").as_deref(), Some("-"));
353 }
354
355 #[test]
356 fn quantifiers_are_greedy_unless_asked_otherwise() {
357 assert_eq!(find("<.+>", "", "<a><b>").as_deref(), Some("<a><b>"));
358 assert_eq!(find("<.+?>", "", "<a><b>").as_deref(), Some("<a>"));
359 assert_eq!(find("ab*", "", "abbbc").as_deref(), Some("abbb"));
360 assert_eq!(find("ab+", "", "ac"), None);
361 assert_eq!(find("colou?r", "", "color").as_deref(), Some("color"));
362 assert_eq!(find("a{2,3}", "", "aaaa").as_deref(), Some("aaa"));
363 assert_eq!(find("a{2}", "", "a"), None);
364 assert_eq!(find("a{2,}", "", "aaaa").as_deref(), Some("aaaa"));
365 assert_eq!(find("a{x}", "", "a{x}").as_deref(), Some("a{x}"));
367 }
368
369 #[test]
370 fn alternation_and_groups() {
371 assert_eq!(find("cat|dog", "", "a dog").as_deref(), Some("dog"));
372 assert_eq!(find("(?:ab)+", "", "ababx").as_deref(), Some("abab"));
373 let regex = Regex::compile("(a)(b)?", Flags::default()).expect("pattern");
374 let input: Vec<char> = "a".chars().collect();
375 let found = regex.exec_at(&input, 0).expect("match");
376 assert_eq!(found.captures[1], Some((0, 1)));
377 assert_eq!(found.captures[2], None);
378 }
379
380 #[test]
381 fn backreferences_and_boundaries() {
382 assert_eq!(find("(a+)-\\1", "", "aa-aa").as_deref(), Some("aa-aa"));
383 assert_eq!(
384 find("\\bword\\b", "", "a word here").as_deref(),
385 Some("word")
386 );
387 assert_eq!(find("\\bword\\b", "", "swordfish"), None);
388 }
389
390 #[test]
391 fn lookahead() {
392 assert_eq!(find("foo(?=bar)", "", "foobar").as_deref(), Some("foo"));
393 assert_eq!(find("foo(?!bar)", "", "foobaz").as_deref(), Some("foo"));
394 assert_eq!(find("foo(?!bar)", "", "foobar"), None);
395 }
396
397 #[test]
398 fn ignore_case_and_sticky() {
399 assert_eq!(find("abc", "i", "xABC").as_deref(), Some("ABC"));
400 assert_eq!(find("[a-z]+", "i", "ABC").as_deref(), Some("ABC"));
401 let regex = Regex::compile("b", Flags::parse("y").expect("flags")).expect("pattern");
402 let input: Vec<char> = "abc".chars().collect();
403 assert!(regex.exec_at(&input, 1).is_some());
404 assert!(regex.exec_at(&input, 0).is_none());
406 }
407
408 #[test]
409 fn unsupported_syntax_is_reported() {
410 assert!(Regex::compile("(?<=a)b", Flags::default()).is_err());
411 assert!(Regex::compile("(?<name>a)", Flags::default()).is_err());
412 assert!(Regex::compile("(a", Flags::default()).is_err());
413 assert!(Regex::compile("a)", Flags::default()).is_err());
414 assert!(Regex::compile("*a", Flags::default()).is_err());
415 assert!(Regex::compile("[z-a]", Flags::default()).is_err());
416 }
417
418 #[test]
419 fn empty_matches_do_not_loop() {
420 let regex = Regex::compile("(?:)", Flags::default()).expect("pattern");
421 assert!(regex.nullable);
422 let input: Vec<char> = "ab".chars().collect();
423 assert_eq!(
424 regex.exec_at(&input, 0).map(|m| (m.start, m.end)),
425 Some((0, 0))
426 );
427 }
428}