Skip to main content

safe_chains/cst/
parse.rs

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