Skip to content

#1488 winux-regex Phase 1-3 - #1603

Merged
caomengxuan666 merged 4 commits into
mainfrom
rust2/winux-regex
Nov 13, 2026
Merged

caomengxuan666 merged 4 commits into
mainfrom
rust2/winux-regex

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Closes #1488 (part: winux-regex Phase 1-3, decision A of DOCS/2.0-regex-engine-decision.md). Unblocks the grep/sed wave: the rust2 side now has its own BRE/ERE engine, no regex crate, std-only.

What

rust2/crates/winux-regex — a semantic port of the C++ portable_regex engine (src/utils/regex.cppm, regex.cppm per-phase cited in commit messages), shaped per the decision doc: Regex::compile(syntax, pattern) -> Result<Regex, Error> + find_at/find_at_bytes (leftmost search from a position), match_at (anchored), matches_entire, find_all; Match carries capture-group spans; WorkLimit replaces the C++ thread_local per the 2.0 no-global-state contract. Perl syntax is out of scope (grep -P stays PCRE2).

Verification (GNU grep 3.11 / glibc regexec, WSL, LC_ALL=C)

  • 138-row pattern x input matrix vs GNU grep -o: 0 differing lines (committed baseline tests/matrix_expected.txt; differential driver examples/matrix_harness.rs; raw artifacts target/regex-probe/).
  • ~230-row accept/reject matrix (every row pre-probed), typed errors, AST-shape checks; ~110 match-semantics asserts transcribed from GNU grep -o / GNU sed probes.
  • cargo test --workspace green (winux-cmds 548 tests untouched & green), cargo fmt --check clean.

GNU divergences found in the C++ engine and fixed here (each probe-backed)

  1. trailing \ accepted (GNU: error); 2. backslash escaped inside [...] (GNU: ordinary member — [a\]] is {a,\} + literal ]); 3. unknown [:name:] accepted (GNU: error); 4. [[:word:]] accepted (GNU: error — word exists only via \w); 5. missing-min \{,n\}/{,n} rejected (GNU: valid, = {0,n}); 6. malformed ERE {...} errored (GNU: literal fallback; reversed bounds error after an atom, literal at expression start); 7. ERE stray top-level ) errored (GNU: literal); 8. BRE ^/$ anchored everywhere (GNU/POSIX: contextual, else literal); 9. BRE * always quantified (POSIX/GNU: literal at branch start / after initial ^); 10. ERE leading quantifiers made literals (GNU: repeat the empty expression); 11. reversed bracket ranges swapped silently (GNU: error, raw endpoints, even caseless); 12. x{} accepted (GNU: error). Remaining documented corner: glibc's leading-brace print quirk ({2,1}/{a} at expression start match with the brace consumed and excluded from the -o text) — pathological, documented in parser.rs, not emulated.

Out of scope / follow-ups

