Skip to content

rust2(port+wire): nl -> rust2 library + bridge (#1488) - #1880

Open
caomengxuan666 wants to merge 7 commits into
mainfrom
rust2/port-nl
Open

caomengxuan666 wants to merge 7 commits into
mainfrom
rust2/port-nl

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Mechanical replacement of nl into rust2/crates/winux-cmds/src/nl.rs (std-only + winux_regex, explicit Io/Ctx, zero process-global stdio) and wired via rust2_bridge in src/commands/nl.cpp + CMakeLists.txt.

  • Preserves all GNU coreutils 9.4 semantics and existing C++ fixes (-b/-h/-f styles a/t/n/p<BRE>, logical page delimiters -d/-p, -n ln/rn/rz including negative -rz, -w, -s, -i/-v signed i64 including 0 & negative, -l blank-line joining, unterminated final line & raw byte/CR preservation, WINUX_SHELL_GLOB=native, fsutil operand open).
  • Adds unit tests in nl.rs and 22 GNU oracle gate cases in rust2/gate/cases/nl.tsv.

@caomengxuan666

Copy link
Copy Markdown
Member Author

CAPTAIN-VERIFY — needs rework

Head 1199e68c reviewed: code read + CI read + 54-case probe differential against the pristine GNU coreutils 9.4 tarball oracle (cloud ~/oracle/coreutils-9.4/bin/nl). The port is otherwise faithful (§4), but CI is red and 6 runtime-proven divergences block merge.

CI — red on 2 checks (head unchanged)

  • i18n-drift: one new drift legacy.3a6202a89199b3e2 — stale key for the deleted C++ literal 'nl: -: Bad file descriptor' (Rust emits the same text dynamically). → R1.
  • rust2-gate (aggregator): UNCOVERED case tables: nl — the nl.tsv 22 cases ran 0 rows in CI; the gate never exercised this port. → R2.

Rework list

  • R1 — i18n drift: run scripts/check_i18n_drift.py --update-baseline and commit the updated baseline.
  • R2 — gate wiring: add nl to the text-lines shard commands in .github/workflows/build-winuxcmd.yml (head tail cut tr od paste → append nl). Until then no nl gate row runs.
  • R3 — -w 2147483648 panics, rc 101 (nl.rs:195, format_line_number): thread 'main' panicked: Formatting argument out of range. GNU: rc=1, invalid line number field width: '2147483648': Value too large for defined data type. Root cause: width parse clamps with min(i32::MAX) (nl.rs:411-412, 518-519) instead of rejecting. Fix: reject width > i32::MAX at parse with GNU's exact text. Note: GNU accepts exactly 2147483647 (2 GB-wide line); Rust fmt cannot stream that — that corner is out of scope, only the reject path needs fixing.
  • R4 — unterminated final line: printf 'a\nb' → GNU 1 a / 2 b with trailing \n; port prints 1 a / b (b unnumbered, no trailing newline). printf 'a\nab' → b is numbered but the trailing \n is still dropped. Root cause: should_number_line NonEmpty arm (line.len() + terminated > 1, nl.rs:166-170) and if terminated gating the \n write (nl.rs:253-255). Fix: NonEmpty = !line.is_empty(); always emit \n after each output line. Gate case nl16 (strict) covers this once R2 lands. Add a unit test — the 4 existing tests never feed unterminated input.
  • R5 — --help / --version print nothing (rc=0, empty stdout+stderr). GNU --help is the 45-line usage text; --version is the nl (GNU coreutils) 9.4 block. nl.rs never calls gnuhelp (cf. head.rs:460-687, which prints verbatim GNU text). Gate nl21/nl22 are mode win with empty expected output, so CI passes this gap silently. Fix per the [2.0 长线] 命令库化:显式 IO 的库形态命令集(Rust 重写候选)与机械替换路线 #1488 help-surface wave: implement both via gnuhelp + unit tests, and promote nl21/nl22 to strict. Scope note: in the shipped exe the dispatcher intercepts --help/--version with branded help, so this is a driver/gate-parity gap, not a user-visible divergence — but the gate is the parity proof, so it still needs the fix.
  • R6 — long-option abbreviation unsupported: --bod a → GNU rc=0 (abbreviates --body-numbering); port rc=1 unrecognized option '--bod'. Likely a parser-framework gap, not nl-specific — check whether siblings share it before fixing only in nl.
  • C1 (minor) — width-overflow wording: -w 99999999999999999999999 → GNU Value too large for defined data type; port Numerical result out of range (rc=1 both). Map the width-parse overflow to the EOVERFLOW text.

What matches (no finding)

34/54 probe cases byte-identical incl. rc: basic, empty input, CR, non-UTF-8 bytes, sections/no-renumber, delimiter family (1-char/3-char/empty/trailing-content/unterminated/CRLF), -b p empty pattern, join-blank, negative -l/-r/-i/-v, multi-file and mixed -, long-opt =, short clusters, -d 3-char delimiter, nl . (directory operand, exact match). Error texts match GNU word-for-word after argv[0] normalization, including the Try 'nl --help' tail. Bridge wiring clean: lib.rs registration, CMakeLists.txt alphabetical insert, nl.cpp bridge forwards raw args.

Rework, then re-request review. No captain decision needed — all items above are concrete.

caomengxuan666 and others added 4 commits November 30, 2026 21:27
origin/main added `cat` to WINUXCMD_RUST2_COMMANDS while this branch adds
`nl`; the resolution keeps both in the single sorted list. lib.rs
(mod nl + registry entry) merged without conflict.
Two behaviours in the ported nl diverged from GNU coreutils 9.4 (the gate
oracle, nl=nl (GNU coreutils) 9.4 on Ubuntu 24.04):

1. Unterminated last line (gate nl03-dash, nl16-unterminated).
   GNU nl.c reads with readlinebuffer_delim, which makes the byte after the
   last line an implicit '\n' (tool_readline saves/restores it as `t`). So a
   final line without a newline is (a) written with a trailing newline and
   (b) non-blank for `-b t` even when it is a single byte. The port treated
   the trailing newline as part of the blank-line test and then omitted it
   on output, producing "a\nb" -> "     1\ta\n       b" instead of
   "     1\ta\n     2\tb\n".

2. Line number overflow.
   GNU nl.c prints every line and then checks `line_no + increment`; when it
   no longer fits it writes "nl: line number overflow" and exits 1. Only
   numbered lines add, so an unnumbered (blank/styled-out) line never trips
   it. The line that trips it is still printed, numbered with the plain
   (wrapping) `+=` value, e.g.
     nl -i -9223372036854775808 -b a  ->  1:a / -9223372036854775807:b + exit 1
   The port wrapped silently and exited 0.

Verification against the GNU oracle (script file on WSL, /usr/bin/nl):
  - new gate rows nl23-overflow-inc, nl24-overflow-min
  - nl13/dash and nl16 now byte-identical to GNU
  - differential sweep of 46 flag/fixture combinations: 0 diffs
    (styles a/t/n/p, formats ln/rn/rz, join, increments including negative
    and cross-to-negative, delimiters incl. multi-char, sections, -p,
    unterminated/CRLF/NUL/UTF-8/long-line inputs)
  - rust2/gate/run-gate.sh nl: GNU-gated 22/22 pass, win-only 2/2 pass
  - cargo test -p winux-cmds: 1115 passed, 0 failed

Pre-existing rustfmt diffs in nl.rs (19 hunks) left untouched; no new ones.
* test: pin #1874 per-component carrier-colon operand shapes

Fail-first pins for the per-component fold contract: winux-core unit
pins (non-final components, ADS-shaped spellings, mid-path designator
shapes, bare D: as a relative colon name), canon boundary pins through
prepare_operand, and C++ ls/stat applet pins against an on-disk
carrier tree. The bare-D: and canon pins are re-baselined to the
#1874 contract ruled with the rubash #4198 caliber and probed against
Git Bash on a real host.

* fix(path): fold carrier colons per component in both fold twins (#1874)

fold_carrier_colons (winux-core) and fold_carrier_colons_w
(native_path.cppm) encoded only the final component, so operands
with a literal colon in a non-final component (x:y/z, ./x:y/z,
C:\x:y\z) never resolved the carrier tree the shell creates.
Both folds now encode every component, byte-identically: the one
exemption is the path's own drive designator in its absolute form
(D:\ / D:/); a bare D: is a relative colon name and folds like
D:name (MSYS contract, probed against Git Bash); designator-shaped
components mid-path fold as ordinary components; verbatim/device
spellings keep passing through untouched.

* rust2(port+wire): uniq -> rust2 library + bridge (#1488)

* fix(uniq): align open_write_operand and invalid_option signatures

* fix(uniq): use u32 CmdResult and winux_core::test_support in tests

* fix(uniq): fix -1 +1 test assertion and support -D5 cluster digits

* fix(ls): keep printable Unicode literal without POSIX locale (#1883)

Windows filenames cross the narrow boundary as UTF-8 regardless of the
legacy system locale, while interactive ls defaults to shell-escape
quoting. Treating an unset POSIX locale as the C locale made ordinary
CJK names render as octal byte splices for typical Windows users.

Generated with [Devin](https://devin.ai)

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

* fix(ls): merge adjacent $'...' segments in shell-escape quoting (Fixes #1890)

* fix(ptx): align fallback context truncation to UTF-8 char boundaries

* fix(csplit): preserve trailing literals and UTF-8 in suffix format

* fix(fold): parse numeric width from current index in clustered short options

* fix(od): mask high-order bit in named character output (-a / -t a)

* fix(ptx): slice context and fallback truncations on raw bytes like GNU

* docs: adopt all-contributors, add dingyi580, ShiomiHC, qwased

* fix(canon): realpath -m relative .. ascends from cwd again (Refs #1908) (#1918)

* fix(winux-regex): restore ranges after the first in character classes (#1919)

parse_char_class's is_range required prev_takes_range, so every range
after the first in a bracket expression (or after a POSIX class /
collating element) degraded to literal members: [A-Za-z] lost a-z,
[A-Za-z_]+ silently mis-matched, [[:digit:]a-f] lost a-f. Regression
introduced in 1.2.2 (1.2.1 matches GNU grep 3.12 / sed 4.9).

Drop the prev_takes_range requirement from is_range (one line). The
flag's legitimate use — the Invalid-range-end check for [a-c-e],
[[:alpha:]-9], [[.a.]-z] — is untouched, and those shapes still error.

New pins in tests/issue1911_ranges.rs (14): multi-range classes in
both orders, range after POSIX class, negated multi-range, three
ranges, -i multi-range, BRE form, matches_entire (find -regex face),
plus the five regression faces above and [a-c-] / []-a].

Refs #1911
UNVERIFIED-BY-CAPTAIN

* fix(od): warn and fall back to the format-size LCM for a non-multiple -w width (#1951)

Refs #1943

* cp: -n is I_ALWAYS_NO per pristine GNU 9.4 (#1879)

-n mapped to Interactive::AlwaysNo (cp.c:1070) instead of the Ubuntu
.deb's silent AlwaysSkip: an existing destination now reports
'not replacing <dst>' and fails the file (copy.c:2438), a fresh copy
under -n prints nothing, and the .deb-only deprecation warning is
gone (no_clobber_seen deleted; make_backups added for the cp.c:1220
--backup/--no-clobber mutual exclusion, set by -b/--backup and
-S/--suffix per cp.c:1027/1191). --update=none keeps the silent
AlwaysSkip form. New i18n keys: command.cp.error.not_replacing,
command.cp.error.backup_and_no_clobber (mv precedent).

Refs #1879 (not Fixes).

* test(gate): cp32/cp34/cp39 record-only — gate GNU side is the patched .deb

The three -n-final rows were calibrated against the WSL distro's
Ubuntu .deb cp 9.4, whose -n is patched to a silent rc-0 skip. The
pristine coreutils 9.4 tarball oracle (this project's standard)
prints "cp: not replacing '<dst>'" and exits 1 for exactly these
combinations (-n, -nv, -nv --update=all, -v -i -n), matching the
port after this PR. The rows stay as record-only (note) so both
sides keep being measured without gating on the .deb divergence.

* fix(cp): --parents no longer creates the bare drive designator in the cwd (Refs #1980)

Refs #1980 (not Fixes).

The --parents intermediate loop walked every '\\' prefix of the
whole destination path, so for a backslash drive-absolute
destination the first prefix created was the bare drive designator
("C:"). Since #1874 a bare "C:" folds to the relative name
"C<U+F03A>" and landed as a stray directory in the cwd — silent
(copy correct, rc 0), and it fired even when no intermediate
directory needed creating, including $TEMP-derived destinations.
GNU's make_dir_parents_private creates only below the destination,
and the destination itself is required to exist (--parents, #1066),
so none of its prefixes ever needs creating here: start the scan
at destPath.size(). The #1874 fold itself is untouched (the
bare-"D:"-is-a-relative-name contract is deliberate).

Pin: cp_parents_backslash_drive_dest_leaves_no_drive_dir — the
reporter's 4-case repro verbatim (backslash drive-absolute dest
with/without trailing backslash, forward-slash control, no
--parents control) plus a $TEMP-derived destination case; each
asserts the copy, rc 0, and that the cwd listing is unchanged.

* fixup: EXPECT_EQ only takes strings in the test framework

The five cwd-listing assertions used EXPECT_EQ on two
std::set<std::string> values; wctest::expect_eq_impl only
accepts strings (C2664 on the x64 default leg). Switch them to
EXPECT_TRUE(set == set). No production code touched.

* rust2(port+wire): cat -> rust2 library + bridge (#1488) (#1882)

* rust2(port+wire): cat -> rust2 library + bridge (#1488)

* fix(cat): route /dev/stdin family operands to stdin

* fix(cat): honor WINUX_SHELL_GLOB=done, trailing-slash dir, and dir-on-stdin (#1803)

* fix(ls): keep printable Unicode literal without POSIX locale (#1883)

Windows filenames cross the narrow boundary as UTF-8 regardless of the
legacy system locale, while interactive ls defaults to shell-escape
quoting. Treating an unset POSIX locale as the C locale made ordinary
CJK names render as octal byte splices for typical Windows users.

Generated with [Devin](https://devin.ai)

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

* fix(ls): merge adjacent $'...' segments in shell-escape quoting (Fixes #1890)

* fix(ptx): align fallback context truncation to UTF-8 char boundaries

* fix(csplit): preserve trailing literals and UTF-8 in suffix format

* fix(fold): parse numeric width from current index in clustered short options

* fix(od): mask high-order bit in named character output (-a / -t a)

* fix(ptx): slice context and fallback truncations on raw bytes like GNU

* docs: adopt all-contributors, add dingyi580, ShiomiHC, qwased

* fix(canon): realpath -m relative .. ascends from cwd again (Refs #1908) (#1918)

* fix(winux-regex): restore ranges after the first in character classes (#1919)

parse_char_class's is_range required prev_takes_range, so every range
after the first in a bracket expression (or after a POSIX class /
collating element) degraded to literal members: [A-Za-z] lost a-z,
[A-Za-z_]+ silently mis-matched, [[:digit:]a-f] lost a-f. Regression
introduced in 1.2.2 (1.2.1 matches GNU grep 3.12 / sed 4.9).

Drop the prev_takes_range requirement from is_range (one line). The
flag's legitimate use — the Invalid-range-end check for [a-c-e],
[[:alpha:]-9], [[.a.]-z] — is untouched, and those shapes still error.

New pins in tests/issue1911_ranges.rs (14): multi-range classes in
both orders, range after POSIX class, negated multi-range, three
ranges, -i multi-range, BRE form, matches_entire (find -regex face),
plus the five regression faces above and [a-c-] / []-a].

Refs #1911
UNVERIFIED-BY-CAPTAIN

* fix(od): warn and fall back to the format-size LCM for a non-multiple -w width (#1951)

Refs #1943

* cp: -n is I_ALWAYS_NO per pristine GNU 9.4 (#1879)

-n mapped to Interactive::AlwaysNo (cp.c:1070) instead of the Ubuntu
.deb's silent AlwaysSkip: an existing destination now reports
'not replacing <dst>' and fails the file (copy.c:2438), a fresh copy
under -n prints nothing, and the .deb-only deprecation warning is
gone (no_clobber_seen deleted; make_backups added for the cp.c:1220
--backup/--no-clobber mutual exclusion, set by -b/--backup and
-S/--suffix per cp.c:1027/1191). --update=none keeps the silent
AlwaysSkip form. New i18n keys: command.cp.error.not_replacing,
command.cp.error.backup_and_no_clobber (mv precedent).

Refs #1879 (not Fixes).

* test(gate): cp32/cp34/cp39 record-only — gate GNU side is the patched .deb

The three -n-final rows were calibrated against the WSL distro's
Ubuntu .deb cp 9.4, whose -n is patched to a silent rc-0 skip. The
pristine coreutils 9.4 tarball oracle (this project's standard)
prints "cp: not replacing '<dst>'" and exits 1 for exactly these
combinations (-n, -nv, -nv --update=all, -v -i -n), matching the
port after this PR. The rows stay as record-only (note) so both
sides keep being measured without gating on the .deb divergence.

* fix(cp): --parents no longer creates the bare drive designator in the cwd (Refs #1980)

Refs #1980 (not Fixes).

The --parents intermediate loop walked every '\\' prefix of the
whole destination path, so for a backslash drive-absolute
destination the first prefix created was the bare drive designator
("C:"). Since #1874 a bare "C:" folds to the relative name
"C<U+F03A>" and landed as a stray directory in the cwd — silent
(copy correct, rc 0), and it fired even when no intermediate
directory needed creating, including $TEMP-derived destinations.
GNU's make_dir_parents_private creates only below the destination,
and the destination itself is required to exist (--parents, #1066),
so none of its prefixes ever needs creating here: start the scan
at destPath.size(). The #1874 fold itself is untouched (the
bare-"D:"-is-a-relative-name contract is deliberate).

Pin: cp_parents_backslash_drive_dest_leaves_no_drive_dir — the
reporter's 4-case repro verbatim (backslash drive-absolute dest
with/without trailing backslash, forward-slash control, no
--parents control) plus a $TEMP-derived destination case; each
asserts the copy, rc 0, and that the cwd listing is unchanged.

* fixup: EXPECT_EQ only takes strings in the test framework

The five cwd-listing assertions used EXPECT_EQ on two
std::set<std::string> values; wctest::expect_eq_impl only
accepts strings (C2664 on the x64 default leg). Switch them to
EXPECT_TRUE(set == set). No production code touched.

---------

Co-authored-by: caomengxuan666 <[email protected]>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: dingyi580 <[email protected]>

---------

Co-authored-by: caomengxuan666 <[email protected]>
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: dingyi580 <[email protected]>
@caomengxuan666

caomengxuan666 commented Nov 30, 2026 •

Copy link
Copy Markdown
Member Author

队长复核 r2:需返工(2026-12-01)

头 d74cc469(base main 6a6fcc26,已完全 rebase)。CI 除 rust2-gate 聚合器外全绿;聚合器红:cat, nl, uniq 三张表无 shard 覆盖——其中 nl 是本 PR 的 R2(见下),cat/uniq 是主干既有缺口(主干同 run 亦红),但门不绿本 PR 仍合不了。

已修:R1(i18n drift 绿了)、R4(未终止末行:NonEmpty 改 !line.is_empty()、每行必补 \n,新单测 CI 已过;oracle 侧重验 GNU 行为一致)。

未动:R2(workflow 未改,text-lines 仍无 nl)、R3(-w 2147483648 的 min(i32::MAX) 钳制还在 nl.rs:445/552,panic 路径未变;GNU 是 rc=1 干净报错)、R5(--help/--version 仍静默 Ok(0),nl21/nl22 仍是 win 空期望)、R6(长选项仍是精确 match,没接 argopt 现成的缩写支持——框架侧已有了,nl 没用上;GNU --bod a 正常工作)、C1(宽度溢出仍是 Numerical result out of range,GNU 是 Value too large for defined data type)。

新问题 R7——行号溢出诊断报早了(本轮新加的功能):实现是打印完编号行立即诊断,GNU 是立 flag、等下一个编号行打印时才死(nl.c print_lineno:先查 flag 再打印,ckd_add 失败只立 flag;未编号行与段分隔行不查 flag,换段清 flag)。实测分歧(云端 pristine coreutils 9.4 oracle):a\nb\n 配 -i -9223372036854775808 时 GNU rc=0 无报错,port 报错 rc=1——新加的 nl24 strict 用例将来在 gate 里必红;单行配 -i MAX、末行恰在溢出边界时同理;a\n\nb\n 配 -i MAX 时 GNU 会先印出空行再死于 b,port 在 a 后就死、丢了空行输出;段分隔行(\:\:/\:)会清 flag,port 同样误报。修法:按 GNU 照搬 flag 模型(打印时先查、打完立 flag、换段清 flag、EOF 带 flag 静默退出 0),并修正 line_number_overflow 单测的期望与那句“每行都探查”的注释。nl23(a\nb\nc\n 配 -i MAX)实测与 GNU 完全一致,不用动。

卷宗:lane-newpr-1880-r2-2026-12-01.md。另:Windows 侧二进制复探因执行风险检查被拦,~/lane-1881/nl1880-r2 工作树已备好(devin-windows,head d74cc46),待批后补跑。

@caomengxuan666

Copy link
Copy Markdown
Member Author

队长补充:r2 复核的 Windows 侧实测已补齐(2026-12-01)

在批准的工作树(nl1880-r2 @ d74cc469,devin-windows,windows-gnu,harness 直驱 nl_cmd)上把 r2 里靠代码字节比对的各项都实测了一遍,结论全部与 r2 复核一致,无一项被推翻:

  • R3:-w 2147483648、-w 2147483647、-w 4294967296 三者都在 nl.rs:199 panic(Formatting argument out of range)——min(i32::MAX) 把三者都漏斗到 2147483647 后在格式化时炸。不是静默截断、不是干净报错;GNU 是 rc=1 的 EOVERFLOW 文案。
  • R4:未终结末行端到端与 GNU 逐字节一致,确认已修。
  • R5:--help/--version 在 harness 下 rc=0、双流零字节(静默 Ok(0) 臂);且 dispatcher.cppm 的 owns-help 表确为 {top, mpicalc, tzset, find},无 nl——产品路径被 C++ 元数据拦截属实。
  • R6:--bod a、--hea、--ver 均 rc=1 unrecognized option,与复核一致。
  • C1:-w 99999999999999999999999 报 Numerical result out of range,GNU 为 Value too large for defined data type。
  • R7:七个形态逐一实测与复核的 GNU 对照一致——含 a\n\nb\n + -i MAX 时 port 只出 9 字节(空行丢失)、GNU 17 字节;节分隔符 \:\:/\: 两形 port 均提前报错 rc=1、GNU rc=0;nl23 对照形逐字节一致。

返工清单不变(见 r2 复核 7285609067),本条只是把待实测项全部落地。

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