Repository navigation
lexer,types,lib: keep the regexp dot operator independent of anchoring, add the m flag - #526
Merged
Merged
Conversation
jow-
force-pushed
the
regexp-runtime-preprocess
branch
2 times, most recently
from
November 26, 2026 10:09
3c2aac4 to
46ce5ad
Compare
Since 8a8b4d1 ("types: fix regexp `/.../s` flag inversion") the dot has been kept from matching newlines by compiling with REG_NEWLINE. That option affects more than the dot operator: it also turns ^ and $ into line anchors and excludes newlines from negated bracket expressions. Anchored patterns therefore no longer describe the whole subject: match("abc\ndef", /^[a-z]+$/); // [ "abc" ] Any validation against an anchored pattern accepts a value as soon as one of its lines matches. A WireGuard key check such as /^[A-Za-z0-9+/]{43}=$/ accepts a key containing an embedded newline, so the remainder of the value is interpreted as further configuration. Compile without REG_NEWLINE and express the flags in the pattern instead: rewrite `.` to [^\n] unless s is given, and leave ^ and $ unchanged. Both glibc and musl make `.` match any character when REG_NEWLINE is unset, so the dot is the only atom that has to be rewritten. Rewriting requires parsing the pattern, and the pattern was already parsed twice, differently: the lexer decoded escape sequences, expanded the \d, \w, \s macros and tracked bracket expressions while searching for the closing slash, while a pattern given to regexp() reached regcomp() unchanged. POSIX makes a backslash inside a bracket expression an ordinary member and both engines follow, so the two paths described different patterns: /[\d]/ the list of `d` regexp("[\\d]") the list of `\` and `d` /[a\-z]/ the range a-z regexp("[a\\-z]") a list of `-`, `\`, `z` regexp("\\d") no macro expansion Preprocess the pattern once instead, in types.c, where it is compiled. The lexer keeps the pattern verbatim and scans only far enough to find the closing slash and the flags, so both paths run through the same code and cannot diverge. A single state machine, shared through include/ucode/internal/regexp.h, determines where a bracket expression ends, so the lexer and the preprocessor cannot disagree about where the literal ends. A bracket expression cannot be passed to the engines as written. It is parsed into members, ranges and elements and written back with each member where the engines read a member: `]` first, `-`, `\`, `[` and `^` last, and `-` last of all so that it cannot pair with what precedes it either. Ranges keep their endpoints, so a quoted range does not become a list and a quoted member does not become a range. Patterns that were previously ambiguous change meaning, every change in the stricter direction: /[a\-z]/ is the list `a`, `-`, `z` rather than the range a-z, which is the reading that matters for input validation, and /[a\]b]/ is the list `a`, `]`, `b` rather than `a` followed by the text `b]`. An escape denotes a character, never an atom of the pattern, so the bytes it denotes are emitted quoted: \u002e is a full stop rather than the dot operator, \u0028 a bracket rather than a capture group. This also keeps the number of groups in the emitted pattern predictable, which the m flag relies on. A bracket expression the pattern does not close is rejected ("Unmatched [ or [^") rather than passed to the engine, which closes it at a quoted `]` and compiles a different pattern. Escapes denoting NUL are rejected: the pattern is a C string, so a NUL byte truncates it rather than denoting itself, and neither engine can match a NUL byte in a subject - musl provides no REG_STARTEND and treats NUL as the end of the string, glibc provides REG_STARTEND but no \x00 escape. An unpaired surrogate denotes U+FFFD at the position of the escape itself. Converting a regexp back to a string yields the pattern as written rather than the pattern passed to regcomp(). Reported-by: Guy Godfroy <guy.godfroy@gugod.fr> Fixes: 8a8b4d1 ("types: fix regexp `/.../s` flag inversion") Signed-off-by: Jo-Philipp Wich <jo@mein.io>
jow-
force-pushed
the
regexp-runtime-preprocess
branch
2 times, most recently
from
November 26, 2026 10:59
b9a5e52 to
ffc7d50
Compare
Without REG_NEWLINE there is no way to match line by line, since ^ and $ now always anchor at the whole subject. Add the JavaScript m flag, which compiles with REG_NEWLINE. REG_NEWLINE has unintended side effects: it also excludes newlines from negated bracket expressions, which would make /[^a]/m stop matching line breaks. Such an expression is wrapped in an alternative against one, ([^a]|\n), unless it already covers a newline. The wrapper is a capture group, so the compiled pattern holds a group the script never wrote. A per-regexp map from visible group to compiled group preserves the numbering of the pattern as written; it is built at compile time and adds no per-match cost. The map requires no second pass over the pattern: the preprocessor already counts the groups of the pattern it emits, because it quotes the bytes an escape denotes - an escape cannot open a group - and records every group it inserts itself. If regcomp() reports a different count, the pattern is prepared again without the wrapper: the negated expression no longer matches a newline, but the group numbering and the flags the script requested are preserved. Under m alone `.` still does not match newlines, as in JavaScript; it does so only when s is given as well. \d, \D, \w, \W, \s and \S expand to bracket expressions and pass through the same normalization, so they are rewritten under m as well. Line boundaries are those of the engine, and REG_NEWLINE recognizes the newline only: a preceding carriage return is an ordinary character, and the Unicode line and paragraph separators are not line breaks. JavaScript breaks lines at all of them, which REG_NEWLINE cannot provide. API: ucv_regexp_new() keeps its signature and delegates to the new ucv_regexp_new_ex(), which takes the flag bitmask the lexer already encodes. Matching goes through the new ucv_regexp_exec(), which permutes the visible groups to the front of the caller's match array; ucv_regexp_nmatch() reports how many entries that array requires, a compiled pattern holding more groups than the script wrote. Callers that only need the whole match pass 1 and require no mapping. Signed-off-by: Jo-Philipp Wich <jo@mein.io>
On an empty match, replace() consumed the first character of the current
search window instead of the character at the match position, and advanced a
single byte instead of to the match position plus one. The first character of
the window was therefore emitted twice:
replace("a\nb\nc", /^/gm, "|"); // "|a\n|\nb\n|c"
// expected "|a\n|b\n|c"
split() advanced an empty match by a single character from the start of the
window as well, which truncated the piece preceding the following match:
split("abc", /b*/); // [ "a", "", "c" ]
// expected [ "a", "c" ]
split("a\nb\nc", /^/m); // [ "a", "\n", "b", "\n", "c" ]
// expected [ "a\n", "b\n", "c" ]
Advance to the match position and consume its character in replace(). In
split(), carry that character as an offset: the next match is searched behind
it, and the piece preceding it is preserved. Both now match the behaviour of
JavaScript.
Signed-off-by: Jo-Philipp Wich <jo@mein.io>
jow-
force-pushed
the
regexp-runtime-preprocess
branch
from
November 26, 2026 11:03
ffc7d50 to
550d4e8
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Anchored patterns no longer describe the whole subject. Since 8a8b4d1 ("types: fix regexp
/.../sflag inversion") the dot has been kept from matching newlines by compiling every pattern withREG_NEWLINE, and that option also turns^and$into line anchors and excludes newlines from negated bracket expressions:Any validation against an anchored pattern therefore accepts a value as soon as one of its lines matches. A WireGuard key check such as
/^[A-Za-z0-9+/]{43}=$/accepts a key containing an embedded newline, so the remainder of the value is interpreted as further configuration. Reported by Guy Godfroy.1. lexer,types: keep the regexp dot operator independent of anchoring
Patterns are compiled without
REG_NEWLINEand the flags are expressed in the pattern instead, by rewriting the atoms whose meaning the flags change:.becomes[^\n]unlesssis given, while^and$stay whole-subject anchors. Both glibc and musl make.match any character whenREG_NEWLINEis unset, so the dot is the only atom that has to be rewritten.Rewriting requires parsing the pattern, which the lexer and the
regexp()constructor used to do differently: the lexer decoded escape sequences, expanded the\d,\w,\smacros and tracked bracket expressions while searching for the closing slash, while a pattern given toregexp()reachedregcomp()unchanged. POSIX makes a backslash inside a bracket expression an ordinary member, and both engines follow, so the two paths described different patterns:regexp()[\d]d\andd[a\-z]a-z-,\,z\dPatterns are now preprocessed once, in
types.c, where they are compiled, so a regexp literal and the equivalent constructor call cannot diverge. A bracket expression is parsed into members, ranges and elements and written back with each member where the engines read a member (]first;-,\,[and^last,-last of all), which changes previously ambiguous patterns in the stricter direction:/[a\-z]/is now the lista,-,zrather than the rangea-z. An escape denotes a character and never an atom, so\u002eis a full stop rather than the dot operator and\u0028a bracket rather than a capture group. Unbalanced bracket expressions and escapes denoting NUL are rejected.2. types,lexer,lib: add support for the regexp multi-line (m) flag
Adds the JavaScript
mflag, which compiles withREG_NEWLINEto obtain line anchoring. SinceREG_NEWLINEalso excludes newlines from negated bracket expressions, such an expression is wrapped in an alternative against one (([^a]|\n)); the capture group that introduces is mapped away at compile time, so the group numbering of the pattern as written is preserved and nothing is added per match.Line boundaries are those of the engine, and
REG_NEWLINErecognizes the newline only: a preceding carriage return is an ordinary character and the Unicode line and paragraph separators are not line breaks. JavaScript breaks lines at all of them, whichREG_NEWLINEcannot provide.ucv_regexp_new()keeps its signature and delegates to the newucv_regexp_new_ex(), which takes the flag bitmask the lexer already encodes. Matching goes through the newucv_regexp_exec(), which permutes the visible groups to the front of the caller's match array;ucv_regexp_nmatch()reports how many entries that array requires.3. lib: advance past zero-length regexp matches
replace()andsplit()advanced an empty match by a single character from the start of the current search window rather than from the match position, which duplicated text in one and truncated a piece in the other: