WEP: Re — Linear-Time Regular Expressions for Wado
Context
Wado has no regular expressions. Code that needs one hand-writes a scanner, and
WEP: Jade listed the JSON Schema pattern keyword
as a known gap for want of an engine. JSON Schema defines pattern as an
ECMA-262 regular expression, so whatever Wado offers should read that syntax.
Compiling Rust's regex crate to Wasm and importing it as a component was the
first idea. It costs too much at the boundary. Each call lowers the subject
String into the other component's linear memory, and each match lifts its
offsets back. A regular expression is typically called many times on short
input, so this fixed cost dominates. The component also carries its own Unicode
tables, which dead-code elimination cannot reach. An engine written in Wado
reads the subject where it lies in the GC heap, returns a StrSlice over it,
and keeps only the code a program uses.
A backtracking engine, as in Perl, PCRE and every JavaScript engine, takes
exponential time on some patterns (ReDoS). A wasi:http service matching a
pattern against request data cannot afford that. RE2 and Rust's regex show
the alternative: give up the features that need backtracking, and match in time
linear in the input.
Decision
Re is a package
Re is wado-lang:re, in package-re/. Nothing of it is in the standard
library or the compiler.
Rust keeps regex out of std, and its reasons were weighed one by one:
| Rust's reason | For Wado |
|---|---|
std is stable forever, and regex 1.x still needed a rewrite of its internals (regex-automata, 2023) |
Applies: the API and its semantics are not settled |
| The design space is wide: backtracking or linear time, Unicode by default or not | Settled here, by the sections below |
Cargo makes a crate as easy to reach as std |
Applies: a package is one [dependencies] entry |
| The Unicode tables cost binary size and compile time | Applies in part: core:icu holds the tables, but a pattern read at run time may name any property or turn on i, so a program that builds one carries them |
A package costs one thing: no module of the standard library can depend on it.
So Re moves to core:re once the standard library
itself needs a regular expression, or once its API settles. The move changes
only the import path.
The syntax is ECMA-262's, in Unicode mode, without backtracking
A pattern is an ECMA-262 Pattern (§22.2.1), read as the u flag reads it.
That is the strict grammar, without the Annex B extensions, and it matches code
points rather than UTF-16 code units. The specification is the source of the
rules; no implementation is.
The pattern supports:
- alternation, groups, non-capturing groups and named groups
(?<name>…); - greedy and lazy quantifiers,
{n,m}included; - character classes,
.,\d\w\sand their negations, and\b\B; \p{…}and\P{…}, with the property data fromcore:icu;- the anchors
^and$; - the modifiers
(?ims-ims:…)of ES2025, which scopei,mandsto a group. They are how a pattern sets a flag, since a tag takes no flag argument. Underieach character and class compiles to what folds as its members do, throughcore:icu's simple case folding (Simple Case Mapping), so matching folds nothing. A negated class compiles to the rest:[^a]matches neitheranorA.
\p{…} reads its properties from core:icu, at the Unicode version
core:icu carries, and accepts every property and value it knows. So it may
accept a name ECMA-262's tables do not list, and a character may have a
property here that it lacks in a JavaScript engine of another Unicode version.
Re does not narrow core:icu to match ECMA-262 or any engine. A conformance
test that turns on the Unicode version is measured against core:icu's data.
ECMA-262's own Any, ASCII and Assigned are no Unicode property, so Re
defines them as ECMA-262 does.
Backreferences (\1, \k<name>) and lookaround ((?= (?! (?<= (?<!)
are rejected. No linear-time engine can run them. The error names the construct
and says so, instead of reporting a syntax error.
The parser still reads them, as it reads the other constructs ECMA-262 admits
and Re refuses (see Known gaps), under all of ECMA-262's early errors. So a syntax
error anywhere in a pattern is reported before what Re refuses.
validate_ecma262_syntax(pattern) stops at the syntax: it accepts every
Pattern the u flag reads, including those Re cannot match. JSON Schema's
regex format asks this of a validator. Two of Re's own rules still apply
there: the bound on nesting below, and \p{…} reading core:icu.
Groups nest at most 256 deep, as Rust's regex bounds its nesting, so a
pattern read at run time cannot exhaust the stack. For the same reason a
pattern compiles to at most 1,000,000 instructions, since a count expands its
atom ((?:a{1000}){1000}). An instruction inside a repetition whose atom can
match empty counts once more for each such repetition around it, since the
Pike VM tracks a thread there by how many of them it entered at the current
position. The #[param] re.max_program raises or lowers that bound. The
error names no byte, so its offset is 0.
Every other rule follows ECMA-262, the surprising ones included. \d is ASCII,
and so are \w and \b except under i. Under i, two characters match when
their simple case foldings are equal (Canonicalize, §22.2.2.7.3), so \w also
matches U+017F and U+212A, which fold to s and k, and \b counts them as
word characters (WordCharacters, §22.2.2.9.3). . and the m-mode anchors treat
\n, \r, U+2028 and U+2029 as line terminators. When alternatives compete,
the leftmost match wins, and within it the priority ECMA-262 gives the
alternatives and quantifiers. This is the leftmost-first rule that Perl and
JavaScript share, not POSIX's leftmost-longest.
Matching takes linear time
A match takes O(m × n) steps for a pattern of size m and an input of n bytes,
for every pattern and every input. A step that records a position copies the
thread's slots: two per group, and one per repetition of a body that can match
empty. With s slots a match takes O(m × s × n) time in the worst case, still
linear in the input. A Pike VM, simulating the NFA one input
position at a time, guarantees this and reports captures. A lazy DFA, built
state by state as the input reaches it, answers is_match and the bounds of a
match faster, and the Pike VM then runs only over the span the DFA found.
The bounds take two DFAs. One over the program finds where the leftmost-first match ends: each of its states is the Pike VM's ordered thread list, so it prefers what the Pike VM prefers. One over the reversed program then scans back from that end for the leftmost start, and is skipped where every match of the program spans as many bytes. A DFA holds a bounded number of transitions, and its states a bounded number of threads between them: a counted repetition makes few states, each of many threads. A pattern that would pass either bound makes it give up and be dropped, and the Pike VM answers for that expression from then on, so no search costs more than linear time.
Over a short span the groups are read by a backtracker instead of the Pike VM. It runs the same threads one at a time, the preferred first, and marks each state at each position so that none runs twice. That keeps it linear in the span, with one set of slots where the Pike VM copies one for each thread.
The DFAs of an expression belong to it and to every copy of it: a search writes the states it reaches where the next search finds them. They are no part of what the expression is: two that compile alike are equal, hash alike and print alike whichever has searched.
The tree a pattern parses to holds code points, since ECMA-262 states its rules
over them. Compiling it turns each character class into the UTF-8 byte
sequences of its code points, so both engines step over the text's bytes and
decode nothing. A DFA's transition table is 256 entries wide, a literal
prefilter searches bytes, and an offset needs no conversion. An assertion
(\b, ^ and $ under m) decodes the characters around its position, and
only there.
The text is UTF-8, and offsets are bytes
The subject is any AsStrSlice, and a match is a StrSlice over it, so
neither copies. Offsets count bytes, as every offset in a Wado string does.
This departs from ECMA-262's UTF-16 indices (lastIndex, match.index), which
only a JavaScript host would want.
A pattern may still name a lone surrogate (\uD800), as ECMA-262 allows. No
UTF-8 text holds one, so that atom never matches.
Two tags, re and rex, and a constructor
re takes the pattern as written. rex is Perl's /x: outside a character
class, whitespace (Pattern_White_Space, the set Perl ignores) is ignored and # starts a comment that runs to the end of
the line. A literal space or # is written in a class ([ ], [#]) or
escaped (\ , \#). The other escapes mean what they mean in re. rex is
the only place Re extends ECMA-262.
Both tags read the template's text (lit(&t)), and a pattern is written as a
raw template, re#`…`#, so each
backslash reaches the pattern as written. In a cooked template the lexer reads
the escapes first: \d is an error there, and \b a backspace.
Regex::new(pattern) builds a regular expression at run time and reports a
malformed pattern as an Err. The tags build theirs the same way and panic on
one, since a literal pattern that does not parse is a bug in the program.
use { re, rex, Regex } from "lib:re";
global DATE: Regex = re#`(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})`#;
global FLOAT: Regex = rex#`
^ [+-]?
( \d+ (\.\d*)? | \.\d+ ) # mantissa
( [eE] [+-]? \d+ )? # exponent
$
`#;
let user_pattern = Regex::new(input)?;
A global builds its regular expression once, on first read.
Raw literals
A cooked template rejects an escape the lexer does not know, so re`\d+` is
an error (invalid escape sequence: \d), and so is `C:\Users`.
Raw literals were added to the language for this, in two forms. A raw template,
#`…`#, takes every backslash as itself, and a hole still opens at ${. A
raw string, #"…"#, opens no hole, so a pattern assembled at run time is
written without escaping a $: Regex::new(`${prefix}${#"\d+$"#}`). A
raw byte string, b#"…"#, completes the set. The lexer keeps each literal's
text as written along with its # count, and decoding it to a value reads the
count: a raw literal's value is its text. A tag reads a raw template like any
template, with raw(&t) equal to lit(&t), and the formatter prints the text
it was given.
The delimiter is # with no prefix, as in Swift. #` and #" were syntax
errors before, and Wado has no macros, so no existing token sequence changes
meaning, which is what Rust's r prefix guards. The closer repeats the
opener's # count, which Wado.g4 keeps on a lexer member and checks in a
predicate, so the grammar Gale builds lexes the same counts the compiler does.
Two other designs were weighed and refused. An attribute marking a tag that reads only raw text, which the tagged-template WEP rules out (no marker, no inspection of the tag). And a check deferred until the tag reads the cooked text, which would make whether a literal lexes depend on the tag's body.
A hole is a literal, unless it is a Regex
A hole holding text matches that text literally, as if it went through Perl's
\Q…\E. A hole holding a Regex is spliced in as a non-capturing group. Its
own groups keep capturing, numbered by where their opening parentheses fall in
the combined pattern. A hole's type implements PatternPart, which Re
implements for String, StrSlice, char and Regex.
Two groups in the combined pattern may not share a name, whichever parts they came from, as ECMA-262 rejects two in one pattern. The tag panics on such a pair, naming the group, like any other malformed pattern.
A hole stands only where an atom may, so a quantifier after it repeats the
whole hole. One inside a class, an escape, a count, a group's opening or a
rex comment is a malformed pattern. A Regex hole keeps the meaning it had
alone: the modifiers enclosing the hole do not reach into it.
A hole's specifier binds whatever the tag does with it, so a ${r} hole needs
Display on Regex. Its Display prints the parsed tree in re's syntax,
which Regex::new reads back to the same regular expression. A text hole is
escaped, and a Regex hole is the group (?-ims:…). rex's whitespace and
comments are gone, so a pattern from either tag, or one combining both, shows
what it matches.
let word = re#`\w+`#;
let greeting = re#`^${prefix}: ${word}$`#; // `prefix` matches as plain text
Perl interpolates text as pattern syntax. Re does not, so that text from a user
cannot inject syntax. A program that means to build a pattern from text says
so with Regex::new.
A template with holes builds a new regular expression each time it is evaluated. Only a hole-less template is constant.
The API
impl Regex {
pub fn new<S: AsStrSlice>(pattern: S) -> Result<Regex, PatternError>;
pub fn is_match<S: AsStrSlice>(&self, text: S) -> bool;
pub fn find<S: AsStrSlice>(&self, text: S) -> Option<Match>;
pub fn find_at<S: AsStrSlice>(&self, text: S, start: i32) -> Option<Match>;
pub fn find_iter<S: AsStrSlice>(&self, text: S) -> Matches;
pub fn captures<S: AsStrSlice>(&self, text: S) -> Option<Captures>;
pub fn captures_at<S: AsStrSlice>(&self, text: S, start: i32) -> Option<Captures>;
pub fn captures_iter<S: AsStrSlice>(&self, text: S) -> CaptureMatches;
pub fn replace<S: AsStrSlice, R: Replacer>(&self, text: S, replacer: R) -> String;
pub fn replace_all<S: AsStrSlice, R: Replacer>(&self, text: S, replacer: R) -> String;
pub fn split<S: AsStrSlice>(&self, text: S) -> Split;
pub fn splitn<S: AsStrSlice>(&self, text: S, n: i32) -> Split;
}
pub fn validate_ecma262_syntax<S: AsStrSlice>(pattern: S) -> Result<(), PatternError>;
Only the pattern syntax is ECMA-262's. The API is designed for Wado and does
not follow RegExp or String.prototype, so a design mistake there is not
inherited. Where a method below shares a name with one of theirs, the
definition here is what holds.
A Match answers start(), end() and as_str(). Captures is indexed by
number (caps[1]) and by name (caps["y"]), each an Option<Match>.
find_iter finds each match left to right. After an empty match it resumes one
character on. It skips an empty match where the previous match ended, so a*
finds "", "aaa" and "" in "baaac", and replace_all with - gives
-b-c-. String.prototype.matchAll reports a second "" before the c, and
replace there gives -b--c-. captures_iter, replace_all and split see
the matches find_iter finds.
find_at and captures_at search from the byte offset start, which must lie
on a character boundary. The text before it still counts as context, so ^
matches only where it would in the whole text, and \b reads the character
before start.
Replacer is what replace writes in place of each match. Re implements it for
a String or StrSlice, which reads $1, $<name>, $& and $$ as
ECMA-262's GetSubstitution does, and for fn(&Captures) -> String, whose
result is inserted as it is.
split yields the pieces of the text around each match, each a StrSlice.
There is one more piece than there are matches, so the pieces and the matches
between them spell the text again. That one rule leaves no special case:
- an empty text yields
[""], or["", ""]where the pattern matches""; - a match at either end yields an empty piece there, which a caller filters out when it does not want one;
- no captured group is yielded, so every item is a piece;
captures_iterreaches the groups.
String.prototype.split breaks each of these. It cuts no empty match at the
end of the text or where a piece just ended, yields no piece for an empty text
that matches, and mixes captured groups in among the pieces.
splitn yields at most n pieces, the last holding the rest of the text with
its matches. Its limit counterpart in String.prototype.split drops the rest
instead.
No Kiln generator
A Kiln generator could lower a pattern to Wado code at build time. It is not offered. It would need the pattern in a file of its own, and it could not build a pattern at run time, so it would be a second API beside the one above.
Compiling a constant pattern ahead of time is the compiler's job instead.
re is a pure function, so a hole-less re#`…`# is a call with constant
arguments. niri can fold that call
(WEP: NIR Interpreter), and the
automaton it produces can become a constant global
(WEP: Constant Object Globalization).
A pattern that does not fold is a missed optimization in the compiler, not a
reason to change Re.
Roadmap
- [x] Raw literals,
#`…`#,#"…"#andb#"…"#: the compiler's lexer, the formatter, the TextMate grammar andWado.g4, with the rules inspec-literals.md. - [x] Vendor the ECMA-262 specification (
tc39/ecma262) and test262's RegExp tests undervendor/. The parser's rules cite the first, and the second is the conformance corpus. - [x] The parser: a
Patternto an AST,rex's whitespace and comments, errors that point at the offending character, and the errors that name a rejected backreference or lookaround. - [x] The Pike VM, behind the whole API. A differential test runs each pattern
through Node's
RegExpwith theuflag, a black-box oracle, and maps its UTF-16 indices to byte offsets. Its patterns and inputs are written by hand, and also collected by running test262's RegExp tests in Node and recording every search they make. test262's parse-phase negative tests hold the parser to its rejections, and the patterns those tests run that Re refuses holdvalidate_ecma262_syntaxto accepting them. - [x] The tags
reandrex, with holes. - [x] Jade's
patternkeyword matches with Re, which closes that known gap. - [x] The lazy DFA, behind
is_matchandfind, with the Pike VM confined to the span the DFA found. A fuel benchmark measures the gain:package-re/benchmark/, which also times Re against Node'sRegExp. - [ ] A literal prefilter on
core:simd, which skips to where a pattern's required literal occurs.
Known gaps
- The
vflag's syntax: set operations in a class ([\p{L}--[a-z]]) and string properties. - Lookaround and backreferences, even in the forms that linear time could admit.
- A malformed literal pattern panics when the program runs, not when it compiles.
- No offsets in UTF-16 code units for a host that speaks JavaScript.
- A whole-pattern flag
(?i)at the start of a pattern. ECMA-262 has only the scoped form. - Duplicate group names in different alternatives (ES2025).
- Matching bytes: no
Regexsearches aByteListor text that is not UTF-8. - A match anchored at a given offset, as ECMA-262's
yflag gives:find_atfinds the leftmost match at or afterstart. - A
Replacerclosure that performs effects. - The DFA resolves
^and$outsidemand no other assertion: a pattern with\b,\B, or^or$undermis matched by the Pike VM alone. - A
Regexreaches the DFAs its searches write, so acontractclause that calls a method of a value holding one is rejected as reaching state it may mutate. - CI does not hold Re's fuel to a baseline:
benchmark/fuel.jsonrecords the benchmarks underbenchmark/only. - A repetition count above 4294967295, which ECMA-262 accepts.
