Repository navigation
feat(parser): support [[ ]] conditional expressions - #325
Conversation
Scripts that agents run, such as the grep and find wrappers that Claude Code writes, test with [[ ]], which the shell reported as command not found. [[ ... ]] is now a compound command, Item::Conditional, which holds its operands unexpanded. The evaluation expands an operand only when it reaches it, without splitting or globbing, so && and || skip the operands they do not need. It supports !, &&, ||, parentheses, the test operators, -v, arithmetic operands for -eq and its kin, and == and != with a case pattern on the right. =~ is refused with status 2. No alias expands inside [[ ]]. A file test on an empty path is false, in test and [ too. The differential cases double_bracket and double_bracket_alias pin it against bash; both fail on main.
|
@strandly-the-agent review this PR |
strandly-the-agent
left a comment
There was a problem hiding this comment.
Changes requested. [[ ]] evaluates well-formed input like bash (11,073 fuzzed expressions, no mismatch in status or short-circuit order), but one case gives a silent wrong answer. @ferdingler
- 🔴 A quoted right-hand side of
==/!=is matched as a glob, so[[ "$a" == "$b" ]]is wrong whenever$bholds*,?or[. Inline, with a tested fix. - 🟡 A short-circuited
=~swallows the rest of the expression and reports nothing. - 🟡 A line break after
[[, before]], or before&&/||is a parse error that stops the script. - 🟡 Ten mutants of the new code survive the two differential cases, including one that removes
&&short-circuiting. Inline, with lines to add. - Merge order: land #324 first. On its own this PR turns the Claude Code
grepwrapper's exit 127 into unbounded recursion: a stack-overflow abort on a debug build,maximum recursion depth exceededon release.
What I verified, questions, reading order, appendix
Verified at head 969a13e against base 4b0bdbc (the merge-base) and bash 5.2.15, debug builds on aarch64 Linux:
cargo test --workspace --all-targets: 2,662 passed, 0 failed, 0 ignored, exit 0.cargo fmt --checkis clean.cargo clippy --workspace --all-targetsprints the same warning summary as base.- Both new cases fail on base with
[[: command not found. - A three-way harness (bash, base, PR) over 3,938 scripts. Of the 1,800 that use
[[, 1,323 match bash; most of the rest trace to gaps that base also has. - 11,073 random valid expressions match bash on status and on the order of operand side effects, apart from 8
-s <dir>cases (the VFS reports size 0, same as[on base). 15,000 malformed inputs caused no hang or crash. [andtestafter theeval_unarychange: 1,612 cases, 116 fixed, 2 regressions (see appendix).- These hold: no splitting or globbing of operands;
</>create no file;-von globals and locals; use inif/while/until, after!, in pipes, subshells, functions,eval, underset -eandset -u; 65,536-term chains and 16 MB operands stay linear. - Not tested: the Python, Node.js and WASM bindings, a real tty for
-t, and the embedder run described in the PR.
Questions (non-blocking)
- Is
=~planned as a follow-up?regexis already a dependency, and=~is common in agent scripts. Today a guard such asif [[ $x =~ re ]]; then exit 1; fiprints the refusal and carries on. - The published Shell language and builtins page says "No
[[ ]]" in thetest,[row, and the PR lists no documentation PR. That row needs updating, with the remaining gaps (=~, extglob,-o,-N,-R). Item::Conditionalandpub enum CondTermextend the publicparserAST, which has no#[non_exhaustive]. #205 added a variant the same way and the crate is at 0.0.0, so I did not treat this as an API change. Say so if the AST is meant to be stable.- Should the empty-path rule live in the kernel under #322 instead of
test.rs:161-164? The guard covers unary operators only:[[ "" -ef "" ]]is still true.
Reading order: parser.rs:284-346 (parse_conditional), exec.rs:2764-2939 (the evaluator), exec.rs:2941-2980 (the skip path, which must mirror the evaluator), test.rs:161-164, then the cases.
Appendix, non-blocking (9)
[[ a =~ b ]] 2>/dev/nullstill prints the refusal; a2>on the conditional or on an enclosing group does not capture its own diagnostic.e=; [ ! -a "$e" ]now returns 0 (bash 1, base 1), from the guard attest.rs:161-164.test -d ""with a literal""still returns 0, because the empty argument is dropped beforetestruns (#299). The fix reaches"$e"withe=and[[ -d "" ]].- Valid bash that is refused:
[[ $n == +([0-9]) ]](status 2),[[ $v == @(a|b) ]](parse error),-o,-N,-R, and[[ -v 1 ]](false). f=a; [[ -N $f ]]prints[[: unexpected`` with an empty name:cond_term_text(`exec.rs:2786`) is blank for any word that has an expansion or quotes.- The new parse errors start with
syntax error:, whichis_definite_error(parser.rs:173) does not recognise, so the rest of the script is read before the error is reported, without a line number. - The alias skip (
parser.rs:232) misses a[[that is the first command of acasearm, andecho then [[ a; foono longer expands the aliasfoo. set -xdoes not trace[[.[[ a ]] | [[ b ]]and{ echo a; } | [[ -n a ]]report[[: command not found.- Pre-existing:
casematches quoted patterns as globs too, filed #327.[ a = ]panics, already #321.
- A quoted part of the right side of ==, = or != now matches literally. Each quoted part is escaped before glob matching, so a mixed word such as *"$y"* also matches as bash does. - =~ is refused before evaluation starts, so a short-circuit can no longer skip the refusal and the terms after it. - A line break inside [[ ]] is now allowed anywhere, as in bash. A literal ; inside [[ ]] is now a syntax error, as in bash. The errors start with "unexpected", so they are reported as definite parse errors. - [ a -a b ] and [ a -o b ] with three arguments use the POSIX binary rule, so [ ! -a "$e" ] is false again for an empty $e. - -ef, -nt and -ot treat an empty path as a missing file. The double_bracket differential case has new lines for each fix and for the short-circuit, grouping and precedence paths, recorded with bash 5.2.15. Rust tests cover the =~ refusal, an unclosed group, a literal ;, two operands, an unclosed [[, the empty-path guard, and a command run through the Claude Code wrapper functions.
|
@strandly-the-agent Please re-review. The fixes are in 511e94d, and e0cbcfe merges Findings
Appendix items fixed in the same commit
Not changed, as follow-ups
Questions These are open for the author to answer:
Verified
|
|
@strandly-the-agent Please review this agent |
|
@strandly-the-agent re-review |
There was a problem hiding this comment.
Approve. All four findings from my last review are fixed at 511e94d, and #324 is in the branch. The fix commit brought in one small regression, which is worth taking before merge. @ferdingler
Previous findings:
- 🔴 Quoted right side of
==/!=: fixed, including mixed words such as*"$y"*. - 🟡 Short-circuited
=~: fixed. It is refused with status 2 before evaluation. - 🟡 Line breaks inside
[[ ]]: fixed. A literal;is now rejected. - 🟡 Test gaps: fixed. I re-ran my ten mutants: nine now fail, and the tenth no longer applies.
- Merge order: resolved. The wrapper repro prints
1and exits 0.
New in this round:
- 🟡
-ntand-otare true when both paths are empty, in[[,[andtest.[andtestreturn 1 onmain. Inline, with a tested fix. - 🟡 Four of twelve mutants of the fix commit pass every test. Inline, with lines to add.
What I verified, open questions, appendix
Verified at head 511e94d against base 55d7816 (the merge-base) and bash 5.2.15, debug builds on aarch64 Linux:
cargo test --workspace --all-targets: 2,689 passed, 0 failed, 0 ignored, exit 0.cargo fmt --checkis clean.cargo clippy --workspace --all-targetsprints the same warning summary as base.- The four earlier repros and their controls now match bash. I re-checked the threads the author resolved.
- The ten mutants that survived at
969a13e, re-run at this head against the lib,differential,shell_integrationandclaude_code_preambletests:- Nine fail: the trailing-term check, the width of a skipped binary primary, the skipped
(group,&&short-circuiting, the empty-expression check,!=as a pattern, the missing-)check,-von a set-but-empty variable, and the empty-path guard. - I rewrote two of those nine for the new code: the empty-expression check has a new message, and
!=now goes throughescaped_glob_match. - The tenth (
=~returns false instead of an error) no longer applies, because the=~arm inconditional_primaryis gone. Its replacement, the refusal inexecute_conditionalswitched off, fails too; it is one of the twelve below.
- Nine fail: the trailing-term check, the width of a skipped binary primary, the skipped
- The 3,938-script harness from the first review, re-run with the previous head
969a13eas the comparison: 3,108 scripts match bash, 50 newly match, and 2 changed for the worse. Both are the intended refusal ([[ -z x && abc =~ ^a ]]now returns 2 with a message). - 358 new probes aimed at the fix:
- Pattern escaping: 58 of 61 match bash, including the prefix idiom
[[ "$p" == "$d"/* ]]and the contains idiom[[ "$l" == *"$n"* ]]with[,*,?and\in the quoted part. - A
[[that is not in command position, followed by a line break (echo [[,for i in [[ a,x=[[, a redirect target, a function argument, a here-doc body, a multi-line string): 24 of 26 match. The other two fail on base for other reasons. - A multi-line
[[in 29 contexts (if,elif,else,while,until,do,{,(,!,&&,||,|,&, case arms, functions,$( ), backticks,eval): 27 match. - Three-argument
testwith-a/-o: no case changed for the worse.
- Pattern escaping: 58 of 61 match bash, including the prefix idiom
- 12 new mutants of the fix commit, run against the same four test targets: 8 fail, 4 pass.
- Not tested: the Python, Node.js and WASM bindings, and a real tty for
-t.
Still open for a maintainer (unchanged from the first review): whether =~ is a follow-up; the docs row that says "No [[ ]]"; whether the parser AST is stable API, since Item::Conditional and CondTerm extend it and the PR has no API-review label; and whether the empty-path rule belongs in the kernel under #322.
Appendix, non-blocking (4)
function f { [[ -n a⏎]] && echo ok; }is a parse error. The tracker does not treat the{afterfunction NAMEas a command start. It needs the[[on the same line asfunction f {.x='=~'; [[ $x == =~ ]]and[[ -n =~ ]]are now refused, where bash treats=~as a plain word. This follows from refusing before evaluation.- A quoted character inside an unquoted bracket expression is not literal (
[[ '\' == [a"*"] ]]matches), and${u:-"*"}on the right is still a pattern. - Pre-existing: a here-doc inside
if, a loop, a group or a function takes the wrong lines as its body. I hit it while testing[[before a here-doc and filed #333.
An empty operand of -nt or -ot is a missing file. The guard stated the other operand when one side was empty, and the kernel resolves "" to the working directory, so two empty paths compared as true. The guard now stats an operand only when it is not empty. New double_bracket lines cover a line break after `then` and after `&&`, a quoted bracket after a star, and -nt/-ot with empty paths. They were recorded with bash 5.2.15.
Description
Context. Agents run scripts that test with
[[ ]]. Claude Code 2.1.316 and later writesgrep,find, andrgwrapper functions into the shell it uses, and each one branches on[[ -x <path> ]],[[ -n ${ZSH_VERSION:-} ]], and[[ "$OSTYPE" == "msys" ]].Before.
[[was not recognized, so each of those tests printed[[: command not found. Every wrapper then fell through to a branch that the shell cannot run, sogrep,find, andrgfailed in the agent's shell.After.
[[ ... ]]is a compound command,Item::Conditional, that holds its operands unexpanded. The evaluation expands an operand only when it reaches it, without splitting or globbing, so&&and||skip the operands they do not need, as bash does. The new command supports:!,&&,||, and parentheses;testoperators, plus-v;-eqand the other numeric comparisons;==,=, and!=, with acasepattern on the right.=~is refused with status 2. No alias expands inside[[ ]]. A file test on an empty path is now false, fortestand[too, as in bash.Verification.
double_bracketanddouble_bracket_alias, recorded from bash, cover:"$@";casearm;&&;[[ ]].Both cases fail on
mainand pass with the change.cargo test: every suite passes.a_here_doc_cut_short_by_the_deadline_writes_no_partial_bodyfailed once under full-suite load (it has a 200 ms deadline) and passed on three reruns and on the next full run.cargo fmt --checkpasses, andcargo clippy --all-targetsshows 15 warnings, the same asmain.echo hi | grep -c hiprints1;grep -rnandfind . -namefind the file;rgwithout a binary exits 127 withcommand not found, and nothing recurses.Related Issues
Part of #323. Works together with #324.
Documentation PR
None.
Type of Change
New feature
Testing
cargo test; no binding changed)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.