Skip to content

fix(expand): propagate quoted-IFS simulation signal instead of IFS_GLUE heuristic (Fixes #3263) - #4073

Merged
caomengxuan666 merged 1 commit into
masterfrom
fix/3263-quoted-ifs-glue
Nov 21, 2026
Merged

caomengxuan666 merged 1 commit into
masterfrom
fix/3263-quoted-ifs-glue

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Fixes #3263.

Summary

Reproduced against WSL GNU Bash 5.3.x (IFS=" ,"; v=; echo ok > " a$[1+2]",$v creates " a3," in GNU, whereas rubash stripped the leading space to "a3," because mark_literal_ifs_chars placed IFS_GLUE on , while mark_quoted_ifs_from_raw bailed out on $[1+2], and expand_redirect_target's trust condition (a) trusted the word based on the presence of IFS_GLUE).

  • src/executor/command_prepare.rs: added mark_quoted_ifs_from_raw_checked(...) -> (String, bool) propagating whether simulated == cooked (mark_quoted_ifs_from_raw delegates to it), plus unit test mark_quoted_ifs_from_raw_checked_reports_simulation_bail (GNU subst.c:11229, 11862, 12377, redir.c:298).
  • src/executor/expand_word.rs: updated expand_redirect_target to gate on quoted_simulation_ok || !raw_word_has_simulation_dependent_ifs(raw, ifs) instead of the IFS_GLUE / ANSI_C_IFS_GUARD existence heuristic.
  • Added regression suite tests/issue3263_quoted_ifs_glue.rs (2 tests).

Verification

  • rustfmt --edition 2021 --check passed on src/executor/command_prepare.rs, src/executor/expand_word.rs, and tests/issue3263_quoted_ifs_glue.rs.
  • cargo test --lib mark_quoted_ifs_from_raw: 1/1 passed.
  • cargo test --test issue3263_quoted_ifs_glue: 2/2 passed.

@caomengxuan666
caomengxuan666 force-pushed the fix/3263-quoted-ifs-glue branch from d007756 to 38eb719 Compare November 21, 2026 16:36
@caomengxuan666
caomengxuan666 merged commit eb39c97 into master Nov 21, 2026
10 of 12 checks passed
caomengxuan666 added a commit that referenced this pull request Nov 30, 2026
…ixes #4043) (#4057)

* fix(redir): materialize undo-save slot saturation EMFILE diagnostics (Fixes #4043)

* fix(vars): preserve GNU export attributes on imported bash-managed variables (Fixes #3534) (#4034)

* fix(redir): preserve undo-saved source bindings against same-walk persist move closes (Fixes #4027) (#4041)

* fix: preserve raw quote delimiters and backslashes in bad substitution diagnostics (rubash#4029) (#4039)

Captain graft onto 54aef437: reconciled with #4025 (rubash#3543) — the raw channel names which word is cited; bad_substitution_display decides how a parser word's comsub spans print (canonicalized), runtime text stays raw. Prompt-string passes now suppress the outer parser word's raw record.

* fix(funsub): accept compound-command-terminated funsub bodies without trailing separator (Fixes #4017) (#4026)

* fix(funsub): accept compound-command-terminated funsub bodies without trailing separator (Fixes #4017)

* chore(funsub): reword tokstr comments to dodge the comment-blind registry scan

The registry consistency test's claim_literals scan is comment-blind and extracted a shadow claim for `{` from the `== "{"` shape in five single-line comment copies (command_substitution.rs, embedded_mutations.rs, alias_stream.rs, skip.rs x2). Reworded to `is the single-char "{"` -- comment text only, zero behavior change. Captain review-4026 section 2.

* fix(expand): propagate quoted-IFS simulation signal instead of IFS_GLUE heuristic (Fixes #3263) (#4073)

* fix(vars): treat UNSET_DYNAMIC_VARS-severed imported scalars as live cells in parameter operators (Fixes #4062) (#4069)

* test(diag): pin #2665 D1 diagnostic line-number shapes against GNU (Fixes #3183) (#4075)

* test(conditional): add regression pins for bounded =~ regex compile cache (Fixes #2827) (#4074)

* fix(stack): track logical stack-top changes under readonly PWD in pushd/popd (Fixes #3421) (#4070)

* fix(verbose): align eval, trap, and interactive stdin set -v read-point echo with GNU (Fixes #3320) (#4071)

* fix(command_text): preserve list-only redirects in async respawn text (Fixes #4047) (#4055)

* fix(case): materialize procsub only from parser metadata, not expanded subject (Fixes #4007) (#4053)

* fix(braces): treat ASSIGN_HOISTED_SQUOTE spans as opaque to brace expansion (Fixes unixwin/niubash#1060) (#4052)

* fix(expand): count extended UTF-8 non-scalar sequences as one character in ${#v} and ${v:off:len} (Fixes #4035) (#4048)

* test(issue3997): snapshot inheritable parent fds in fd-enumeration pins (Fixes #4054) (#4061)

* test(goldens): split upstream_suite_slice_snapshots per slice and serialize comsub2 (Refs #4038)

Per-slice split of the goldens snapshot test so one slice's mismatch no longer masks later slices; comsub2 serialized via the existing heavy_lock. Refs #4038 (the slice nondeterminism itself remains open there).

* fix(exec): convert POSIX path values in native child env and honor MSYS2_ENV_CONV_EXCL (Fixes unixwin/niubash#1001) (#4064)

* fix(coproc): record foreground wait on Windows external child waits (Fixes #3948)

* fix(cat): classify the `-` operand's stdin source without draining it (Refs #3995)

* fix(redir): share single open file description for <> on /dev/zero and map <> list bounds (Fixes #3939)

* fix(fd): isolate kernel stdio closes in nested subshell, comsub, and scoped exec walks (Fixes #4044) (#4049)

* fix(coproc): settle displaced stdout writer at child exit/apply instead of retirement (Fixes #4008) (#4014)

* fix(expand): protect quoted non-blank IFS chars in ${...} operator RHS (Fixes #4003) (#4015)

* fix(cat): serve dup2 fd-table face for >&N redirects instead of /dev/fd reopen (Fixes #3980) (#4021)

* fix(print_cmd): render $BASH_COMMAND redirections via ast_print::print_redirection_text (Fixes #3539) (#4023)

* fix(expand): reject unclosed backticks in glued brace-expansion products (Refs #3969) (#4020)

Captain graft on top of the original PR head (rebased to master 38fdd995): the brace-product bad-substitution verdict is latched with a discard-only class marker (ShellState.bad_substitution_discard_only), so the generic latch consumers no longer promote it to FORCE_EOF under POSIX mode. GNU returns &expand_wdesc_error for expand_word_internal's backquote case in every mode (subst.c:11568-11593) - under the argv[0] `sh` name the un-grafted head aborted the whole script (exit 1, -c exit 127) where GNU-as-sh discards the command and continues (exit 0, -c exit 1). The ${...} class keeps its FORCE_EOF semantics. Adds sh-name regression pins (script-file and -c forms) to tests/issue3969_brace_backquote_rescan_regressions.rs.

* fix(driver): track multi-line quote and substitution state in heredoc scanner (Fixes #3962) (#4018)

* fix(executor): materialize procsub redirect targets on null commands (Refs #3994)

execute_empty_words_command never routed through
command_with_process_substitution_files, so a parser-recorded
<(...) / >(...) redirect target on a command-less assignment
reached the redirect apply layer as literal text and was probed
as a filesystem path: `x=1 < <(sleep 1)` reported
`<(sleep 1): No such file or directory` and failed, where GNU
(execute_null_command -> do_redirections over the same list;
redirection_expand, redir.c:298) silently succeeds.

The wrapper admits exactly the redirects the materialization
arms themselves admit (redirect_target_span_is_recorded,
rubash#1931 — a quoted "<(cmd)" stays a literal filename),
materializes through the same function, and finishes through
the same finish_process_substitutions with the materialized
paths' completion convention (inner Err governs, finish runs
best-effort; on inner Ok the finish result governs).

What this PR deletes: nothing. The former
execute_empty_words_command body is renamed
execute_empty_words_command_inner unchanged; the wrapper is the
only new code.

UNVERIFIED-BY-CAPTAIN

* fix(executor): let the reject gate adjudicate nounset redirect words (Refs #4001)

* fix(complete): exclude declared-unset variables from compgen listings (#3986)

GNU pcomplete.c:400 it_init_arrayvars -> variables.c:4416 all_array_variables
(visible_array_vars: invisible_p(var) == 0), pcomplete.c:619 it_init_variables
-> variables.c:4319 all_visible_variables (visible_var: invisible_p(var) == 0),
and variables.c:4350 all_exported_variables (visible_and_exported:
invisible_p(var) == 0) all exclude att_invisible (declared-but-never-assigned)
variables.

Filter DECLARED_UNSET_VARS (and underlay attrs.declared_unset) in
variable_completion_candidates, array_variable_completion_candidates, and
exported_variable_completion_candidates in src/builtins/complete.rs.

Fixes #3950

* perf(parser): add bounded alias-aware content-keyed runtime parse cache for eval/trap/source (Fixes #2828) (#4078)

Captain rebase assembly onto current master (per-file three-way merges; PR per-file stats preserved exactly).

* refactor(platform): introduce runtime Platform semantic axis for signal table (Refs #2829) (#4085)

Captain rebase assembly onto current master (per-file three-way merges; PR per-file stats preserved exactly).

* fix(signals): re-queue trapped SIGINT when foreground child exits normally (Refs #4002) (#4066)

Captain rebase assembly onto current master (code half only; pin-expectation half split to PR #4104). Includes the captain comment correction above the hunk: the child_caught_sigint == 1 discard holds only while SIGINT is untrapped; the trapped case is re-queued by the new branch.

* test(signals): flip issue698/issue977 mid-wait pins to the adjudicated DISCARD expectations (Refs #4002) (#4104)

Captain rebase assembly onto current master (pin files un-drifted; PR blobs taken verbatim).

* fix(exec): preserve raw bytes in child process environment on Unix (Fixes #3965) (#4010)

Captain rebase assembly onto current master (per-file three-way merges; PR per-file stats preserved exactly).

* fix(parser,driver): report token syntax errors inside unclosed funsub ${ (Fixes #4080) (#4084)

Captain rebase assembly onto current master (per-file three-way merges; PR per-file stats preserved exactly).

* fix(parser): case `;` after `in` is a syntax error; print procsub body newlines verbatim before closers (Refs #4080) (#4100)

Captain rebase assembly onto current master (base redirected from the #4084 graft branch to master; per-file three-way merges; #4100 incremental stats preserved exactly).

* feat(api): add Session cooperative cancellation token polled at safe points and builtin wait loops (Fixes #2810) (#4079)

Captain rebase assembly onto current master (per-file three-way merges with the graft's TRUE parent 19e73b70; PR per-file stats preserved exactly).

* fix(vars): track imported SECONDS offset separately from SHELL_START_EPOCH (Fixes #4059) (#4063)

Captain rebase assembly onto current master (init.rs three-way merge; PR per-file stats preserved exactly).

* fix(vars): key att_noassign/att_nounset on live dynamic status for imported bash-managed scalars (Fixes #4060) (#4067)

Captain rebase assembly onto current master (5 drifted files three-way merged; PR per-file stats preserved exactly).

* release: rubash 1.5.1 version bump (Cargo.toml + lock, captain) (#4121)

Roll CHANGELOG [Unreleased] to [1.5.1] - 2026-11-22, open a fresh Unreleased.
Refs niubash#792 release line; frozen head eeb424da (captain freeze 2026-11-22).

* docs(changelog): expand [1.5.1] with the full window closure list (#4124)

* docs: refresh code-size table + badge for release

* style: cargo fmt — clear the v1.5.1 release formatting gate (#4134)

Whitespace-only reformatting plus rustfmt canonical trailing-comma
removals (3 files, 1 byte each). No token, AST, or codegen change.
Unblocks the v1.5.1 tag Release run, which died at Verify formatting.

Co-authored-by: caomengxuan666 <[email protected]>

* docs: refresh code-size table + badge for release

* wave2 assembly of #4082 onto 71e433f2 (content = PR tree, verified) (#4082)

* wave2 assembly of #4081 onto 71e433f2 (content = PR tree, verified) (#4081)

* wave2 assembly of #4013 onto 71e433f2 (content = PR tree, verified) (#4013)

* wave2 assembly of #4076 onto cce4930d (content = PR tree, verified) (#4076)

* wave2 assembly of #4072 onto cce4930d (content = PR tree, verified) (#4072)

* wave2 assembly of #4112 onto cce4930d (content = PR tree, verified) (#4112)

* wave2 assembly of #4115 onto c97fc2eb (content = PR tree, verified) (#4115)

* wave2 assembly of #4106 onto 69ff4485 (content = PR tree, verified) (#4106)

* wave2 assembly of #4108 onto 69ff4485 (content = PR tree, verified) (#4108)

* wave2 assembly of #4110 onto 69ff4485 (content = PR tree, verified) (#4110)

* wave2 assembly of #4107 onto 69ff4485 (content = PR tree, verified) (#4107)

* wave2 assembly of #4116 onto 2446d931 (content = PR tree, verified) (#4116)

* wave2 assembly of #4113 onto 3105c3b5 (content = PR tree, verified) (#4113)

* wave2 assembly of #4118 onto 07fb1e2c (content = PR tree, verified) (#4118)

* wave2 assembly of #4111 onto 07fb1e2c (content = PR tree, verified) (#4111)

* wave2 assembly of #3987 onto 593d6f66 (content = PR tree, verified) (#3987)

* wave2 assembly of #4058 onto 593d6f66 (content = PR tree, verified) (#4058)

* fix(lexer): comsub heredoc header scan follows the $( quote-stack discipline (Refs #4128) (#4139)

UNVERIFIED-BY-CAPTAIN

* fix(executor): store =~ captures through the assignment storage encoding (Refs #4125) (#4136)

UNVERIFIED-BY-CAPTAIN

* fix(windows): case-colliding env entries ride the respawn state file (#4145)

On Windows the std Command environment block is keyed
case-insensitively, so procsub/coproc respawns collapsed V/v and
foo/FOO/Foo into one entry — the first spelling survived carrying
the last value. spill_respawn_env_entries gains a Windows-only
third spill rule: an entry whose key case-folds to an earlier
entry's key (without being that key) rides the respawn state file
and is spliced back verbatim at import, in original relative
order. First occurrences stay inline; exact duplicates never
spill; no collision, no state file.

Verified on X299 with a master build: pins fail first on pristine
sources (collapse signatures in both the procsub and coproc
shapes) and pass 3/3 with the fix; respawn_state_spill lib tests
6/6 including the two new #[cfg(windows)] unit tests.

Refs #4127

UNVERIFIED-BY-CAPTAIN

* Retire unadopted preopened redirect handles at command end (Refs #4131) (#4142)

* Quoted << inside a backquote body declares no heredoc (Refs #4132) (#4144)

* wave2 assembly of #4143 onto a8fad616 (content = PR tree, verified) (#4143)

* graft assembly of #4086 onto c618ca83 (semantic synthesis: #4001 nounset gate onto #4072 _and_defer core, verified; rustfmt-clean) (#4086)

* Assignment: evaluate $((...))/$[...] RHS units whole when they nest a substitution (Refs #4130) (#4147)

GNU expands the whole arithmetic expression first and evaluates it
once (subst.c:10862 chk_arithsub -> expand_arith_string -> evalexp).
Two sites broke that unit invariant:

- assignment_value_is_quoted counted quotes inside a top-level
  $((...))/$[...] unit, so x=$(( $(echo "1") + 1 )) was classified as
  a quoted RHS, never reached the lone-arithmetic fast path, and the
  expression was stored as text. The classifier now skips a whole
  top-level arithmetic unit with the lexer's corrected span scanners,
  like it already skipped ${...} bodies; a $(( that chk_arithsub
  calls a command substitution is not skipped.

- expand_mixed_command_substitution_assignment split out every
  $(...) span scan_substitution_spans reported, including spans
  nested inside a top-level arithmetic unit, leaving "$(( " and
  " + 1 ))" as plain text around the substitution output (and a
  spurious "no closing ]" error for $[...]). Spans inside a top-level
  arithmetic region now stay with the embedded walker, exactly like
  spans inside a top-level ${...} region (rubash#150). Region extents
  are measured by the embedded walker's own extraction collectors
  (subst.c:1301 extract_arithmetic_subst via subst.c:1361
  extract_delimited_string), not a new scanner.

What this PR deletes: no mechanism. It deletes the cross-unit span
splitting and the cross-unit quote counting, and widens one
collector's visibility. Net lines: src +146, tests +126.

Pins: tests/issue4130_arith_assignment_subst_regressions.rs, 24-shape
battery, fail-first on master (both locales), green after; every
expectation byte-verified against the GNU Bash 5.3.20 oracle, plus a
41-shape extended matrix (stdout+stderr byte-identical).

UNVERIFIED-BY-CAPTAIN

Co-authored-by: caomengxuan666 <[email protected]>

* Procsub: resolve plan-untouched consumer fds 1/2 through the ambient table (Refs #4129) (#4148)

GNU's process_substitute fork (subst.c:6362) inherits the shell's
whole ambient fd table. The consumer spawn took fds 1-2 from the
spawn plan (rubash#2195), which only records the consuming command's
own redirect prefix; for a plan-untouched fd, procsub_plan_stdio's
None arm fell back to Stdio::inherit() — the process standard
handles — so the consumer's output escaped an enclosing $( )
capture, group redirection, or exec >.

The ambient adjudication already exists (ambient_procsub_spawn_fd,
rubash#2212) but its pass stopped at fd 3. Plan-untouched fds 1/2
now resolve through the same adjudication at the stdio site, and a
CaptureWrite verdict registers the consumer as a writer of the
capture scope (the rubash#2484 registration the fd >= 3 transport
already performs). StreamWrite does not register, mirroring the
fd >= 3 arm (rubash#3149). Plan entries and live pipe ends still
win where present.

What this PR deletes: no mechanism — it deletes the fd<3 exemption
that kept fds 1/2 out of the existing ambient adjudication.
Net lines: src +31, tests +103.

Pins: tests/issue4129_procsub_ambient_fd_regressions.rs, 12-shape
battery, fail-first on master (both locales), green after; every
expectation byte-verified against the GNU Bash 5.3.20 oracle, plus a
10-shape extended matrix (stdout+stderr byte-identical) and the
adjacent procsub suites (44 tests) green.

UNVERIFIED-BY-CAPTAIN

* fix(executor): cat heredoc arm adopts the retained walk's parked open (Refs #4138) (#4152)

Under set -C, a simple command carrying both a heredoc and a >
redirect to a not-yet-existing target failed rc=1 with 'cannot
overwrite existing file' and left an empty file behind.

Root cause: the cat emulation's heredoc arm re-opened the fd-1
target by path (create_redirect_output_for, O_EXCL under
noclobber) after the emulation layer's retained setup walk had
already performed that entry's one open and parked the handle.
The re-open's O_EXCL judged the file the retained open itself
had just created. GNU redir.c do_redirections opens each
redirect entry exactly once, and the noclobber verdict rides
that single open.

Fix: the heredoc arm adopts the parked open through
take_parked_output_mirror before falling back to the path open,
exactly like its sibling writers (write_cat_output,
open_cat_output_sink, both #3875). take_parked_output_mirror is
widened to pub(in crate::executor) for the cross-module call.
No other redirect semantics change: existing targets are still
refused by the retained walk's own O_EXCL open, and >| still
forces the write.

Pins: tests/issue4138_noclobber_heredoc_regressions.rs - new
target writes the body (fail-first red on master), existing
target refused and preserved, >| forces, plain + compound
guard cells (#1025 faces) keep creating.

* Procsub: resolve producer fds 0/2 through the ambient table (Refs #4135) (#4153)

GNU's process_substitute fork (subst.c:6412 make_child) inherits the expansion-time descriptor table and replaces only fd 1 with the pipe (subst.c:6557). The input form's spawn set the child's stdin/stderr to Stdio::inherit() unconditionally, so a `<(...)` producer's stderr escaped an enclosing `{ ...; } 2> file`, `/bin/bash: line 1: ...: command not found`, `f 2> file` and `exec 2>`, and its stdin missed an enclosing `< file` binding — the producer-side counterpart of rubash#4129, whose fix (rubash#4148) covered only the consumer spawn in external_setup.rs.

The producer's fd 0 / fd 2 now resolve through the same ambient adjudication (ambient_procsub_spawn_fd, rubash#2212) and the same stdio conversion (procsub_plan_stdio, now pub(in crate::executor)) the consumer uses; a CaptureWrite verdict on fd 2 registers the producer as a writer of the capture scope (rubash#2484). An Inherit verdict keeps Stdio::inherit(), so here-string / heredoc / pipe endpoints on the enclosing fd 0 / fd 2 behave as before.

Ordering guard (the reporter's pitfall): when the spawn binds a `< <(...)` target of a compound command's own redirect list, GNU forks the producer at the entry's own turn (redir.c:767), before the list's later entries apply — but rubash's binder passes have already applied the whole list. The two binder call sites in command_input_scope.rs pass the list's undo saves (compound_binder_saves) to the spawn, and a saved fd resolves through its save slot (the pre-list state) via the new procsub_producer_stdio_disposition helper. The redirect-first shapes keep their pre-fix behavior; seeing the list state at the entry's own position remains out of scope (cf. the rubash#2195 prefix plan).

What this PR deletes: the unconditional Stdio::inherit() pair at the producer spawn (the fd<3 exemption at this site); no new mechanism — the fd 0/2 verdicts, the stdio conversion and the capture-writer registration are the consumer side's existing ones.

Net lines: src +94/-7 across 5 files; tests +127 (new issue4135 pin battery, dual locale).

* docs(api-ledger): record respawn_provenance_validated_from_process_env (Refs niubash#1091) (#4156)

* Rename env-conversion escape hatch to __RUBASH_ENV_CONV_EXCL (Refs #4154) (#4155)

* Rename the env-conversion escape hatch MSYS2_ENV_CONV_EXCL -> __RUBASH_ENV_CONV_EXCL (Refs #4154)

Owner ruling (b') on #4154: env-value conversion of path-shaped dialect
values at native spawn stands, but the escape hatch moves to the house
prefix family and the MSYS2 name stops being honored (the published
contract states MSYS2 conversion variables do not exist in niubash).

Pure rename: the exclusion lookup, the verbatim self-entry, the doc
comment and the helper name; pattern semantics (';'-separated name
prefixes, '*' = exempt all, trailing '=' = exact) byte-identical.
Conversion behavior otherwise untouched. The #1001 pins switch to the
new name; a new negative pin asserts MSYS2_ENV_CONV_EXCL no longer
exempts anything.

* Register __RUBASH_ENV_CONV_EXCL in the env namespace census (Refs #4154)

* declare/local: emit the function-named first diagnostic for a readonly compound operand in a function (Refs #4123) (#4157)

GNU subst.c:12949 expand_declaration_argument binds a W_COMPASSIGN
operand of declare/typeset/local through a nested declare during word
expansion. When the operand would create a fresh local but the variable
it copies from is the readonly global, make_local_variable refuses the
copy itself (variables.c:2658) and the refusal surfaces through
builtin_error with this_command_name = the enclosing function name
(builtins/common.c:240 sh_readonly): a first, function-named
'readonly variable' layer. The bind is skipped and the outer builtin's
own pre-check reports the same operand a second time under its own
name; the function continues, rc unaffected.

Rubash's nested-bind adjudication exempted the localizing case
outright (a fresh local binds mutable), so only the outer builtin's
layer was ever printed. Add the copy-refusal arm at that single
adjudication point in declare_local.rs: locally-scoped + readonly
mark + the name lives in no local scope => emit the function-named
layer at expansion time; the existing outer report supplies the
second layer. An outer frame's readonly local never refuses the copy
(varenv19), so presence in any local scope disqualifies the arm; the
same-scope case stays with the existing nested_readonly arm.

Verified: the three #4123 pins fail-first on master and pass now;
a 20-shape script-file matrix against the real GNU bash 5.3.20 oracle
matches byte-for-byte on the whole #4123 class plus the adjacent
readonly/export bare forms (pre-existing -g / same-scope DISCARD
faces unchanged, recorded in the lane dossier).

* fix(lexer): comsub heredoc gather ends at delimiter + IFS_GLUE record (Refs #4141)

A quoted comsub whose heredoc feeds a pipeline declined by the cat
plan (plain sort / cat / a third stage models only [sort, -u]) falls
to the real executor, which re-tokenizes the extracted body. In that
text the delimiter line carries the reader's IFS_GLUE record byte in
place of the consumed closing paren, and feed_awaiting_body's
in-comsub trailing-residue arm required the rest after the delimiter
to trim to empty — 0x1c is not whitespace — so the line failed every
terminator arm and was pushed into the body (the delimiter line
leaked into the captured output).

GNU gather_here_documents (make_cmd.c:602) ends the document at the
exact delimiter line; the PST_EOFTOKEN arm (make_cmd.c:606-611) ends
it at the delimiter followed by the substitution's EOF token. In the
extracted body the EOF token is already consumed and the glue record
is its only trace, so the residue test now ignores IFS_GLUE before
the trim check: delimiter + glue/whitespace terminates, delimiter +
real words still does not.

* Mint /dev/std* and /dev/tty console mappings in device-namespace form (Refs #4151) (#4162)

Co-authored-by: caomengxuan666 <[email protected]>

* fix(executor): scope heredoc EOF warning dedup to one command dispatch (Refs #4140) (#4163)

GNU make_cmd.c:627 make_here_document warns per heredoc occurrence
per parse when the delimiter line is not found before end-of-input;
there is no cross-command dedup in GNU. rubash's
last_heredoc_warning_source record lived on the Executor for the
whole script run, so two distinct commands whose comsub sources were
textually identical warned only once.

The dedup's legitimate domain is a single command dispatch, where
one occurrence can be planned through several expansion paths
(assignment-value pass, embedded-parameter pass, typed-to-readback
retry). Stamp the record with the dispatch's preopened_generation --
the same per-command scoping the parked-handle channel uses -- so a
record from an earlier command no longer suppresses a later
command's identical source.

* fix(exec,redir): gate redirect-word expansion errors in the background and coproc spawn walks (Refs #4099) (#4167)

* Settle arithmetic expansion-error latches with the DISCARD (Refs #4159) (#4168)

A DISCARD-class expansion failure during redirect processing
(> ${a[1x]}) left the arithmetic expansion-error latches standing:
the redirect-gate scan latches them after the owning command's
abort_on_expansion_errors funnel has passed, so the NEXT command's
funnel consumed them as its own failure and that command was
silently discarded — one command past the list GNU's
jump_to_top_level (DISCARD) abandons (eval.c:111 reader_loop; the
catch leaves last_command_exit_value = 1, shell.c:1477).

Settle the latches where the discard itself is settled: the list
loop's abandon fall-through, alongside the evalerror family it
already clears there, and the fresh-unit reset in execute_ast.

* mkdir -p: drive prefixes resolve as the root, colon components chain (Refs #4150) (#4164)

* mkdir -p: drive prefixes resolve as the root, colon components chain (Refs #4150)

mkdir_create_parents resolved every ancestor prefix independently through shell_path_to_windows. For a drive-absolute operand the first prefix is the bare designator C:, which the funnel encodes as the relative name C<U+F03A>; session_path cwd-joined it and created a stray directory in the cwd. GNU coreutils mkdir.c make_ancestors never creates the root: a bare drive prefix (C: or /C:) of an operand that continues with '/' now resolves as the drive root X:\ instead.

The same independent resolution is not chain-preserving when a non-final component carries a colon (x:y/z): the funnel encodes a colon only in the final component, so the prefix x:y landed under its encoded name while the full operand kept the literal colon and failed ENOENT. Such operands now resolve as a chain — each later prefix resolves only the component it adds, as a standalone final component, joined onto the previous prefix's resolved path (the per-component encoding the MSYS2/cygwin layer applies).

The funnel is untouched: a bare C: OPERAND keeps its relative colon-name encoding, the Git Bash agreement of the report's example 3. All new resolution is cfg(windows)-gated; the unix walk is byte-identical.

Pins: tests/issue4150_mkdir_p_drive_prefix_regressions.rs (Windows-gated) — C:/ existing target, C:/ root operand, the reported three-operand combination, /c single-operand guard, drive-absolute target creation, x:y/z chain creation, bare C: control.

* utf8-hygiene: allowlist the mkdir drive-letter widening (Refs #4150)

The gate flagged mkdir_drive_root_prefix's *letter as char. The widened byte is pinned to ASCII by the same match arm's is_ascii_alphabetic() guard — an ASCII drive letter by construction, never a UTF-8 continuation byte. Add the tight allowlist entry the gate's review step prescribes, mirroring the existing cd.rs/pwd.rs drive-letter entries. Verified locally: check-utf8-boundary-hygiene clean, check-marker-literals OK.

* docs: refresh repo-stats snapshot

* Strip the blank guard from in-process pipeline stage operands

An escaped blank (a\ b) lexes to ANSI_C_IFS_GUARD + blank. The cat
pipeline arm and expand_pipeline_stage_arg_words expand their operands
themselves and never stripped the guard, so with a DEBUG trap armed
(oh-my-niu's preexec hook) `cat a\ b | wc -l` opened "a<U+E401> b" and
failed with No such file or directory. Route the operands through one
helper that drops CTLESC pairs and the guard, like command_prepare does
for simple commands.

* Foreground-child console stdin: apply the canonical line discipline (Refs #4149)

GNU hands a foreground child the tty in canonical mode and the KERNEL
applies the discipline: VEOF at an empty buffer is a zero-length read
(lib/sh/zread.c:99 consumes it as EOF; builtins/read.def:767 the eof
verdict), VEOF with bytes buffered flushes exactly those bytes with no
EOF and no newline, and ICRNL delivers CR, LF and CRLF each as one
'\n'. A Windows cooked console has no such discipline — it assembles
a line and hands its raw bytes, CRLF and 0x04 included, to whoever
reads — so niubash 1.5.1's emulated cat wrote abc\r\n (5 bytes where
GNU writes 4), dropped a mid-line ^D silently, and only honoured a
line-head ^D once Enter arrived.

Single mechanism, in the engine's stdin transport layer (the #684
doctrine: the transport self-translates):

- read_helpers: veof_verdict(byte, buffer_empty) is now the one pure
  verdict unit; the two inline read verdicts (read_io, read_helpers)
  migrate to it unchanged in behaviour. Beside it, ConsoleLineDiscipline
  is the byte-stream state machine: VEOF flush/EOF via veof_verdict,
  CR/LF/CRLF -> LF, finish() flushes a partial line at source EOF,
  disciplined() is the whole-buffer form truncated at the verdict.
- external_file_builtins: the emulated cat's three inherited-stdin
  readers (inherited stream, '-' operand stream, '-' buffered drain)
  run through the discipline only when cfg!(windows) &&
  stdin_veof_armed holds, reading byte-wise so an EOF verdict stops
  the read with the rest of the stream queued for the next reader.
  Every other source (pipes, files, Unix) keeps the raw copy verbatim.

Platform boundary, stated plainly: a cooked read releases no byte
before Enter, so wall-clock immediacy of a mid-line ^D flush is not
reachable on this read path; what is delivered is the verdict
granularity, the byte accounting and the exact stop point. True
immediacy needs a one-char mode (the read -n ConsoleOnecharGuard
shape) — a different order of intervention, out of scope here; the
#684 ConPTY pins live inside the same boundary.

UNVERIFIED-BY-CAPTAIN

* Bind eval's own input redirections for the reparsed body (Refs #4158)

* fix(lexer): route comsub delimiter glue strip through markers::strip_ifs_glue (Refs #4141)

The heredoc gatherer's in-comsub arm stripped the reader's IFS_GLUE
record from the post-delimiter residue with a bare .replace() keyed
on the registry const. The marker-lint L3 gate rejects needle
operations on registry consts at unreviewed sites: a blind replace
cannot see the escape pairs that make a typed marker char data
(rubash#2885 E7), so marker surgery belongs in
src/executor/markers.rs.

Move the strip into a new pair-aware helper there,
markers::strip_ifs_glue: IFS_GLUE is a prefix carrier
(protect_ifs_chars splices it in front of the character it
protects), so the walk drops every bare glue byte and copies the
protected data char verbatim. A user-typed U+001C never arrives as a
bare char — typed C0 data rides raw-byte marker pairs, whose
codepoints are distinct and pass through untouched — so the strip
cannot fold data into protocol. Output is byte-identical to the
.replace() it supersedes; the lexer's residue test, its #4141
comment, and the guard behavior (delimiter + real words still does
not terminate) are unchanged.

marker-lint: OK (was 1 violation at src/lexer/mod.rs:1213).
Unit pin: strip_ifs_glue_drops_carrier_preserves_data.

* release: rubash 1.5.2 version bump (Cargo.toml + lock, captain) (#4176)

* fix(executor): serve the console line discipline to the inherited-stdin drain consumer (rubash#4172)

read_inherited_process_stdin_to_string — the drain-style fallback serving the emulated sed and both mapfile inherit arms — read a live Windows console raw: no VEOF verdicts, CRLF unnormalized, while the streaming foreground readers got the canonical discipline in #4149. When the one armed gate holds, the drained text now goes through ConsoleLineDiscipline's whole-buffer form (the form landed for buffered consumers), via a new text adapter disciplined_text at the String layer the drain serves. The gate itself (console_line_discipline_armed) is widened to pub(in crate::executor) so every inherited-stdin consumer shares the one spelling. The raw-empty -> None contract is unchanged; a verdict-emptied text still serves Some("") — the consumer was served an instant EOF, and None would re-enter the fallback cascade.

GNU hands every tty consumer the kernel-disciplined stream (termios VEOF + ICRNL; bash-side anchors lib/sh/zread.c:99 and builtins/read.def:767, the #684/#4149 doctrine); a Windows cooked console applies neither, so the engine's transports translate. Refs #4172.

* fix(executor): register a coproc whose redirect walk declines (Refs #4170)

GNU applies a coproc's redirects in the forked child
(execute_cmd.c:2546 execute_coproc -> execute_in_subshell), so a
do_redirections failure kills only the child: the parent
registers the coproc (coproc_setvars) and execute_coproc returns
EXECUTION_SUCCESS once the fork succeeds (execute_cmd.c:2592).
The child reports the diagnostic through fd 2 as bound by the
list's earlier entries (redir.c:135 redirection_error) and exits
1 without running the body; wait reaps 1.

The parent-side walk (apply_coproc_redirects) cannot fork first.
Its Declined disposition created no coproc and failed the
statement with status 1, and ordinary open failures escaped as
an Err with the same statement-level result. Now:

- every Declined point (expansion gate, ambiguous-redirect arms,
  and the list-entry opens, converted from Err to Declined via
  coproc_open_or_report) reports its diagnostic through the fd-2
  binding in force at that point (write_coproc_redirect_diagnostic)
  and returns the fd-1/fd-0 dispositions the walk had reached;
- the caller swaps the body child for a stillborn respawn
  (-c "exit 1") carrying those dispositions and falls through
  the shared spawn/registration, so the COPROC array/_PID, the
  job entry and $! bind, the statement reports 0 (an enclosing
  ! inverts it like any launch), and wait reaps 1;
- the walk owns the coproc pipe reader (the caller used to set
  it on the child before the walk) so a Declined return can hand
  it to the stillborn child: the read end lives exactly as long
  as GNU's failing child holds it, and an immediate parent write
  to ${COPROC[1]} buffers instead of meeting a reader-less pipe.

Pins: new tests/issue4170_coproc_declined_launch.rs (17 pins,
one per Declined class plus routing / side-effect / named /
invert / EOF / jobs / noclobber faces; all red on pristine
86ce7911, green here). The four coproc pins in
tests/issue4099_redirect_word_spawn_walks.rs and one pin in
tests/issue1644_1655_coproc_dup_stderr_regressions.rs asserted
the old Declined statement status 1 and now assert GNU's 0.

Net lines: src +364/-65 (two new helpers, the Declined payload
at 13 walk return points, the caller stillborn swap); tests
+331/-16 plus the new 311-line pin file.

UNVERIFIED-BY-CAPTAIN

* fix(executor): refuse emulated cat operands naming the stdout file (Refs #4175)

* fix(executor): stop dropping cat operands that spell redirect targets (Refs #4180)

parse_cat_argv re-derived redirection from word text: it dropped
every word equal to one of the command's redirect targets and every
word shaped like a redirect operator (plus the word after it).
cmd.words is pure argv — the parser already separated redirections
into the node's redirect fields — so for `cat out >> out` the only
operand vanished, the operand list came up empty, and the emulated
cat fell through to its no-operand stdin serve: it drained fd 0,
blocking forever on a live pipe stdin (and silently appending
whatever stdin delivered when stdin had data); the `>` form still
truncated the file first. `cat '>' f` lost both operands to the
operator arm the same way.

Remove both text-layer re-derivations and the two helpers that
served only them (cat_redirect_targets, is_cat_redirect_operator_
word). The operand now reaches the plain serve, where the existing
rubash#4175 judgment (cat_operand_is_output_file — the one same-file
predicate, reused unchanged) refuses the append form with GNU's
`input file is output file` at status 1; the truncate form serves
the file the redirection already emptied, status 0, and stdin is
never read. GNU caliber verified byte-for-byte against the cloud
GNU Bash 5.3.20 oracle and a local GNU coreutils 9.4 cat across a
seven-shape script matrix (append/truncate self-target with data
stdin, redirect-first, quoted operator x2, pipeline last stage,
input-redirect same name).

Pins: tests/issue4180_cat_own_redirect_target.rs, 10 pins, each with
a 20s timeout guard (the pristine failure is a hang; a timeout
records as the failure). Fail-first on the new base: 8 red (two by
timeout kill), 2 guard pins green; fixed: 10/10. Adjacent cat /
redirect / pipeline suites: no unique reds (three pre-existing
environment artifacts reproduce identically on pristine).

* fix(executor): close coproc endpoints in subshell children (Refs #4181)

GNU runs coproc_closeall in every forked child
(execute_cmd.c:1713-1715 execute_in_subshell; also :4229/:4575):
a subshell never inherits the parent's coproc endpoints, live or
dead, so a redirect naming one inside ( ) fails EBADF and only
the subshell dies. Rubash executes ( ) in place on the parent's
live fd table, so ( echo hi >&${COPROC[1]} ) after read-EOF
wrote into a readerless pipe and SIGPIPE killed the whole shell
(141, no diagnostic); with a live coproc the write wrongly
succeeded.

Child side: the region's fd table now drops the coproc arms at
the boundary (FdTable::close_coproc_endpoints_for_subshell,
called at both ( ) entries after the parent's saved_table
snapshot). The arms are dropped without retiring them — the
snapshot's duplicated descriptors restore the parent's endpoints
at the close, so the parent and the coproc see no change.

Parent side: GNU's wait for the subshell child is a coproc
disposal point (jobs.c:3494, wait_for's notify_and_cleanup ->
coproc_reap), so a death recorded before the ( ) is retired
before the next command expands. The region closes now record
the emulated foreground wait (note_emulated_foreground_wait,
the #2053 whole-command-emulation mark) at the node-form close
and in both flat-region close macros.

Command substitution is not a coproc_closeall path in GNU and
is untouched (a comsub write to a live coproc still succeeds);
the no-boundary direct write still dies 141 exactly like GNU,
and the external-command boundary is unchanged.

Pins: tests/issue4181_coproc_subshell_sigpipe.rs, 12 pins —
7 discriminating (dead/live subshell write, parent var
retirement, own-redirect, pipeline stage, nested, subshell
read) red on pristine, 5 invariance guards green on both.
Verified against the cloud GNU Bash 5.3.20 oracle via script
files; adjacent coproc/sigpipe/subshell families show no
unique new reds. UNVERIFIED-BY-CAPTAIN.

* fix(executor): background respawn snapshot severs coproc endpoints (GNU coproc_closeall) (rubash#4185)

* fix(executor): note a foreground wait at command-substitution completion so recorded coproc deaths retire (Refs #4184)

GNU command_substitute() waits for the substitution child in the
parent (subst.c:7449 wait_for), and coproc_reap runs on wait_for's
return path (jobs.c:3494): a coproc death recorded before an
x=$(...) assignment therefore unbinds COPROC/COPROC_PID (and the
NAME/NAME_PID pair) once the substitution completes. Rubash's
parent-side substitution completion carried no disposal mark, so
the recorded death stayed pending until some later foreground
wait happened to flush it.

Carry the family's established emulated foreground-wait mark at
the single parent-side completion point
(expand_command_substitution_with_context) — the same note the
emulated-external and rubash#4181 subshell faces use, flushed by
the next boundary refresh. Parent-side bookkeeping only: the
substitution child's own coproc endpoints are untouched (the
comsub write face is GNU-correct as-is, rubash#4181 q3).

Pins (tests/issue4184_comsub_completion_coproc_retire.rs):
- q5 unnamed + named discriminating pins (fail on pristine
  161837d0, pass with the fix; GNU 5.3.20 oracle byte-identical)
- q3 guard: a live coproc still serves a write from inside a
  substitution after the completion point
- q2 guard: subshell disposal then a substitution — no
  double retirement, a fresh coproc round-trips

UNVERIFIED-BY-CAPTAIN

* fix(lexer): record delimiter-line mark when a line closes one heredoc and opens the next comsub (rubash#4169)

GNU make_cmd.c:602-611 records the delimiter line carrying the
closing `)` for every here-document, and make_cmd.c:627 warns when
the delimiter line is not found before end-of-input. In
Lexer::push_line (GroupScanFeeder), the IFS_GLUE record insert
existed only in the arm where no substitution stays open after the
appended line; the line that closes heredoc #1 while opening
comsub #2 (e.g. `E); w=$(cat <<E`) took the other arm, which popped
the heredoc without inserting the record, so the earlier
substitution's plan saw closed_by_paren=false and its end-of-file
warning never fired.

Extract the insert into mark_comsub_heredoc_delimiter_paren and
call it from both arms; the exact-delimiter arm still pops only.
src/lexer/continuation.rs untouched.

Refs #4169. Split per captain ruling: the one-command
multi-comsub shapes are blocked by two consumer-side defects
(warning attribution anchored at the command start line, and
identical-source dedup suppressing a distinct occurrence),
tracked as #4190; their pins land there and #4169 stays open
until #4190 lands. UNVERIFIED-BY-CAPTAIN.

* executor: key comsub heredoc EOF warnings by occurrence identity (rubash#4190)

GNU warns per heredoc occurrence per parse: make_cmd.c:627
make_here_document emits the "delimited by end-of-file" warning while
gather_here_documents (parse.y:3120) walks each command's heredoc list,
so two textually identical substitutions in one command warn twice,
each numbered from its own header line.

The comsub heredoc plan keyed both halves of that by text instead:
the body-line seed came from the whole command's start line (every
comsub of a command inherited the first line), and the emission dedup
keyed on (source text, dispatch generation), swallowing a second,
distinct occurrence whose source was byte-identical.

Fix: a per-occurrence identity (dispatch generation, word slot,
ordinal within the word) plus the occurrence's header line, carried
from the expansion site to the plan. The parser stamps each command
word's physical start line (CommandNode::word_start_lines, the
end-line precedent of rubash#3028); expand_command_word stamps a site
frame for the word's expansion; dispatch sites in both word walkers,
the substitution-fragment path, and the whole-word entries mint a
mark (ordinal + newlines before the span); the two heredoc entries
resolve mark against frame and hand the site to the plan. The plan
seeds from the site header line and dedups on (slot, ordinal) when
sited; the legacy (source, generation) record is still written on a
marked emission so an unmarked re-plan in the same dispatch stays
suppressed. Contexts no site reaches (assignment values, redirect
words, compound-command elements) keep the legacy seed and keying
exactly — the #4140 contract (one occurrence, several planning
paths, exactly one warning) is preserved on both tiers.

Pins: tests/issue4190_comsub_warning_occurrence_identity_regressions.rs
carries the #4169 r3/r3q/r4 shapes, the defect-A continued-line shape,
and two defect-B face mixes (6 discriminating pins red on pristine,
1 same-occurrence guard green); issue4140 and issue4169 suites stay
green.

Refs #4190, #4169. UNVERIFIED-BY-CAPTAIN.

* fix(executor): procsub producer inherits the fd state at its redirect entry's turn (Refs #4189)

GNU do_redirections (redir.c:237) walks a command's redirect list
in order, expanding each entry's word at its own turn
(redirection_expand, redir.c:298); process_substitute
(subst.c:6362) forks the producer at that turn with the descriptor
state the preceding entries leave behind. rubash adjudicated the
producer's fd 0 / fd 2 from the pre-list state (the earliest undo
save) on compound faces and from the bare ambient table on simple
commands, so a redirect written BEFORE the '<' entry never reached
the producer: 'cat 2>/dev/null < <(...)' leaked the producer's
stderr to the shell's stderr, and a '0<file' prefix never became
its stdin. The capture face held producer bytes in the background
capture pipe until scope end, landing them after foreground bytes
GNU's single substitution pipe (subst.c:7143 command_substitute)
merges by arrival.

One mechanism - the entry-time state, priority plan > saves >
ambient - at the single adjudication point
(procsub_producer_stdio_disposition):

- binder saves resolve to the first save earned at or after the
  spawn entry's index (a save slot holds the pre-entry state, so
  that save IS the turn state); no later save means the current
  table entry is the turn state. The #4135 pitfall shapes (spawn
  entry first) resolve exactly as before.
- procsub_spawn_plan gains include_fd0 (old call sites pass false,
  behavior verbatim); the simple-command materialize faces and
  both compound spawn faces compute the prefix plan for the
  producer's own list position with fd 0 included and pass it to
  the spawn. Compound faces need it ahead of the saves: an fd 0
  file binding rides the FUNCTION_STDIN text channel (its save
  slot never materializes) and the numbered walk runs before the
  output binder has applied its side of the list.
- stdout_capture_write drains the background capture pipe's
  available producer bytes before appending a foreground chunk;
  the scope-end drain stays as the backstop.

Pins: tests/issue4189_procsub_redirect_first_regressions.rs -
three batteries x {C, C.UTF-8}, byte-verified against the GNU
Bash 5.3.20 oracle, fail-first on pristine (6/6 red), green after.

UNVERIFIED-BY-CAPTAIN

* fix(lexer): comsub heredoc header scan takes `<<<` as one operator (Refs #4193)

GNU read_token (parse.y:3689-3703) decides the redirect operator
by maximal munch at the first '<': '<<' plus a third '<' is
LESS_LESS_LESS, the here-string token - never a '<' followed by a
heredoc '<<'. The lexer's comsub-heredoc header scan stepped over
only the first '<' of '<<<', so the remaining '<<' was read as a
heredoc header whose delimiter was the here-string word itself
('$(cat'). That bogus header queued ahead of the real one in
comsub_heredocs, so when the delimiter line ('E)') arrived it
matched neither the queue front's close nor its delimiter-line
mark, the IFS_GLUE record byte was never spliced, and a
here-string-fed comsub lost its here-document end-of-file warning
entirely (make_cmd.c:627 warns per heredoc occurrence).

Skip all three bytes of '<<<' in the header scan, mirroring the
token rule. The real header inside the here-string word now queues
and marks exactly as on the command-word path, and the warning
flows through the family's single existing emission site; no
second warning site is added and no mechanism is deleted - the
bogus header is gone by construction.

Net: src +14/-0, tests +132 (6 pins: 4 discriminating fail-first,
2 guards, dual locale).

* docs: refresh code-size table + badge for release

* test(path): fail-first pins for the #4188 per-component colon funnel

Unit pins call the funnel mapping directly (platform-free text):
non-final colon components must encode, the absolute drive
designator stays exempt, bare/drive-relative designators encode
(the #4150 control), UNC and verbatim prefixes keep their shape.
Integration pins (windows-gated) replay the report script against
the binary: mkdir -p x:y/z, then [ -d ] / touch / ls / cd / pwd /
redirect by the literal spelling, plus the absolute spelling and
a multi-colon chain. On the base the unit pin fails at the first
non-final shape (x:y\z passes through literal) and the funnel
still encodes the final component only.

Refs #4188. UNVERIFIED-BY-CAPTAIN.

* fix(path): encode the NTFS colon per component in the shell-name funnel

The funnel (shell_path_to_windows) encoded ':' as U+F03A only in
the final component, while the build side encodes per component
(the #4150 named-mkdir chain resolves every component as a
standalone final component) and the MSYS2/cygwin contract encodes
per component on both sides. A directory the shell itself created
was therefore unreachable by lookup: [ -d x:y/z ], cd, ls and the
absolute spelling all missed the x<F03A>y tree (#4188, host-proven
on Windows Server 2022 against Git Bash as the reference layer).

GNU side: ':' is an ordinary filename byte — redir.c:298
redirection_expand expands the target as one word and redir.c:706
redir_open passes it to open(2) verbatim; the encoding is purely
the Windows platform contract from #359, now at matching
granularity.

map_ntfs_colon_final_component becomes map_ntfs_colon_components:
every component encodes, exempting only the path's own drive
designator in absolute form (D:\, D:/, also behind a \\?\ or
\\.\ prefix). A bare C: stays a relative colon name (the #4150
Git Bash control), C:foo and designator-shaped mid-path
components encode as ordinary components. The display direction
already decodes with a plain replace, so it is per-component
unchanged. One existing pin moves with the mechanism: the
bashdb doubled-drive expectation now spells the invalid mid-path
component D<F03A>; the anti-truncation invariant it guards (the
path stays anchored under the first drive, the stat still fails)
is unchanged and restated in its comment.

No consumer is patched individually; the mkdir chain walk from
#4150 is untouched (it stays correct — and becomes redundant,
which the PR body flags for a separate convergence call).

Refs #4188. UNVERIFIED-BY-CAPTAIN.

* style(fmt): clear pre-existing rustfmt drift blocking the release gate

The v1.5.2 release workflow's Verify formatting step failed on drift
that accumulated in already-merged PRs (PR CI has no fmt gate):
src/executor/parameter_words.rs and four test files. Mechanical
rustfmt output only - token stream verified unchanged (one trailing
comma dropped by a line join in issue4159). Verified on a real host:
cargo build green, lib tests 1419/0, the four drifted test files all
green.

* docs: refresh code-size table + badge for release

* fix(expand): single-quote backslash is data — one pass_next quote-state rule (rubash#4195)

GNU brace_gobbler pass_next: a backslash escapes the next byte only
in unquoted, double-quote and backquote state; inside single quotes
it is plain data. Three faces of the one misconception, one rule:

- braces.rs: find_first_valid_brace's single-quote skip consumed the
  byte after a backslash inside '...', swallowing the closing quote
  of a '\' span and running the span away (C1-C3); the group scan
  had the asymmetry inverted (\" inside "..." toggled the state
  shut, C5) and no $'...' arm (F10); split_brace_commas set its
  escape state inside single quotes (C4). The top-level skips now
  share skip_plain_single_quoted / skip_plain_double_quoted, the
  group scan mirrors the same asymmetry and gains the $'...' arm,
  and the comma splitter guards its backslash arm with !single.
- embedded_mutations.rs: in a protecting walk over a lexer-cooked
  word a surviving raw backslash is quoted-span data, not escape
  syntax (every live source escape already rode in as a carrier),
  so the general backslash arm no longer resolves the pair and the
  following $ / backquote stays live syntax (F5-F8). The
  operator-half (no-restore) and prompt-render entries walk raw or
  synthetic text whose pairs are genuine escapes; a new cooked_word
  entry flag keeps the arm for them (the prompt channel gets its own
  entry, expand_embedded_parameters_mut_prompt). The rubash#2999
  protect branch of the backslash-backslash arm is deleted: the
  gate plus the #2999 fall-through carrier subsume it.
- arrays.rs: a partially quoted compound element now takes
  dequote_compound_element_rhs — the single dequote composition the
  [sub]= path received in the rubash#288 fix — instead of a second
  unquote_stored_element_value pass over dequoted text, which
  re-read the span's literal backslash as escape syntax and ate it
  (F1-F3).

Regression pins: tests/issue4195_brace_quote_state_regressions.rs
runs the 16-group triage repro verbatim against the GNU bash
5.3.20 baseline (14/16 divergent before, 16/16 byte-identical
after); braces unit tests cover the C1/C3/C4/C5/F10 shapes.

Refs #4195
UNVERIFIED-BY-CAPTAIN

* fix(ci,expand): add PR rustfmt gate, fix repo-stats, and close diagnostic-guard UAF

- .github/workflows/ci.yml: add fast PR rustfmt check job running
  scripts/check-rustfmt.py so formatting drift cannot accumulate until
  the release gate (Refs #4203).
- .github/workflows/repo-stats.yml: checkout with fetch-depth: 0 so
  Commits on master is accurate instead of 1, and sum Rust LOC via
  git ls-files -z + python3 instead of xargs wc -l | tail -1 (Refs #4211).
- src/executor/expand_word.rs (+ callers): make PendingDiagnosticWordGuard
  and PendingDiagnosticRawGuard private with PhantomData<&'a str> and
  expose only closure-scoped helpers (with_pending_diagnostic_word{,_if},
  with_pending_diagnostic_raw), closing the safe-API dangling-pointer /
  mem::forget UAF hole while preserving zero heap allocation on the hot
  path (Refs #4211).

Refs #4203, #4211, #4210

* perf(cond): upgrade [[ =~ ]] regex cache to 64-entry Rc LRU and drop fabricated Regex error

GNU reference: execute_cmd.c:4096 -> lib/sh/shmatch.c sh_regmatch (inputs are
the expanded pattern and REG_ICASE; compat31 already selects caller-side RHS
quoting before sh_regmatch, and locale reaches compilation only via byte-mode).

- Replace the 16-entry FIFO clone-on-hit regex cache in src/executor/conditional.rs
  with a 64-entry move-to-front LRU cache returning Rc<CompiledConditionalRegex>
  with borrowed-key lookup on hits; remove #[derive(Clone)] from
  CompiledConditionalRegex to prevent accidental compiled-program cloning.
- Replace the Regex::new("(").unwrap_err() error-fabrication hack with a
  zero-cost ConditionalRegexCompileError marker type.
- Add unit tests for Rc::ptr_eq hits, case-insensitive/byte-mode key separation,
  LRU eviction at capacity, and invalid-pattern caching.

Refs #4211, #3232, #4210

* refactor(windows): unify Win32 extern declarations onto windows-sys and re-enable clashing_extern_declarations

- Remove `#![allow(clashing_extern_declarations)]` from `src/lib.rs`.
- Replace all hand-written `extern "system" { ... }` Win32 blocks across
  `src/` and `tests/console_window_gate.rs` (19 files) with canonical
  `windows-sys` calls, adding only the required `windows-sys` features in
  `Cargo.toml` (`Cargo.lock` unchanged).
- Add minimal 11-line `#[cfg(windows)] pub(crate) mod win32_ffi` adapter
  bridging `isize` fd-table handles to `windows_sys::Win32::Foundation::HANDLE`.
- Net code reduction: -146 lines; zero `extern "system" { ... }` blocks and
  zero `clashing_extern_declarations` warnings remain.

Refs #4206, #2792, #4210

* fix(locale): keep synced locale variables thread-local instead of mutating process env

- Replace `std::env::set_var` / `remove_var` in `src/locale.rs::sync_process_locale`
  with a thread-local 7-slot locale table (`LC_ALL`, `LC_CTYPE`, `LC_COLLATE`,
  `LC_MESSAGES`, `LC_NUMERIC`, `LC_TIME`, `LANG`) so concurrent `Session`s on
  different threads never race on or unsafely mutate the process-global
  environment.
- Route all locale readers (`locale_name`, `active_numeric_locale_name`,
  collation lookup, etc.) through `read_effective_locale_var` (precedence:
  `ShellLocaleGuard` overlay -> thread synced table -> inherited process env).
- Snapshot and restore the thread-local synced locale table across `Executor`
  construction (`init.rs`, `command_substitution.rs`) and `Drop`
  (`public_accessors.rs`) so same-thread fork copies neither erase nor leak
  into their enclosing parent executor's locale state.
- Update `local_helpers.rs` (`set_process_env` / `unset_process_env`) and
  `export_builtin.rs` to keep the thread-local locale table synchronized.
- Add unit tests for multi-threaded isolation, assignment-funnel updates,
  root drop cleanup, and command-substitution child drop restoration.

Refs #4205, #4210

* fix(windows,fd): close Winsock SOCKET handles via closesocket instead of CloseHandle

Windows fd-table teardown (FdTable::close, FdTable::install eviction,
and close_handle) previously called CloseHandle() unconditionally even
for adopted /dev/tcp and /dev/udp SOCKET handles, leaking Winsock's
user-space socket table entry.

Route generic fd handle closure through close_os_handle(), dispatching
is_socket_handle(h) handles to windows_sys::Win32::Networking::WinSock::closesocket()
and non-socket handles to CloseHandle(). Also switch three pure
connect-and-drop probe sites in src/executor/redirection.rs from
open_net_redirect() (which converts SOCKET to File) to
connect_net_stream() with identical posix_errors::path_error wrapping so
their drop runs TcpStream/UdpSocket::drop (closesocket).

Refs #4211

* fix(executor): narrow the #4201 walker escape gate to introducer pairs, restore #2999 protect branch (rubash#4195)

Round 1 (f4d31335) gated backslash protection on the cooked-word state alone; three word classes share the walker entry (lexer-stripped fragments where a backslash is data, comsub re-words where " and \ are real escapes, double-quoted assignment values), so the wide gate regressed the escaped-quote comsub arithmetic body and the issue3337/issue3354 escaped-backquote pair on PR CI. FIX3 protects only after an introducer byte (dollar in any context, backquote only when Unquoted) and restores the #2999 trailing-backslash protect branch round 1 deleted. Adds issue4201_walker_escape_pair_regressions (3 pins: escaped-backquote pair + #2999 q1 shape); the 16 #4195 groups stay byte-identical to GNU bash 5.3.20.

* refactor(lint): remove unreachable_patterns, unused_mut, and unused_assignments allows from lib.rs

Re-enable three crate-level lints in src/lib.rs (stacked on #4214 which
already removed clashing_extern_declarations) and resolve all 84
resulting warnings across 43 files (including cfg(unix) paths and one
dead token_boundary assignment in src/lexer/continuation.rs:4450 that
fell through to immediate overwrite at line 4532):
- 2 unreachable_patterns arms (command_input_scope.rs, expand_braced_replacement.rs)
  plus 1 Unix-gated duplicate pattern in builtins/kill.rs (SIG_DFL | 0)
- 29 unused_mut bindings (using #[cfg_attr(not(unix), allow(unused_mut))]
  where mutability is Unix-only)
- 53 unused_assignments (dead overwrites / redundant initializers)

Refs #4206

* refactor(executor): isolate external command emulation behind ExternalCommandBackend seam

Replace the raw `external_file_builtins_enabled: bool` field scattered
across 7 executor files with a single explicit `ExternalCommandBackend`
enum (`EmulatedInProcess` / `ExternalSpawnOnly`) and a single backend
dispatch entry point `try_execute_via_external_backend()` in
`src/executor/external_backend.rs`.

This establishes the #4204 architectural invariant with zero behavioral
change: built-in external command emulation and any future WinuxCmd FFI
backend (unixwin/WinuxCmd#1487) are mutually exclusive backend variants
behind one exit seam. Public API `set_external_file_builtins_enabled`
keeps its exact signature and semantics.

Refs #4204

* refactor(executor): deduplicate builtin dispatch boilerplate across primary, late, no-alias, and direct faces

Eliminate redundant per-arm `is_disabled` checks in `command_no_alias.rs`
and `command_no_alias_late.rs` (already gated upfront at line 28) and
extract shared dispatch helpers in `command_dispatch.rs` (including the
shared `builtin_help_gate`, no-output builtin redirects, completion/fg-bg
helpers, and fast-path `dirname`/`basename` execution) consumed across:
- `src/executor/command_dispatch_primary.rs`
- `src/executor/command_dispatch_late.rs`
- `src/executor/command_no_alias.rs`
- `src/executor/command_no_alias_late.rs`
- `src/executor/builtin_direct_command.rs`

Net reduction of 299 lines across 6 files with zero behavioral change,
zero edits to `src/executor/mod.rs`, and all 21 `command_registry`
consistency tests passing.

Refs #4204

* refactor(executor): split 9,740-line compound_exec.rs into 7 cohesive submodules

Replace the 9,740-line src/executor/compound_exec.rs monolith with a
src/executor/compound_exec/ module directory without modifying
src/executor/mod.rs (zero behavioral change, zero API change):
- mod.rs (44 lines): submodule wiring and crate::executor re-exports
- transport.rs (758 lines): fork/respawn inherited state and line-span transport
- subshell.rs (548 lines): subshell execution helpers
- case.rs (1,440 lines): case statement dispatch and pattern matching
- control_flow.rs (2,026 lines): if/for/while/until/select/group/time/! execution
- background.rs (2,346 lines): async/background job execution and respawn
- coproc.rs (2,629 lines): coproc fd specs, endpoints, launch, and stderr forwarding

All 12 unit tests are preserved in their owning submodules.

Refs #4208

* chore(lint): update marker-lint-allowlist paths after compound_exec split

* chore(cargo,ci): update MSRV to 1.91 and align release.yml with check-rustfmt and --locked

Cargo.toml previously declared rust-version = "1.70", while the codebase
and Cargo.lock already require newer toolchains:
- const { ... } blocks (1.79)
- Option::is_none_or (1.82)
- std::io::pipe() (1.87: src/fd/unix.rs:1297, src/executor/compound_exec.rs:6265,
  src/executor/trap_exec.rs:6270, src/executor/shell_options.rs:636)
- psm 0.1.32 & ar_archive_writer 0.5.3 in Cargo.lock (1.88)
- str::floor_char_boundary (1.91: src/builtins/complete.rs:1369)

Update rust-version in Cargo.toml (and the README badge) to 1.91 without
touching dependencies or Cargo.lock. Also align .github/workflows/release.yml
to use python3 scripts/check-rustfmt.py (consistent with pre-commit hook
and PR CI) and cargo build --locked in the shell-functionality job.

Refs #4203
Refs #4211

* refactor(lint): remove crate-level unused_variables allow from src/lib.rs

Re-enable the unused_variables lint in src/lib.rs (stacked on #4218,
bringing removed crate-level allows to 5 of 6, leaving only dead_code)
and clean all 50 resulting warnings across 36 files (including cfg(unix)
and cfg(not(unix)) bindings via platform-scoped guards and the 3 unused
bindings in src/lexer/continuation.rs).

Pure warning cleanup with zero behavioral changes.

Refs #4206

* refactor(signals): extract signal runtime infrastructure from builtins/kill.rs into src/signals/

Split the 4,790-line src/builtins/kill.rs into a focused kill builtin
CLI (~557 lines) and a crate-private src/signals/ runtime hierarchy:
- src/signals/mod.rs: module hub and internal re-exports
- src/signals/table.rs (422 lines): signal name/number tables and decoding
- src/signals/mailbox.rs (691 lines): cross-process mailbox registration and pruning
- src/signals/dispositions.rs (1,824 lines): kernel signal dispositions and trap hooks
- src/signals/delivery.rs (1,312 lines): signal delivery, console Ctrl-C/Ctrl-Z hooks,
  and background wrapper handshakes

Re-export all public and crate-internal faces from src/builtins/kill.rs
so existing callers and docs/api-ledger.md remain 100% compatible with
zero behavioral change. All 24 unit tests are preserved in their owning
modules.

Refs #4205

* refactor(tests): consolidate 1,661 top-level issue*.rs tests into 17 grouped integration crates

Consolidate eligible top-level tests/issue*.rs regression files into 17
balanced numeric-range integration test crates (tests/issues_0001_0399.rs
through tests/issues_3900_4199.rs, 74-118 modules each) using git mv to
preserve rename history.

Impact:
- Top-level tests/*.rs integration targets: 1,857 -> 213 (-88.5%)
- scripts/check-rustfmt.py targets: 1,862 -> 218 (14 batches -> 2 batches)
- Native `cargo fmt --check` now passes on Windows without os error 206
- Exact #[test] conservation: 16,241 before == 16,241 after
- Zero changes to src/, Cargo.toml, Cargo.lock, .github/, or
  scripts/ci-pin-exclusions.txt; all 104 excluded stems and all 9
  hardcoded ci.yml `--test issue*` stems remain untouched at tests/*.rs

Refs #4202

* test(fault-injection): add 4-arm deterministic fault-injection differential harness (Refs #2811)

* refactor(lint): remove final crate-level dead_code allow from src/lib.rs

Remove the last remaining crate-level `#![allow(dead_code)]` (6 of 6
crate-level allows eliminated from src/lib.rs; stacked on #4222) and
resolve all resulting dead_code warnings across ~85 files (deleting
~1,500+ lines of genuinely unreferenced private helpers/fields/variants
and accurately gating test-only / platform-only helpers with #[cfg(...)]).

To keep zero merge conflicts with open PRs #4216 (windows_impl.rs),
files are left untouched behind temporary module-level #[allow(dead_code)]
annotations referencing their follow-up PRs.

Refs #4206

…
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.

信任条件 (a) 理论误触:同词 glue 落他字时引号内 IFS 空白未受保护仍被判可信(#3089 返工面外观察)

1 participant