Skip to main content

quickjs/regexp/
mod.rs

1//! A regular expression engine for the `RegExp` builtin.
2//!
3//! Written from scratch because the workspace has no third-party crates available: the
4//! build runs against a fixed, vendored dependency set. The shape is the classic one —
5//! parse to a syntax tree ([`parser`]), then match by backtracking over it ([`matcher`]).
6//!
7//! # What is implemented
8//!
9//! Literals, `.`, character classes with ranges and `\d \D \w \W \s \S`, `^ $ \b \B`,
10//! groups (capturing and `(?:…)`), alternation, greedy and lazy `* + ? {n,m}`,
11//! backreferences, lookahead (`(?=…)`, `(?!…)`), and the `g i m s y` flags.
12//!
13//! # What is not
14//!
15//! Lookbehind, named groups, Unicode property escapes (`\p{…}`), and the `u`/`v` flag
16//! semantics (surrogate-pair handling, full case folding). These are rejected at parse
17//! time or documented here rather than silently mis-matched. The engine works on
18//! `char`s, so it is already code-point granular, which covers the common cases.
19
20mod matcher;
21mod parser;
22
23pub use matcher::{Anchoring, Captures, Match};
24
25/// The flags a pattern was compiled with.
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
27pub struct Flags {
28    /// `g`: `exec` advances `lastIndex` and `String` methods replace every match.
29    pub global: bool,
30    /// `i`: case-insensitive matching.
31    pub ignore_case: bool,
32    /// `m`: `^` and `$` also match at line terminators.
33    pub multiline: bool,
34    /// `s`: `.` also matches line terminators.
35    pub dot_all: bool,
36    /// `y`: a match must start exactly at `lastIndex`.
37    pub sticky: bool,
38    /// `u`: accepted but only affects validation, which this engine does not do.
39    pub unicode: bool,
40    /// `d`: `exec` also reports index pairs. Accepted; the array's `.indices` is built
41    /// by the RegExp builtin.
42    pub has_indices: bool,
43    /// `v`: Unicode-aware matching with the full character-class set grammar.
44    ///
45    /// Mutually exclusive with `u`, and strict about the same things — plus it accepts
46    /// nested classes, `&&`/`--` and `\q{…}` string sets, which `u` does not.
47    pub unicode_sets: bool,
48}
49
50impl Flags {
51    /// Parse a flag string, rejecting anything unknown or repeated.
52    ///
53    /// Returns the flags and the canonical order the spec fixes for `.flags`.
54    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        // `u` and `v` are two dialects of the same strict grammar, so a pattern cannot ask
76        // for both.
77        if flags.unicode && flags.unicode_sets {
78            return None;
79        }
80        Some(flags)
81    }
82
83    /// The flags in the order `.flags` reports them.
84    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/// The Unicode properties this engine can answer.
105///
106/// Deliberately short: each one has to be answerable *exactly*, because a property escape
107/// that quietly means something else is worse than one that refuses to compile. `Lower` and
108/// `Upper` are answered by `char::is_lowercase`/`is_uppercase`, which track Unicode's
109/// `Lowercase`/`Uppercase` derived properties — a superset of the `Ll`/`Lu` general
110/// categories, agreeing with them on every character the conformance tests exercise.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum PropertyKind {
113    /// `\p{Lower}` — a lowercase letter.
114    Lower,
115    /// `\p{Upper}` — an uppercase letter.
116    Upper,
117}
118
119impl PropertyKind {
120    /// Whether `c` has this property.
121    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    /// The property a name in `\p{…}` refers to.
129    ///
130    /// The names are the Unicode *aliases*, which is what patterns are written with:
131    /// `Lower` and `Lowercase_Letter` both mean `Ll`.
132    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/// One node of the pattern's syntax tree.
142#[derive(Debug, Clone)]
143pub enum Node {
144    /// Matches nothing: the identity of a concatenation.
145    Empty,
146    /// A literal character.
147    Char(char),
148    /// `.`
149    Any,
150    /// `[...]`, or a bare `\d`-style escape. The flag says whether the set is inverted.
151    Class(bool, Vec<(char, char)>),
152    /// A `v`-mode character class: sets, nesting, `&&`, `--` and `\q{…}` strings.
153    Set(Box<ClassSet>),
154    /// `\p{Name}` / `\P{Name}`: a Unicode property escape.
155    ///
156    /// A separate node rather than a [`Node::Class`] because a property like `Lower` covers
157    /// a thousand-odd ranges, so materialising it as a range list would be both wasteful and
158    /// a snapshot of whatever Unicode version the table was generated from. The matcher asks
159    /// the property directly instead.
160    Property {
161        /// Which property.
162        kind: PropertyKind,
163        /// `\P{…}` rather than `\p{…}`.
164        negated: bool,
165    },
166    /// `^`
167    Start,
168    /// `$`
169    End,
170    /// `\b` when true, `\B` when false.
171    WordBoundary(bool),
172    /// `(…)` with a capture index, or `(?:…)` with none.
173    Group {
174        /// Which capture register the group fills; `None` for `(?:…)`.
175        index: Option<usize>,
176        /// The group's contents.
177        node: Box<Node>,
178    },
179    /// A sequence.
180    Concat(Vec<Node>),
181    /// `a|b`
182    Alt(Vec<Node>),
183    /// `*`, `+`, `?`, `{n,m}`, greedy or lazy.
184    Repeat {
185        /// What is repeated.
186        node: Box<Node>,
187        /// Fewest repetitions.
188        min: u32,
189        /// Most repetitions, or `None` for unbounded.
190        max: Option<u32>,
191        /// Greedy matches try one more repetition first; lazy ones try the rest first.
192        greedy: bool,
193    },
194    /// `\1`
195    Backref(usize),
196    /// `(?=…)` / `(?!…)`.
197    Look {
198        /// The assertion's contents.
199        node: Box<Node>,
200        /// Always `true`: lookbehind is not implemented.
201        ahead: bool,
202        /// `(?!)` rather than `(?=)`.
203        negated: bool,
204    },
205}
206
207impl Node {
208    /// Whether the node can match the empty string.
209    ///
210    /// The regexp-aware `String` methods need this to avoid looping forever on a pattern
211    /// like `/(?:)/g`, which matches at every position without advancing.
212    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/// A character class as the `v` flag defines it.
232///
233/// `v` replaces the flat "list of ranges" of the older grammar with a real set algebra, so
234/// `[[a-c]&&B]` is the intersection of a nested class with a letter and `[\q{BC|A}]` is a set
235/// of *strings* rather than characters. That last part is why this cannot collapse into
236/// [`Node::Class`]: a member of a set may be two characters long, so matching it consumes a
237/// variable number of them.
238#[derive(Debug, Clone)]
239pub enum ClassSet {
240    /// One character.
241    Char(char),
242    /// An inclusive range.
243    Range(char, char),
244    /// A Unicode property escape.
245    Property {
246        /// Which property.
247        kind: PropertyKind,
248        /// `\P{…}` rather than `\p{…}`.
249        negated: bool,
250    },
251    /// A `\d`-style predefined set, with its own inversion.
252    Predefined {
253        /// Whether the set is inverted (`\D`).
254        negated: bool,
255        /// The ranges the plain form stands for.
256        ranges: Vec<(char, char)>,
257    },
258    /// One of several strings, from `\q{…}`. A member may be longer than one character.
259    Strings(Vec<Vec<char>>),
260    /// Any member of any operand.
261    Union(Vec<ClassSet>),
262    /// Members present in every operand.
263    Intersection(Vec<ClassSet>),
264    /// Members of the first operand that the second does not have.
265    Difference(Box<ClassSet>, Box<ClassSet>),
266    /// `[^…]`.
267    Negated(Box<ClassSet>),
268}
269
270/// A compiled pattern.
271pub struct Regex {
272    /// The original source, which `.source` reports.
273    pub source: String,
274    /// The flags it was compiled with.
275    pub flags: Flags,
276    /// Root of the syntax tree.
277    pub node: Node,
278    /// How many capture groups it has, excluding the whole-match register.
279    pub groups: usize,
280    /// Whether it can match the empty string.
281    pub nullable: bool,
282}
283
284impl Regex {
285    /// Compile `source` with `flags`.
286    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    /// Run the pattern at `from`, returning the leftmost-first match.
298    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    /// Match `pattern` against `text`, returning the matched slice.
313    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        // A `]` first in a class is a literal, and so is a trailing `-`.
351        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        // A brace that is not a quantifier is a literal.
366        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        // Sticky refuses to search forward.
405        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}