Skip to main content

quickjs/regexp/
matcher.rs

1//! A backtracking matcher over the tree [`parser`](super::parser) produces.
2//!
3//! The matcher is written in continuation-passing style: `seq` walks a list of nodes and
4//! calls `k` with the position it reached, and `k` returns `false` to ask for another
5//! possibility. That is what makes greedy quantifiers work — a repeat tries one more
6//! iteration first and falls back to the continuation — and it is why captures are
7//! passed by shared reference and copied when a group is entered, rather than mutated in
8//! place: a branch that fails must not leave its captures behind.
9
10use super::{ClassSet, Flags, Node, PropertyKind};
11
12/// Capture register: `caps[0]` is the whole match, `caps[n]` is group `n`.
13pub type Captures = Vec<Option<(usize, usize)>>;
14
15/// One successful match.
16pub struct Match {
17    /// Byte-independent character offsets; the caller turns them into string slices.
18    pub start: usize,
19    /// Exclusive end of the match.
20    pub end: usize,
21    /// Group captures, indexed like [`Captures`].
22    pub captures: Captures,
23}
24
25/// Where a match may begin.
26#[derive(Clone, Copy, PartialEq, Eq)]
27pub enum Anchoring {
28    /// Try every starting position, as `exec` does.
29    Search,
30    /// Only at the given position, as a sticky (`y`) or global-scan step does.
31    At(usize),
32}
33
34/// Try to match `node` against `input`, returning the leftmost match.
35pub fn exec(
36    node: &Node,
37    groups: usize,
38    flags: Flags,
39    input: &[char],
40    from: usize,
41    anchoring: Anchoring,
42) -> Option<Match> {
43    let matcher = Matcher { input, flags };
44    let starts: Box<dyn Iterator<Item = usize>> = match anchoring {
45        Anchoring::At(position) => Box::new(std::iter::once(position)),
46        Anchoring::Search => Box::new(from..=input.len()),
47    };
48    for start in starts {
49        if start > input.len() {
50            break;
51        }
52        let caps: Captures = vec![None; groups + 1];
53        let mut found = None;
54        let mut record = |end: usize, caps: &Captures| {
55            let mut caps = caps.clone();
56            caps[0] = Some((start, end));
57            found = Some(Match {
58                start,
59                end,
60                captures: caps,
61            });
62            // `true` stops the search: the first end position reached for this start is
63            // the match, because alternatives and greedy repeats are tried in order.
64            true
65        };
66        if matcher.seq(std::slice::from_ref(node), start, &caps, &mut record) {
67            return found;
68        }
69    }
70    None
71}
72
73struct Matcher<'a> {
74    input: &'a [char],
75    flags: Flags,
76}
77
78impl Matcher<'_> {
79    fn at(&self, position: usize) -> Option<char> {
80        self.input.get(position).copied()
81    }
82
83    fn fold(&self, c: char) -> char {
84        if self.flags.ignore_case {
85            // Full Unicode case folding needs the case tables; the simple mapping covers
86            // the ASCII and Latin-1 ranges scripts actually use.
87            c.to_lowercase().next().unwrap_or(c)
88        } else {
89            c
90        }
91    }
92
93    fn chars_equal(&self, a: char, b: char) -> bool {
94        if self.flags.ignore_case {
95            self.fold(a) == self.fold(b)
96        } else {
97            a == b
98        }
99    }
100
101    /// How many characters a set can consume here, longest first.
102    ///
103    /// A set of single characters answers `0` or `1`; `\q{BC|A}` answers `2` or `1`. Returning
104    /// the lengths rather than the strings is what makes intersection and subtraction
105    /// expressible: two sets agree on a string exactly when they agree on a length at the
106    /// same position, because the string is the input either way.
107    fn set_lengths(&self, set: &ClassSet, position: usize) -> Vec<usize> {
108        let mut lengths = self.set_lengths_unsorted(set, position);
109        lengths.sort_unstable_by(|a, b| b.cmp(a));
110        lengths.dedup();
111        lengths
112    }
113
114    fn set_lengths_unsorted(&self, set: &ClassSet, position: usize) -> Vec<usize> {
115        match set {
116            ClassSet::Char(expected) => match self.at(position) {
117                Some(actual) if self.chars_equal(actual, *expected) => vec![1],
118                _ => Vec::new(),
119            },
120            ClassSet::Range(lo, hi) => match self.at(position) {
121                Some(c) if self.in_range(c, *lo, *hi) => vec![1],
122                _ => Vec::new(),
123            },
124            ClassSet::Property { kind, negated } => match self.at(position) {
125                Some(c) if self.property_holds(*kind, *negated, c) => vec![1],
126                _ => Vec::new(),
127            },
128            ClassSet::Predefined { negated, ranges } => match self.at(position) {
129                Some(c) => {
130                    let inside = ranges.iter().any(|(lo, hi)| self.in_range(c, *lo, *hi));
131                    if inside != *negated {
132                        vec![1]
133                    } else {
134                        Vec::new()
135                    }
136                }
137                None => Vec::new(),
138            },
139            ClassSet::Strings(members) => members
140                .iter()
141                .filter(|member| self.matches_sequence(member, position))
142                .map(|member| member.len())
143                .collect(),
144            ClassSet::Union(operands) => operands
145                .iter()
146                .flat_map(|operand| self.set_lengths_unsorted(operand, position))
147                .collect(),
148            ClassSet::Intersection(operands) => {
149                let mut iter = operands.iter();
150                let Some(first) = iter.next() else {
151                    return Vec::new();
152                };
153                let mut lengths = self.set_lengths(first, position);
154                for operand in iter {
155                    let other = self.set_lengths(operand, position);
156                    lengths.retain(|length| other.contains(length));
157                }
158                lengths
159            }
160            ClassSet::Difference(left, right) => {
161                let mut lengths = self.set_lengths(left, position);
162                let excluded = self.set_lengths(right, position);
163                lengths.retain(|length| !excluded.contains(length));
164                lengths
165            }
166            // A negated set is a complement of *characters*: it consumes exactly one, and
167            // only when the inner set does not accept that one character.
168            ClassSet::Negated(inner) => match self.at(position) {
169                Some(c) if !self.set_lengths(inner, position).contains(&1) => {
170                    let _ = c;
171                    vec![1]
172                }
173                _ => Vec::new(),
174            },
175        }
176    }
177
178    /// Whether `member` matches the input starting at `position`.
179    fn matches_sequence(&self, member: &[char], position: usize) -> bool {
180        member
181            .iter()
182            .enumerate()
183            .all(|(index, expected)| match self.at(position + index) {
184                Some(actual) => self.chars_equal(actual, *expected),
185                None => false,
186            })
187    }
188
189    /// Whether `c` lies in a range, honouring case-insensitivity.
190    fn in_range(&self, c: char, lo: char, hi: char) -> bool {
191        self.in_class(c, &[(lo, hi)])
192    }
193
194    /// Whether `c` has a property, honouring `\P` and case-insensitivity.
195    ///
196    /// `u` and `v` disagree about *where* the negation goes under `i`, and the difference is
197    /// observable: `\P{Lower}/ui` matches `a` (the negation is applied per case variant, and
198    /// `a` canonicalises to the non-lowercase `A`), while `\P{Lower}/vi` does not (the set is
199    /// case-closed first and only then complemented, so `a` stays inside). The test suite
200    /// pins both, so the dialect decides.
201    fn property_holds(&self, kind: PropertyKind, negated: bool, c: char) -> bool {
202        let mut candidates = vec![c];
203        if self.flags.ignore_case {
204            candidates.push(self.fold(c));
205            if let Some(upper) = c.to_uppercase().next() {
206                candidates.push(upper);
207            }
208            if let Some(lower) = c.to_lowercase().next() {
209                candidates.push(lower);
210            }
211        }
212        if self.flags.unicode_sets {
213            // `v`: close over case, then negate.
214            let holds = candidates
215                .into_iter()
216                .any(|candidate| kind.holds(candidate));
217            holds != negated
218        } else {
219            // `u`: negate each variant, then ask whether any answers yes.
220            candidates
221                .into_iter()
222                .any(|candidate| kind.holds(candidate) != negated)
223        }
224    }
225
226    /// Whether `c` is in a character class's ranges.
227    ///
228    /// Case-insensitive matching has to fold *both* sides of the comparison, which
229    /// `chars_equal` does for literals. A range is not a
230    /// single character, so it is folded at its bounds: `[A-Z]` folds to `a`..`z` and
231    /// therefore matches `a`. The folded form is only used while it is still ordered —
232    /// `[A-_]` has a non-letter upper bound, and folding `A` to `a` would put the bound
233    /// *below* `_`, so the unfolded comparison stays authoritative for that range.
234    fn in_class(&self, c: char, ranges: &[(char, char)]) -> bool {
235        let folded = self.fold(c);
236        ranges.iter().any(|(lo, hi)| {
237            (*lo..=*hi).contains(&c) || (*lo..=*hi).contains(&folded) || {
238                let (folded_lo, folded_hi) = (self.fold(*lo), self.fold(*hi));
239                folded_lo <= folded_hi && (folded_lo..=folded_hi).contains(&folded)
240            }
241        })
242    }
243
244    /// Match a sequence of nodes, calling `k` at each position the whole sequence can end.
245    fn seq(
246        &self,
247        nodes: &[Node],
248        position: usize,
249        caps: &Captures,
250        k: &mut dyn FnMut(usize, &Captures) -> bool,
251    ) -> bool {
252        let Some((first, rest)) = nodes.split_first() else {
253            return k(position, caps);
254        };
255        self.node(first, position, caps, &mut |next, caps| {
256            self.seq(rest, next, caps, k)
257        })
258    }
259
260    /// Match one node, calling `k` for each position it can end at.
261    fn node(
262        &self,
263        node: &Node,
264        position: usize,
265        caps: &Captures,
266        k: &mut dyn FnMut(usize, &Captures) -> bool,
267    ) -> bool {
268        match node {
269            Node::Empty => k(position, caps),
270            Node::Char(expected) => match self.at(position) {
271                Some(actual) if self.chars_equal(actual, *expected) => k(position + 1, caps),
272                _ => false,
273            },
274            Node::Any => match self.at(position) {
275                Some(c) if self.flags.dot_all || c != '\n' => k(position + 1, caps),
276                _ => false,
277            },
278            Node::Class(negated, ranges) => match self.at(position) {
279                Some(c) if self.in_class(c, ranges) != *negated => k(position + 1, caps),
280                _ => false,
281            },
282            // A property escape outside a class. `property_holds` decides where the negation
283            // goes for the dialect in force, which is the one place `u` and `v` disagree.
284            Node::Property { kind, negated } => match self.at(position) {
285                Some(c) if self.property_holds(*kind, *negated, c) => k(position + 1, caps),
286                _ => false,
287            },
288            // A `v`-mode set may consume one character or several (`\q{BC}`), so matching it
289            // yields a *set of lengths* rather than a single one. The continuation is tried
290            // longest-first, which is the greedy reading every engine gives an alternation
291            // of literals.
292            Node::Set(set) => {
293                for length in self.set_lengths(set, position) {
294                    if k(position + length, caps) {
295                        return true;
296                    }
297                }
298                false
299            }
300            Node::Start => {
301                let at_start =
302                    position == 0 || (self.flags.multiline && self.after_newline(position));
303                if at_start { k(position, caps) } else { false }
304            }
305            Node::End => {
306                let at_end = position == self.input.len()
307                    || (self.flags.multiline && self.at_newline(position));
308                if at_end { k(position, caps) } else { false }
309            }
310            Node::WordBoundary(want) => {
311                let before = position
312                    .checked_sub(1)
313                    .and_then(|p| self.at(p))
314                    .is_some_and(is_word);
315                let after = self.at(position).is_some_and(is_word);
316                if (before != after) == *want {
317                    k(position, caps)
318                } else {
319                    false
320                }
321            }
322            Node::Group { index, node } => match index {
323                // A non-capturing group only scopes its contents.
324                None => self.node(node, position, caps, k),
325                Some(index) => {
326                    // The capture is committed only if the continuation accepts, so a
327                    // branch that later fails leaves the register untouched.
328                    self.node(node, position, caps, &mut |end, inner| {
329                        let mut inner = inner.clone();
330                        if let Some(slot) = inner.get_mut(*index) {
331                            *slot = Some((position, end));
332                        }
333                        k(end, &inner)
334                    })
335                }
336            },
337            Node::Concat(nodes) => self.seq(nodes, position, caps, k),
338            Node::Alt(branches) => {
339                for branch in branches {
340                    if self.node(branch, position, caps, k) {
341                        return true;
342                    }
343                }
344                false
345            }
346            Node::Repeat {
347                node,
348                min,
349                max,
350                greedy,
351            } => self.repeat(node, *min, *max, *greedy, 0, position, caps, k),
352            Node::Backref(index) => {
353                let Some(Some((start, end))) = caps.get(*index) else {
354                    // A backreference to a group that did not participate matches the
355                    // empty string, which is what the spec says.
356                    return k(position, caps);
357                };
358                let (start, end) = (*start, *end);
359                if end - start > self.input.len() - position {
360                    return false;
361                }
362                let ok = (0..end - start).all(|offset| {
363                    self.chars_equal(self.input[start + offset], self.input[position + offset])
364                });
365                if ok {
366                    k(position + (end - start), caps)
367                } else {
368                    false
369                }
370            }
371            Node::Look {
372                node,
373                ahead,
374                negated,
375            } => {
376                if !*ahead {
377                    // Lookbehind is rejected by the parser, so this arm is unreachable.
378                    return false;
379                }
380                // A lookahead matches the empty string: `position` does not move, and the
381                // captures it makes are kept when it succeeds.
382                let mut captured = None;
383                let found = self.node(node, position, caps, &mut |_, inner| {
384                    captured = Some(inner.clone());
385                    true
386                });
387                match (found, negated) {
388                    (true, false) => {
389                        let inner = captured.unwrap_or_else(|| caps.clone());
390                        k(position, &inner)
391                    }
392                    (true, true) => false,
393                    (false, _) => {
394                        if *negated {
395                            k(position, caps)
396                        } else {
397                            false
398                        }
399                    }
400                }
401            }
402        }
403    }
404
405    #[allow(clippy::too_many_arguments)]
406    fn repeat(
407        &self,
408        node: &Node,
409        min: u32,
410        max: Option<u32>,
411        greedy: bool,
412        count: u32,
413        position: usize,
414        caps: &Captures,
415        k: &mut dyn FnMut(usize, &Captures) -> bool,
416    ) -> bool {
417        let may_iterate = max.is_none_or(|max| count < max);
418        // Greedy tries one more iteration first; lazy tries the continuation first.
419        let try_iterate = |k: &mut dyn FnMut(usize, &Captures) -> bool| {
420            if !may_iterate {
421                return false;
422            }
423            // Every iteration starts from a clean slate for the groups inside it. Without
424            // this, a group that matched in an earlier iteration survives into one where it
425            // did not participate: `/(z)((a+)?(b+)?(c))*/.exec("zaacbbbcac")` left group 4
426            // as `bbb` from iteration two instead of resetting it to `undefined` in the
427            // final `ac`.
428            let mut entry = caps.clone();
429            if let Some((low, high)) = inner_groups(node) {
430                for slot in entry.iter_mut().take(high + 1).skip(low) {
431                    *slot = None;
432                }
433            }
434            let caps = &entry;
435            self.node(node, position, caps, &mut |end, inner| {
436                // A repeat that can match the empty string would loop forever, so an
437                // iteration that consumed nothing is not taken unless the minimum still
438                // has to be met.
439                if end == position && count >= min {
440                    return false;
441                }
442                self.repeat(node, min, max, greedy, count + 1, end, inner, k)
443            })
444        };
445        if greedy {
446            if try_iterate(k) {
447                return true;
448            }
449            if count >= min {
450                k(position, caps)
451            } else {
452                false
453            }
454        } else {
455            if count >= min && k(position, caps) {
456                return true;
457            }
458            try_iterate(k)
459        }
460    }
461
462    fn after_newline(&self, position: usize) -> bool {
463        position > 0 && self.at(position - 1) == Some('\n')
464    }
465
466    fn at_newline(&self, position: usize) -> bool {
467        self.at(position) == Some('\n')
468    }
469}
470
471/// The range of capture indices a node can fill, if it contains any group.
472fn inner_groups(node: &Node) -> Option<(usize, usize)> {
473    let mut low = usize::MAX;
474    let mut high = 0usize;
475    fn walk(node: &Node, low: &mut usize, high: &mut usize) {
476        match node {
477            Node::Group { index, node } => {
478                if let Some(index) = index {
479                    *low = (*low).min(*index);
480                    *high = (*high).max(*index);
481                }
482                walk(node, low, high);
483            }
484            Node::Concat(nodes) | Node::Alt(nodes) => {
485                for node in nodes {
486                    walk(node, low, high);
487                }
488            }
489            Node::Repeat { node, .. } | Node::Look { node, .. } => walk(node, low, high),
490            _ => {}
491        }
492    }
493    walk(node, &mut low, &mut high);
494    (low != usize::MAX).then_some((low, high))
495}
496
497/// Whether `c` is a word character, as `\b` and `\w` define it.
498fn is_word(c: char) -> bool {
499    c.is_alphanumeric() || c == '_'
500}