Perf: the C++ literal-prefix/first-byte fast paths (#1531) are not ported yet — semantics first; the grep wave should port them before perf-sensitive use. Unicode classes stay out (C-locale only, as scoped).

…x (winx#1488)

Port src/utils/regex.cppm detail::Parser to rust2/crates/winux-regex
(std-only, zero deps): AST nodes Literal/Dot/anchors/CharClass/
Sequence/Alternation/Capture/BackReference/Repeat, POSIX classes,
[[.coll.]]/[[=equiv=]], BRE \|\+\?\{m,n\} and GNU \b\B\<\>\s\w
shorthands, ERE + GNU backrefs, opening-order capture numbering (#1496).

GNU grep 3.11 (WSL, LC_ALL=C, glibc regcomp) was re-probed
pattern-by-pattern (target/regex-probe/*.sh, ~150 probes) and the
divergences found in the C++ engine were fixed to GNU behavior:
trailing backslash = error; backslash is an ORDINARY member inside
[...] (GNU [a\]] = {a,\} + literal ]); unknown [:name:] = compile
error; \{,n\}/{,n} missing-min forms valid; malformed ERE {...} falls
back to literal braces while reversed bounds error after an atom and
stay literal at expression start; glibc RE_DUP_MAX 32767 enforced in
both syntaxes; stray ERE top-level ) is a literal while BRE \) errors;
BRE context-dependent ^/$ anchors and POSIX literal-* positions;
ERE leading quantifiers repeat the empty expression; single-digit
backrefs with \0 a literal zero.

~230-row accept/reject matrix (tests/parser_accept.rs) encoded from the
probe outputs, plus typed-error and AST-shape checks. cargo test green,
rustfmt clean.
…ure semantics (winx#1488)

Port src/utils/regex.cppm Pattern (regex.cppm:630-1245) to matcher.rs:

- POSIX leftmost-longest: every attempt enumerates the full end-state
  set, first-maximal pos wins (GNU regexec order, NOT leftmost-first:
  'a|ab' over 'ab' -> 'ab').
- glibc-aligned captures: opening-order groups, exploration-order
  register selection, update_regs-style trailing empty-iteration undo
  for repeated groups (#1496: ((x)*)* on xxxx keeps \1=xxxx \2=x;
  \(a*\)\{2\} leaves the group empty while \{2,3\}/\{1,2\} keep aaa).
- #1495 anti-blowup: repeat expansion memoized per (iteration count,
  full state) with step/memo/output caps; a tripped cap degrades to a
  conservative no-match surfaced as ErrorKind::WorkLimit through the
  checked_* API (the C++ thread_local moved into the return path per
  the 2.0 no-process-global-state contract).
- Structural stack safety: sequence matching is an iterative fold and
  repeat expansion an explicit-stack DFS (a 32767-copy interval cannot
  blow the stack).
- UTF-8 codepoint '.' and word boundaries (D7 rule), \< \> \b \B,
  C-locale POSIX classes with -i cross-fold for lower/upper, folded
  backrefs, compile-time class-bound folding under -i (GNU-verified:
  raw reversed ranges error even caseless).

Two port bugs found by the matrix and fixed: parse_sequence dropped
the C++ is_alt_at_current break ('|' became a literal), and ERE
quantifier-at-branch-start handling. Also probed + fixed vs GNU:
reversed bracket ranges error on RAW endpoints even under -i (the C++
engine silently swapped); [a-Z] -i errors like [Z-A].

11 match tests (~110 asserts) transcribed from GNU grep -o / GNU sed
(glibc regexec) probes in target/regex-probe/: leftmost-longest,
capture selection, backrefs, anchors, word boundaries, UTF-8, -i
folding, find/find_at/match_at/matches_entire/find_all spans, work
budget. cargo test green, rustfmt clean.
…nterval expansion matrix (winx#1488)

- Per-byte class audit: the engine's 13 POSIX class tables are compared
  byte-by-byte (0x01..=0xFF minus 0x0A, line-framing limits) against the
  GNU grep 3.11 table probed under LC_ALL=C
  (target/regex-probe/class_table.sh -> gnu_class_table.txt) — 3302
  comparisons, all equal; newline kept POSIX-correct for cntrl/space.
- GNU divergence found and fixed: grep 3.11 REJECTS [[:word:]] as a
  class name ('Invalid character class name', probed) — the C++ engine
  accepted it as a never-matching class. PosixClass::from_name no longer
  knows 'word'; the word class exists only via the \w shorthand.
- Interval expansion matrix: {m}/{m,n}/{m,}/{0,n}/{0,0}/{,n}//\{,\}
  spans, intervals over groups/classes/backreferences, nested
  a{1,2}{3}, last-copy register rule (\(a\)\{3\} keeps 'a'),
  RE_DUP_MAX 32767 boundary at match time, -i cross-folded negated
  classes, xdigit/alpha composition shapes.

21 tests green (accept/reject ~230 rows, match matrix ~110 asserts,
3302 class-table comparisons + interval rows), rustfmt clean.
…o (winx#1488)

tests/matrix.tsv: 138 pattern x input combinations across BRE + ERE;
tests/matrix_expected.txt is the WSL GNU grep 3.11 (LC_ALL=C, glibc
regexec) output over the same table via
target/regex-probe/gnu_matrix.sh; tests/grep_matrix.rs re-runs the
engine over the table and requires byte-identical output. The engine
side diffed CLEAN against the GNU side (0 differing lines of 414).

Probing this matrix pinned three glibc brace corners and fixed one real
divergence:
- x{} is a GNU compile error ('Invalid content of {}') - the engine now
  errors after an atom; at an expression start glibc instead consumes
  {} zero-width (documented, not emulated).
- Leading invalid-interval braces ({2,1} / {a} at expression start)
  match with glibc's brace-consumption print quirk (the -o text
  excludes the leading brace); pathological shape, documented and
  excluded from the matrix rather than emulated.
- matrix_harness example added as the differential driver for the
  grep/sed wave gates.
- work_budget test shrunk to n=40 with a 30s hang guard (timing is not
  a perf gate under parallel runs).

cargo test --workspace green (winux-cmds 548 incl.), rustfmt clean.
@caomengxuan666
caomengxuan666 merged commit 2bc6f11 into main Nov 13, 2026
9 of 10 checks passed
aphrody-labs Bot pushed a commit to aphrody-labs/WinuxCmd that referenced this pull request Nov 15, 2026
…st (winx#1488, unixwin#1531)

Port of the C++ engine's compile-time prefilters (regex.cppm
Pattern::fast_ / build_fast_path — the kwset/dfa "must" analysis
precedent of unixwin#1531) to rust2/crates/winux-regex:

- anchored: first consumable element is `^` -> single attempt at 0,
  none when start > 0 (AnchorStart compares absolute positions).
- prefix: required literal prefix (Literal runs, single-member classes,
  {m} literal expansions, zero-width assertions transparent) ->
  memchr-style candidate jumps; the interpreter still validates every
  candidate through the unchanged local_attempt path.
- first: 256-byte first-byte set expanded per byte through the engine's
  own class_matches/fold rule (single source of truth, matcher's rule
  hoisted to a pub(crate) fn); legacy advance rule kept, only the
  futile attempts are skipped.
- pure_literal: whole tree Literal-only with no captures -> a prefix
  candidate IS the match, byte-for-byte the interpreter's result.
- Unmodeled shapes fall back to the legacy scan; a continuation-range
  prefix first byte is rejected in build (candidates would sit on
  positions the legacy traversal never attempts). Necessary conditions
  only — no semantic fork (unixwin#1550 lesson).

Correctness gates: the unixwin#1603 138-row GNU grep -o matrix is byte-identical
to the pre-change baseline in BOTH feature modes; new
tests/fastpath_equiv.rs (hand corpus per tier + 120k-seed deterministic
fuzz) requires fast vs disable_fast_path equality across checked_find /
checked_match / find_all / matches_entire, WorkLimit surfaced identically.
The filters live behind the default `fast-path` feature plus a
doc(hidden) disable_fast_path() knob for A/B diffing.

Performance (47 MiB / 819k lines, release, unixwin#1531 shape): grep -c fox
9.713s -> 57.979ms (167x); first-tier (f|F)(o|O)(x|X) 16.726s ->
405ms (41x); dot-head fallback control unchanged (~1% noise);
pathological (.*)*b and \(.*\)*b long lines stay WorkLimit-bounded in
both modes (75-80s, unchanged) — the unixwin#1603 caps are untouched.
@caomengxuan666
caomengxuan666 deleted the rust2/winux-regex branch November 18, 2026 05:50
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.

[2.0 长线] 命令库化:显式 IO 的库形态命令集(Rust 重写候选)与机械替换路线

1 participant