Skip to content

rust2(sed): GNU sed 4.9 library port on winux-regex + 379-row gate (#1488) - #1635

Closed
caomengxuan666 wants to merge 7 commits into
mainfrom
rust2/sed-impl
Closed

caomengxuan666 wants to merge 7 commits into
mainfrom
rust2/sed-impl

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Library landing for the sed big-ticket lane (compile.c/execute.c/regexp.c port on winux-regex: s/// full flag matrix, y///, addresses incl. 0,/re/ and first~step, hold space, b/t/T/D/P/N/F/=/a/i/c/r/w/e, -i family, --follow-symlinks, --debug) + review-wave gate rows.

Evidence: gate 379 rows GNU-gated 378 PASS / 0 FAIL, win 1/0; cargo test sed 18/0; #1496/#1495 nested-quantifier capture matrix 15/15 byte-identical vs GNU sed 4.9 (9 rows now pinned as gate rows). Perf 64MiB best-of-3: s/foo/bar/g 0.36s (C++ 0.70, GNU 0.41); y/// 0.20s (C++ 5.51); s/\(a\)\(b\)/\2\1/ 0.59s (C++ 7.36) — 1.9-24x over C++ 1.x, GNU parity.

Review outcome: one behavioral divergence found and fixed in this series — --follow-symlinks failures now panic 'couldn't readlink' rc 4 like GNU (sd599), previously fell through to can't-read rc 2.

Known wording note: GNU interpolates argv[0] into usage/INTERNAL ERROR lines; the Rust side prints the literal 'sed' (identical in the multicall product).

Expected CI status: i18n-drift will report keys until the wire commit lands tr! keys (checkpoint I18N prerequisite — sed's message face is currently hardcoded English). Compile/test legs should be green.

caomengxuan666 and others added 7 commits November 14, 2026 12:39
…bc strict syntax bits (#1488)

Additive CompileOptions / Regex::compile_with for the sed port; the
default options reproduce compile_bytes exactly (grep unchanged, pinned
by tests/sed_dialect.rs default_dialect_is_unchanged).

* multiline (glibc REG_NEWLINE, sed M): ^/$ match around the line
  delimiter (LineStart/LineEnd nodes), . and [^...] never match newline;
  \W / \S are unaffected (probed).
* buffer_anchors: GNU \` and \' (BufferStart/BufferEnd), absolute even
  in M mode.
* posix_strict: GNU sed's glibc syntax bits — ERE RE_CONTEXT_INVALID_OPS
  (* + ? { at an expression start, after ( | or an anchor -> Invalid
  preceding regular expression), BRE RE_CONTEXT_INVALID_DUP (\{ at a
  start, a** / a*\{2\} -> BADRPT), anchors take no repetition, glibc
  fetch_number interval errors in both syntaxes (Unmatched \{ vs
  Invalid content of \{\}), stray ERE ) is Unmatched ) or \).
  BADRPT reuses ErrorKind::InvalidInterval (message carries the text)
  so no exhaustive match in another consumer breaks.
* strict_utf8_dot: . skips bytes that do not start a well-formed UTF-8
  sequence (glibc under C.UTF-8).

tests/sed_dialect.rs: every row probed on WSL GNU sed 4.9, plus the
#1495/#1496 capture rows from fix/1496 (sed_unit_test.cpp).

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ons for sed --posix (#1488)

Two more additive CompileOptions fields (defaults off, grep unchanged):

* no_gnu_ops (glibc RE_NO_GNU_OPS, + RE_LIMITED_OPS in BRE): \w \W \s
  \S \b \B \< \> \` \' are literals and BRE \+ \? \| are literals —
  sed --posix (probed: s/a\+/X/ on aa+ -> aX, s/a\|b/X/ on a|b -> X).
* unmatched_right_paren_ord: a stray ERE ) / BRE \) is a literal even
  under posix_strict — sed under POSIXLY_CORRECT (probed: -E s/)/X/ on
  a)b -> aXb).

tests/sed_dialect.rs posix_mode_ops_and_paren_ord pins both.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
#1488)

The backtracking matcher clones capture vectors per state per position;
sed -n '/lorem.*amet/p' over 64 MiB took 22.7 s (GNU 0.4 s).

* pike.rs: a Pike VM without submatches over the same AST, candidate
  starts, .-width rule and assertion predicates as the backtracker.
  POSIX leftmost-longest by construction: threads dedup per (position,
  instruction) keeping the smallest start, winner = smallest start then
  largest end. Backreference patterns and interval expansions above
  20k instructions have no NFA and keep the backtracker.
* Regex::new_cache / is_match_with / find_at_bytes_with (additive API,
  MatchCache scratch reused across lines): the NFA locates the bounds,
  the backtracker runs once, anchored at the start, only for patterns
  with groups; pure literals keep the memchr path.
* fixed_captures: when every piece is fixed-width and no group sits
  under an alternation / repetition, group spans are static offsets from
  the match start (s/\(a\)\(b\)/\2\1/: 3.2 s -> 0.67 s on 64 MiB).

tests/pike_equiv.rs: span-and-capture differential vs find_at_bytes
over ~60 patterns x ~60 subjects x every start offset, grep and sed
dialects (I/M), plus the fixed-capture shapes. Existing suites green.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Structural port of GNU sed 4.9 (sed.c / compile.c / execute.c /
regexp.c / debug.c, read against the v4.9 sources) in the rust2 shape
contract: injected IO, explicit env/cwd, status returned.

* sed.rs: getopt_long-shaped option loop processed IN ORDER (-e/-f
  compile when seen; -n -e -f --expression --file, -f -, -E/-r, -s,
  -i[SUF]/--in-place[=SUF] with *, -z, -u, -l N, --posix, --debug,
  --sandbox, --follow-symlinks, -b, COLS, POSIXLY_CORRECT), GNU usage /
  ambiguity / missing-argument diagnostics, --help/--version.
* sed/compile.rs: inchar/savchar/in_nonblank character accounting so
  every diagnostic is byte-exact ("-e expression #N, char M" /
  "file F line L"), match_slash + snarf_char_class, normalize_text
  (\n \t \a \f \v \r \cX \dNNN \oNNN \xHH, TEXT_REPLACEMENT re-escape),
  setup_replacement (\0-\9 & \L \U \l \u \E), mark_subst_opts (g p N
  w i/I m/M e), a/i/c classic + one-liner + cross -e continuation, y
  (unibyte table / multibyte pairs), labels, blocks, #n, v, w/R files
  opened at compile time, the dfa [:space:] colon warning (rc 4).
* sed/exec.rs: read_pattern_space / test_eof / last_file_with_data_p
  lookahead across files, missing-final-newline tracking per output
  (chomped travels through g/G/h/H/x and the s///e exchange exactly like
  GNU line_copy/line_append/line_exchange), match_address_p ranges
  (0,/re/, N,+M, N,~M, first~step, reversed ranges), do_subst with the
  empty-match-after-match rule and the empty-replacement fast path,
  append queue (a r R), c/i/D/n/N (GNU N-at-EOF autoprint unless
  POSIXLY_CORRECT), l wrapping, = F z q Q e, w/W to files and
  /dev/stdout /dev/stderr, r//R /dev/stdin, the --debug printers.
* Windows: bytes end to end (CRLF is data); -i writes sedXXXXXX next to
  the target, renames to the backup, replaces the target and restores
  its file attributes (read-only targets unlocked for the replace);
  e / s///e run through sh -c when a POSIX shell resolves, else
  cmd.exe /d /c.
* Streaming: 64 KiB BufRead per input (1 byte under -u), 64 KiB output
  buffer flushed per record under -u; address/s regexes run through the
  winux-regex NFA (MatchCache per regex).

Unit tests (18): substitution, case conversion, chomped propagation,
GNU vs POSIXLY_CORRECT N, parse diagnostics, -f line numbers, rc 2
after bad input, $ lookahead, -i backup/star/attributes, -i errors,
special files, --debug dump, option order, address forms, y/UTF-8.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
lib.rs: pub mod sed + ("sed", sed::sed_cmd) appended to the registry.
gen-cases.py: sed_rows (367 rows) appended before collect(), plus the
("sed", sed_rows) entry; cases/sed.tsv regenerated (no other table
changed). Multi-line scripts travel through printf'd -f script files
(_sed_multiline: TSV rows cannot carry a raw newline); scripts starting
with / get one leading blank (the niubash harness channel rewrites a
leading-slash argv token, /a/d -> A:\d, measured).

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* gate/stderr-check.sh <cmd>: byte-compares the Rust side's stderr with
  GNU's for every non-win row of a table, from the artifacts run-gate.sh
  already keeps (run-gate gates stdout + rc only; sed's diagnostics are
  part of its contract). STDERR_ALLOW=id,... reports without failing.
* gate/sed-bench.py [CPP_EXE]: 64 MiB three-way timing (rust2 release
  driver / C++ dispatcher / WSL GNU sed on ext4), best of 3, sha1 of
  every side's output checked against GNU's.

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…eview-wave gate rows (#1488)

Closes the one behavioral divergence the review found:

- exec.rs follow_symlink() -> Result<String, Fatal>: a stat/readlink
  failure on a chain element is benign only when it means 'not a
  symlink' ([GNU sed 4.9 utils.c follow_symlinks]; EINVAL is the sole
  benign errno). Everything else — above all ENOENT on a missing
  operand — is now GNU's 'couldn't readlink X: <reason>' Fatal with
  status 4, wording via fsutil::reason. Previously the failure fell
  through to the can't-read path (rc 2).

Review-wave gate additions (sd590-601): the #1496/#1495 nested-
quantifier capture family (9 rows — opening-order numbering, empty
iteration counting toward {m,n} lower bounds, {2} empty match, {2,3}
recovery, POSIX equal-length alternation), the follow-symlinks
missing-file row sd599 (now PASSING after the fix), stdin 2q3 exit
code, v9.0 strverscmp rejection.

Gate: 379 rows, GNU-gated 378 PASS / 0 FAIL, win 1/0 (was 377/1 with
sd599 pinned as the known divergence).
cargo test -p winux-cmds sed: 18/0.

Also carried: run-gate.sh composite local-array split (backslash
stripping under the niubash gate host, probe-attested) — same fix
the xargs lane shipped.
@caomengxuan666

Copy link
Copy Markdown
Member Author

Review verdict: FAIL (F1 — blocking)

PR #1635 (head 09df368d, base b781ff35) cannot merge on this head: one real GNU divergence under -z + M.

The port is otherwise in strong shape: the strict parser matches GNU on 25+ probed BRE/ERE edge cases, the compiler/executor mirror compile.c/execute.c closely (including expression numbering, -V usage behavior, -i backup discipline, N-at-EOF), 17 sed unit tests pass in CI as part of the 719-passed suite, and the 379-row gate table is well-formed. Two things are not PR defects and need no author action: the head-CI i18n-drift red is a stale-base echo key (command.echo.option.repeat, resolved on the live tip — expected to clear on rebase), and the three merge conflicts are mechanical keep-both-sides additions (registry + gate scripts).

F1 — -z + M: . / [^...] / \W / \S diverge from GNU

Under -z+M, . and negated classes must exclude both \n and the NUL delimiter, and \W/\S must exclude the NUL delimiter (while still matching \n); the PR excludes only \n (and nothing for the shorthands). I re-probed the GNU side myself against local GNU sed 4.9 and confirmed the reviewer's results:

  • printf 'a\0b\0' | sed -z 'N;s/./X/gM' → GNU X\0X; the PR gives XXX (. matches the NUL).
  • printf 'a\0b\0' | sed -z 'N;s/[^a]/Y/gM' → GNU a\0Y; the PR matches the NUL.
  • N;s/\W/X/gM on a\nb\0c → GNU aXb\0c (\W matches \n, not NUL); same shape for \S.

Root: hardcoded \n at parser.rs:801 (negated-class push), matcher.rs:639 (DotRestricted), pike.rs:329 (Inst::Dot); shorthands at parser.rs:636-639 carry no delimiter exclusion. I confirmed in the diff that DotRestricted defaults line_delimiter to b'\n' while the ^/$ anchors are already delimiter-parameterized — so the anchors are correct and only these four constructs are wrong. The gate has no -z+M row for these constructs (only sd030 for $, which is correct), and no unit test uses line_delimiter = 0.

Rework spec

  1. Thread line_delimiter into DotRestricted (parser + matcher + NFA) so . excludes \n and the delimiter.
  2. Push the delimiter literal into negated classes when it differs from \n.
  3. Add the delimiter literal to \W/\S atoms under M when it differs from \n (\W must keep matching \n — pinned by the existing dialect test).
  4. Add gate rows + sed_dialect.rs cases with line_delimiter = 0.
  5. Re-run cargo test -p winux-regex, cargo test -p winux-cmds, the gate + stderr-check; then update-branch (resolving the three mechanical conflicts: lib.rs keep both registry lines, gen-cases.py keep both blocks + both registry entries, run-gate.sh comment-only) and re-verify the merged shape.

Note: the winux-regex suites (pike_equiv, sed_dialect) never run in CI (the workflow runs -p winux-cmds only — 0 occurrences in the rust-tests log), so their first green run is owed in the rework round either way. The gate is also not wired into CI and GATE-REPORT.md at head has no sed section (the 379/379 claim is body-asserted only), so the gate needs a Windows re-run at merge time.

Merge notes

Do not merge on this head. On eventual merge: Refs #1488 only (library landing; #1488 stays open until wire time).

@caomengxuan666

Copy link
Copy Markdown
Member Author

Library landed on main via #1690 (sed wire).

aphrody-dev pushed a commit to aphrody-labs/WinuxCmd that referenced this pull request Nov 20, 2026
The inventory still called six commands c++-only after their rust2
library/wire landed. Rows now say state=wired, status=rust2-wired,
engine=rust2, with commit evidence in the anchor:

- ls:   unixwin#1762 library 3025942; f87be22 wire (this branch)
- rm:   unixwin#1751 library 38e6835; f14bc60 wire (this branch)
- find: unixwin#1634 library; 792c31f (unixwin#1696 wire); unixwin#1633/unixwin#1658 help/version
- grep: unixwin#1660 library; 0eb0d28 (unixwin#1660 wire); -P face stayed on the C++
        PCRE2 path per DOCS/2.0-regex-engine-decision.md
- mv:   unixwin#1649; a0cfcd7 (unixwin#1773 reland that wired the 1.x retirement)
- sed:  unixwin#1635 library; f36f306 (unixwin#1690 wire)

No code changes; loc/oracle/test columns are historical measurements and
stay as recorded.
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