Skip to content

fix(executor): report a bad array subscript in a compound assignment (#631) - #634

Merged
caomengxuan666 merged 2 commits into
masterfrom
fix/issue631-neg-subscript
Oct 15, 2026
Merged

caomengxuan666 merged 2 commits into
masterfrom
fix/issue631-neg-subscript

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

What

Closes #631.

a+=( [-2]=q ) on a one-element array discarded the element in silence and
carried on:

stdout stderr status
master AFTER (nothing) 0
GNU (nothing) [-2]=q: bad array subscript 1
branch (nothing) [-2]=q: bad array subscript 1

Why (GNU C source is the spec)

assign_compound_array_list (arrayfunc.c:700) computes each element
subscript, counts a negative one back from the end
(array_max_index + 1 + ind, arrayfunc.c:802-803) and, when it is still
below zero, reports err_badarraysub (w) — the whole element word, through
report_error (error.c:440; message arrayfunc.c:63) — counts
any_failed and breaks the list (arrayfunc.c:804-809):

	      ind = array_expand_index (var, w + 1, len, avflags);
	      /* negative subscripts to indexed arrays count back from end */
	      if (ind < 0)
		ind = array_max_index (array_cell (var)) + 1 + ind;
	      if (ind < 0)
		{
		  err_badarraysub (w);
		  any_failed++;
		  break;
		}

The elements inserted before the failure stay stored (arrayfunc.c:768-772
inserts as it scans), and assign_array_var_from_string (arrayfunc.c:913-932)
returns NULL, so the assignment fails: bash_variable_assignment_error
(subst.c:11169) → exp_jump_to_top_level (DISCARD) (subst.c:11174).

The wrong invariant

array_assignment_index (src/executor/arrays.rs) returned Option<usize>,
conflating "this word is not a [subscript] header" with "this subscript
resolved out of range"
. The scan's

if array_assignment_has_subscript(left) {
    continue;
}

therefore dropped the element in silence. Both element forms ([sub]=,
[sub]+=) and both compound forms (a+=(...), a=(...)) were affected.

Fix

array_assignment_index returns a three-state
ArrayAssignmentIndex { Index, NegativeOutOfRange, Unresolved }. The scan
stops on NegativeOutOfRange, carrying the word in
IndexedAppendOutcome::bad_subscript; the caller stores the partial outcome
(GNU keeps the earlier elements), then reports <word>: bad array subscript
and fails the assignment with the same DISCARD jump the plain a[-2]=q path
already makes.

The message uses diagnostic_prefix(), not assignment_diagnostic_prefix():
err_badarraysub goes through report_error, so it carries no command:
segment (unlike declare: x: readonly variable).

$ a=(p); a+=( [0]=x [-2]=q )
  # EXIT trap sees `a=x` — the element before the failure is stored (GNU: same)
$ f(){ a=(p); a+=( [-2]=q ); echo IN; }; f; echo AFTER
  # nothing printed, status 1 — the jump discards the function and the caller
$ ( a=(p); a+=( [-2]=q ); echo SUB ); echo AFTER
  # AFTER — inside `( )` only the subshell ends

Verification

  • 3-way failure-set differential vs GNU, 43 cases: controls, every
    compound form, negative-index arithmetic, fatality scope (function /
    subshell / nested subshell / loop / if / multi-assignment), and the partial
    store read back through an EXIT trap. 25 fixed, 0 regressions, 6
    pre-existing divergences unchanged (see below).
  • New regression target tests/issue631_neg_subscript_regressions.rs:
    9/9.
  • cargo test --lib: 584/584.
  • Test-target failure sets vs master 81c0df5, serial
    (--test-threads=1): cli_tests 1 = 1; array_compound_quote_regressions,
    array_store_parity, issue536_malformed_subscript_regressions,
    issue532_unclosed_brace_subscript_regressions,
    issue148_glob_in_compound_array_assignment,
    issue298_299_array_fieldsplit_regressions, issue614_regressions,
    arrdefault_quoted_array_default_regressions,
    issue371_assoc_assignment_transform, assignment_chain_regressions all
    0 = 0; executor_tests 1173 = 1173 apart from the nondeterministic
    command_chaining::part_080 coproc family (3 rows in, 3 rows out, all six
    pass in isolation).

Not in this change

Each is a pre-existing divergence with its own issue:

  1. the declare-side duplicate of this scan — declare -a a=( [-2]=q ) and
    local -a a=( [-2]=q ) still drop the element; it needs the declare
    builtin's own error channel to reach a fatal jump;
  2. a+=( [@]=q ) / a+=( [*]=q ) — GNU rejects the header with
    cannot assign to non-numeric index (arrayfunc.c:787-792), rubash
    reports an arithmetic error;
  3. rubash's eval does not contain the DISCARD jump — the plain
    eval 'a[-2]=q' path has the identical defect on master, so the compound
    path is now consistent with it rather than with GNU.

Measured on Termux/Android aarch64 against the local bash 5.3.20; the
repository oracle is WSL bash 5.3.0, and every rule applied here is taken from
the vendored 5.3 source rather than from a version's behaviour.

…631)

`a+=( [-2]=q )` on a one-element array discarded the element in silence and
carried on:

    a=(p); a+=( [-2]=q ); echo AFTER
      master: AFTER                        (element gone, status 0)
      GNU   : [-2]=q: bad array subscript  (status 1, no AFTER)

