Skip to content

fix(sed): POSIX subexpression capture rules (Fixes #1496) - #1501

Merged
caomengxuan666 merged 2 commits into
mainfrom
fix/1496-posix-subexpression-capture
Nov 2, 2026
Merged

caomengxuan666 merged 2 commits into
mainfrom
fix/1496-posix-subexpression-capture

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

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, same
engine file): this branch is cut from #1498's head (981210f7) to avoid
conflicts; review/merge #1498 first.

Root cause 1 — group numbering was closing-order, not opening-order

make_capture allocated ++capture_count_ after parsing the group body,
so \(\(x\)*\)* numbered the inner \(x\) as \1 and the outer group as \2:

printf 'xxxx\n' | sed 's/^\(\(x\)*\)*$/[\1|[\2]]/'   # gnu: [xxxx|[x]]  was: [x|[xxxx]]

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]/ over xxxx prints [xxxx|x]). Fix: allocate the
capture index before parse_expression() for both BRE \( and ERE (.

Root cause 2 — empty iterations were discarded instead of counted

collect_repeat skipped every empty iteration (next.pos == state.pos), so
a \{m,n\} lower bound could only be satisfied by advancing iterations and
the trailing empty copies' register effects were lost:

printf 'abcabc\n' | sed 's/^\(.*\)\{2,\}$/[\1]/'   # gnu: [abcabc]  was: [c]

glibc's actual semantics (source-cited)

  • posix/regexec.c:1386 set_regs() — after the DFA phase fixes the
    leftmost-longest overall match, a forward walk fills captures.
  • posix/regexec.c:1495 update_regs() — OP_OPEN_SUBEXP re-opens the group
    on every iteration (last iteration's span wins). OP_CLOSE_SUBEXP empty
    branch: "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 first
    destination in compiled order (written alternation branch, iterate-before-
    exit), with the (a*)* anti-loop rule stopping an unbounded star after one
    empty iteration. This is why the engine's existing first-arrival state
    order already matched GNU's picks for alternations ((a|ab)(c|bcd)(d*) on
    abcd → a,bcd,empty).
  • posix/regcomp.c parse_dup_op() — X{m,n} is expanded as X^m plus
    right-nested optionals (((X₁?X₂)?X₃)?…Xₙ)? where only X₁ is
    opt_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:

  • The empty iterations count toward the {m,n} minimum (so
    ^\(.*\)\{2,\}$ = one full iteration + one empty one, whole-line \1).
  • If the trailing copy is the opt-marked one (unbounded max, or
    max == min+1
    ) and the empty parse rewrote a capture that held a
    non-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.
  • If an unmarked copy runs last (bounded max != min+1), its empty match
    stands: \(a*\)\{2\} on aaa → 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

  • empty line), \(a\|ab\)\(c\|bcd\)\(d*\) (BRE+ERE, anchored+not),
    \(.*\)\(.*\), \(a*\)*, \(a*\)\+, \([ab]\)*, \(a\|ab\)\{2,\},
    \(a\)*b repeats, 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 GNU
oracle). 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 the
unmodified base 981210f7 — pre-existing environment issues, unrelated.

Refs #1496 #1495

caomengxuan666 and others added 2 commits November 2, 2026 08:28
…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
caomengxuan666 marked this pull request as ready for review November 2, 2026 01:31
@caomengxuan666 caomengxuan666 changed the title WIP: fix(regex): POSIX subexpression captures — opening-order numbering + glibc empty-iteration accounting (Fixes #1496, Refs #1495) fix(sed): POSIX subexpression capture rules (Fixes #1496) Nov 2, 2026
@caomengxuan666
caomengxuan666 merged commit f840104 into main Nov 2, 2026
13 checks passed
@caomengxuan666
caomengxuan666 deleted the fix/1496-posix-subexpression-capture branch November 3, 2026 09:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant