Skip to main content

corvus_regex_ecma262/
lib.rs

1//! Regular expressions with the grammar and the answers of ECMA-262 (the `RegExp` of JavaScript), for Rust.
2//!
3//! ```
4//! use corvus_regex_ecma262::Regex;
5//!
6//! let re = Regex::new(r"(?<word>\p{L}+)(?=!)", "gu").unwrap();
7//! let words: Result<Vec<&str>, _> = re.find_iter("Hej! Grüß dich!").map(|m| m.map(|m| m.as_str())).collect();
8//! assert_eq!(words.unwrap(), ["Hej", "dich"]);
9//! assert_eq!(re.replace("Hej! Grüß dich!", "<$<word>>").unwrap(), "<Hej>! Grüß <dich>!");
10//! ```
11//!
12//! [`Regex`] has `is_match`, `find`, `find_iter`, `captures`, `captures_iter`, `replace`, `replace_all` and
13//! `split` over `&str`, and the same over UTF-16 (`&[u16]`, which may hold lone surrogates) with the suffix `_utf16`.
14//! Positions are in the units of the text: bytes of UTF-8, or UTF-16 code units. Nothing is transcoded, and a match
15//! allocates nothing once the thread's working memory has grown to what the pattern and the text need (a
16//! [`Captures`] is a vector of its groups; [`Regex::captures_read_at`] reads them into a [`CaptureLocations`]
17//! without allocating).
18//!
19//! A pattern is read as `new RegExp(pattern, flags)` reads it: with the u flag by the grammar of the u flag and
20//! matched by code point; with none by the Annex B grammar and matched by UTF-16 code unit, as ECMA-262 matches a
21//! pattern with no u flag. The i, m and s flags are the modifiers in force at the start of the pattern, which a
22//! modifier group of ECMAScript 2025 (`(?i:...)`, `(?-m:...)`) changes for part of it.
23//!
24//! The engine came out of the Corvus JSON Schema evaluator for Rust, where it was a port of the `ecmaregex`
25//! package of the Go module, which the Object Pascal and OCaml ports carry too. The files and the names still
26//! follow the Go source, so that a fix made in one can be carried to the others: `parse.rs` is `parse.go`,
27//! `compile.rs` is `compile.go`, `vm.rs` is `vm.go`, `dfa.rs` is `dfa.go`, `charset.rs`, `fold.rs` and `units.rs`
28//! are the files of the same names, and `ucd.rs` with `tables<major>.rs` is the `ucd` package.
29//!
30//! # Code units
31//!
32//! A pattern with no u flag is matched by UTF-16 code unit. A character beyond the Basic Multilingual Plane is then
33//! two characters, a high surrogate and a low one, to the dot, a class, a quantifier, a group and a backreference. A
34//! match can start or end between the two. Such a character in the pattern is two atoms, and a class range between
35//! two of them is an error. Case is folded by the Canonicalize of a pattern with no u flag. The text stays UTF-8
36//! and no UTF-16 copy of it is made (see `units.rs`): the position between the halves of a character is the offset
37//! of its third byte. Only a text with a character beyond the Basic Multilingual Plane is read differently with the
38//! u flag and without it.
39//!
40//! # The matcher
41//!
42//! Every pattern is compiled for a backtracking matcher. A pattern with no lookaround, no backreference, no
43//! multiline anchor and no case-insensitive word boundary also gets a deterministic automaton over ASCII text when
44//! it is small enough and has no word boundary (see `dfa.rs`), which decides an ASCII text with one table read per
45//! byte.
46//!
47//! The backtracking matcher keeps its choices on an explicit stack that the thread reuses, so a long text cannot
48//! overflow the stack of the thread and a match does not allocate once the stack has grown. Four things keep it
49//! from the time a backtracking matcher can take. A repetition whose body cannot consume a character is run once,
50//! or not at all (see `simplify`), as V8 runs it. A counted loop gives up at a position from which the rest of the
51//! pattern, with the iterations the loop still owes, needs more text than is left (see `set_needs`). A way the next
52//! character of the text rules out is not taken (see `set_quick`), as in V8. And where a pattern has no
53//! backreference the matcher remembers the places from which every way has failed (see `memo` in `vm.rs`), so a
54//! repetition inside a repetition takes time proportional to the pattern times the text. What is left, a group read
55//! back inside a repetition above all, can still take time that doubles with each character, and is ended by the
56//! limit of the match.
57//!
58//! # Limits
59//!
60//! A pattern has a match timeout, as a `Regex` of `System.Text.RegularExpressions` has: the time each match may take
61//! before it is abandoned, which brings with it a cap on the memory of its backtracking. Every member that matches
62//! returns `Result`, and a match that reaches either is an [`Err`] of [`MatchError`], never an answer.
63//! [`Regex::with_timeout`] gives a pattern one, and [`set_default_match_timeout`] gives one to every pattern compiled
64//! after it. Without one (the default) a match has no limit of time or of memory, so a program that matches patterns
65//! or texts from outside should set one. The members that end in `_within` give one match a limit of its own.
66//! [`Regex::new`] refuses a pattern over a limit of size ([`MAX_PATTERN_LENGTH`], [`MAX_NESTING`], [`MAX_SIZE`])
67//! with [`Error::TooLarge`], so that reading and compiling a pattern take bounded time and memory whatever the
68//! pattern holds.
69//!
70//! # Coverage
71//!
72//! The grammar is that of ECMAScript 2025. It includes lookbehind, named groups, group names shared between
73//! separate alternatives, modifier groups, and Unicode property escapes for every property, value and alias
74//! ECMA-262 lists, with Unicode 17 data, and the v flag of ECMAScript 2024: nested classes, the difference and the
75//! intersection of classes, strings in a class (`\q{...}`) and the seven properties of strings. The properties and
76//! the case folding come from the tables of `ucd.rs`, `tables<major>.rs` and `strings<major>.rs` and never from the
77//! standard library or from a dependency, so a pattern matches the same texts whatever built the program.
78//!
79//! [`RegexBuilder`] reads a pattern with the grammar of ECMAScript 2020 ([`Edition::Es2020`]), the grammar JSON
80//! Schema 2020-12 names, and with the tables of Unicode 13, 17 or 18 ([`UnicodeVersion`]), each chosen on its own.
81//! Both are read when the pattern is compiled, so a match costs the same whichever is chosen.
82
83mod adfa;
84mod charset;
85mod compile;
86mod dfa;
87// Generated: the property names and values of the tables of ECMAScript 2020.
88#[rustfmt::skip]
89mod es2020;
90mod fold;
91mod pair8;
92mod parse;
93mod re2;
94mod regex;
95mod replace;
96mod search;
97mod simd16;
98// Generated: the properties of strings of the v flag of each version of Unicode, with the version they are from.
99#[allow(dead_code)]
100#[rustfmt::skip]
101mod strings13;
102#[allow(dead_code)]
103#[rustfmt::skip]
104mod strings17;
105#[allow(dead_code)]
106#[rustfmt::skip]
107mod strings18;
108// Generated: the Unicode tables of each version of Unicode. They have names of scripts and properties that only the
109// tests read.
110#[allow(dead_code)]
111#[rustfmt::skip]
112mod tables13;
113#[allow(dead_code)]
114#[rustfmt::skip]
115mod tables17;
116#[allow(dead_code)]
117#[rustfmt::skip]
118mod tables18;
119#[cfg(test)]
120mod tests;
121mod ucd;
122mod units;
123mod validate;
124mod vm;
125
126use std::fmt::{self, Write as _};
127use std::sync::atomic::{AtomicU64, Ordering};
128use std::time::Duration;
129
130pub use parse::{Limit, MAX_NESTING, MAX_PATTERN_LENGTH, MAX_SIZE, TooLargeError};
131pub(crate) use re2::MAX_RE2_COST;
132pub use regex::{CaptureLocations, CaptureMatches, Captures, Haystack, Match, Matches, Regex, RegexBuilder};
133pub use vm::{MAX_STACK, MatchError};
134
135/// A code point, or a UTF-16 code unit of a pattern read without the u flag. It is signed, as the `rune` of the Go
136/// source is, and -1 stands for "none".
137pub(crate) type Rune = i32;
138
139/// The match timeout every pattern compiled without one of its own takes, in nanoseconds; 0 for none.
140static DEFAULT_MATCH_TIMEOUT: AtomicU64 = AtomicU64::new(0);
141
142/// Sets the match timeout of every pattern compiled from now on by [`Regex::new`] and [`Regex::with_flags`]: the time
143/// each match may take before it is abandoned with [`MatchError::Time`], or `None` (or zero) for no limit, which is
144/// the default. It is the process-wide default of `System.Text.RegularExpressions` (`REGEX_DEFAULT_MATCH_TIMEOUT`),
145/// and a program that matches patterns or texts from outside should set it when it starts (see
146/// [`Regex::with_timeout`]). A pattern already compiled keeps the timeout it was compiled with.
147///
148/// ```
149/// use std::time::Duration;
150/// use corvus_regex_ecma262::{Regex, default_match_timeout, set_default_match_timeout};
151///
152/// set_default_match_timeout(Some(Duration::from_secs(1)));
153/// assert_eq!(Regex::new("a+", "").unwrap().match_timeout(), Some(Duration::from_secs(1)));
154/// set_default_match_timeout(None);
155/// assert_eq!(default_match_timeout(), None);
156/// ```
157pub fn set_default_match_timeout(timeout: Option<Duration>) {
158    let nanos = timeout.map_or(0, |t| u64::try_from(t.as_nanos()).unwrap_or(u64::MAX));
159    DEFAULT_MATCH_TIMEOUT.store(nanos, Ordering::Relaxed);
160}
161
162/// The match timeout a pattern compiled now by [`Regex::new`] takes (see [`set_default_match_timeout`]).
163pub fn default_match_timeout() -> Option<Duration> {
164    match DEFAULT_MATCH_TIMEOUT.load(Ordering::Relaxed) {
165        0 => None,
166        nanos => Some(Duration::from_nanos(nanos)),
167    }
168}
169
170/// Why a pattern does not compile.
171#[derive(Clone, Debug, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum Error {
174    /// The pattern is over a limit of size. It was not read to its end, so nothing is known of whether it is valid.
175    TooLarge(TooLargeError),
176    /// The pattern is not valid in the grammar of its flags (the `SyntaxError` of `new RegExp`).
177    Invalid(String),
178    /// The flags are not valid: a letter that is not a flag, a flag given twice, or `u` with `v`.
179    Flags(String),
180}
181
182impl fmt::Display for Error {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        match self {
185            Error::TooLarge(e) => e.fmt(f),
186            Error::Invalid(message) | Error::Flags(message) => f.write_str(message),
187        }
188    }
189}
190
191impl std::error::Error for Error {}
192
193/// What reading a pattern tells of it, without compiling it.
194#[derive(Clone, Copy, Debug)]
195pub(crate) struct Facts {
196    /// The pattern is valid with the u flag. When it is not, it was read with the Annex B grammar.
197    #[cfg_attr(not(test), allow(dead_code))]
198    pub(crate) unicode: bool,
199    /// The pattern has a construct only the backtracking matcher can run.
200    pub(crate) needs_backtracking: bool,
201    /// The size the parser counted for the pattern (see [`MAX_SIZE`]).
202    #[cfg_attr(not(test), allow(dead_code))]
203    pub(crate) size: usize,
204    /// The number of instructions estimated for the program a linear matcher compiles for the pattern, which stops
205    /// counting above [`MAX_RE2_COST`].
206    pub(crate) re2_cost: i64,
207}
208
209fn invalid(pattern: &str, msg: &str, pos: usize) -> Error {
210    Error::Invalid(format!("ecmaregex: {msg} at offset {pos} in {pattern:?}"))
211}
212
213/// Reads a pattern with the u flag grammar and, when that refuses it, with the Annex B grammar.
214#[cfg(test)]
215fn read(pattern: &str) -> Result<(parse::Node, Facts, parse::Parser), Error> {
216    let (root, ps, unicode) = match parse::parse(pattern, true) {
217        Ok((root, ps)) => (root, ps, true),
218        Err(parse::ParseError::TooLarge(large)) => return Err(Error::TooLarge(large)),
219        Err(parse::ParseError::Syntax(msg, pos)) => match parse::parse(pattern, false) {
220            Ok((root, ps)) => (root, ps, false),
221            Err(parse::ParseError::TooLarge(large)) => return Err(Error::TooLarge(large)),
222            Err(parse::ParseError::Syntax(..)) => return Err(invalid(pattern, msg, pos)),
223        },
224    };
225    let facts =
226        Facts { unicode, needs_backtracking: ps.needs_backtracking, size: ps.size, re2_cost: re2::re2_cost(&root) };
227    Ok((root, facts, ps))
228}
229
230/// The number of groups (and with the v flag, classes) a pattern may open and still be read on the stack of the
231/// thread that asks.
232const SHALLOW: usize = 32;
233
234/// The stack of the thread that reads a pattern with more groups than that. The parser, the compiler and the
235/// dropping of the syntax tree go one level deeper for each level of groups, and [`MAX_NESTING`] allows a thousand
236/// levels, which is more than the stack of a thread can be relied on to hold: a thread of a language runtime that
237/// embeds the crate may have a few hundred kilobytes. Only the pages the work touches are used.
238const DEEP_STACK: usize = 64 << 20;
239
240/// Runs the reading of a pattern, with everything that walks its syntax tree, where the depth of the tree cannot
241/// overflow the stack. A pattern that opens few groups is shallow, and is read where it is. Any other is read on a
242/// thread of its own with a stack for the deepest nesting the limits allow. (Go grows the stack of a goroutine as
243/// it is needed, so the Go engine has no such step.) `None` when that thread could not be started.
244pub(crate) fn on_a_deep_stack<T: Send>(
245    pattern: &str,
246    unicode_sets: bool,
247    work: impl FnOnce() -> T + Send,
248) -> Option<T> {
249    if shallow(pattern, unicode_sets) {
250        return Some(work());
251    }
252    deep(work)
253}
254
255/// Runs work that goes a level deeper for each level of groups of a pattern on a thread with a stack for the
256/// deepest nesting the limits allow. `None` when the thread could not be started.
257pub(crate) fn deep<T: Send>(work: impl FnOnce() -> T + Send) -> Option<T> {
258    std::thread::scope(|scope| {
259        let thread = std::thread::Builder::new().stack_size(DEEP_STACK).spawn_scoped(scope, work).ok()?;
260        match thread.join() {
261            Ok(result) => Some(result),
262            Err(panic) => std::panic::resume_unwind(panic),
263        }
264    })
265}
266
267/// Whether a pattern opens few enough groups to be read on the stack of the thread that asks. With the v flag a class
268/// may hold a class, and the parser goes a level deeper for each, as it does for a group, so there a `[` counts as a
269/// `(` does. In the other grammars a class holds no class and a `[` opens no level: counting it would send a pattern
270/// of many classes to a thread of its own for nothing, at some times the cost of compiling it, and refuse it where no
271/// thread can be started.
272pub(crate) fn shallow(pattern: &str, unicode_sets: bool) -> bool {
273    pattern.bytes().filter(|&b| b == b'(' || (unicode_sets && b == b'[')).count() <= SHALLOW
274}
275
276/// The error of a pattern that nests deeply when no thread could be started to read it: the pattern is refused as
277/// one over the limit of nesting, which is the limit the thread is there to serve.
278pub(crate) const NO_DEEP_STACK: Error = Error::TooLarge(TooLargeError { limit: Limit::Nesting, value: MAX_NESTING });
279
280/// The edition of ECMA-262 whose grammar a pattern is read with.
281#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
282#[non_exhaustive]
283pub enum Edition {
284    /// Today's grammar, ECMAScript 2025: the default.
285    #[default]
286    Current,
287    /// The grammar of ECMAScript 2020 (ECMA-262, 11th edition), which JSON Schema 2020-12 names. It refuses what later
288    /// editions added, and nothing else: the `d` and `v` flags, modifier groups such as `(?i:...)`, a group name used
289    /// by two groups, and a property name or value that is not in the edition's tables. A pattern it accepts has the
290    /// same answers as in today's grammar, under the same version of Unicode.
291    Es2020,
292}
293
294/// The version of Unicode whose character database a pattern is read with: the members of each `\p{...}`, the
295/// characters of a group name, and the case folding of the `i` flag. It is independent of the [`Edition`].
296#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
297#[non_exhaustive]
298pub enum UnicodeVersion {
299    /// The version of the V8 the answers are held to, Unicode 17 today. It moves when that V8 moves.
300    #[default]
301    Default,
302    /// Unicode 13.0, the version of the year of ECMAScript 2020.
303    V13,
304    /// Unicode 17.0.
305    V17,
306    /// Unicode 18.0.
307    V18,
308    /// The latest version the crate carries, Unicode 18 today. It moves when a later version is added.
309    Latest,
310}
311
312impl UnicodeVersion {
313    /// The version this one stands for: [`Default`](UnicodeVersion::Default) is V8's (17) and
314    /// [`Latest`](UnicodeVersion::Latest) the newest the crate carries (18). Any other is itself.
315    pub fn resolve(self) -> UnicodeVersion {
316        match self {
317            UnicodeVersion::Default => UnicodeVersion::V17,
318            UnicodeVersion::Latest => UnicodeVersion::V18,
319            other => other,
320        }
321    }
322
323    /// The major number of the version, resolved: 13, 17 or 18.
324    pub fn major(self) -> u32 {
325        match self.resolve() {
326            UnicodeVersion::V13 => 13,
327            UnicodeVersion::V18 => 18,
328            _ => 17,
329        }
330    }
331}
332
333/// The flags of a pattern, as `new RegExp(pattern, flags)` takes them.
334#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
335pub struct Flags {
336    /// `d`: accepted for completeness. The positions of the groups are always kept, so it changes nothing.
337    pub has_indices: bool,
338    /// `g`: [`Regex::replace`] replaces every match rather than the first.
339    pub global: bool,
340    /// `i`: case is ignored, by the Canonicalize of the mode in force.
341    pub ignore_case: bool,
342    /// `m`: `^` and `$` hold at line terminators.
343    pub multiline: bool,
344    /// `s`: the dot matches line terminators.
345    pub dot_all: bool,
346    /// `u`: the grammar of the u flag, and matching by code point.
347    pub unicode: bool,
348    /// `v`: the grammar of the v flag (set notation and properties of strings), and matching by code point.
349    pub unicode_sets: bool,
350    /// `y`: a match only at the position the search starts from.
351    pub sticky: bool,
352}
353
354impl Flags {
355    /// Reads the flags as `new RegExp` does: each of the letters `dgimsuvy` at most once, and not `u` with `v`.
356    pub fn parse(flags: &str) -> Result<Flags, Error> {
357        let mut f = Flags::default();
358        for c in flags.chars() {
359            let flag = match c {
360                'd' => &mut f.has_indices,
361                'g' => &mut f.global,
362                'i' => &mut f.ignore_case,
363                'm' => &mut f.multiline,
364                's' => &mut f.dot_all,
365                'u' => &mut f.unicode,
366                'v' => &mut f.unicode_sets,
367                'y' => &mut f.sticky,
368                _ => return Err(Error::Flags(format!("invalid flag {c:?} in {flags:?}"))),
369            };
370            if *flag {
371                return Err(Error::Flags(format!("the flag {c:?} is given twice in {flags:?}")));
372            }
373            *flag = true;
374        }
375        if f.unicode && f.unicode_sets {
376            return Err(Error::Flags(format!("the flags u and v are given together in {flags:?}")));
377        }
378        Ok(f)
379    }
380
381    pub(crate) fn syntax(&self) -> parse::Syntax {
382        parse::Syntax {
383            unicode: self.unicode || self.unicode_sets,
384            sets: self.unicode_sets,
385            icase: self.ignore_case,
386            multiline: self.multiline,
387            dot_all: self.dot_all,
388            edition: Edition::Current,
389            unicode_version: UnicodeVersion::Default,
390        }
391    }
392}
393
394impl fmt::Display for Flags {
395    /// The flags as `RegExp.prototype.flags` writes them, in the order `dgimsuvy`.
396    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
397        for (on, c) in [
398            (self.has_indices, 'd'),
399            (self.global, 'g'),
400            (self.ignore_case, 'i'),
401            (self.multiline, 'm'),
402            (self.dot_all, 's'),
403            (self.unicode, 'u'),
404            (self.unicode_sets, 'v'),
405            (self.sticky, 'y'),
406        ] {
407            if on {
408                f.write_char(c)?;
409            }
410        }
411        Ok(())
412    }
413}
414
415/// Reads a pattern with one grammar.
416pub(crate) fn read_with(pattern: &str, syntax: parse::Syntax) -> Result<(parse::Node, Facts, parse::Parser), Error> {
417    let (root, ps) = match parse::parse_with(pattern, syntax) {
418        Ok(read) => read,
419        Err(parse::ParseError::TooLarge(large)) => return Err(Error::TooLarge(large)),
420        Err(parse::ParseError::Syntax(msg, pos)) => return Err(invalid(pattern, msg, pos)),
421    };
422    let facts = Facts {
423        unicode: syntax.unicode,
424        needs_backtracking: ps.needs_backtracking,
425        size: ps.size,
426        re2_cost: re2::re2_cost(&root),
427    };
428    Ok((root, facts, ps))
429}
430
431/// Compiles a pattern as JSON Schema reads one, which is what the tests of the engine's first home ask of it: with
432/// the u flag grammar, and when that refuses it, with the Annex B grammar.
433#[cfg(test)]
434pub(crate) fn compile(pattern: &str) -> Result<Regex, Error> {
435    on_a_deep_stack(pattern, false, || {
436        let (root, facts, ps) = read(pattern)?;
437        let flags = Flags { unicode: facts.unicode, ..Flags::default() };
438        Ok(Regex::from_tree(pattern, flags, None, flags.syntax(), root, facts, &ps))
439    })
440    .unwrap_or(Err(NO_DEEP_STACK))
441}
442
443/// Reports whether the pattern is a valid ECMA-262 pattern with the u flag. A pattern over a limit of size is not
444/// read to its end and is reported as not valid.
445#[cfg(test)]
446pub(crate) fn valid(pattern: &str) -> bool {
447    on_a_deep_stack(pattern, false, || parse::parse(pattern, true).is_ok()).unwrap_or(false)
448}
449
450/// Reads the pattern without compiling it, as [`compile`] reads it.
451#[cfg(test)]
452pub(crate) fn check(pattern: &str) -> Result<Facts, Error> {
453    on_a_deep_stack(pattern, false, || read(pattern).map(|(_, facts, _)| facts)).unwrap_or(Err(NO_DEEP_STACK))
454}
455
456/// The examples of the README, run as tests.
457#[cfg(doctest)]
458#[doc = include_str!("../README.md")]
459struct ReadmeExamples;
460
461/// The examples of the getting-started page the documentation site publishes (docs/getting-started.md), run as tests.
462#[cfg(doctest)]
463#[doc = include_str!("../../docs/getting-started.md")]
464struct GettingStartedExamples;