GNU assign_compound_array_list (arrayfunc.c:700) computes the element
subscript, counts a negative one back from the end (`array_max_index + 1 +
ind`, arrayfunc.c:802-803) and, when it is still below zero, reports
`err_badarraysub (w)` — the WHOLE element word, through report_error
(error.c:440; message arrayfunc.c:63) — counts `any_failed` and `break`s the
list (arrayfunc.c:804-809). The elements it already inserted stay stored (it
array_inserts as it scans, arrayfunc.c:768-772), and
assign_array_var_from_string (arrayfunc.c:913-932) then returns NULL, so the
assignment fails: bash_variable_assignment_error (subst.c:11169) ->
exp_jump_to_top_level (DISCARD) (subst.c:11174).

The wrong invariant was in `array_assignment_index` (src/executor/arrays.rs):
returning `Option<usize>` conflated "this word is not a `[subscript]` header"
with "this subscript resolved out of range", so the scan's
`if array_assignment_has_subscript(left) { continue; }` dropped the element in
silence. Both element forms (`[sub]=` and `[sub]+=`) and both compound forms
(`a+=(...)` and `a=(...)`) were affected.

`array_assignment_index` now returns a three-state
`ArrayAssignmentIndex { Index, NegativeOutOfRange, Unresolved }`. The scan
stops on `NegativeOutOfRange`, carrying the offending word in
`IndexedAppendOutcome::bad_subscript`; the caller stores the partial outcome
(GNU keeps the earlier elements), then reports `<word>: bad array subscript`
and fails the assignment with the same DISCARD jump the plain `a[-2]=q` path
already makes. The message uses diagnostic_prefix(), not
assignment_diagnostic_prefix(): err_badarraysub goes through report_error, so
it carries no `command:` segment (unlike `declare: x: readonly variable`).

Out of scope here, each a pre-existing divergence with its own issue filed:
the declare-side duplicate of this scan (`declare -a a=( [-2]=q )`,
`local -a a=( [-2]=q )`), which needs the declare builtin's own error channel
to reach a fatal jump; the `[@]=`/`[*]=` header, which GNU rejects with
`cannot assign to non-numeric index` (arrayfunc.c:787-792) and rubash reports
as an arithmetic error; and rubash's `eval`, which does not contain the
DISCARD jump (the plain `eval 'a[-2]=q'` path has the same defect on master).

Gates: cargo test --lib 584/584. New regression target
tests/issue631_neg_subscript_regressions.rs 9/9. Byte-exact 3-way
differential against GNU (43 cases: controls, every compound form, fatality
scope, partial store observed through an EXIT trap): 25 cases fixed, ZERO
regressions, 6 pre-existing divergences unchanged (the three follow-ups
above). Test-target failure sets vs master 81c0df5, compared serial
(--test-threads=1): cli_tests 1 = 1; array_compound_quote_regressions,
array_store_parity, issue536_malformed_subscript_regressions,
issue532_unclosed_brace_subscript_regressions,
issue148_glob_in_compound_array_assignment,
issue298_299_array_fieldsplit_regressions, issue614_regressions,
arrdefault_quoted_array_default_regressions, issue371_assoc_assignment_transform
and assignment_chain_regressions all 0 = 0; executor_tests 1173 = 1173 apart
from the nondeterministic command_chaining::part_080 coproc family (3 rows in,
3 rows out, all six pass in isolation).

Measured on Termux/Android aarch64 against the local bash 5.3.20; the
repository oracle is WSL bash 5.3.0, and every rule applied here is taken from
the vendored 5.3 source (arrayfunc.c:700-850, error.c:440, subst.c:11169) and
its own probes rather than from a version's behaviour.
The perf doc already listed the silently-dropped compound element as '#631,
filed separately'. Replace that note with the resolved contract (GNU
arrayfunc.c:700-850 / :913-932, subst.c:11169-11174), the invariant that was
wrong in array_assignment_index, the verification evidence, the three
follow-ups filed while characterising the class (#635 declare-side route,
#636 [@]/[*] message, #637 eval containment), and the measurement caveat
(local bash 5.3.20, WSL 5.3.0 is the oracle).
@caomengxuan666
caomengxuan666 merged commit 12da0b5 into master Oct 15, 2026
6 checks passed
@caomengxuan666
caomengxuan666 deleted the fix/issue631-neg-subscript branch October 15, 2026 23:14
caomengxuan666 added a commit that referenced this pull request Oct 16, 2026
#635) (#658)

declare -a a=( [-2]=q ) printed AFTER with status 0 and an empty array.
GNU computes max+1+ind and, still negative, reports [-2]=q: bad array
subscript on the whole word with no AFTER (arrayfunc.c:804-809 +
assign_array_var_from_string NULL + bash_variable_assignment_error
DISCARD). The assignment route was fixed by #631/#634; the builtin route
conflated "no [..] header" with "out of range" and skipped the element.

array_assignment_index now resolves 3 states (Index / NoHeader /
NegativeOutOfRange); the scan breaks with prior elements kept and the
whole word travels up via out-params (append fn -> assign fns ->
declare executor fn). declare/local translate at the Executor layer
mirroring the arith_eval_failure precedent but with the bare report_error
diagnostic (no command: segment): partial already installed, exit 1,
DISCARD abort. Eval containment reuses the #637 absorption primitive.
export/readonly record failure status with the same diagnostic; their
list-abort threading is a documented follow-up.

Verification: new 20-case GNU differential 6/20 -> 20/20; new
tests/issue635_builtin_oob.rs (10 tests); focused suites green; full
serial failure-set gate vs d4d8dc4 identical targets (NEW=0/
DISAPPEARED=0; 2/2 part_080 coproc flake passing in isolation); niubash
A/B failure sets byte-identical (49=49).

Co-authored-by: caomengxuan666 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant