Repository navigation
fix(test): reject a non-integer operand of an integer operator - #348
ferdingler wants to merge 9 commits into
Conversation
|
@strandly-the-agent Please review this PR |
strandly-the-agent
left a comment
There was a problem hiding this comment.
No blocking findings. This fixes #334 and matches bash 5.2.15 on every realistic integer-operand case I ran. Posted as a comment; approval is a maintainer's call.
- 🟡 A number after a leading newline or CR is rejected where bash accepts it. One-line fix inline.
- 🟡 Five mutations of the new code pass the new tests; four extra differential lines catch four of them. Inline, optional.
- Heads-up, not caused by this PR:
$UID,$SECONDS,$PPIDand friends are empty in this shell, so[ "$UID" -eq 0 ]goes from silently comparing 0 to an error and status 2 once this merges. Filed #367.
✅ What I verified
Head 9ef3e56 against base dbb6189 (= main). Linux aarch64, debug builds, bash 5.2.15 with LC_ALL=C as the oracle.
- Suite at head:
cargo test --workspace --all-targetsexits 0 with 2,735 passed, 0 failed, 0 ignored.cargo fmt --checkexits 0.cargo clippy --workspace --all-targetsexits 0 with 14 warnings, none insrc/builtins/test.rs. CI is green. - New tests fail without the fix: with head's
tests/on base's source,--test differentialfails exactly the two new cases and--test shell_integration test_int_fails the two new tests. All pass on head. .expectedfiles: a fresh bash recording of both new cases is byte-identical to the committed files.- Differential run: 231,006 scripts through bash, base and head, comparing status, stdout and whether stderr is empty.
- 83,146 cases that differed from bash on base now match.
[[ ]]: 30,252 cases, byte-identical between base and head.exec.rs:2961-2970passes both operands througheval_arith(...).to_string(), so the new trim innum()is a no-op there.- Expressions without an integer operator: 48,108 cases, byte-identical to base.
- 3,647 cases matched bash on base and differ on head: 3,411 leading whitespace (inline), 230 parenthesised unary test (appendix), 6 unset special variables (#367).
- Contexts that match bash:
if/while/until,&&/||,!,set -e, unset$1in a function,2>/dev/null,-a/-oon either side,( ). - Not run: Python and Node bindings, WASM, the MCP server, release builds, other platforms.
Questions, reading order, appendix
Question (non-blocking)
- The checklist leaves "I have reviewed and understand every line of code in this PR" unchecked.
AGENTS.mdasks that every box can be checked truthfully before opening.
Reading order
src/builtins/test.rs:115-129 (the operand check), :28-41 (the message and status 2), :263-270 (integer), then the two differential cases.
Appendix, non-blocking (5)
- ⚪
v=-lt; [ \( -n "$v" \) ]returns 2 with[: -n: integer expression expected; bash says true.-n -lt )was already read as a binary comparison attest.rs:115-122, and the new check now rejects-n. It needs a lone parenthesised unary test on a string that is itself an integer operator. - ⚪ The name in the message comes from a trailing
], not the command:test abc -eq 0 ]reports[:where bash reportstest:. Status is 2 in both. - ⚪ Still silent with status 1, same as base, where bash returns 2:
[ "!" -eq 3 ],[ "(" -lt 3 ],test 3 -eq ],[ ! ! abc -eq 0 ]. - This conflicts with #347 in
builtin_test(both addlet bracket), so the second to merge needs a rebase. - Pre-existing, same on base and head, filed: #367 (empty
$UID,$SECONDS, …), #368 ($(( ))reads a blank-padded variable as 0), #369 (cmd &>file), #370 (stderr inside$( )is dropped), #371 (a redirect onif/while/untilskips the condition).
…leading newline or CR
|
@strandly-the-agent Please review this PR |
strandly-the-agent
left a comment
There was a problem hiding this comment.
Both findings from the first review are fixed at 581183f; nothing new. Still a comment, not an approval.
- ✅ Leading newline or CR before a number: fixed in
581183f. The repros match bash 5.2.15, and trailing\rand\nare still rejected as in bash. - ✅ Untested paths: fixed in
a522f74. All five mutants that passed the old tests now fail.
✅ What I verified
Head 581183f against the previously reviewed 9ef3e56 and base dbb6189. Linux aarch64, debug builds, bash 5.2.15 with LC_ALL=C.
- Suite at head:
cargo test --workspace --all-targetsexits 0 with 2,736 passed, 0 failed, 0 ignored (one more than before: the new integration test).cargo fmt --checkexits 0.cargo clippy --workspace --all-targetsexits 0 with no warning insrc/builtins/test.rs. CI is green on all platforms. - Sweep: 1,172 scripts through bash, base,
9ef3e56and581183f: every ASCII byte 1 to 127 before the number, after it, between sign and digits, between digits and alone; six multi-byte spaces; all six operators with LF, CR, VT, FF and CRLF on either operand.581183fdiffers from bash on 2: a lone!or(as the left operand ([ "!" -eq 0 ]), unchanged and already listed in the first review's appendix.9ef3e56differed on 122. The 120 lines that changed are exactly the ones that were wrong.
[[ ]]: a leading or trailing newline in an operand gives the same result on base, both heads and bash..expectedfiles: a fresh bash recording of both cases is byte-identical to the committed files.581183fmatches both.9ef3e56fails the valid case on exactlyleading-newlineandleading-cr, so the test-first commit does fail before the fix. Base fails both cases.- Mutation re-run on a copy of
581183f(unmutated control passes both suites):
| Mutant | Result |
|---|---|
| tabs not trimmed | fails test_integer_operand_valid |
error right of -o dropped |
fails test_integer_operand_invalid |
error inside ( ) dropped |
fails test_integer_operand_invalid |
| blanks-only operand accepted as 0 | fails test_integer_operand_invalid |
| message prints the trimmed operand | fails test_int_error_names_the_operand_untrimmed |
| leading trim back to space and tab | fails test_integer_operand_valid |
| leading LF not trimmed | fails test_integer_operand_valid |
| leading CR not trimmed | fails test_integer_operand_valid |
| trailing LF, VT, FF, CR also trimmed | fails test_integer_operand_invalid |
| leading VT and FF not trimmed | passes both suites |
- Not run: Python and Node bindings, WASM, the MCP server, release builds, other platforms locally.
Appendix, non-blocking (1)
- ⚪ A leading vertical tab or form feed isn't pinned by a test (last row above). Head is correct for both; I wouldn't hold the PR for it.
The other appendix items from the first review (parenthesised unary test, message name, ! and ( operands, the #347 conflict, the unchecked checklist box) are unchanged.
kevin-orellana
left a comment
There was a problem hiding this comment.
A valid nonempty-string check now reports an integer error when the string happens to be -eq. Could we evaluate the expression inside the parentheses before treating -eq as a comparison operator?
With v=-eq, [ \( -n "$v" \) ] returns 0 in Bash and on main. This branch exits 2 with -n: integer expression expected.
With v=-eq, [ \( -n "$v" \) ] is true in bash and on main but exits 2 on this branch. Recorded from bash 5.2.15.
Up to four arguments are read by count, as bash does, so a parenthesized -n or -z takes -eq as its operand and ( -eq ) is a comparison. Longer expressions still go to the parser.
@kevin-orellana thanks, good catch. Fixed in 886a4b2. The test-first commit 51bfd03 adds I also checked every 1 to 4 argument combination of |
|
@strandly-the-agent Please review this PR |
strandly-the-agent
left a comment
There was a problem hiding this comment.
One new wrong answer in 886a4b2: ! now inverts a malformed expression to true. The fix for kevin-orellana's ( -n -eq ) repro works; this is a side effect of the new eval. Small fix inline, tested.
- 🔴
v="a b"; [ ! $v ]is now true (status 0).mainreturns 1 and bash errors with status 2. So anif [ ! $v ]whose variable is unquoted and holds two or three words now takes the branch. Across 141,128 fuzz expressions, 6,690 go from false onmainto true on this head where bash reports an error. - Otherwise the new arg-count rules hold up. No expression that matched bash on
main(status and stderr) differs now, and 992 that the previous head got wrong now match. The new differential case is a byte-for-byte bash recording that fails on581183f.
✅ What I verified
Head 886a4b2. I compared it with the previous review's head 581183f and with main 4f838f9, after the merge. Only 648a7aa..886a4b2 is new code here: the merge brings in main unchanged. Linux aarch64, debug builds, bash 5.2.15 with LC_ALL=C.
- Suite at head:
cargo test --workspace --all-targetsexits 0 with 2,777 passed, 0 failed, 0 ignored.cargo fmt --checkandcargo clippy --workspace --all-targetsexit 0, with no clippy warning insrc/builtins/test.rs. The only non-green check is the cancelled2 Approvers for Botsjob. test_paren_operator_as_operand: a fresh bash recording is byte-identical to the committed.expected.886a4b2matches it.581183ffails 6 lines andmainfails 5.- Fuzz: I ran every 0 to 4 argument combination of
! ( ) -n -z -eq -lt -a -o = != x "" 3 " 3" abc -f -nt, plus 30,000 random 5 to 7 argument ones. That is 141,128 expressions, each as[ … ]andtest …(282,256 runs). They were split into 4,000-line chunks because a single run hits the 30 s deadline.
main |
581183f |
886a4b2 |
with suggested fix | |
|---|---|---|---|---|
| matches bash (status + stderr presence) | 15,880 | 46,890 | 47,838 | 47,838 |
regressions vs main |
— | — | 0 | 0 |
false on main → true here, where bash errors |
— | — | 6,690 | 158 |
- Suggested fix tested: it leaves the match count unchanged and adds no regression against
mainor886a4b2. The differential andshell_integrationsuites pass with it (1 + 2,079), andcargo fmt --checkpasses. The remaining 158 cases are a dangling-a/-osuch as[ ! x -a ]. The parser already accepts that form onmain:[ x -a ]is a silent 1 there. That is #321 territory. - Not run: Python and Node bindings, WASM, the MCP server, release builds, other platforms.
Appendix, non-blocking (1)
- ⚪
[ \( x -eq \) ]returns 1 here. Bash errors withx: unary operator expectedand status 2.581183fhappened to error too, through the integer check, andmainreturned 0. This is the missing-operand case #347 covers, not something to fix in this PR.
| } | ||
| [open, arg, close] if open == "(" && close == ")" => Ok(!arg.is_empty()), | ||
| [bang, rest @ ..] if bang == "!" && matches!(rest.len(), 2 | 3) => { | ||
| Ok(!eval(rest, os, proc).await?) |
There was a problem hiding this comment.
! inverts a malformed sub-expression, so [ ! $v ] with a two-word $v is now true
When rest isn't one of the fixed 2- or 3-argument forms, eval(rest) falls through to the parser. The _ arm then returns Ok(false) because pos != args.len(), and this arm turns that into true. With v="a b", [ ! $v ] becomes [ ! a b ]. Bash prints a: unary operator expected and returns 2; main and 581183f return 1; this head returns 0. So if [ ! $v ]; then … runs the branch. set -- x y; [ ! "$@" ] and a three-word $v behave the same way. In the fuzz run, 6,690 expressions go from false on main to true here, all where bash errors.
Suggestion: have eval report "malformed" separately from "false" so that ! can't flip it. For example, return Result<Option<bool>, String>, with None from the _ arm when pos != args.len(). The ! arm then becomes Ok(eval(rest, os, proc).await?.map(|r| !r)), and builtin_test treats anything other than Some(true) as status 1, as main does. That keeps status 1 for now; #347 could later turn it into 2.
Reproduction details
Head 886a4b2, previous head 581183f, main 4f838f9, bash 5.2.15 with LC_ALL=C. Linux aarch64, debug builds, each script run with -c.
| Script | bash | main |
581183f |
886a4b2 |
with fix |
|---|---|---|---|---|---|
v="a b"; if [ ! $v ]; then echo empty; else echo nonempty; fi |
error, nonempty |
nonempty |
nonempty |
empty |
nonempty |
v="a b c"; [ ! $v ]; echo rc=$? |
error, rc=2 |
rc=1 |
rc=1 |
rc=0 |
rc=1 |
set -- x y; [ ! "$@" ] && echo taken; echo rc=$? |
error, rc=2 |
rc=1 |
rc=1 |
taken, rc=0 |
rc=1 |
v=-eq; [ \( -n "$v" \) ]; echo rc=$? (control) |
rc=0 |
rc=0 |
error, rc=2 |
rc=0 |
rc=0 |
[ ! \( x \) ]; echo rc=$? (control) |
rc=1 |
rc=1 |
rc=1 |
The fix I tested, applied to 886a4b2:
- Ok(result) => result,
+ Ok(result) => result == Some(true),
...
-) -> Pin<Box<dyn Future<Output = Eval> + 'a>> {
+) -> Pin<Box<dyn Future<Output = Result<Option<bool>, String>> + 'a>> {
Box::pin(async move {
- match args {
+ let result = match args {
...
- Ok(!eval(rest, os, proc).await?)
+ return Ok(eval(rest, os, proc).await?.map(|r| !r));
...
- eval(rest, os, proc).await
+ return eval(rest, os, proc).await;
...
- Ok(result && pos == args.len())
+ return Ok((pos == args.len()).then_some(result));
}
- }
+ };
+ result.map(Some)With it, the 282,256-run fuzz still matches bash on 47,838, the same as 886a4b2, with 0 regressions against main or 886a4b2. --test differential passes (including test_paren_operator_as_operand), --test shell_integration passes 2,079, and cargo fmt --check passes. A regression line such as v="a b"; [ ! $v ]; echo "not-two-words: $?" would pin it. Bash records 2 for that line, so it may belong in a known-difference case until #347 lands.
There was a problem hiding this comment.
Agreed, thanks. Applied in 8eeef48: eval returns Option<bool>, ! maps over it, and builtin_test treats anything other than Some(true) as status 1.
I also closed the remaining 158. Any form of three or fewer arguments that the POSIX rules don't cover now returns None without reaching the parser. Bash reports all of those as syntax errors, so [ ! x -a ] and [ ! ! \( ! ] stay false.
The test-first commit d410f83 adds [ ! $v ] with two and three words, [ ! "$@" ], [ \( a b \) ], [ ! x -a ] and [ ! ! \( ! ] to test_paren_operator_as_operand. Each is an if, so its output matches bash. Five of those lines fail on 886a4b2, and all pass now.
I swept every 0 to 4 argument combination of ! ( ) -n -z -eq -lt -a -o = x "" 3 -f against bash and main. No expression goes from false on main to true here. The only results that differ from main without matching bash are 159 bash syntax errors that main called true and this branch calls false (status 1), for example [ \( -n ].
There was a problem hiding this comment.
Verified at 8eeef48: [ ! $v ] with two or three words, [ ! "$@" ] and [ ! x -a ] now return 1 like main, and the five new lines in test_paren_operator_as_operand fail on 886a4b2 and pass here. Across 282,256 fuzz runs, 0 cases that matched bash on main differ now, and the false→true flips dropped from 6,690 to 8, all pre-existing parser leniency (see the review).
With v="a b", [ ! $v ] errors in bash and is false on main, but is true on 886a4b2. So are [ ! x -a ] and [ ! ! \( ! ].
eval reports a test it can't read whole as None, and ! leaves None as is, so the test is false as on main. Forms of three or fewer arguments outside POSIX's rules are malformed, as in bash, instead of going to the lenient parser.
|
@strandly-the-agent Please review this PR |
strandly-the-agent
left a comment
There was a problem hiding this comment.
The ! finding is fixed at 8eeef48; nothing new. Still a comment, not an approval.
- ✅
!no longer turns a malformed test true:[ ! $v ]with a two- or three-word$v,[ ! "$@" ],[ ! x -a ]. The new_ if args.len() <= 3 => Nonearm also closes the dangling-a/-ocases my suggestion left open. - The red
Rust (windows-latest)check iscompound_pipe_into_function_redirected_from_clioverflowing the stack. That is the known flaky failure in #406, in a pipe test that doesn't go throughtest, and886a4b2passed the same job. A re-run should clear it.
✅ What I verified
Head 8eeef48 against 886a4b2 and main 4f838f9. Linux aarch64, debug builds, bash 5.2.15 with LC_ALL=C.
- Suite:
cargo test --workspace --all-targetsexits 0 with 2,777 passed, 0 failed, 0 ignored.cargo fmt --checkexits 0, and clippy reports nothing insrc/builtins/test.rs. test_paren_operator_as_operand: a fresh bash recording is byte-identical to the committed.expected.8eeef48matches it.886a4b2fails exactly the five newnot-*lines.- Fuzz: the same 282,256 runs as last time (141,128 expressions ×
[ ]/test).
main |
886a4b2 |
8eeef48 |
|
|---|---|---|---|
| matches bash (status + stderr presence) | 15,880 | 47,838 | 47,842 |
regressions vs main |
— | 0 | 0 |
false on main → true here, where bash errors |
— | 6,690 | 8 |
true on main and bash, not here |
— | — | 0 |
- Not run: Python and Node bindings, WASM, the MCP server, release builds, Windows locally.
Appendix, non-blocking (1)
- ⚪ The 8 remaining false→true cases are an unclosed
(or a dangling-oafter a blank-padded integer, e.g.[ \( 3 -eq " 3" ]and[ " 3" -eq 3 -o ]. Bash reports a syntax error. The parser already accepts both forms onmain, where[ \( 3 -eq 3 ]is also true. They only flip here because" 3"now reads as 3. That is #321 territory, not this PR.
Description
[andtestread an empty or non-numeric operand of an integer comparison as 0, so[ "" -lt 3 ]was true and[ abc -eq 0 ]passed quietly. A script that loops on an unset counter or checks a value it didn't validate would take the wrong branch with no error. Bash reports the bad operand and returns status 2, so the condition isn't taken.Now
[andtestdo the same: an operand that isn't a decimal integer gets an error and status 2. Like bash, blanks around the number and a leading sign are still accepted, and[[ ]]is unchanged because there these operands are arithmetic. This is in the sametestcode as #321 (a missing operand), so the two may conflict, but I kept this one to integer operands only.Related Issues
Fixes #334
Documentation PR
N/A
Type of Change
Bug fix
Testing
I added differential cases for bad operands and for forms that should still work, plus a check on the status and the error message. On main the bad operands came back true or false with nothing on stderr, and blanks around a number were rejected. With the change everything matches bash and the full test suite passes.
cargo test --workspace --all-targets,pytest tests/python,npm test)cargo fmtandcargo clippyChecklist
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.