Skip to main content

safe_chains/cst/
parse.rs

1mod function;
2
3use super::budget::{self, DepthGuard};
4use super::escape::{self, dq_escape, escaped, fd_target, join_continuation, only_continuations, skip_continuation};
5use super::heredocs;
6use super::sub_close::find_sub_close;
7use super::*;
8use function::function_def;
9use winnow::ModalResult;
10use winnow::combinator::{alt, delimited, not, opt, preceded, repeat, separated, terminated};
11use winnow::error::{ContextError, ErrMode};
12use winnow::prelude::*;
13use winnow::token::{any, take_while};
14
15pub fn parse(input: &str) -> Option<Script> {
16    heredocs::reset();
17    budget::reset(input.len());
18    escape::begin(input);
19    let result = script.parse(input).ok().filter(|_| !budget::spent() && heredocs::drained() && escape::all_plain());
20    heredocs::reset();
21    result
22}
23
24fn backtrack<T>() -> ModalResult<T> {
25    Err(ErrMode::Backtrack(ContextError::new()))
26}
27
28/// Charge one parsing attempt; over budget it fails, and `parse` then refuses.
29fn step() -> ModalResult<()> {
30    if budget::charge(1, 0) { Ok(()) } else { backtrack() }
31}
32
33/// Charge `bytes` consumed or looked ahead at, outside any counted attempt.
34fn scan(bytes: usize) -> ModalResult<()> {
35    if budget::charge(0, bytes) { Ok(()) } else { backtrack() }
36}
37
38/// Run a parser, charging the step budget for what it consumed.
39fn consumed<'a, O>(input: &mut &'a str, p: impl FnOnce(&mut &'a str) -> ModalResult<O>) -> ModalResult<O> {
40    let before = input.len();
41    let out = p(input);
42    scan(before - input.len())?;
43    out
44}
45
46fn comment(input: &mut &str) -> ModalResult<()> {
47    if input.starts_with('#') {
48        *input = input.find('\n').map_or("", |pos| &input[pos..]);
49    }
50    Ok(())
51}
52
53fn ws(input: &mut &str) -> ModalResult<()> {
54    consumed(input, ws_raw)
55}
56
57fn ws_raw(input: &mut &str) -> ModalResult<()> {
58    loop {
59        take_while(0.., [' ', '\t']).void().parse_next(input)?;
60        if input.starts_with('#') {
61            comment(input)?;
62        } else if !skip_continuation(input) {
63            break;
64        }
65    }
66    Ok(())
67}
68
69fn sep(input: &mut &str) -> ModalResult<()> {
70    while consumed(input, sep_raw)? {
71        heredocs::drain(input);
72    }
73    Ok(())
74}
75
76fn sep_raw(input: &mut &str) -> ModalResult<bool> {
77    loop {
78        // Consume separators one at a time so a `;;` stays intact: it terminates a case arm, and
79        // eating its first `;` here would let the arm's body run on into the next arm's pattern.
80        while let Some(c) = input.chars().next() {
81            if input.starts_with(";;") {
82                return Ok(false);
83            }
84            if !matches!(c, ' ' | '\t' | ';' | '\n') {
85                break;
86            }
87            *input = &input[c.len_utf8()..];
88            if c == '\n' && heredocs::pending() {
89                return Ok(true);
90            }
91        }
92        if input.starts_with('#') {
93            comment(input)?;
94        } else {
95            break;
96        }
97    }
98    Ok(false)
99}
100
101fn eat_keyword(input: &mut &str, kw: &str) -> ModalResult<()> {
102    if !input.starts_with(kw) {
103        return backtrack();
104    }
105    if input.as_bytes().get(kw.len()).is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_') {
106        return backtrack();
107    }
108    *input = &input[kw.len()..];
109    Ok(())
110}
111
112const SCRIPT_STOPS: &[&str] = &["do", "done", "elif", "else", "esac", "fi", "then"];
113
114fn at_script_stop(input: &str) -> bool {
115    input.starts_with(')')
116        || input.starts_with('}')
117        // `;;` ends a case arm's body. Without this a body script would run on into the next arm's
118        // pattern and read it as a command.
119        || input.starts_with(";;")
120        || SCRIPT_STOPS.iter().any(|kw| {
121            input.starts_with(kw)
122                && !input
123                    .as_bytes()
124                    .get(kw.len())
125                    .is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_')
126        })
127}
128
129fn is_word_boundary(c: char) -> bool {
130    matches!(c, ' ' | '\t' | '\n' | ';' | '|' | '&' | ')' | '>' | '<')
131}
132
133fn is_word_literal(c: char) -> bool {
134    !is_word_boundary(c) && !matches!(c, '\'' | '"' | '`' | '\\' | '(' | '$')
135}
136
137fn is_dq_literal(c: char) -> bool {
138    !matches!(c, '"' | '\\' | '`' | '$')
139}
140
141// === Script ===
142
143fn script(input: &mut &str) -> ModalResult<Script> {
144    // Bound recursion depth: every nested `(`/`{`/`$(`/`<(`/`` ` `` funnels back through `script`,
145    // so this one guard caps stack depth against deeply-nested adversarial input (see `budget`).
146    let Some(_depth) = DepthGuard::enter() else {
147        return backtrack();
148    };
149    sep.parse_next(input)?;
150    let mut stmts = Vec::new();
151    while let Some(pl) = opt(pipeline).parse_next(input)? {
152        ws.parse_next(input)?;
153        let before = *input;
154        let op = opt(list_op).parse_next(input)?;
155        stmts.push(Stmt { pipeline: pl, op });
156        if before[..before.len() - input.len()].ends_with('\n') {
157            heredocs::drain(input);
158        }
159        if op.is_none() {
160            break;
161        }
162        sep.parse_next(input)?;
163    }
164    Ok(Script(stmts))
165}
166
167fn list_op(input: &mut &str) -> ModalResult<ListOp> {
168    ws.parse_next(input)?;
169    alt((
170        "&&".value(ListOp::And),
171        "||".value(ListOp::Or),
172        '\n'.value(ListOp::Semi),
173        // `;;` is a case-arm terminator, not a statement separator — matching the first `;` here
174        // would let the body swallow it and continue into the next arm.
175        (';', not(';')).value(ListOp::Semi),
176        ('&', not('>')).value(ListOp::Amp),
177    ))
178    .parse_next(input)
179}
180
181/// A pipe. `|&` (bash) pipes stdout AND stderr into the next command; what flows through the pipe
182/// does not change which commands run, so it classifies exactly as `|`. Matched before the bare
183/// `|` so the `&` is not left to start a bogus background statement. `||` stays an OR, not a pipe.
184fn pipe_sep(input: &mut &str) -> ModalResult<()> {
185    (ws, alt(("|&".void(), ('|', not('|')).void())), ws).void().parse_next(input)
186}
187
188// === Pipeline ===
189
190fn pipeline(input: &mut &str) -> ModalResult<Pipeline> {
191    ws.parse_next(input)?;
192    if at_script_stop(input) {
193        return backtrack();
194    }
195    let bang = opt(terminated('!', ws)).parse_next(input)?.is_some();
196    opt_time_keyword_before_compound(input);
197    let commands: Vec<Cmd> = separated(1.., command, pipe_sep).parse_next(input)?;
198    Ok(Pipeline { bang, commands })
199}
200
201/// Consume a leading `time` / `time -p` when it prefixes a COMPOUND command.
202///
203/// `time` is a shell reserved word, not just `/usr/bin/time`: bash lets it prefix a whole pipeline
204/// or compound, so `time (cmd)` and `time { cmd; }` are ordinary shell. The parser only ever
205/// offered `time` to `simple_cmd`, which wants a command NAME, so those forms did not parse at all
206/// and fell to "could not parse this command" — fail-closed, but a prompt for valid shell that was
207/// reported from real use.
208///
209/// NOT handled, deliberately: `time ! (cmd)`. bash accepts the keyword and the `!` in either order
210/// (`bash -n` validates all four spellings), and the caller parses the bang first, so a bang
211/// BETWEEN `time` and the compound leaves nothing this can commit on. `time ! ls` — the simple
212/// form — does work, through the wrapper entry, so the two spellings genuinely disagree. It stays
213/// unfixed because the fix is not local: the helper would have to consume the bang itself and hand
214/// it back for `Pipeline.bang`, which means editing the shared `pipeline()` path that every command
215/// in the corpus goes through. That is a poor trade against a form nobody writes, and the failure
216/// is a prompt, not a hole — `time ! (rm -rf /)` denies, as does every other spelling of it.
217///
218/// Deliberately narrow: it commits ONLY when a `(` or `{` follows. `time ls` keeps going through
219/// the existing `[command.wrapper]` entry in `commands/wrappers/time.toml`, which already handles
220/// the simple-command form and its `-p` flag, so nothing that parses today changes shape. Widening
221/// this to consume `time` unconditionally would work too, but it would silently retire that wrapper
222/// entry for the bare spelling, and a maintenance fix should not move a path that already works.
223fn opt_time_keyword_before_compound(input: &mut &str) -> bool {
224    let mut probe = *input;
225    if eat_keyword(&mut probe, "time").is_err() || !probe.starts_with([' ', '\t', '\n']) {
226        return false;
227    }
228    if ws.parse_next(&mut probe).is_err() {
229        return false;
230    }
231    // `time -p (…)` — the POSIX output flag, the only one the keyword form takes.
232    if probe.starts_with("-p") {
233        let mut with_flag = &probe[2..];
234        if with_flag.starts_with([' ', '\t', '\n']) && ws.parse_next(&mut with_flag).is_ok() {
235            probe = with_flag;
236        }
237    }
238    if !probe.starts_with(['(', '{']) {
239        return false;
240    }
241    *input = probe;
242    true
243}
244
245// === Command ===
246
247fn command(input: &mut &str) -> ModalResult<Cmd> {
248    step()?;
249    ws.parse_next(input)?;
250    if at_script_stop(input) {
251        return backtrack();
252    }
253    let committed = super::reserved::opens_compound(input);
254    alt((subshell, brace_group, for_cmd, while_cmd, until_cmd, if_cmd, case_cmd, double_bracket_cmd, function_def, move |i: &mut &str| {
255        if committed { backtrack() } else { simple_cmd.map(Cmd::Simple).parse_next(i) }
256    }))
257    .parse_next(input)
258}
259
260/// A non-empty run of `pred` characters, charged to the step budget.
261fn run<'a>(input: &mut &'a str, pred: fn(char) -> bool) -> ModalResult<&'a str> {
262    consumed(input, |i| take_while(1.., pred).parse_next(i))
263}
264
265fn trailing_redirs(input: &mut &str) -> ModalResult<Vec<Redir>> {
266    let mut redirs = Vec::new();
267    loop {
268        ws.parse_next(input)?;
269        if let Some(r) = opt(redirect).parse_next(input)? {
270            redirs.push(r);
271        } else {
272            break;
273        }
274    }
275    Ok(redirs)
276}
277
278fn subshell(input: &mut &str) -> ModalResult<Cmd> {
279    let body = delimited(('(', ws), script, (ws, ')')).parse_next(input)?;
280    let redirs = trailing_redirs(input)?;
281    Ok(Cmd::Subshell { body, redirs })
282}
283
284fn brace_group(input: &mut &str) -> ModalResult<Cmd> {
285    if !input.starts_with('{') {
286        return backtrack();
287    }
288    if !input.as_bytes().get(1).is_some_and(|b| matches!(b, b' ' | b'\t' | b'\n')) {
289        return backtrack();
290    }
291    *input = &input[1..];
292    sep.parse_next(input)?;
293    let body = script.parse_next(input)?;
294    if body.0.is_empty() {
295        return backtrack();
296    }
297    sep.parse_next(input)?;
298    if !input.starts_with('}') {
299        return backtrack();
300    }
301    let last_op = body.0.last().and_then(|s| s.op);
302    if last_op.is_none() {
303        return backtrack();
304    }
305    *input = &input[1..];
306    let redirs = trailing_redirs(input)?;
307    Ok(Cmd::BraceGroup { body, redirs })
308}
309
310// === Simple Command ===
311
312fn simple_cmd(input: &mut &str) -> ModalResult<SimpleCmd> {
313    let env: Vec<(String, Word)> = repeat(0.., terminated(assignment, ws)).parse_next(input)?;
314    let mut words = Vec::new();
315    let mut redirs = Vec::new();
316
317    loop {
318        ws.parse_next(input)?;
319        if at_cmd_end(input) {
320            break;
321        }
322        if let Some(r) = opt(redirect).parse_next(input)? {
323            redirs.push(r);
324        } else if let Some(w) = opt(word).parse_next(input)? {
325            words.push(w);
326        } else {
327            break;
328        }
329    }
330
331    if env.is_empty() && words.is_empty() && redirs.is_empty() {
332        return backtrack();
333    }
334    Ok(SimpleCmd { env, words, redirs })
335}
336
337fn at_cmd_end(input: &str) -> bool {
338    // `&>`/`&>>` REDIRECT this command; only a bare `&` backgrounds it and ends it. Without this
339    // the command stopped at the `&` and the redirect parser never saw the operator at all.
340    if input.starts_with("&>") {
341        return false;
342    }
343    input.is_empty() || matches!(input.as_bytes().first(), Some(b'\n' | b';' | b'|' | b'&' | b')'))
344}
345
346fn assignment(input: &mut &str) -> ModalResult<(String, Word)> {
347    let n = run(input, |c| c.is_ascii_alphanumeric() || c == '_')?;
348    let (appends, _) = (opt('+'), '=').parse_next(input)?;
349    let value = opt(word).parse_next(input)?.unwrap_or(Word(vec![WordPart::Lit(String::new())]));
350    Ok((n.to_string(), Word(appends.map(|_| WordPart::Lit(format!("${{{n}}}"))).into_iter().chain(value.0).collect())))
351}
352
353// === Redirect ===
354
355fn redirect(input: &mut &str) -> ModalResult<Redir> {
356    let fd = opt(fd_prefix).parse_next(input)?;
357    alt((
358        preceded("<<<", (ws, word)).map(|(_, target)| Redir::HereStr(target)),
359        heredoc,
360        preceded(">>", (ws, word)).map(move |(_, target)| Redir::Write { fd: fd.unwrap_or(1), target, mode: WriteMode::Append }),
361        // `&>>` / `&>` send stdout AND stderr to a FILE (bash). `&>` must follow `&>>` so the
362        // append form is not read as a truncate followed by a stray `>`.
363        preceded("&>>", (ws, word)).map(|(_, target)| Redir::Write { fd: 1, target, mode: WriteMode::AppendBoth }),
364        preceded("&>", (ws, word)).map(|(_, target)| Redir::Write { fd: 1, target, mode: WriteMode::TruncateBoth }),
365        preceded(">&", fd_target).map(move |dst| Redir::DupFd { src: fd.unwrap_or(1), dst }),
366        // `>&WORD` where WORD is not a file descriptor is the older spelling of `&>`: it opens a
367        // FILE for both streams. It must follow the `>&`-fd form, so `>&2` stays a descriptor dup
368        // rather than a write to a file named `2`.
369        preceded(">&", (ws, word)).map(|(_, target)| Redir::Write { fd: 1, target, mode: WriteMode::TruncateBoth }),
370        // `>|` (POSIX 2.7.2) overrides `noclobber`. The override is about whether the shell
371        // REFUSES an existing file, not about what lands there, so it classifies as the plain
372        // overwrite it is. Must precede `>` or the `|` reads as a pipe into an empty command.
373        preceded(">|", (ws, word)).map(move |(_, target)| Redir::Write { fd: fd.unwrap_or(1), target, mode: WriteMode::Clobber }),
374        preceded('>', (ws, word)).map(move |(_, target)| Redir::Write { fd: fd.unwrap_or(1), target, mode: WriteMode::Truncate }),
375        // `<>` (POSIX 2.7.5) opens the target for BOTH reading and writing. Must precede `<`,
376        // which would otherwise match and leave `>` to start a bogus second redirect.
377        preceded("<>", (ws, word)).map(move |(_, target)| Redir::ReadWrite { fd: fd.unwrap_or(0), target }),
378        preceded('<', (ws, word)).map(move |(_, target)| Redir::Read { fd: fd.unwrap_or(0), target }),
379    ))
380    .parse_next(input)
381}
382
383fn heredoc(input: &mut &str) -> ModalResult<Redir> {
384    "<<".parse_next(input)?;
385    let strip_tabs = opt('-').parse_next(input)?.is_some();
386    ws.parse_next(input)?;
387    let before = input.len();
388    let delimiter = heredoc_delimiter.parse_next(input);
389    scan(if delimiter.is_ok() { before - input.len() } else { before })?;
390    let (delimiter, expands) = delimiter?;
391    if delimiter.contains('\n') {
392        escape::refuse();
393    }
394    // With a BARE delimiter the shell expands the body, so `cat <<EOF` with `$(rm -rf /)` in it
395    // runs that command. The body is looked up now (it is already present in `input`, after this
396    // line) rather than at drain time, so the expansions land on the redirect that owns them.
397    let start = heredocs::expected_body_start(input);
398    let body = if expands { heredoc_body_word(input, start, &delimiter, strip_tabs)? } else { Word(Vec::new()) };
399    // Bash semantics: the heredoc body lives on lines AFTER the
400    // command line is finished, not immediately after `<<DELIM`. The
401    // command line can continue with more redirects, a pipe, etc.
402    // Push the delimiter onto a thread-local queue; the body is
403    // drained at the next newline by heredocs::drain.
404    let start = start.map_or(0, |s| s.as_ptr() as usize);
405    heredocs::push(heredocs::Pending { delimiter: delimiter.clone(), strip_tabs, joins: expands, start });
406    Ok(Redir::HereDoc { delimiter, strip_tabs, body })
407}
408
409/// This heredoc's body, parsed for the expansions the shell performs on it. Reads without
410/// consuming; `heredocs::drain` still does the consuming, and refuses when the body it
411/// reaches does not start where this one was read.
412///
413/// FAILS CLOSED: a body that does not parse (a lone backtick opens a substitution that is never
414/// closed) refuses the whole parse, which denies. That matches the shell, which reports
415/// `unexpected EOF while looking for matching backquote` and runs nothing.
416fn heredoc_body_word(input: &str, start: Option<&str>, delimiter: &str, strip_tabs: bool) -> ModalResult<Word> {
417    let Some((body, after)) = start.and_then(|rest| heredocs::split_body(rest, delimiter, strip_tabs, true)) else {
418        scan(input.len())?;
419        return Ok(Word(Vec::new()));
420    };
421    scan(input.len() - after.len())?;
422    let mut text = body;
423    let parts: Vec<WordPart> = repeat(0.., heredoc_part).parse_next(&mut text)?;
424    if !text.is_empty() {
425        return backtrack();
426    }
427    Ok(Word(parts))
428}
429
430/// A heredoc body expands like a double-quoted string, with one difference that matters: `"` and
431/// `'` are ORDINARY characters there, so `'$(id)'` in a body still runs `id`. Skipping quoted spans
432/// the way `find_sub_close` does would therefore miss a live substitution.
433fn is_heredoc_literal(c: char) -> bool {
434    !matches!(c, '"' | '\\' | '`' | '$')
435}
436
437fn heredoc_part(input: &mut &str) -> ModalResult<WordPart> {
438    step()?;
439    if input.is_empty() {
440        return backtrack();
441    }
442    if input.starts_with('"') {
443        *input = &input[1..];
444        return Ok(WordPart::Lit("\"".to_string()));
445    }
446    alt((dq_escape, arith_sub, cmd_sub, backtick_part, dollar_lit(is_heredoc_literal), lit(is_heredoc_literal))).parse_next(input)
447}
448
449/// The delimiter, and whether the body EXPANDS. Any quoting or escaping anywhere in the delimiter
450/// suppresses expansion (`<<'EOF'`, `<<"EOF"`, `<<\EOF`, `<<E"O"F`); only a wholly bare word leaves
451/// the body live. Reported as a flag because that single bit decides whether the body is data or
452/// code, and treating a quoted body as code would over-deny every ordinary commit message.
453fn heredoc_delimiter(input: &mut &str) -> ModalResult<(String, bool)> {
454    alt((
455        delimited('\'', take_while(0.., |c| c != '\''), '\'').map(|s: &str| (s.to_string(), false)),
456        delimited('"', take_while(0.., |c| c != '"'), '"').map(|s: &str| (s.to_string(), false)),
457        escaped_delimiter,
458        take_while(1.., |c: char| c.is_ascii_alphanumeric() || c == '_').map(|s: &str| (s.to_string(), true)),
459    ))
460    .parse_next(input)
461}
462
463/// A delimiter carrying a backslash or an inner quote — `<<\EOF`, `<<E"O"F`, `<<EO'F'`. The shell
464/// treats ANY such quoting as suppressing expansion over the WHOLE delimiter, so these parse to the
465/// unquoted spelling with expansion off. Without this they failed to parse at all, denying a valid
466/// (and, being unexpanded, entirely inert) heredoc.
467fn escaped_delimiter(input: &mut &str) -> ModalResult<(String, bool)> {
468    let mut rest = *input;
469    let mut name = String::new();
470    let mut quoted = false;
471    let mut joined = false;
472    loop {
473        let mut chars = rest.chars();
474        match chars.next() {
475            Some('\\') if join_continuation(&mut rest) => joined = true,
476            Some('\\') => match chars.next() {
477                Some(c) => {
478                    name.push(c);
479                    quoted = true;
480                    rest = &rest[1 + c.len_utf8()..];
481                }
482                None => break,
483            },
484            Some(q @ ('\'' | '"')) => {
485                let inner_end = rest[1..].find(q).map(|i| i + 1);
486                let Some(end) = inner_end else { break };
487                name.push_str(&rest[1..end]);
488                quoted = true;
489                rest = &rest[end + 1..];
490            }
491            Some(c) if c.is_ascii_alphanumeric() || c == '_' => {
492                name.push(c);
493                rest = &rest[c.len_utf8()..];
494            }
495            _ => break,
496        }
497    }
498    if !(quoted || joined) || name.is_empty() {
499        return backtrack();
500    }
501    *input = rest;
502    Ok((name, !quoted))
503}
504
505fn fd_prefix(input: &mut &str) -> ModalResult<u32> {
506    let b = input.as_bytes();
507    if b.len() >= 2 && b[0].is_ascii_digit() && matches!(b[1], b'>' | b'<') {
508        let d = (b[0] - b'0') as u32;
509        *input = &input[1..];
510        Ok(d)
511    } else {
512        backtrack()
513    }
514}
515
516// === Word ===
517
518fn word(input: &mut &str) -> ModalResult<Word> {
519    repeat(1.., word_part).map(Word).verify(|w: &Word| !only_continuations(&w.0)).parse_next(input)
520}
521
522fn word_part(input: &mut &str) -> ModalResult<WordPart> {
523    step()?;
524    if input.is_empty() {
525        return backtrack();
526    }
527    if input.starts_with("<(") || input.starts_with(">(") {
528        return proc_sub(input);
529    }
530    if is_word_boundary(input.as_bytes()[0] as char) {
531        return backtrack();
532    }
533    alt((
534        single_quoted,
535        double_quoted,
536        dollar_quoted,
537        arith_sub,
538        cmd_sub,
539        backtick_part,
540        escaped,
541        dollar_lit(is_word_literal),
542        lit(is_word_literal),
543    ))
544    .parse_next(input)
545}
546
547fn single_quoted(input: &mut &str) -> ModalResult<WordPart> {
548    delimited_scan(input, '\'', |i| {
549        delimited('\'', take_while(0.., |c| c != '\''), '\'')
550            .map(|s: &str| WordPart::SQuote(s.to_string()))
551            .parse_next(i)
552    })
553}
554
555fn double_quoted(input: &mut &str) -> ModalResult<WordPart> {
556    delimited('"', repeat(0.., dq_part).map(Word), '"').map(WordPart::DQuote).parse_next(input)
557}
558
559fn dollar_quoted(input: &mut &str) -> ModalResult<WordPart> {
560    alt((super::ansi_c::ansi_c_quoted, |i: &mut &str| super::ansi_c::locale_quoted(i, double_quoted))).parse_next(input)
561}
562
563/// Parse a substitution body (`$( … )`, `<( … )`, `>( … )`) as a full script.
564///
565/// FAST PATH: `find_sub_close` locates the matching `)` and we parse only the bounded interior, so
566/// nested substitutions stay linear instead of the old `delimited(script, ')')` shape that recursed
567/// into the tail before knowing a close existed (the `a$(a<(a` × N exponential).
568///
569/// FALLBACK: a heredoc or a `case` moves the real close PAST that first balanced `)` (a heredoc body
570/// is drained out-of-band; an arm's pattern ends in a bare `)`), so an interior holding either goes
571/// to the EXACT old grammar over the full body instead. Otherwise the fast path is the ONLY reading:
572/// a refused interior refuses the substitution. Re-running the grammar there doubled the work per
573/// nested `$(`, since each level parsed its interior once bounded and once more in full.
574///
575/// A `None` from `find_sub_close` normally means no unquoted `)` exists at all, so the grammar
576/// could not close the sub either and we fail fast. The exception is a heredoc: its body is data the scanner reads as code, so a lone apostrophe in prose (`the shell's
577/// grammar`) opens a quote that never closes and swallows the real `)`. `git commit -m "$(cat <<EOF`
578/// with any contraction in the message lands here, so `None` + a heredoc operator takes the grammar
579/// fallback — which drains the body correctly — rather than failing the whole parse.
580fn sub_body(input: &mut &str, open_len: usize) -> ModalResult<Script> {
581    let body = &input[open_len..];
582    let close = find_sub_close(body);
583    scan(close.map_or(2 * body.len(), |rel| 3 * rel))?;
584    let Some(rel) = close else {
585        return if body.contains("<<") { sub_body_via_grammar(input, body) } else { backtrack() };
586    };
587    // A heredoc body is drained out-of-band (`heredocs::drain`) and can run PAST `rel`, so the
588    // bounded interior would be truncated mid-heredoc and still parse "clean" — the fast path is
589    // unreliable whenever the interior holds a heredoc operator. Skip straight to the grammar fallback
590    // there. `<<` covers `<<`, `<<-`, and `<<<`; the latter (herestring) is inline and would be fine,
591    // but taking the fallback for it is merely slower, never wrong.
592    let interior = &body[..rel];
593    // `case` has the same hazard as a heredoc: the `)` closing an arm's pattern is not a nesting
594    // paren, so `find_sub_close` stops at `$(case A in *)` and the truncated interior still parses
595    // "clean" — as a simple command whose words are `case A in *`. A wrong-but-clean fast parse is
596    // worse than a slow one, so hand any interior mentioning `case` to the grammar fallback. The
597    // test is deliberately the bare substring: a literal word `case` merely costs a slower path.
598    if !interior.contains("<<") && !interior.contains("case") {
599        let mut fast: &str = interior;
600        let parsed = script.parse_next(&mut fast)?;
601        ws.parse_next(&mut fast)?;
602        if !fast.is_empty() {
603            return backtrack();
604        }
605        *input = &body[rel + 1..];
606        return Ok(parsed);
607    }
608    sub_body_via_grammar(input, body)
609}
610
611/// The EXACT old grammar over the full body: it drains heredocs and tracks `case` arms, so it finds
612/// a close that `find_sub_close`'s byte scan places wrongly or misses. Bounded by `budget`.
613fn sub_body_via_grammar<'a>(input: &mut &'a str, body: &'a str) -> ModalResult<Script> {
614    let mut rest: &str = body;
615    ws.parse_next(&mut rest)?;
616    let parsed = script.parse_next(&mut rest)?;
617    ws.parse_next(&mut rest)?;
618    if !rest.starts_with(')') {
619        return backtrack();
620    }
621    *input = &rest[1..];
622    Ok(parsed)
623}
624
625fn cmd_sub(input: &mut &str) -> ModalResult<WordPart> {
626    if !input.starts_with("$(") {
627        return backtrack();
628    }
629    heredocs::own(|| sub_body(input, 2)).map(WordPart::CmdSub)
630}
631
632fn proc_sub(input: &mut &str) -> ModalResult<WordPart> {
633    if !(input.starts_with("<(") || input.starts_with(">(")) {
634        return backtrack();
635    }
636    heredocs::own(|| sub_body(input, 2)).map(WordPart::ProcSub)
637}
638
639/// The parts of an arithmetic BODY: literal text plus the substitutions that actually run.
640fn arith_body_part(input: &mut &str) -> ModalResult<WordPart> {
641    step()?;
642    if input.is_empty() {
643        return backtrack();
644    }
645    alt((
646        dq_escape,
647        // Nested `$(( ))` must be recognised as ARITHMETIC before `cmd_sub` sees it, or `$((` is
648        // read as `$(` plus a subshell and `$(( $((1+1)) ))` refuses on an inner "command" `(1+1)`.
649        // It cannot be skipped as literal text either: `$(( $(( $(rm -rf /) )) ))` would then hide
650        // a real substitution, which is a fail-OPEN. So it recurses, bounded by the guard below.
651        arith_sub,
652        cmd_sub,
653        backtick_part,
654        dollar_lit(is_heredoc_literal),
655        lit(is_heredoc_literal),
656    ))
657    .parse_next(input)
658}
659
660fn arith_sub(input: &mut &str) -> ModalResult<WordPart> {
661    if !input.starts_with("$((") {
662        return backtrack();
663    }
664    // Parsing the body makes this a recursion source that does NOT funnel through `script()`, where
665    // the depth cap is enforced — unguarded, `$((1+` x50000 overflowed the stack and ABORTED,
666    // which for a hook is a fail-open crash `catch_unwind` cannot recover. Taking the guard here
667    // was previously rejected because bailing backtracks into `cmd_sub`, which re-parsed the same
668    // nest for 68 seconds; that is affordable now only because `budget` charges what each retry
669    // reads, which bounds the retry as well as the descent.
670    let Some(_depth) = DepthGuard::enter() else {
671        return backtrack();
672    };
673    let body_start = 3;
674    let bytes = input.as_bytes();
675    let mut depth: i32 = 1;
676    let mut i = body_start;
677    while i < bytes.len() {
678        match bytes[i] {
679            b'(' => depth += 1,
680            b')' => {
681                if depth == 1 && i + 1 < bytes.len() && bytes[i + 1] == b')' {
682                    // The body is PARSED, not kept as text. It used to backtrack whenever it held
683                    // a substitution, which handed `$((` to `cmd_sub` and re-read it as `$(` plus a
684                    // subshell — `--explain` rendered `$( (1 + …))`, a command nobody wrote, and
685                    // refused it because `(1` is not a command. That cost a false deny on the
686                    // everyday `$(( now - $(date +%s) ))`.
687                    //
688                    // The old backtrack was the conservative choice: treating the body as opaque
689                    // text would hide the inner command, a fail-OPEN. Parsing keeps it visible and
690                    // stops the misparse. `arith_body_part` deliberately excludes `arith_sub`, so
691                    // arithmetic is not a recursion source — nested `$(( ))` is literal text here,
692                    // which costs nothing since arithmetic is inert either way.
693                    scan(i)?;
694                    let mut body = &input[body_start..i];
695                    let parts: Vec<WordPart> = repeat(0.., arith_body_part).parse_next(&mut body)?;
696                    if !body.is_empty() {
697                        return backtrack();
698                    }
699                    *input = &input[i + 2..];
700                    return Ok(WordPart::Arith(Word(parts)));
701                }
702                depth -= 1;
703                if depth < 0 {
704                    scan(i)?;
705                    return backtrack();
706                }
707            }
708            _ => {}
709        }
710        i += 1;
711    }
712    scan(i)?;
713    backtrack()
714}
715
716fn backtick_part(input: &mut &str) -> ModalResult<WordPart> {
717    delimited_scan(input, '`', |i| delimited('`', backtick_inner, '`').map(escape::backtick).parse_next(i))
718}
719
720/// A quoted span scans to its close, or to the end of the input when there is none, so an unclosed
721/// one is charged for everything it read even though it consumes nothing.
722fn delimited_scan<O>(input: &mut &str, open: char, p: impl FnOnce(&mut &str) -> ModalResult<O>) -> ModalResult<O> {
723    if !input.starts_with(open) {
724        return backtrack();
725    }
726    let before = input.len();
727    let out = p(input);
728    scan(if out.is_ok() { before - input.len() } else { before })?;
729    out
730}
731
732fn lit(pred: fn(char) -> bool) -> impl FnMut(&mut &str) -> ModalResult<WordPart> {
733    move |input: &mut &str| {
734        let s: &str = consumed(input, |i| take_while(1.., pred).parse_next(i))?;
735        Ok(WordPart::Lit(s.to_string()))
736    }
737}
738
739fn dollar_lit(pred: fn(char) -> bool) -> impl FnMut(&mut &str) -> ModalResult<WordPart> {
740    move |input: &mut &str| {
741        (not(escape::opens_function_substitution), '$', not('(')).void().parse_next(input)?;
742        let rest: &str = consumed(input, |i| take_while(0.., pred).parse_next(i))?;
743        Ok(WordPart::Lit(format!("${rest}")))
744    }
745}
746
747// === Double-quoted parts ===
748
749fn dq_part(input: &mut &str) -> ModalResult<WordPart> {
750    step()?;
751    if input.is_empty() || input.starts_with('"') {
752        return backtrack();
753    }
754    alt((dq_escape, arith_sub, cmd_sub, backtick_part, dollar_lit(is_dq_literal), lit(is_dq_literal))).parse_next(input)
755}
756
757// === Backtick inner content ===
758
759fn backtick_inner(input: &mut &str) -> ModalResult<String> {
760    repeat(0.., alt((bt_escape, bt_literal)))
761        .fold(String::new, |mut acc, chunk: &str| {
762            acc.push_str(chunk);
763            acc
764        })
765        .parse_next(input)
766}
767
768fn bt_escape<'a>(input: &mut &'a str) -> ModalResult<&'a str> {
769    ('\\', any).take().parse_next(input)
770}
771
772fn bt_literal<'a>(input: &mut &'a str) -> ModalResult<&'a str> {
773    take_while(1.., |c: char| c != '`' && c != '\\').parse_next(input)
774}
775
776// === Compound Commands ===
777
778fn for_cmd(input: &mut &str) -> ModalResult<Cmd> {
779    eat_keyword(input, "for")?;
780    ws.parse_next(input)?;
781    let var = name.parse_next(input)?;
782    ws.parse_next(input)?;
783
784    let items = if eat_keyword(input, "in").is_ok() {
785        ws.parse_next(input)?;
786        repeat(0.., terminated(word, ws)).parse_next(input)?
787    } else {
788        vec![]
789    };
790
791    let body = do_done_body.parse_next(input)?;
792    let redirs = trailing_redirs(input)?;
793    Ok(Cmd::For { var, items, body, redirs })
794}
795
796fn while_cmd(input: &mut &str) -> ModalResult<Cmd> {
797    eat_keyword(input, "while")?;
798    ws.parse_next(input)?;
799    let cond = script.parse_next(input)?;
800    let body = do_done_body.parse_next(input)?;
801    let redirs = trailing_redirs(input)?;
802    Ok(Cmd::While { cond, body, redirs })
803}
804
805fn until_cmd(input: &mut &str) -> ModalResult<Cmd> {
806    eat_keyword(input, "until")?;
807    ws.parse_next(input)?;
808    let cond = script.parse_next(input)?;
809    let body = do_done_body.parse_next(input)?;
810    let redirs = trailing_redirs(input)?;
811    Ok(Cmd::Until { cond, body, redirs })
812}
813
814fn do_done_body(input: &mut &str) -> ModalResult<Script> {
815    sep.parse_next(input)?;
816    eat_keyword(input, "do")?;
817    sep.parse_next(input)?;
818    let body = script.parse_next(input)?;
819    sep.parse_next(input)?;
820    eat_keyword(input, "done")?;
821    Ok(body)
822}
823
824fn if_cmd(input: &mut &str) -> ModalResult<Cmd> {
825    eat_keyword(input, "if")?;
826    ws.parse_next(input)?;
827    let mut branches = vec![cond_then_body.parse_next(input)?];
828    let mut else_body = None;
829
830    loop {
831        sep.parse_next(input)?;
832        if eat_keyword(input, "elif").is_ok() {
833            ws.parse_next(input)?;
834            branches.push(cond_then_body.parse_next(input)?);
835        } else if eat_keyword(input, "else").is_ok() {
836            sep.parse_next(input)?;
837            else_body = Some(script.parse_next(input)?);
838            break;
839        } else {
840            break;
841        }
842    }
843
844    sep.parse_next(input)?;
845    eat_keyword(input, "fi")?;
846    let redirs = trailing_redirs(input)?;
847    Ok(Cmd::If { branches, else_body, redirs })
848}
849
850fn cond_then_body(input: &mut &str) -> ModalResult<Branch> {
851    let cond = script.parse_next(input)?;
852    sep.parse_next(input)?;
853    eat_keyword(input, "then")?;
854    sep.parse_next(input)?;
855    let body = script.parse_next(input)?;
856    Ok(Branch { cond, body })
857}
858
859/// `case WORD in [(] PATTERN [| PATTERN]… ) BODY ;; … esac` (POSIX 2.9.4.3).
860fn case_cmd(input: &mut &str) -> ModalResult<Cmd> {
861    eat_keyword(input, "case")?;
862    ws.parse_next(input)?;
863    let subject = word.parse_next(input)?;
864    blank.parse_next(input)?;
865    eat_keyword(input, "in")?;
866
867    let mut arms = Vec::new();
868    loop {
869        blank.parse_next(input)?;
870        if eat_keyword(input, "esac").is_ok() {
871            break;
872        }
873        let arm = case_arm.parse_next(input)?;
874        let had_terminator = opt(";;").parse_next(input)?.is_some();
875        arms.push(arm);
876        // POSIX lets the LAST arm omit `;;`, and only the last. Anything else here is malformed —
877        // backtrack rather than guess, so a shape we don't understand fails closed.
878        if !had_terminator {
879            blank.parse_next(input)?;
880            eat_keyword(input, "esac")?;
881            break;
882        }
883    }
884
885    let redirs = trailing_redirs(input)?;
886    Ok(Cmd::Case { subject, arms, redirs })
887}
888
889fn case_arm(input: &mut &str) -> ModalResult<CaseArm> {
890    blank.parse_next(input)?;
891    opt('(').parse_next(input)?;
892    let mut patterns = Vec::new();
893    loop {
894        ws.parse_next(input)?;
895        patterns.push(word.parse_next(input)?);
896        ws.parse_next(input)?;
897        if opt('|').parse_next(input)?.is_none() {
898            break;
899        }
900    }
901    ')'.parse_next(input)?;
902    let body = script.parse_next(input)?;
903    blank.parse_next(input)?;
904    Ok(CaseArm { patterns, body })
905}
906
907/// Whitespace including newlines, but NOT `;` — used where a `;;` must stay visible to the caller.
908fn blank(input: &mut &str) -> ModalResult<()> {
909    consumed(input, heredocs::skip_blank)
910}
911
912fn double_bracket_cmd(input: &mut &str) -> ModalResult<Cmd> {
913    if !input.starts_with("[[") {
914        return backtrack();
915    }
916    let bytes = input.as_bytes();
917    if bytes.len() < 3 || !matches!(bytes[2], b' ' | b'\t' | b'\n') {
918        return backtrack();
919    }
920    *input = &input[2..];
921
922    let mut words: Vec<Word> = Vec::new();
923    loop {
924        ws.parse_next(input)?;
925        if at_double_bracket_end(input) {
926            *input = &input[2..];
927            let redirs = trailing_redirs(input)?;
928            return Ok(Cmd::DoubleBracket { words, redirs });
929        }
930        if input.is_empty() {
931            return backtrack();
932        }
933        let w = bracket_word.parse_next(input)?;
934        words.push(w);
935    }
936}
937
938fn at_double_bracket_end(input: &str) -> bool {
939    if !input.starts_with("]]") {
940        return false;
941    }
942    let after = &input[2..];
943    after.is_empty() || after.starts_with([' ', '\t', '\n', ';', '&', '|', ')', '>', '<'])
944}
945
946fn bracket_word(input: &mut &str) -> ModalResult<Word> {
947    repeat(1.., bracket_word_part).map(Word).parse_next(input)
948}
949
950fn bracket_word_part(input: &mut &str) -> ModalResult<WordPart> {
951    step()?;
952    if input.is_empty() {
953        return backtrack();
954    }
955    if matches!(input.as_bytes()[0], b' ' | b'\t' | b'\n') {
956        return backtrack();
957    }
958    if at_double_bracket_end(input) {
959        return backtrack();
960    }
961    alt((
962        single_quoted,
963        double_quoted,
964        dollar_quoted,
965        arith_sub,
966        cmd_sub,
967        backtick_part,
968        escaped,
969        dollar_lit(is_bracket_literal),
970        bracket_lit,
971    ))
972    .parse_next(input)
973}
974
975fn is_bracket_literal(c: char) -> bool {
976    !matches!(c, '\'' | '"' | '`' | '\\' | '$' | ' ' | '\t' | '\n')
977}
978
979fn bracket_lit(input: &mut &str) -> ModalResult<WordPart> {
980    // Byte-by-byte scan relies on every stop char being single-byte ASCII —
981    // multibyte UTF-8 continuation bytes always pass `is_bracket_literal` and
982    // get consumed as part of the same `Lit`, so `end` only lands on a char
983    // boundary.
984    let bytes = input.as_bytes();
985    let mut end = 0;
986    while end < bytes.len() {
987        let c = bytes[end] as char;
988        if !is_bracket_literal(c) {
989            break;
990        }
991        if c == ']' && at_double_bracket_end(&input[end..]) {
992            break;
993        }
994        end += 1;
995    }
996    scan(end)?;
997    if end == 0 {
998        return backtrack();
999    }
1000    let lit = input[..end].to_string();
1001    *input = &input[end..];
1002    Ok(WordPart::Lit(lit))
1003}
1004
1005fn name(input: &mut &str) -> ModalResult<String> {
1006    run(input, |c| c.is_ascii_alphanumeric() || c == '_').map(String::from)
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011    use super::budget::MAX_PARSE_WORK_CEILING;
1012    /// The parse work budget must bound NESTED input without refusing anything real.
1013    ///
1014    /// Both halves are measured, because the constant is only defensible as a ratio between them:
1015    ///
1016    ///   - Real commands are FLAT and cost 1-2 `script()` entries. Across every example the
1017    ///     registry ships (1338 of them) the most any one needs is 2 — the worst being
1018    ///     `eval "$(conda shell.bash hook)"`. Flat input is free regardless of size: 400
1019    ///     side-by-side `$((1))` in 2805 bytes costs ONE entry.
1020    ///   - Nested input is what blows up, and it blew up because the budget GREW with the input
1021    ///     (`16384 + 512 * len`), so a bigger adversarial input bought itself more time. At depth
1022    ///     400 that allowed 1_453_119 entries and took 1.55s in release purely to fail; depth 1000
1023    ///     read as a hang.
1024    ///
1025    /// So the guard pins the ratio, not a timing: real examples must stay far under the ceiling,
1026    /// and a deep nest must be stopped BY the ceiling rather than by exhausting a length-scaled
1027    /// allowance. Timings are deliberately not asserted — they are machine-dependent — but for the
1028    /// record the same depth-400 input now parses in 0.028s, below process startup.
1029    #[test]
1030    fn the_parse_work_budget_bounds_nesting_without_refusing_real_commands() {
1031        let worst_real = crate::registry::corpus_examples()
1032            .into_iter()
1033            .flat_map(|(_, safe, denied)| safe.iter().chain(denied.iter()).cloned().collect::<Vec<_>>())
1034            .map(|ex| {
1035                let _ = super::parse(&ex);
1036                budget::work()
1037            })
1038            .max()
1039            .expect("the registry ships examples");
1040        assert!(
1041            worst_real * 100 < MAX_PARSE_WORK_CEILING,
1042            "a real example needs {worst_real} entries against a {MAX_PARSE_WORK_CEILING} ceiling; \
1043             the margin that makes this constant safe is gone"
1044        );
1045
1046        // Flat input stays LINEAR however long it is — that is why a flat ceiling is safe, and it
1047        // is the property, not a particular number. Arithmetic began costing one unit each when
1048        // `arith_sub` took the depth guard (it is a recursion source now), so 400 expansions cost
1049        // ~400 rather than the ~1 they cost when arithmetic was outside the accounting. Still two
1050        // orders of magnitude under the ceiling, which is what matters.
1051        let flat = format!("echo {}", "$((1)) ".repeat(400));
1052        let _ = super::parse(&flat);
1053        let flat_work = budget::work();
1054        assert!(
1055            flat_work < MAX_PARSE_WORK_CEILING / 10,
1056            "flat input cost {flat_work}, close to the {MAX_PARSE_WORK_CEILING} ceiling — a long \
1057             flat command is at risk of being refused"
1058        );
1059
1060        // A deep nest is stopped by the CEILING, not by a length-scaled allowance. The property
1061        // asserted is that the work stops GROWING with the input — doubling the nest must not
1062        // double the work — which is precisely what the old `BASE + PER_BYTE * len` budget failed
1063        // to do. An exact cap is not asserted: `enter()` bumps the counter before it checks, so
1064        // calls on the unwind path overshoot slightly (59 entries when this was written).
1065        let work_at = |depth: usize| {
1066            let deep = format!("echo {}1{}", "$((1+".repeat(depth), "))".repeat(depth));
1067            let _ = super::parse(&deep);
1068            assert!(budget::spent(), "the nest should actually reach a bound, or this proves nothing");
1069            budget::work()
1070        };
1071        let (w2k, w4k) = (work_at(2000), work_at(4000));
1072        assert!(w4k <= w2k + w2k / 10, "work still scales with input length: depth 2000 used {w2k}, depth 4000 used {w4k}");
1073        assert!(w4k < MAX_PARSE_WORK_CEILING + MAX_PARSE_WORK_CEILING / 10, "work {w4k} ran far past the {MAX_PARSE_WORK_CEILING} ceiling");
1074    }
1075
1076    use super::*;
1077
1078    /// An unclosed compound, nested, must cost parse work LINEAR in its depth.
1079    ///
1080    /// Found by the `explain_render` fuzzer as a timeout: `{\n` repeated in front of a
1081    /// `"$([[ … <<` tail. Every level was parsed as a brace group, failed at the far end, and was
1082    /// parsed again as a simple command named `{`, so the work doubled per brace until the entry
1083    /// budget stopped it, 0.35s per parse and several parses per classification. The rule is not
1084    /// about braces: any reserved word that opens a compound had the same second reading. So this
1085    /// walks every opener `reserved` knows, and a new one without an unclosed form here fails.
1086    #[test]
1087    fn unclosed_compound_nesting_costs_linear_work() {
1088        let unclosed = |opener: &str| match opener {
1089            "{" => "{\n",
1090            "[[" => "[[ a\n",
1091            "if" => "if a; then\n",
1092            "for" => "for x in a; do\n",
1093            "while" => "while a; do\n",
1094            "until" => "until a; do\n",
1095            "case" => "case x in a)\n",
1096            "function" => "function f {\n",
1097            other => panic!("no unclosed form for the reserved word {other:?}; add one here"),
1098        };
1099        let tail = "\"$([[ <<\"\"<\"$( [[ x ]] ) $(ls <<EOF\n)\nEOF\n)\" ls";
1100        let openers = super::super::reserved::BLANK_OPENERS.iter().chain(super::super::reserved::KEYWORD_OPENERS.iter());
1101        for opener in openers {
1102            let unit = unclosed(opener);
1103            for prefix in [unit.to_string(), format!("{unit}{{\n")] {
1104                for depth in [10u64, 20, 40] {
1105                    let text = format!("{}{tail}", prefix.repeat(depth as usize));
1106                    let _ = parse(&text);
1107                    let work = budget::work();
1108                    assert!(
1109                        work <= 4 * depth + 64,
1110                        "{depth} nested unclosed {prefix:?} cost {work} parse entries, more than \
1111                         linear in the nesting: a failed compound is being re-read another way"
1112                    );
1113                }
1114            }
1115        }
1116    }
1117
1118    /// A refused substitution interior, nested, must also cost work linear in the nesting.
1119    ///
1120    /// `sub_body` used to follow a refused bounded interior with a full-grammar re-parse of the
1121    /// same text, so every `$(` level read its interior twice and depth 10 cost 2047 entries. The
1122    /// interiors here are refused for different reasons (an unclosed `[[`, an unclosed brace group,
1123    /// an `if` without `then`, a stray `}`), in plain and double-quoted substitutions, because the
1124    /// doubling did not depend on why the interior failed.
1125    #[test]
1126    fn refused_substitution_nesting_costs_linear_work() {
1127        for refused in ["[[ a", "{ a", "if a", "a; }"] {
1128            for (open, close) in [("$(", ")"), ("\"$(", ")\""), ("<(", ")")] {
1129                for depth in [10u64, 20, 40] {
1130                    let n = depth as usize;
1131                    let text = format!("echo {}x{}", format!("{open}{refused} ").repeat(n), close.repeat(n));
1132                    let _ = parse(&text);
1133                    let work = budget::work();
1134                    assert!(
1135                        work <= 4 * depth + 64,
1136                        "{depth} nested {open}{refused} cost {work} parse entries, more than linear: \
1137                         a refused interior is being parsed a second time"
1138                    );
1139                }
1140            }
1141        }
1142    }
1143
1144    /// A nest that still backtracks is stopped by how much it READS, not by how often it enters.
1145    ///
1146    /// `$((` is read as arithmetic first and as `$(` plus a subshell when that fails, as bash does,
1147    /// so a failing nest of them still doubles per level. The entry ceiling caps the count at
1148    /// 20,000, but each entry here re-reads a 100 KB tail, and before the step budget that took 15s
1149    /// to refuse. Stopping it after a few hundred entries is the step budget doing its job; hitting
1150    /// the entry ceiling instead means some scan is not being charged.
1151    #[test]
1152    fn a_backtracking_nest_over_a_long_tail_is_stopped_by_what_it_reads() {
1153        let tail = "a ".repeat(50_000);
1154        for (open, close) in [("$(( $({ ", ") ))"), ("\"$(( $( [[ ", ") ))\"")] {
1155            let text = format!("echo {}x {tail}{}", open.repeat(20), close.repeat(20));
1156            assert!(parse(&text).is_none(), "{open:?} nest parsed");
1157            assert!(budget::spent(), "{open:?} nest was refused, but not by the budget");
1158            let work = budget::work();
1159            assert!(work < 1_000, "{open:?} nest ran {work} entries before the step budget stopped it");
1160        }
1161    }
1162
1163    /// The explain_render timeout's own input, with its brace nest regrown to 10..40: parse work
1164    /// and steps must grow linearly in the braces, never double.
1165    ///
1166    /// The seed is the minimized fuzzer find. Its backtick body is an unclosed `{` nest in front of
1167    /// a `"$([[ … <<` tail, and classifying it re-parses that body several times, so before the
1168    /// fix it took 4s. Keeping the seed's actual tail here, rather than a hand-written look-alike,
1169    /// is what makes this the regression it claims to be.
1170    #[test]
1171    fn the_explain_render_timeout_seed_scales_linearly_in_its_braces() {
1172        let seed = include_bytes!("../../fuzz/corpus/explain_render/seed-unclosed-brace-nest");
1173        let seed = String::from_utf8_lossy(seed);
1174        let body = seed.split('`').nth(1).expect("the seed carries a backtick body");
1175        let deep = body.find("$([[").expect("the seed's tail opens a `$([[`");
1176        let tail = &body[body[..deep].rfind("\n{").expect("the nest ends before the tail") + 2..];
1177        let cost = |k: usize| {
1178            let _ = parse(&format!("{}{tail}", "{\n".repeat(k)));
1179            assert!(!budget::spent(), "{k} braces spent the budget; the nest is not linear");
1180            (budget::work(), budget::steps())
1181        };
1182        let [(w10, s10), (w20, s20), (w40, s40)] = [cost(10), cost(20), cost(40)];
1183        assert!(w40 - w20 <= 2 * (w20 - w10) + 4, "entries {w10}/{w20}/{w40} for 10/20/40 braces");
1184        assert!(s40 - s20 <= 2 * (s20 - s10) + 16, "steps {s10}/{s20}/{s40} for 10/20/40 braces");
1185        assert!(!crate::is_safe_command(&seed));
1186    }
1187
1188    proptest::proptest! {
1189        #![proptest_config(proptest::prelude::ProptestConfig::with_cases(300))]
1190
1191        /// A random nest of unclosed compounds and substitutions, then random material, parses in
1192        /// work linear in its size, and never by running out of budget.
1193        ///
1194        /// The two tests above pin the shapes that were found; this is the class. An unclosed
1195        /// compound used to be re-read as a simple command, and a refused substitution interior
1196        /// was re-parsed by the grammar, and either alone doubled the work per level of nesting.
1197        /// The nest is generated as one opener repeated on purpose: a random walk, and even a random
1198        /// mix of openers, almost never stacks ten failing levels, and both stayed green with the
1199        /// fixes reverted. Counting entries rather
1200        /// than timing makes the check exact on any machine. `$((` is left out because it still
1201        /// legitimately tries two readings, which the step budget bounds (see
1202        /// `a_backtracking_nest_over_a_long_tail_is_stopped_by_what_it_reads`).
1203        #[test]
1204        fn a_random_unclosed_nest_parses_in_linear_work(
1205            opener in proptest::sample::select(OPENERS.to_vec()),
1206            depth in 0..24usize,
1207            mixed in proptest::collection::vec(proptest::sample::select(OPENERS.to_vec()), 0..8),
1208            tail in proptest::collection::vec(proptest::sample::select(vec![
1209                "}", " ]]", "fi", "done", ";;", "esac", ")", "\"", "<<", "<<E\n", "\n", ";", "a ",
1210                "$(", "[[ ", "`",
1211            ]), 0..24),
1212            closes in 0..24usize,
1213        ) {
1214            let input = format!(
1215                "{}{}{}{}", opener.repeat(depth), mixed.concat(), tail.concat(), ")".repeat(closes)
1216            );
1217            let _ = parse(&input);
1218            let work = budget::work();
1219            let tokens = (depth + mixed.len() + tail.len() + closes) as u64;
1220            proptest::prop_assert!(!budget::spent(), "spent the budget on {input:?}");
1221            proptest::prop_assert!(work <= 4 * tokens + 16, "{work} entries for {tokens} tokens: {input:?}");
1222        }
1223    }
1224
1225    const OPENERS: [&str; 14] = [
1226        "{\n", "{ ", "[[ a\n", "if a; then\n", "for x in a; do\n", "while a; do\n", "case x in a)\n", "function f {\n", "(\n", "$(",
1227        "\"$(", "<(", "$([[ ", "$({ ",
1228    ];
1229
1230    /// Every committed seed of the two command-string fuzz targets parses without spending the
1231    /// budget, and in work linear in its length.
1232    ///
1233    /// `classifier_terminates_on_the_committed_fuzz_corpus` times the `parse` seeds against a
1234    /// clock; this counts work instead, and also walks `explain_render`, whose seed is the
1235    /// unclosed-brace-nest timeout. Enumerating the directories means a seed committed later is
1236    /// covered without editing this list.
1237    #[test]
1238    fn committed_command_seeds_parse_in_linear_work() {
1239        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fuzz/corpus");
1240        let mut checked = 0;
1241        for target in ["parse", "explain_render"] {
1242            let dir = std::fs::read_dir(root.join(target)).expect("the fuzz corpus is committed");
1243            for path in dir.flatten().map(|e| e.path()) {
1244                if !path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("seed-")) {
1245                    continue;
1246                }
1247                let text = String::from_utf8_lossy(&std::fs::read(&path).expect("readable seed")).into_owned();
1248                // A backtick body stays raw text in the tree and is parsed when classified, which
1249                // is where the brace-nest seed does its work, so each body is parsed here too.
1250                for piece in std::iter::once(text.as_str()).chain(text.split('`').skip(1).step_by(2)) {
1251                    let _ = parse(piece);
1252                    let (work, len) = (budget::work(), piece.len() as u64);
1253                    assert!(!budget::spent(), "{} spent the parse budget", path.display());
1254                    assert!(work <= len + 16, "{} cost {work} entries for {len} bytes", path.display());
1255                }
1256                checked += 1;
1257            }
1258        }
1259        assert!(checked >= 16, "only {checked} seeds found; the corpus has moved");
1260    }
1261
1262    /// The step budget refuses nothing real: no registry example spends it, and long real shapes
1263    /// (a big heredoc commit message, a long flat script) stay far inside their allowance.
1264    #[test]
1265    fn the_step_budget_refuses_nothing_real() {
1266        for (_, safe, denied) in crate::registry::corpus_examples() {
1267            for example in safe.iter().chain(denied.iter()) {
1268                let _ = parse(example);
1269                assert!(!budget::spent(), "a registry example spent the step budget: {example}");
1270            }
1271        }
1272        let message = "it's a line of prose (with parens) and $vars\n".repeat(5_000);
1273        for text in [format!("git commit -m \"$(cat <<'EOF'\n{message}EOF\n)\""), "ls -la foo/bar; ".repeat(20_000)] {
1274            assert!(parse(&text).is_some(), "a long real command no longer parses");
1275            let (steps, len) = (budget::steps(), text.len() as u64);
1276            assert!(
1277                steps * 4 < budget::STEPS_PER_BYTE * len,
1278                "{len} bytes of ordinary input spent {steps} steps, within 4x of the allowance"
1279            );
1280        }
1281    }
1282
1283    fn p(input: &str) -> Script {
1284        parse(input).unwrap_or_else(|| panic!("failed to parse: {input}"))
1285    }
1286
1287    fn words(script: &Script) -> Vec<String> {
1288        match &script.0[0].pipeline.commands[0] {
1289            Cmd::Simple(s) => s.words.iter().map(|w| w.eval()).collect(),
1290            _ => panic!("expected simple command"),
1291        }
1292    }
1293
1294    fn simple(script: &Script) -> &SimpleCmd {
1295        match &script.0[0].pipeline.commands[0] {
1296            Cmd::Simple(s) => s,
1297            _ => panic!("expected simple command"),
1298        }
1299    }
1300
1301    #[test]
1302    fn simple_command() {
1303        assert_eq!(words(&p("echo hello")), ["echo", "hello"]);
1304    }
1305    #[test]
1306    fn flags() {
1307        assert_eq!(words(&p("ls -la")), ["ls", "-la"]);
1308    }
1309    #[test]
1310    fn single_quoted() {
1311        assert_eq!(words(&p("echo 'hello world'")), ["echo", "hello world"]);
1312    }
1313    #[test]
1314    fn double_quoted() {
1315        assert_eq!(words(&p("echo \"hello world\"")), ["echo", "hello world"]);
1316    }
1317    #[test]
1318    fn mixed_quotes() {
1319        assert_eq!(words(&p("jq '.key' file.json")), ["jq", ".key", "file.json"]);
1320    }
1321
1322    #[test]
1323    fn pipeline_test() {
1324        assert_eq!(p("grep foo | head -5").0[0].pipeline.commands.len(), 2);
1325    }
1326    #[test]
1327    fn sequence_and() {
1328        assert_eq!(p("ls && echo done").0[0].op, Some(ListOp::And));
1329    }
1330    #[test]
1331    fn sequence_semi() {
1332        assert_eq!(p("ls; echo done").0.len(), 2);
1333    }
1334    #[test]
1335    fn newline_separator() {
1336        assert_eq!(p("echo foo\necho bar").0.len(), 2);
1337    }
1338    #[test]
1339    fn blank_line_between_statements() {
1340        assert_eq!(p("echo foo\n\necho bar").0.len(), 2);
1341    }
1342    #[test]
1343    fn multiple_blank_lines() {
1344        assert_eq!(p("echo foo\n\n\n\necho bar").0.len(), 2);
1345    }
1346    #[test]
1347    fn blank_line_with_whitespace() {
1348        assert_eq!(p("echo foo\n   \necho bar").0.len(), 2);
1349    }
1350    #[test]
1351    fn comment_between_statements() {
1352        assert_eq!(p("echo foo\n# comment\necho bar").0.len(), 2);
1353    }
1354    #[test]
1355    fn semi_then_blank() {
1356        assert_eq!(p("echo foo;\n\necho bar").0.len(), 2);
1357    }
1358    #[test]
1359    fn and_then_blank() {
1360        assert_eq!(p("echo foo &&\n\necho bar").0.len(), 2);
1361    }
1362
1363    #[test]
1364    fn brace_group_simple() {
1365        assert!(matches!(
1366            &p("{ echo hello; }").0[0].pipeline.commands[0],
1367            Cmd::BraceGroup { body, redirs } if body.0.len() == 1 && redirs.is_empty()
1368        ));
1369    }
1370    #[test]
1371    fn brace_group_multiple_stmts() {
1372        if let Cmd::BraceGroup { body, .. } = &p("{ echo a; echo b; echo c; }").0[0].pipeline.commands[0] {
1373            assert_eq!(body.0.len(), 3);
1374        } else {
1375            panic!("expected BraceGroup");
1376        }
1377    }
1378    #[test]
1379    fn brace_group_with_redirect() {
1380        if let Cmd::BraceGroup { redirs, .. } = &p("{ echo a; echo b; } > /tmp/out.txt").0[0].pipeline.commands[0] {
1381            assert_eq!(redirs.len(), 1);
1382            assert!(matches!(redirs[0], Redir::Write { .. }));
1383        } else {
1384            panic!("expected BraceGroup");
1385        }
1386    }
1387    #[test]
1388    fn brace_group_with_append_redirect() {
1389        if let Cmd::BraceGroup { redirs, .. } = &p("{ echo a; } >> log.txt").0[0].pipeline.commands[0] {
1390            assert!(matches!(redirs[0], Redir::Write { mode: WriteMode::Append, .. }));
1391        } else {
1392            panic!("expected BraceGroup");
1393        }
1394    }
1395    #[test]
1396    fn brace_group_with_stderr_redirect() {
1397        if let Cmd::BraceGroup { redirs, .. } = &p("{ echo a; } 2>&1").0[0].pipeline.commands[0] {
1398            assert!(matches!(redirs[0], Redir::DupFd { src: 2, .. }));
1399        } else {
1400            panic!("expected BraceGroup");
1401        }
1402    }
1403    #[test]
1404    fn brace_group_newline_separated() {
1405        if let Cmd::BraceGroup { body, .. } = &p("{\n  echo a\n  echo b\n}").0[0].pipeline.commands[0] {
1406            assert_eq!(body.0.len(), 2);
1407        } else {
1408            panic!("expected BraceGroup");
1409        }
1410    }
1411    /// `time` is a reserved word, so it may prefix a COMPOUND command — and those forms did not
1412    /// parse at all, falling to "could not parse this command" on valid shell.
1413    ///
1414    /// The compound must survive as itself: if `time` were swallowed into a simple command the
1415    /// subshell would vanish, and with it whatever the inner command is. That is what makes the
1416    /// classification still follow the inner command rather than the wrapper.
1417    #[test]
1418    fn time_keyword_prefixes_a_compound() {
1419        for (src, want_subshell) in [("time (ls)", true), ("time -p (ls)", true), ("time { ls; }", false)] {
1420            let pl = &p(src).0[0].pipeline;
1421            assert_eq!(pl.commands.len(), 1, "{src}: one compound command");
1422            if want_subshell {
1423                assert!(matches!(&pl.commands[0], Cmd::Subshell { .. }), "{src}: kept the subshell");
1424            } else {
1425                assert!(matches!(&pl.commands[0], Cmd::BraceGroup { .. }), "{src}: kept the group");
1426            }
1427        }
1428        // A pipeline inside the subshell survives too.
1429        let pl = &p("time (ls | head -5)").0[0].pipeline;
1430        assert!(matches!(&pl.commands[0], Cmd::Subshell { .. }));
1431
1432        // NOT consumed for a simple command: `time ls` keeps going through the wrapper entry in
1433        // commands/wrappers/time.toml, so this fix cannot move a path that already worked.
1434        let pl = &p("time ls").0[0].pipeline;
1435        assert!(matches!(&pl.commands[0], Cmd::Simple(_)), "time ls stays a simple command");
1436
1437        // And a command genuinely NAMED time-something is not mistaken for the keyword.
1438        let pl = &p("timeout 5 ls").0[0].pipeline;
1439        assert!(matches!(&pl.commands[0], Cmd::Simple(_)), "timeout is not the time keyword");
1440
1441        // `! time (cmd)` parses — the bang is read first, then the keyword. The reverse spelling
1442        // `time ! (cmd)` does NOT, and is a known accepted false deny (see the fn's doc comment).
1443        // Pinned so that if anyone ever moves the bang handling, the change is deliberate: this
1444        // assertion flipping is the signal that the ordering was touched.
1445        let pl = &p("! time (ls)").0[0].pipeline;
1446        assert!(pl.bang, "the bang survives the time keyword");
1447        assert!(matches!(&pl.commands[0], Cmd::Subshell { .. }), "and the compound survives too");
1448    }
1449
1450    #[test]
1451    fn brace_group_in_pipeline() {
1452        let pl = &p("{ echo a; echo b; } | grep a").0[0].pipeline;
1453        assert_eq!(pl.commands.len(), 2);
1454        assert!(matches!(&pl.commands[0], Cmd::BraceGroup { .. }));
1455    }
1456    #[test]
1457    fn brace_group_followed_by_other() {
1458        let stmts = &p("{ echo a; }; echo b").0;
1459        assert_eq!(stmts.len(), 2);
1460        assert!(matches!(&stmts[0].pipeline.commands[0], Cmd::BraceGroup { .. }));
1461    }
1462    #[test]
1463    fn brace_group_nested() {
1464        if let Cmd::BraceGroup { body, .. } = &p("{ { echo inner; }; echo outer; }").0[0].pipeline.commands[0] {
1465            assert_eq!(body.0.len(), 2);
1466            assert!(matches!(&body.0[0].pipeline.commands[0], Cmd::BraceGroup { .. }));
1467        } else {
1468            panic!("expected outer BraceGroup");
1469        }
1470    }
1471    #[test]
1472    fn brace_group_with_subshell_inside() {
1473        if let Cmd::BraceGroup { body, .. } = &p("{ (echo sub); echo grp; }").0[0].pipeline.commands[0] {
1474            assert_eq!(body.0.len(), 2);
1475            assert!(matches!(&body.0[0].pipeline.commands[0], Cmd::Subshell { .. }));
1476        } else {
1477            panic!("expected BraceGroup");
1478        }
1479    }
1480    #[test]
1481    fn brace_open_requires_whitespace() {
1482        // {echo (no space) is NOT a brace group; it's a literal word
1483        // that becomes part of a simple command. Parser should not
1484        // treat it as a brace group.
1485        let cmds = &p("{echo a}").0;
1486        // Either parsed as a simple_cmd with a literal `{echo` token,
1487        // or fails. Either way, it should NOT be a BraceGroup.
1488        if !cmds.is_empty() {
1489            assert!(!matches!(&cmds[0].pipeline.commands[0], Cmd::BraceGroup { .. }));
1490        }
1491    }
1492    #[test]
1493    fn subshell_with_redirect() {
1494        if let Cmd::Subshell { redirs, .. } = &p("(echo hello) > /tmp/out.txt").0[0].pipeline.commands[0] {
1495            assert_eq!(redirs.len(), 1);
1496        } else {
1497            panic!("expected Subshell with redir");
1498        }
1499    }
1500    #[test]
1501    fn for_loop_with_redirect() {
1502        if let Cmd::For { redirs, .. } = &p("for f in a b; do echo $f; done 2>/dev/null").0[0].pipeline.commands[0] {
1503            assert_eq!(redirs.len(), 1);
1504        } else {
1505            panic!("expected For with redir");
1506        }
1507    }
1508    #[test]
1509    fn for_loop_redirect_then_pipe() {
1510        // `done 2>&1 | head` — redirect on the loop, then a pipe.
1511        let pl = &p("for f in a b; do echo $f; done 2>&1 | head -5").0[0].pipeline;
1512        assert_eq!(pl.commands.len(), 2);
1513        assert!(matches!(&pl.commands[0], Cmd::For { redirs, .. } if redirs.len() == 1));
1514    }
1515    #[test]
1516    fn while_and_if_with_redirect() {
1517        assert!(matches!(
1518            &p("while true; do echo x; done 2>/dev/null").0[0].pipeline.commands[0],
1519            Cmd::While { redirs, .. } if redirs.len() == 1
1520        ));
1521        assert!(matches!(
1522            &p("if true; then echo x; fi 2>&1").0[0].pipeline.commands[0],
1523            Cmd::If { redirs, .. } if redirs.len() == 1
1524        ));
1525    }
1526    #[test]
1527    fn background() {
1528        assert_eq!(p("ls & echo done").0[0].op, Some(ListOp::Amp));
1529    }
1530
1531    #[test]
1532    fn redirect_dev_null() {
1533        let s = p("echo hello > /dev/null");
1534        let cmd = simple(&s);
1535        assert_eq!(cmd.words.len(), 2);
1536        assert!(matches!(&cmd.redirs[0], Redir::Write { fd: 1, mode: WriteMode::Truncate, .. }));
1537    }
1538    #[test]
1539    fn redirect_stderr() {
1540        assert!(matches!(&simple(&p("echo hello 2>&1")).redirs[0], Redir::DupFd { src: 2, dst } if dst == "1"));
1541    }
1542    #[test]
1543    fn here_string() {
1544        assert!(matches!(&simple(&p("grep -c , <<< 'hello,world,test'")).redirs[0], Redir::HereStr(_)));
1545    }
1546    #[test]
1547    fn heredoc_bare() {
1548        assert!(matches!(&simple(&p("cat <<EOF")).redirs[0], Redir::HereDoc { delimiter, strip_tabs: false, .. } if delimiter == "EOF"));
1549    }
1550    #[test]
1551    fn heredoc_with_content() {
1552        let s = p("cat <<EOF\nhello world\nEOF");
1553        assert!(matches!(&simple(&s).redirs[0], Redir::HereDoc { delimiter, .. } if delimiter == "EOF"));
1554    }
1555    #[test]
1556    fn heredoc_quoted_delimiter() {
1557        assert!(matches!(&simple(&p("cat <<'EOF'")).redirs[0], Redir::HereDoc { delimiter, .. } if delimiter == "EOF"));
1558    }
1559    #[test]
1560    fn heredoc_strip_tabs() {
1561        assert!(matches!(&simple(&p("cat <<-EOF")).redirs[0], Redir::HereDoc { strip_tabs: true, .. }));
1562    }
1563    #[test]
1564    fn heredoc_pipe_on_command_line() {
1565        // Correct bash: pipe is on the command line BEFORE the body,
1566        // body terminator is on its own line.
1567        let s = p("cat <<EOF | grep hello\nhello\nEOF");
1568        assert_eq!(s.0[0].pipeline.commands.len(), 2);
1569    }
1570    #[test]
1571    fn heredoc_body_does_not_swallow_pipe() {
1572        // Regression for the `cat <<EOF | bash\n...\nEOF` bypass: the
1573        // heredoc parser must NOT consume the pipe + downstream
1574        // commands as part of the body.
1575        let s = p("cat <<EOF | bash\nrm\nEOF");
1576        assert_eq!(s.0[0].pipeline.commands.len(), 2, "pipeline must keep `bash` as a second command");
1577    }
1578    #[test]
1579    fn heredoc_followed_by_next_statement() {
1580        // After the heredoc body terminator, the script can continue
1581        // with another statement.
1582        let s = p("cat <<EOF\nhello\nEOF\nls");
1583        assert_eq!(s.0.len(), 2);
1584    }
1585
1586    #[test]
1587    fn a_heredoc_body_starts_after_the_line_not_after_the_separator() {
1588        for line in [
1589            "cat <<EOF; rm -rf ~/x\nhi\nEOF",
1590            "cat <<EOF && rm -rf ~/x\nhi\nEOF",
1591            "cat <<EOF; echo ok\nhi $(rm -rf ~/x)\nEOF",
1592            "cat <<EOF\nhi\nEOF\nrm -rf ~/x",
1593            "cat <<EOF\necho $(rm -rf ~/x)",
1594            "cat <<EOF; echo \"a\nEOF\n\"\n$(rm -rf ~/x)\nEOF",
1595            "cat <<EOF; echo $(\nrm -rf ~/x\nEOF\necho)",
1596            "echo $(cat <<EOF)\nrm -rf ~/x\nEOF",
1597            "cat <<true; echo \"[$(cat <<'ls')]\"\ntrue\nls\necho '$(rm -rf ~/x)'\ntrue",
1598            "echo \"[$(cat <<'ls')]\"\nls\necho hi",
1599        ] {
1600            assert!(!crate::is_safe_command(line), "{line:?} must not approve");
1601        }
1602        for line in [
1603            "cat <<EOF; echo ok\nhi\nEOF",
1604            "cat <<EOF | grep h\nhi\nEOF",
1605            "cat <<EOF;\nhi\nEOF\necho done",
1606            "cat <<EOF &&\nhi\nEOF\necho done",
1607            "cat <<A <<B; echo x\na\nA\nb\nB",
1608            "{ cat <<EOF; }\nhi\nEOF",
1609            "x=$(cat <<EOF\nhi\nEOF\n); echo $x",
1610            "cat <<true; echo \"[`cat <<'ls'`]\"\ntrue\nls\necho '$(rm -rf ~/x)'\ntrue",
1611        ] {
1612            assert!(crate::is_safe_command(line), "{line:?} should approve");
1613        }
1614        assert_eq!(p("cat <<EOF; ls\nhi\nEOF").0.len(), 2);
1615    }
1616
1617    #[test]
1618    fn env_prefix() {
1619        let s = p("FOO='bar baz' ls -la");
1620        let cmd = simple(&s);
1621        assert_eq!(cmd.env[0].0, "FOO");
1622        assert_eq!(cmd.env[0].1.eval(), "bar baz");
1623    }
1624    #[test]
1625    fn an_appending_assignment_is_the_old_value_followed_by_the_new() {
1626        for (src, name, value) in [
1627            ("PATH+=:/tmp/evil; ls", "PATH", "${PATH}:/tmp/evil"),
1628            ("LD_PRELOAD+=/tmp/e.so ls", "LD_PRELOAD", "${LD_PRELOAD}/tmp/e.so"),
1629            ("X+='a b'", "X", "${X}a b"),
1630            ("X+=", "X", "${X}"),
1631        ] {
1632            let s = p(src);
1633            let cmd = simple(&s);
1634            assert_eq!((cmd.env[0].0.as_str(), cmd.env[0].1.eval().as_str()), (name, value), "{src}");
1635        }
1636    }
1637    #[test]
1638    fn cmd_substitution() {
1639        assert!(matches!(&simple(&p("echo $(ls)")).words[1].0[0], WordPart::CmdSub(_)));
1640    }
1641    #[test]
1642    fn backtick_substitution() {
1643        // `pwd` declares `[command.output]`, so its value is bounded rather than worst-cased —
1644        // and a backtick must reach that the same way `$( … )` does.
1645        assert_eq!(simple(&p("ls `pwd`")).words[1].eval(), "__SAFE_CHAINS_CMDSUB_WORKTREE__");
1646        // An undeclared inner command keeps the opaque sentinel.
1647        assert_eq!(simple(&p("ls `hostname`")).words[1].eval(), "__SAFE_CHAINS_CMDSUB__");
1648    }
1649    #[test]
1650    fn nested_substitution() {
1651        if let WordPart::CmdSub(inner) = &simple(&p("echo $(echo $(ls))")).words[1].0[0] {
1652            assert!(matches!(&simple(inner).words[1].0[0], WordPart::CmdSub(_)));
1653        } else {
1654            panic!("expected CmdSub");
1655        }
1656    }
1657
1658    #[test]
1659    fn subshell_test() {
1660        assert!(matches!(&p("(echo hello)").0[0].pipeline.commands[0], Cmd::Subshell { .. }));
1661    }
1662    #[test]
1663    fn negation() {
1664        assert!(p("! echo hello").0[0].pipeline.bang);
1665    }
1666
1667    #[test]
1668    fn for_loop() {
1669        assert!(matches!(&p("for x in 1 2 3; do echo $x; done").0[0].pipeline.commands[0], Cmd::For { var, .. } if var == "x"));
1670    }
1671    #[test]
1672    fn while_loop() {
1673        assert!(matches!(&p("while test -f /tmp/foo; do sleep 1; done").0[0].pipeline.commands[0], Cmd::While { .. }));
1674    }
1675    #[test]
1676    fn if_then_fi() {
1677        if let Cmd::If { branches, else_body, .. } = &p("if test -f foo; then echo exists; fi").0[0].pipeline.commands[0] {
1678            assert_eq!(branches.len(), 1);
1679            assert!(else_body.is_none());
1680        } else {
1681            panic!("expected If");
1682        }
1683    }
1684    #[test]
1685    fn if_elif_else() {
1686        if let Cmd::If { branches, else_body, .. } =
1687            &p("if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi").0[0].pipeline.commands[0]
1688        {
1689            assert_eq!(branches.len(), 2);
1690            assert!(else_body.is_some());
1691        } else {
1692            panic!("expected If");
1693        }
1694    }
1695
1696    #[test]
1697    fn escaped_outside_quotes() {
1698        assert_eq!(words(&p("echo hello\\ world")), ["echo", "hello world"]);
1699    }
1700    #[test]
1701    fn a_line_continuation_joins_a_word() {
1702        assert_eq!(words(&p("imp\\\nort a")), ["import", "a"]);
1703        assert_eq!(words(&p("echo \"incl\\\nude\"")), ["echo", "include"]);
1704        assert_eq!(words(&p("echo 'incl\\\nude'")), ["echo", "incl\\\nude"]);
1705    }
1706    #[test]
1707    fn a_line_continuation_between_words_is_whitespace() {
1708        assert_eq!(words(&p("echo a \\\n b")), ["echo", "a", "b"]);
1709        assert_eq!(words(&p("echo a\\\n b")), ["echo", "a", "b"]);
1710        assert_eq!(words(&p("echo \\\n\\\nb")), ["echo", "b"]);
1711    }
1712    #[test]
1713    fn double_quoted_escape() {
1714        assert_eq!(words(&p("echo \"hello\\\"world\"")), ["echo", "hello\"world"]);
1715    }
1716    #[test]
1717    fn assign_subst() {
1718        assert_eq!(simple(&p("out=$(ls)")).env[0].0, "out");
1719    }
1720
1721    #[test]
1722    fn unmatched_single_quote_fails() {
1723        assert!(parse("echo 'hello").is_none());
1724    }
1725    #[test]
1726    fn unmatched_double_quote_fails() {
1727        assert!(parse("echo \"hello").is_none());
1728    }
1729    #[test]
1730    fn unclosed_subshell_fails() {
1731        assert!(parse("(echo hello").is_none());
1732    }
1733    #[test]
1734    fn unclosed_cmd_sub_fails() {
1735        assert!(parse("echo $(ls").is_none());
1736    }
1737    #[test]
1738    fn for_missing_do_fails() {
1739        assert!(parse("for x in 1 2 3; echo $x; done").is_none());
1740    }
1741    #[test]
1742    fn if_missing_fi_fails() {
1743        assert!(parse("if true; then echo hello").is_none());
1744    }
1745
1746    #[test]
1747    fn subshell_for() {
1748        if let Cmd::Subshell { body, .. } = &p("(for x in 1 2; do echo $x; done)").0[0].pipeline.commands[0] {
1749            assert!(matches!(&body.0[0].pipeline.commands[0], Cmd::For { .. }));
1750        } else {
1751            panic!("expected Subshell");
1752        }
1753    }
1754    #[test]
1755    fn proc_sub_input() {
1756        let s = p("diff <(sort a.txt) <(sort b.txt)");
1757        let cmd = simple(&s);
1758        assert_eq!(cmd.words.len(), 3);
1759        assert!(matches!(&cmd.words[1].0[0], WordPart::ProcSub(_)));
1760        assert!(matches!(&cmd.words[2].0[0], WordPart::ProcSub(_)));
1761    }
1762    #[test]
1763    fn proc_sub_output() {
1764        let s = p("tee >(grep error > /dev/null)");
1765        let cmd = simple(&s);
1766        assert_eq!(cmd.words.len(), 2);
1767        assert!(matches!(&cmd.words[1].0[0], WordPart::ProcSub(_)));
1768    }
1769
1770    // === Function definitions ===
1771    fn func_def(s: &Script) -> (&str, &Script) {
1772        match &s.0[0].pipeline.commands[0] {
1773            Cmd::FunctionDef { name, body } => (name.as_str(), body),
1774            other => panic!("expected FunctionDef, got {other:?}"),
1775        }
1776    }
1777    #[test]
1778    fn function_def_posix_form() {
1779        let s = p("probe(){ echo hi; }");
1780        let (name, body) = func_def(&s);
1781        assert_eq!(name, "probe");
1782        assert_eq!(words(body), ["echo", "hi"]);
1783    }
1784    #[test]
1785    fn function_def_spaced_and_keyword_forms() {
1786        assert_eq!(func_def(&p("foo () { echo hi; }")).0, "foo");
1787        assert_eq!(func_def(&p("function foo { echo hi; }")).0, "foo");
1788        assert_eq!(func_def(&p("function foo () { echo hi; }")).0, "foo");
1789    }
1790    #[test]
1791    fn function_def_subshell_body() {
1792        let s = p("foo() ( echo sub )");
1793        assert_eq!(func_def(&s).0, "foo");
1794    }
1795    #[test]
1796    fn function_def_body_on_next_line() {
1797        assert_eq!(func_def(&p("foo()\n{\n  echo hi\n}")).0, "foo");
1798    }
1799    #[test]
1800    fn function_def_name_with_dashes_and_dots() {
1801        assert_eq!(func_def(&p("my-func.v2(){ echo hi; }")).0, "my-func.v2");
1802    }
1803    #[test]
1804    fn plain_command_is_not_a_function_def() {
1805        // A bare `name` with no `()` must NOT be read as a definition.
1806        assert!(matches!(&p("ls -la").0[0].pipeline.commands[0], Cmd::Simple(_)));
1807        assert!(matches!(&p("echo foo bar").0[0].pipeline.commands[0], Cmd::Simple(_)));
1808    }
1809    #[test]
1810    fn function_def_roundtrips() {
1811        let rendered = p("greet(){ echo hi; }").to_string();
1812        assert!(parse(&rendered).is_some(), "did not reparse: {rendered}");
1813        assert_eq!(func_def(&p(&rendered)).0, "greet");
1814    }
1815    #[test]
1816    fn comment_only() {
1817        let s = p("# just a comment");
1818        assert!(s.0.is_empty());
1819    }
1820    #[test]
1821    fn comment_before_command() {
1822        let s = p("# comment\necho hello");
1823        assert_eq!(words(&s), ["echo", "hello"]);
1824    }
1825    #[test]
1826    fn inline_comment() {
1827        let s = p("echo hello # this is a comment");
1828        assert_eq!(words(&s), ["echo", "hello"]);
1829    }
1830    #[test]
1831    fn comment_between_commands() {
1832        let s = p("echo hello\n# middle comment\necho world");
1833        assert_eq!(s.0.len(), 2);
1834    }
1835    #[test]
1836    fn comment_after_semicolon() {
1837        let s = p("echo hello; # comment\necho world");
1838        assert_eq!(s.0.len(), 2);
1839    }
1840    #[test]
1841    fn comment_in_for_loop() {
1842        assert!(parse("for x in 1 2; do\n# loop body\necho $x\ndone").is_some());
1843    }
1844    #[test]
1845    fn quoted_redirect_in_echo() {
1846        let s = p("echo 'greater > than' test");
1847        let cmd = simple(&s);
1848        assert_eq!(cmd.words.len(), 3);
1849        assert_eq!(cmd.redirs.len(), 0);
1850    }
1851
1852    #[test]
1853    fn parses_all_safe_commands() {
1854        let cmds = [
1855            "grep foo file.txt",
1856            "cat /etc/hosts",
1857            "jq '.key' file.json",
1858            "base64 -d",
1859            "ls -la",
1860            "wc -l file.txt",
1861            "ps aux",
1862            "echo hello",
1863            "cat file.txt",
1864            "echo $(ls)",
1865            "ls `pwd`",
1866            "echo $(echo $(ls))",
1867            "echo \"$(ls)\"",
1868            "out=$(ls)",
1869            "out=$(git status)",
1870            "a=$(ls) b=$(pwd)",
1871            "(echo hello)",
1872            "(ls)",
1873            "(ls && echo done)",
1874            "(echo hello; echo world)",
1875            "(ls | grep foo)",
1876            "(echo hello) | grep hello",
1877            "(ls) && echo done",
1878            "((echo hello))",
1879            "(for x in 1 2; do echo $x; done)",
1880            "echo 'greater > than' test",
1881            "echo '$(safe)' arg",
1882            "FOO='bar baz' ls -la",
1883            "FOO=\"bar baz\" ls -la",
1884            "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
1885            "grep foo file.txt | head -5",
1886            "cat file | sort | uniq",
1887            "ls && echo done",
1888            "ls; echo done",
1889            "ls & echo done",
1890            "grep -c , <<< 'hello,world,test'",
1891            "cat <<EOF\nhello world\nEOF",
1892            "cat <<'MARKER'\nsome text\nMARKER",
1893            "cat <<-EOF\n\thello\nEOF",
1894            "echo foo\necho bar",
1895            "ls\ncat file.txt",
1896            "git log --oneline -20 | head -5",
1897            "echo hello > /dev/null",
1898            "echo hello 2> /dev/null",
1899            "echo hello >> /dev/null",
1900            "git log > /dev/null 2>&1",
1901            "ls 2>&1",
1902            "cargo clippy 2>&1",
1903            "git log < /dev/null",
1904            "for x in 1 2 3; do echo $x; done",
1905            "for f in *.txt; do cat $f | grep pattern; done",
1906            "for x in 1 2 3; do; done",
1907            "for x in 1 2; do echo $x; done; for y in a b; do echo $y; done",
1908            "for x in 1 2; do for y in a b; do echo $x $y; done; done",
1909            "for x in 1 2; do echo $x; done && echo finished",
1910            "for x in $(seq 1 5); do echo $x; done",
1911            "while test -f /tmp/foo; do sleep 1; done",
1912            "while ! test -f /tmp/done; do sleep 1; done",
1913            "until test -f /tmp/ready; do sleep 1; done",
1914            "if test -f foo; then echo exists; fi",
1915            "if test -f foo; then echo yes; else echo no; fi",
1916            "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
1917            "for x in 1 2; do if test $x = 1; then echo one; fi; done",
1918            "if true; then for x in 1 2; do echo $x; done; fi",
1919            "diff <(sort a.txt) <(sort b.txt)",
1920            "comm -23 file.txt <(sort other.txt)",
1921            "cat <(echo hello)",
1922            "# comment only",
1923            "# comment\necho hello",
1924            "echo hello # inline comment",
1925            "echo one\n# between\necho two",
1926            "! echo hello",
1927            "! test -f foo",
1928            "echo for; echo done; echo if; echo fi",
1929        ];
1930        let mut failures = Vec::new();
1931        for cmd in &cmds {
1932            if parse(cmd).is_none() {
1933                failures.push(*cmd);
1934            }
1935        }
1936        assert!(failures.is_empty(), "failed on {} commands:\n{}", failures.len(), failures.join("\n"));
1937    }
1938
1939    // === Balanced-scan divergence guards ===
1940    // `cmd_sub`/`proc_sub` find their closing `)` with `find_sub_close`, then parse the bounded
1941    // interior. The `roundtrip` proptest exercises this, but its `arb_shell_word` is paren-free, so
1942    // these lock the case it can't reach: a `)` inside a quote / escape / backtick / nested sub must
1943    // NOT be mistaken for the substitution's own close.
1944    fn inner_sub(s: &Script) -> &Script {
1945        match &simple(s).words[1].0[0] {
1946            WordPart::CmdSub(inner) | WordPart::ProcSub(inner) => inner,
1947            other => panic!("expected a substitution, got {other:?}"),
1948        }
1949    }
1950
1951    #[test]
1952    fn cmd_sub_squote_paren_is_not_close() {
1953        assert_eq!(words(inner_sub(&p("echo $(echo ')')"))), ["echo", ")"]);
1954    }
1955    #[test]
1956    fn cmd_sub_dquote_paren_is_not_close() {
1957        assert_eq!(words(inner_sub(&p("echo $(echo \")\")"))), ["echo", ")"]);
1958    }
1959    #[test]
1960    fn cmd_sub_escaped_paren_is_not_close() {
1961        assert_eq!(words(inner_sub(&p("echo $(echo \\))"))), ["echo", ")"]);
1962    }
1963    #[test]
1964    fn cmd_sub_backtick_paren_is_not_close() {
1965        // the ) lives inside a backtick span in the sub body; the real close is the final ).
1966        let s = p("echo $(x `)` y)");
1967        let inner = simple(inner_sub(&s));
1968        assert_eq!(inner.words.len(), 3);
1969        assert!(matches!(&inner.words[1].0[0], WordPart::Backtick(_)));
1970    }
1971    #[test]
1972    fn cmd_sub_escaped_backtick_does_not_end_span() {
1973        // The `\` escapes the next backtick, so the span — and the ) inside it — belong to the sub
1974        // body; the real close is the final ). Until find_sub_close honored backtick escapes it
1975        // mis-placed the span boundary and rejected this (a fail-closed divergence from the grammar).
1976        let s = p("echo $(`\\`)`)");
1977        assert!(matches!(&simple(&s).words[1].0[0], WordPart::CmdSub(_)));
1978    }
1979    #[test]
1980    fn proc_sub_squote_paren_is_not_close() {
1981        assert_eq!(words(inner_sub(&p("cat <(grep ')' f)"))), ["grep", ")", "f"]);
1982    }
1983    #[test]
1984    fn proc_sub_out_squote_paren_is_not_close() {
1985        assert_eq!(words(inner_sub(&p("tee >(grep ')' f)"))), ["grep", ")", "f"]);
1986    }
1987    #[test]
1988    fn cmd_sub_nested_picks_outer_close() {
1989        let s = p("echo $(a $(b) c)");
1990        let inner = simple(inner_sub(&s));
1991        assert_eq!(inner.words.len(), 3);
1992        assert!(matches!(&inner.words[1].0[0], WordPart::CmdSub(_)));
1993    }
1994    #[test]
1995    fn cmd_sub_literal_after_close_stays_in_outer_word() {
1996        let s = p("echo $(ls)tail");
1997        let w = &simple(&s).words[1];
1998        assert_eq!(w.0.len(), 2);
1999        assert!(matches!(&w.0[0], WordPart::CmdSub(_)));
2000        assert!(matches!(&w.0[1], WordPart::Lit(s) if s == "tail"));
2001    }
2002    #[test]
2003    fn cmd_sub_heredoc_body_paren_does_not_close() {
2004        // The ) sits in the heredoc body (drained out-of-band), so it must not close the sub — the
2005        // real close is the final ). find_sub_close can't see heredocs, so sub_body falls back to the
2006        // full grammar here. This parsed before the balanced-scan rewrite and must keep parsing.
2007        let s = p("x=$(cat <<EOF\na)b\nEOF\n)");
2008        assert!(matches!(&simple(&s).env[0].1.0[0], WordPart::CmdSub(_)));
2009    }
2010    #[test]
2011    fn cmd_sub_with_only_a_quoted_paren_is_unclosed() {
2012        // the sole ) is single-quoted, so the sub never closes → whole parse fails (fail closed).
2013        assert!(parse("echo $(echo ')").is_none());
2014    }
2015    #[test]
2016    fn proc_sub_with_only_a_quoted_paren_is_unclosed() {
2017        assert!(parse("cat <(grep ')").is_none());
2018    }
2019}