Repository navigation
fix(sed): POSIX subexpression capture rules (Fixes #1496) - #1501
Merged
Merged
Conversation
…ng + glibc empty-iteration accounting (Fixes #1496, Refs #1495) Two root causes behind the #1496 capture divergences, both in src/utils/regex.cppm: 1. Capture groups were numbered when they CLOSED (post-order), so `\(\(x\)*\)*` numbered the inner group \1 and printed `[x|[xxxx]]` where GNU prints `[xxxx|[x]]`. POSIX XBD 9.1 counts subexpressions from left to right; glibc numbers by opening delimiter (measured: `s/^((x)*)*$/[\1|\2]/` on `xxxx` -> `[xxxx|x]`). The index is now allocated before the group body is parsed (BRE and ERE). 2. collect_repeat discarded empty iterations entirely, so `\{m,n\}` lower bounds could only be met by advancing iterations and `^\(.*\)\{2,\}$` captured the last chunk `[c]` instead of the whole line. glibc set_regs (posix/regexec.c update_regs, OP_CLOSE_SUBEXP empty branch) runs the repeat's remaining copies on the body's empty parse: the trailing empty copy either restores the last non-empty commit ("Copy back the old content of the registers") or records the empty match when the group has none yet. Ported as an exit-state rule: empty iterations count toward the {m,n} minimum; the exit keeps the pre-iteration registers when the trailing copy is the opt-marked one of glibc parse_dup_op's X^m (((X?X)?X)?...) expansion (unbounded max, or max == min+1) and the empty parse rewrote a non-empty capture; otherwise the empty parse's captures stand (matches GNU `\(a*\)\{2\}` -> empty vs `\{2,3\}` -> `aaa`). The overall leftmost-longest match and the per-alternation pick (`(a|ab)(c|bcd)(d*)` on `abcd` -> a|bcd|empty) were already correct via first-arrival exploration order, equivalent to glibc's proceed_next_node first-destination walk; 45-case differential matrix against WSL GNU sed is now byte-identical, the #1495 17-case matrix stays green (32/64/128-char shapes all < 1s), and the #1498 memoization is untouched (the new exit state is a pure function of the memo key).
caomengxuan666
marked this pull request as ready for review
November 2, 2026 01:31
This was referenced Nov 2, 2026
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.
Summary
Fixes the two root causes behind #1496 (nested-quantifier capture selection
diverging from glibc), both in
src/utils/regex.cppm. Target release: 1.2.1.Depends on #1498 (
fix/1495-sed-nested-quantifier-backtracking, sameengine file): this branch is cut from #1498's head (
981210f7) to avoidconflicts; review/merge #1498 first.
Root cause 1 — group numbering was closing-order, not opening-order
make_captureallocated++capture_count_after parsing the group body,so
\(\(x\)*\)*numbered the inner\(x\)as \1 and the outer group as \2:Rule: POSIX.1-2017 XBD 9.1 counts subexpressions from left to right; glibc
numbers groups by their opening delimiter (measured on WSL GNU sed 4.9:
s/^((x)*)*$/[\1|\2]/overxxxxprints[xxxx|x]). Fix: allocate thecapture index before
parse_expression()for both BRE\(and ERE(.Root cause 2 — empty iterations were discarded instead of counted
collect_repeatskipped every empty iteration (next.pos == state.pos), soa
\{m,n\}lower bound could only be satisfied by advancing iterations andthe trailing empty copies' register effects were lost:
glibc's actual semantics (source-cited)
posix/regexec.c:1386 set_regs()— after the DFA phase fixes theleftmost-longest overall match, a forward walk fills captures.
posix/regexec.c:1495 update_regs()—OP_OPEN_SUBEXPre-opens the groupon every iteration (last iteration's span wins).
OP_CLOSE_SUBEXPemptybranch: "We transited through an empty match for an optional subexpression,
like (a?) … Copy back the old content of the registers"* — a trailing
empty copy restores the last non-empty commit; an empty match is only
recorded when the group has no non-empty match yet.
posix/regexec.c:1218 proceed_next_node()— the walk prefers the firstdestination in compiled order (written alternation branch, iterate-before-
exit), with the
(a*)*anti-loop rule stopping an unbounded star after oneempty iteration. This is why the engine's existing first-arrival state
order already matched GNU's picks for alternations (
(a|ab)(c|bcd)(d*)onabcd→a,bcd,empty).posix/regcomp.c parse_dup_op()—X{m,n}is expanded asX^mplusright-nested optionals
(((X₁?X₂)?X₃)?…Xₙ)?where only X₁ isopt_subexp-marked.Ported rule (exit-state selection in
collect_repeat)Stopping the loop = no more advancing iterations, but glibc's walk then runs
the repeat's remaining copies on the body's empty parse. Those empty copies
decide the surviving captures:
^\(.*\)\{2,\}$= one full iteration + one empty one, whole-line \1).max == min+1) and the empty parse rewrote a capture that held anon-empty match, the pre-iteration registers stand (the memcpy-back);
otherwise the empty match is recorded. Non-first empty matches of other
groups inside the body are likewise not committed.
max != min+1), its empty matchstands:
\(a*\)\{2\}onaaa→ empty \1, while\{2,3\}/\{1,2\}keep
aaa— byte-matching GNU.The #1498 memoization is untouched: the new exit state is a pure function of
the
(node, count, state)memo key, so first-arrival order stays exact.Differential matrix (WSL GNU sed 4.9 / glibc 2.39, sed -f script files)
45/45 byte-identical (was 27/45 at the #1498 head), covering:
\(\(x\)*\)*,\(\(\(x\)*\)*\)*,((x)*)*(ERE),\(.*\)\{2,\}(6/32-char\(a\|ab\)\(c\|bcd\)\(d*\)(BRE+ERE, anchored+not),\(.*\)\(.*\),\(a*\)*,\(a*\)\+,\([ab]\)*,\(a\|ab\)\{2,\},\(a\)*brepeats,x(y*)nesting,{m,n}boundary family({2},{3},{1,2},{2,3},{1,3},{2,4},{0,2},{0,3},{1,4},{2,},{1,}).
Artifacts:
D:\tmp\wc1496\(cases.txt, gnu/, wc/).#1495 regression matrix: 17/17 (nested/bounded/bounded32/bound02/plus32/
double16/ere32/nonanch/bashit); issue shapes at 32/64/128 chars all still
complete well under 1 s (full 17-case run: 1.8 s).
Tests
5 new gtest cases in
tests/unit/sed/sed_unit_test.cpp(
nested_quantifier_issue1496_*, expectations byte-copied from the GNUoracle). ctest: sed group 174/175, regex consumers (grep/expr/csplit/nl/
find/less/diff) 370/372. The 2 failures (
nul_txt_reads_file_issue1333,less_file_operand_uses_shell_root_issue1385) fail identically on theunmodified base
981210f7— pre-existing environment issues, unrelated.Refs #1496 #1495