From f60f51fe89f1d3737389047cb2f3671b1b21e56d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 17:56:44 -0300 Subject: tests: what mvzr compiles it can walk: core/regexp.zig's test of that name searches `()a` on `b` and `a()b` on `a` (no match) and on `ba` and `xab` (what they match), expects `a|*` `|+` `(|?)` `|??` `^*` `^+?` `a|{2}` `({1))` `a{1b` refused, and searches every pattern up to five characters over `()|*+?a` and four over `()|*+?a^{1}` from every offset of `aa\n\na`: refused, or answered inside the budget (Debug: its test program runs in 50 ms); on this base it aborts at its first case, `()a` on `b` (index out of bounds, index 0 of len 0, mvzr.zig:999 `patternAcceptsEmpty` from `groupAcceptsEmpty` :1040 from `matchPattern` :333 of the build's patched copy: the frames of the abort in .scratch/sketch/reorg/merge57/replicas-2.log, where the soak's random typist, narrowing a selection by a regex (`s`) a key at a time, took its session down); outside the tree (.scratch/sketch/reorg/pardes-regex-2/enum: this core/regexp.zig over the build's patched mvzr in a safe build, a forked child per panic) 18,746 of the 960,799 patterns up to seven characters over `()|*+?a` panic, every one indexing an empty slice: `patternAcceptsEmpty` (an empty group with more after it: `()a`, `a()b`), `thisPattern` and `nextPattern` (a repeat right after `|`: `a|*`, `|*`, `|??`); over wider alphabets two more kinds, a repeat right after `^` (`^*`: reached unreachable code) and a count ending in neither `,` nor `}` (`({1))`: index 1 of len 1): 68,627 of 5,229,042 up to six over `()|*+?a^$.{}1`, 40,135 of 5,399,042 up to five over `()[]{},*+?|\^$.-a1xnbf`; the next change is the fix Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/regexp.zig | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/core/regexp.zig b/core/regexp.zig index 2936b491..4a51d0ce 100644 --- a/core/regexp.zig +++ b/core/regexp.zig @@ -681,3 +681,48 @@ test "a pattern that stops inside a count or an escape is refused, not read past } } } + +test "what mvzr compiles it can walk: an empty group matches the empty string; a repeat of `|` or `^`, and a count without its `}`, are refused" { + std.testing.log_level = .err; // mvzr warns of each bad string + // An empty group with more after it, searched to a line's end, where + // mvzr asks whether the group may match nothing (build/patches.zig). + const Case = struct { pat: []const u8, text: []const u8, hit: ?[2]usize }; + for ([_]Case{ + .{ .pat = "()a", .text = "b", .hit = null }, + .{ .pat = "()a", .text = "ba", .hit = .{ 1, 2 } }, + .{ .pat = "a()b", .text = "a", .hit = null }, + .{ .pat = "a()b", .text = "xab", .hit = .{ 1, 3 } }, + }) |c| { + var rx = try Regex.compile(c.pat); + const m = try rx.find(c.text, 0, c.text.len, c.text.len); + try std.testing.expectEqual(c.hit, if (m) |h| [2]usize{ h.start, h.end } else null); + } + // A repeat right after `|` or `^` took it for what it repeats, and a + // count ending in neither `,` nor `}` left a hole in the program: each + // walked off an empty slice in the matcher. + for ([_][]const u8{ "a|*", "|+", "(|?)", "|??", "^*", "^+?", "a|{2}", "({1))", "a{1b" }) |pat| + try std.testing.expectError(error.Bad, Regex.compile(pat)); + // Every pattern up to five characters over the first alphabet and four + // over the second, searched from every offset of a text with an empty + // line: refused, or searched to an answer inside the budget. + const text = "aa\n\na"; + var pat: [5]u8 = undefined; + for ([_][]const u8{ "()|*+?a", "()|*+?a^{1}" }, [_]usize{ 5, 4 }) |alphabet, longest| { + for (1..longest + 1) |len| { + var n: usize = 1; + for (0..len) |_| n *= alphabet.len; + for (0..n) |k| { + var rest = k; + for (pat[0..len]) |*c| { + c.* = alphabet[rest % alphabet.len]; + rest /= alphabet.len; + } + var rx = Regex.compile(pat[0..len]) catch continue; + for (0..text.len + 1) |from| { + const m = try rx.find(text, from, text.len, text.len) orelse continue; + try std.testing.expect(from <= m.start and m.start <= m.end and m.end <= text.len); + } + } + } + } +} -- cgit v1.3 From 19386feb0074afc1afed6e8ebe8596c426e4bdb0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 22 Nov 2026 18:06:54 -0300 Subject: mvzr: what it compiles it can walk: three Edits in build/patches.zig (docs/mvzr-empty-group.md, the report for upstream, its patch checked against trunk 3efcfe33): `patternAcceptsEmpty` answers true for an empty pattern (a group with nothing inside and more after it took `groupAcceptsEmpty`'s alternatives branch, `hasAlt` counting the group's own `)`, whose last line asked the empty inside for its first operation: `()a` searched to a line's end, the soak's abort); `prefixModifier` refuses a repeat right after `^` or `|`, as it refuses one at the start (its test read `patt[j]`, the slot being written, where `patt[j - 1]` was meant: `^*` compiled to `star, begin`, which the matcher holds unreachable, and `a|*` to `a, star, alt`, whose first alternative's lone `star` had nothing to repeat); a count followed by anything but `,` or `}` is a bad string (`{1` then any other character wrote no operation and skipped that character, a hole that ended the program: `a{1b` ran as `a`, `({1))` as a lone `(`); a user hits the first by typing `()` and one more character into `s` or `/` over a line it does not match (a safe build's session aborts, the installed one too: the same pin and the same Edits), the second by typing `a|*` or `^*`, the third by `({1))`; with the Edits the drive outside the tree finds no panic in 11,588,883 patterns (up to seven characters over `()|*+?a`, six over `()|*+?a^$.{}1`, five over `()[]{},*+?|\^$.-a1xnbf`, from every offset of three short texts; 18,746, 68,627 and 40,135 on the base), no search out of budget, every match inside its text, and the patterns it newly refuses are exactly those with a repeat right after `|` or `^` (up to six over `()|*+?a`: 4,068 of the base's 8,778 compiled, 3,096 of them panicked; the rest were the same miscompile on texts that did not reach it); mvzr's own tests on an upstream copy (its four `**` replaced for Zig 0.17) 32/32 with the report's test, 31 and an abort at `patternAcceptsEmpty` without the Edits; mvzr's trunk on this machine (~/05-genizah/mvzr, origin/trunk 3efcfe33, the pin) has none of it, and nothing newer could be looked at here; the previous change's test passes; core-test 917/1074 (157 skipped), shell-test 1116/1119 (3 skipped), each the base's plus that test; the soak that found it (`replicas --clients 5`, TMPDIR /tmp/claude-1000/rs2, load 2-4) ends: diverged 0/0/0, unequal 0/0/0, quiet checks 546/0 442/0 666/0, unlisted stops 0/0/0, the corpus scene 22 of 22, no leak, no panic (1,054 patterns refused in words on the way, 584 of them `missing closing parenthesis`); left as they are (in the report): `patternAcceptsEmpty` judges a sequence by its first operation (`x(a*b)` matches `x`; `(()a)` now matches the empty string at the end of `b`, where it aborted), and a repeat right after `(` takes the `(` (`(*a)` compiles as `(a)*`), neither a panic Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- build/patches.zig | 15 ++++++ docs/mvzr-empty-group.md | 132 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 147 insertions(+) create mode 100644 docs/mvzr-empty-group.md diff --git a/build/patches.zig b/build/patches.zig index 7d87b9f1..410d27ab 100644 --- a/build/patches.zig +++ b/build/patches.zig @@ -356,6 +356,15 @@ pub fn ghosttyKitty(b: *std.Build, patch: *std.Build.Step.Compile, dep: *std.Bui /// could compile one typed pattern differently. Unreported upstream as /// of 3efcfe33 (its trunk on 2026-11-19); docs/mvzr-bounds.md is the /// report for it. +/// - Three kinds of pattern the matcher indexed an empty slice on (a panic +/// in a safe build, at a key typed into `s` or `/`): an empty group with +/// more after it (`()a`, `a()b`: whether the group may match nothing was +/// asked of its inside's first operation, which it has not got); a +/// repeat right after `|` or `^` (`a|*`, `|??`, `^*`: it took the `|` or +/// the `^` for what it repeats; at the pattern's start it was already +/// refused); and a count that ends in neither `,` nor `}` (`({1))`: the +/// character after it was skipped and a hole left in the program, which +/// ends it there). docs/mvzr-empty-group.md is the report for upstream. const mvzr_edits = [_]Edit{ .{ .old = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n", @@ -419,6 +428,12 @@ const mvzr_edits = [_]Edit{ .{ .old = "fn valueFor(in: []const u8) ?u8 {\n", .new = "fn valueFor(in: []const u8) ?u8 {\n if (in.len == 0) return null;\n" }, .{ .old = " return parseHex(in[1..4]) catch return null;\n", .new = " return parseHex(in[1..3]) catch return null;\n" }, .{ .old = " if (i == in.len or in[i] != ']') {\n return BadString;\n", .new = " if (i >= in.len or in[i] != ']') {\n return BadString;\n" }, + // What compiles is a program the matcher can walk: an empty pattern + // accepts the empty string; a repeat repeats an operation; a count is + // closed. + .{ .old = "fn patternAcceptsEmpty(patt: []const RegOp) bool {\n", .new = "fn patternAcceptsEmpty(patt: []const RegOp) bool {\n if (patt.len == 0) return true;\n" }, + .{ .old = " if (j == 0 or patt[j] == .begin) return BadString;\n", .new = " if (j == 0 or patt[j - 1] == .begin or patt[j - 1] == .alt) return BadString;\n" }, + .{ .old = " } else if (in[i] == '}') {\n // {M}\n", .new = " } else if (in[i] != '}') {\n bad_string = true;\n break :dispatch;\n } else {\n // {M}\n" }, .{ .old = "for (c1..c2 + 1) |c_range|", .new = "for (c1..@as(usize, c2) + 1) |c_range|" }, .{ .old = "[1]RegOp{.{ .unused = {} }} ** ops", .new = "@splat(.{ .unused = {} })" }, .{ .old = "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", .new = "@splat(.{ .low = 0, .hi = 0 })" }, diff --git a/docs/mvzr-empty-group.md b/docs/mvzr-empty-group.md new file mode 100644 index 00000000..a3028fc7 --- /dev/null +++ b/docs/mvzr-empty-group.md @@ -0,0 +1,132 @@ +# mvzr: three kinds of pattern compile into a program the matcher walks off an empty slice + +A report for upstream (https://github.com/mnemnion/mvzr), against trunk +3efcfe3 (0.3.9; its trunk when last fetched here, 2026-11-19). pardes +patches its fetched copy at build time (build/patches.zig) until it is +fixed there. + +## What happens + +```zig +const mvzr = @import("mvzr"); +// each of these panics in Debug and ReleaseSafe: index out of bounds, +// or (`^*`) reached unreachable code +_ = mvzr.compile("()a").?.match("b"); +_ = mvzr.compile("a()b").?.match("a"); +_ = mvzr.compile("a|*").?.match("a"); +_ = mvzr.compile("|*").?.match("b"); +_ = mvzr.compile("|??").?.match(""); +_ = mvzr.compile("^*").?.match("a"); +_ = mvzr.compile("({1))").?.match("a"); +// and these compile to something else: `a{1b` to `a` (it matches "a"), +// `a|{2}` to a program that matches "" at the start of "a" +``` + +A program that searches with what a person types, at each key (an +editor's incremental search), reaches the first as soon as the person has +typed `()` and one character more, wherever a line ends before a match. + +Searched from every offset of three short texts (each line its own +haystack), every pattern up to seven characters over `()|*+?a` (960,799): +18,746 panic; up to six over `()|*+?a^$.{}1` (5,229,042): 68,627; up to +five over `()[]{},*+?|\^$.-a1xnbf` (5,399,042): 40,135. + +## Why + +**An empty group with more after it.** At the end of the haystack +`matchPattern` asks `groupAcceptsEmpty` whether a group may match nothing. +`hasAlt` answers true at the group's own `)` when more pattern follows it +(docs/mvzr-group-backtrack.md, the same quirk), so a group with no `|` +takes the alternatives branch, whose last line is +`return (patternAcceptsEmpty(inner_patt));`, and `patternAcceptsEmpty` +switches on `patt[0]` of the empty inside. (The branch without +alternatives checks `inner.len == 0` first; this one does not.) + +**A repeat right after `|` or `^`.** `prefixModifier` refuses a repeat with +nothing before it by `if (j == 0 or patt[j] == .begin)`, but `patt[j]` is +the slot about to be written and is never `.begin`. So `^*` compiles to +`star, begin`, and the matcher meets `.begin` where it is `unreachable`; +and a repeat after `|` takes the `.alt` for what it repeats: `|*` compiles +to `star, alt`. Split at the `|`, the first alternative is a lone `star`, +and `thisPattern` (from `matchStar`) or `nextPattern` (`|??`) reads +`patt[0]` of the empty slice after it. + +**A count that ends in neither `,` nor `}`.** After `{` and a number, +`compileRegex` handles `,` and `}`; any other character writes no +operation, and the dispatch loop's step moves past it, so the program has +an `.unused` slot there, which `findPatternEnd` takes for its end. `a{1b` +runs as `a`; `({1))` (its first `)` skipped, its second closing the `(`) +runs as a lone `.left`, and `sliceGroup` reads past it. + +## The fix + +An empty pattern accepts the empty string; a repeat after `^` or `|` is a +bad string, as one at the start of the pattern is (`patt[j - 1]`, as the +`.begin` test seems to have meant); a count followed by anything but `,` +or `}` is a bad string, as the other unfinished counts are. With it the +same patterns make no panic (0 of 11,588,883), and mvzr's own tests pass +with the one below (32 of 32; the copy tested had its four uses of `**` +replaced, which Zig 0.17 needs: PR #16; without the fix the new test +aborts at `patternAcceptsEmpty`). + +```diff +diff --git a/src/mvzr.zig b/src/mvzr.zig +index d4ea747..791664e 100644 +--- a/src/mvzr.zig ++++ b/src/mvzr.zig +@@ -983,6 +983,7 @@ fn thisGroup(patt: []const RegOp) []const RegOp { + } + + fn patternAcceptsEmpty(patt: []const RegOp) bool { ++ if (patt.len == 0) return true; + switch (patt[0]) { + .optional, + .star, +@@ -1190,7 +1191,7 @@ pub fn resourcesNeeded(comptime in: []const u8) struct { comptime_int, comptime_ + + /// Move modifiers to prefix position. + fn prefixModifier(patt: []RegOp, j: usize, op: RegOp) !usize { +- if (j == 0 or patt[j] == .begin) return BadString; ++ if (j == 0 or patt[j - 1] == .begin or patt[j - 1] == .alt) return BadString; + var find_j = j - 1; + // travel back before last group + switch (patt[find_j]) { +@@ -1518,7 +1519,10 @@ fn compileRegex(RegexT: type, in: []const u8) ?RegexT { + bad_string = true; + break :dispatch; + }; +- } else if (in[i] == '}') { ++ } else if (in[i] != '}') { ++ bad_string = true; ++ break :dispatch; ++ } else { + // {M} + j += prefixModifier(patt, j, RegOp{ .some = c1 }) catch { + bad_string = true; +@@ -2552,3 +2556,15 @@ test "iterator with empty alternation terminates" { + while (r_iter.next()) |_| {} + try expectEqual(null, r_iter.next()); + } ++ ++test "an empty group, a repeat after | or ^, a count without its }: no walk off an empty slice" { ++ // An empty group with more after it may match nothing. ++ try expect(compile("()a").?.match("b") == null); ++ try expect(compile("a()b").?.match("a") == null); ++ try expectEqual(1, compile("()a").?.match("ba").?.start); ++ try expectEqual(3, compile("a()b").?.match("xab").?.end); ++ // A repeat needs something to repeat; a count needs its `}`. ++ for ([_][]const u8{ "a|*", "|+", "(|?)", "|??", "^*", "^+?", "a|{2}", "({1))", "a{1b" }) |patt| { ++ try expect(compile(patt) == null); ++ } ++} +``` + +## Left as they are + +- `patternAcceptsEmpty` judges a pattern by its first operation: `x(a*b)` + matches `x` (the group is taken to accept the empty string because `a*` + does), and `(()a)` now matches the empty string at the end of `b` where + it panicked. Asking it of every piece of the sequence is the full fix. +- A repeat right after `(` takes the `(` for what it repeats: `(*a)` + compiles as `(a)*` and matches `aa`. Testing `.left` in the same line + refuses it; nothing panics on it, so pardes leaves it. -- cgit v1.3