Skip to main content

safe_chains/cst/
parse.rs

1use super::*;
2use winnow::ModalResult;
3use winnow::combinator::{alt, delimited, not, opt, preceded, repeat, separated, terminated};
4use winnow::error::{ContextError, ErrMode};
5use winnow::prelude::*;
6use winnow::token::{any, take_while};
7
8pub fn parse(input: &str) -> Option<Script> {
9    script.parse(input).ok()
10}
11
12fn backtrack<T>() -> ModalResult<T> {
13    Err(ErrMode::Backtrack(ContextError::new()))
14}
15
16fn ws(input: &mut &str) -> ModalResult<()> {
17    take_while(0.., [' ', '\t']).void().parse_next(input)
18}
19
20fn sep(input: &mut &str) -> ModalResult<()> {
21    take_while(0.., [' ', '\t', ';', '\n'])
22        .void()
23        .parse_next(input)
24}
25
26fn eat_keyword(input: &mut &str, kw: &str) -> ModalResult<()> {
27    if !input.starts_with(kw) {
28        return backtrack();
29    }
30    if input
31        .as_bytes()
32        .get(kw.len())
33        .is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_')
34    {
35        return backtrack();
36    }
37    *input = &input[kw.len()..];
38    Ok(())
39}
40
41const SCRIPT_STOPS: &[&str] = &["do", "done", "elif", "else", "fi", "then"];
42
43fn at_script_stop(input: &str) -> bool {
44    input.starts_with(')')
45        || SCRIPT_STOPS.iter().any(|kw| {
46            input.starts_with(kw)
47                && !input
48                    .as_bytes()
49                    .get(kw.len())
50                    .is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_')
51        })
52}
53
54fn is_word_boundary(c: char) -> bool {
55    matches!(c, ' ' | '\t' | '\n' | ';' | '|' | '&' | ')' | '>' | '<')
56}
57
58fn is_word_literal(c: char) -> bool {
59    !is_word_boundary(c) && !matches!(c, '\'' | '"' | '`' | '\\' | '(' | '$')
60}
61
62fn is_dq_literal(c: char) -> bool {
63    !matches!(c, '"' | '\\' | '`' | '$')
64}
65
66// === Script ===
67
68fn script(input: &mut &str) -> ModalResult<Script> {
69    let mut stmts = Vec::new();
70    while let Some(pl) = opt(pipeline).parse_next(input)? {
71        ws.parse_next(input)?;
72        let op = opt(list_op).parse_next(input)?;
73        stmts.push(Stmt { pipeline: pl, op });
74        if op.is_none() {
75            break;
76        }
77    }
78    Ok(Script(stmts))
79}
80
81fn list_op(input: &mut &str) -> ModalResult<ListOp> {
82    ws.parse_next(input)?;
83    alt((
84        "&&".value(ListOp::And),
85        "||".value(ListOp::Or),
86        '\n'.value(ListOp::Semi),
87        ';'.value(ListOp::Semi),
88        ('&', not('>')).value(ListOp::Amp),
89    ))
90    .parse_next(input)
91}
92
93fn pipe_sep(input: &mut &str) -> ModalResult<()> {
94    (ws, '|', not('|'), ws).void().parse_next(input)
95}
96
97// === Pipeline ===
98
99fn pipeline(input: &mut &str) -> ModalResult<Pipeline> {
100    ws.parse_next(input)?;
101    if at_script_stop(input) {
102        return backtrack();
103    }
104    let bang = opt(terminated('!', ws)).parse_next(input)?.is_some();
105    let commands: Vec<Cmd> = separated(1.., command, pipe_sep).parse_next(input)?;
106    Ok(Pipeline { bang, commands })
107}
108
109// === Command ===
110
111fn command(input: &mut &str) -> ModalResult<Cmd> {
112    ws.parse_next(input)?;
113    if at_script_stop(input) {
114        return backtrack();
115    }
116    alt((
117        subshell,
118        for_cmd,
119        while_cmd,
120        until_cmd,
121        if_cmd,
122        simple_cmd.map(Cmd::Simple),
123    ))
124    .parse_next(input)
125}
126
127fn subshell(input: &mut &str) -> ModalResult<Cmd> {
128    delimited(('(', ws), script, (ws, ')'))
129        .map(Cmd::Subshell)
130        .parse_next(input)
131}
132
133// === Simple Command ===
134
135fn simple_cmd(input: &mut &str) -> ModalResult<SimpleCmd> {
136    let env: Vec<(String, Word)> =
137        repeat(0.., terminated(assignment, ws)).parse_next(input)?;
138    let mut words = Vec::new();
139    let mut redirs = Vec::new();
140
141    loop {
142        ws.parse_next(input)?;
143        if at_cmd_end(input) {
144            break;
145        }
146        if let Some(r) = opt(redirect).parse_next(input)? {
147            redirs.push(r);
148        } else if let Some(w) = opt(word).parse_next(input)? {
149            words.push(w);
150        } else {
151            break;
152        }
153    }
154
155    if env.is_empty() && words.is_empty() && redirs.is_empty() {
156        return backtrack();
157    }
158    Ok(SimpleCmd { env, words, redirs })
159}
160
161fn at_cmd_end(input: &str) -> bool {
162    input.is_empty()
163        || matches!(
164            input.as_bytes().first(),
165            Some(b'\n' | b';' | b'|' | b'&' | b')')
166        )
167}
168
169fn assignment(input: &mut &str) -> ModalResult<(String, Word)> {
170    let n: &str = take_while(1.., |c: char| c.is_ascii_alphanumeric() || c == '_')
171        .parse_next(input)?;
172    '='.parse_next(input)?;
173    let value = opt(word)
174        .parse_next(input)?
175        .unwrap_or(Word(vec![WordPart::Lit(String::new())]));
176    Ok((n.to_string(), value))
177}
178
179// === Redirect ===
180
181fn redirect(input: &mut &str) -> ModalResult<Redir> {
182    let fd = opt(fd_prefix).parse_next(input)?;
183    alt((
184        preceded("<<<", (ws, word)).map(|(_, target)| Redir::HereStr(target)),
185        heredoc,
186        preceded(">>", (ws, word)).map(move |(_, target)| Redir::Write {
187            fd: fd.unwrap_or(1),
188            target,
189            append: true,
190        }),
191        preceded(">&", fd_target).map(move |dst| Redir::DupFd {
192            src: fd.unwrap_or(1),
193            dst,
194        }),
195        preceded('>', (ws, word)).map(move |(_, target)| Redir::Write {
196            fd: fd.unwrap_or(1),
197            target,
198            append: false,
199        }),
200        preceded('<', (ws, word)).map(move |(_, target)| Redir::Read {
201            fd: fd.unwrap_or(0),
202            target,
203        }),
204    ))
205    .parse_next(input)
206}
207
208fn heredoc(input: &mut &str) -> ModalResult<Redir> {
209    "<<".parse_next(input)?;
210    let strip_tabs = opt('-').parse_next(input)?.is_some();
211    ws.parse_next(input)?;
212    let delimiter = heredoc_delimiter.parse_next(input)?;
213    let needle = format!("\n{delimiter}");
214    if let Some(pos) = input.find(&needle) {
215        let after = pos + needle.len();
216        *input = input[after..].trim_start_matches([' ', '\t', '\n']);
217    }
218    Ok(Redir::HereDoc { delimiter, strip_tabs })
219}
220
221fn heredoc_delimiter(input: &mut &str) -> ModalResult<String> {
222    alt((
223        delimited('\'', take_while(0.., |c| c != '\''), '\'').map(|s: &str| s.to_string()),
224        delimited('"', take_while(0.., |c| c != '"'), '"').map(|s: &str| s.to_string()),
225        take_while(1.., |c: char| c.is_ascii_alphanumeric() || c == '_').map(|s: &str| s.to_string()),
226    ))
227    .parse_next(input)
228}
229
230fn fd_prefix(input: &mut &str) -> ModalResult<u32> {
231    let b = input.as_bytes();
232    if b.len() >= 2 && b[0].is_ascii_digit() && matches!(b[1], b'>' | b'<') {
233        let d = (b[0] - b'0') as u32;
234        *input = &input[1..];
235        Ok(d)
236    } else {
237        backtrack()
238    }
239}
240
241fn fd_target(input: &mut &str) -> ModalResult<String> {
242    alt((
243        '-'.value("-".to_string()),
244        take_while(1.., |c: char| c.is_ascii_digit()).map(|s: &str| s.to_string()),
245    ))
246    .parse_next(input)
247}
248
249// === Word ===
250
251fn word(input: &mut &str) -> ModalResult<Word> {
252    repeat(1.., word_part)
253        .map(Word)
254        .parse_next(input)
255}
256
257fn word_part(input: &mut &str) -> ModalResult<WordPart> {
258    if input.is_empty() || is_word_boundary(input.as_bytes()[0] as char) {
259        return backtrack();
260    }
261    alt((single_quoted, double_quoted, cmd_sub, backtick_part, escaped, dollar_lit(is_word_literal), lit(is_word_literal)))
262        .parse_next(input)
263}
264
265fn single_quoted(input: &mut &str) -> ModalResult<WordPart> {
266    delimited('\'', take_while(0.., |c| c != '\''), '\'')
267        .map(|s: &str| WordPart::SQuote(s.to_string()))
268        .parse_next(input)
269}
270
271fn double_quoted(input: &mut &str) -> ModalResult<WordPart> {
272    delimited('"', repeat(0.., dq_part).map(Word), '"')
273        .map(WordPart::DQuote)
274        .parse_next(input)
275}
276
277fn cmd_sub(input: &mut &str) -> ModalResult<WordPart> {
278    delimited(("$(", ws), script, (ws, ')'))
279        .map(WordPart::CmdSub)
280        .parse_next(input)
281}
282
283fn backtick_part(input: &mut &str) -> ModalResult<WordPart> {
284    delimited('`', backtick_inner, '`')
285        .map(WordPart::Backtick)
286        .parse_next(input)
287}
288
289fn escaped(input: &mut &str) -> ModalResult<WordPart> {
290    preceded('\\', any).map(WordPart::Escape).parse_next(input)
291}
292
293fn lit(pred: fn(char) -> bool) -> impl FnMut(&mut &str) -> ModalResult<WordPart> {
294    move |input: &mut &str| {
295        take_while(1.., pred)
296            .map(|s: &str| WordPart::Lit(s.to_string()))
297            .parse_next(input)
298    }
299}
300
301fn dollar_lit(pred: fn(char) -> bool) -> impl FnMut(&mut &str) -> ModalResult<WordPart> {
302    move |input: &mut &str| {
303        ('$', not('(')).void().parse_next(input)?;
304        let rest: &str = take_while(0.., pred).parse_next(input)?;
305        Ok(WordPart::Lit(format!("${rest}")))
306    }
307}
308
309// === Double-quoted parts ===
310
311fn dq_part(input: &mut &str) -> ModalResult<WordPart> {
312    if input.is_empty() || input.starts_with('"') {
313        return backtrack();
314    }
315    alt((dq_escape, cmd_sub, backtick_part, dollar_lit(is_dq_literal), lit(is_dq_literal)))
316        .parse_next(input)
317}
318
319fn dq_escape(input: &mut &str) -> ModalResult<WordPart> {
320    preceded('\\', any)
321        .map(|c: char| match c {
322            '"' | '\\' | '$' | '`' => WordPart::Escape(c),
323            _ => WordPart::Lit(format!("\\{c}")),
324        })
325        .parse_next(input)
326}
327
328// === Backtick inner content ===
329
330fn backtick_inner(input: &mut &str) -> ModalResult<String> {
331    repeat(0.., alt((bt_escape, bt_literal)))
332        .fold(String::new, |mut acc, chunk: &str| {
333            acc.push_str(chunk);
334            acc
335        })
336        .parse_next(input)
337}
338
339fn bt_escape<'a>(input: &mut &'a str) -> ModalResult<&'a str> {
340    ('\\', any).take().parse_next(input)
341}
342
343fn bt_literal<'a>(input: &mut &'a str) -> ModalResult<&'a str> {
344    take_while(1.., |c: char| c != '`' && c != '\\').parse_next(input)
345}
346
347// === Compound Commands ===
348
349fn for_cmd(input: &mut &str) -> ModalResult<Cmd> {
350    eat_keyword(input, "for")?;
351    ws.parse_next(input)?;
352    let var = name.parse_next(input)?;
353    ws.parse_next(input)?;
354
355    let items = if eat_keyword(input, "in").is_ok() {
356        ws.parse_next(input)?;
357        repeat(0.., terminated(word, ws)).parse_next(input)?
358    } else {
359        vec![]
360    };
361
362    let body = do_done_body.parse_next(input)?;
363    Ok(Cmd::For { var, items, body })
364}
365
366fn while_cmd(input: &mut &str) -> ModalResult<Cmd> {
367    eat_keyword(input, "while")?;
368    ws.parse_next(input)?;
369    let cond = script.parse_next(input)?;
370    let body = do_done_body.parse_next(input)?;
371    Ok(Cmd::While { cond, body })
372}
373
374fn until_cmd(input: &mut &str) -> ModalResult<Cmd> {
375    eat_keyword(input, "until")?;
376    ws.parse_next(input)?;
377    let cond = script.parse_next(input)?;
378    let body = do_done_body.parse_next(input)?;
379    Ok(Cmd::Until { cond, body })
380}
381
382fn do_done_body(input: &mut &str) -> ModalResult<Script> {
383    sep.parse_next(input)?;
384    eat_keyword(input, "do")?;
385    sep.parse_next(input)?;
386    let body = script.parse_next(input)?;
387    sep.parse_next(input)?;
388    eat_keyword(input, "done")?;
389    Ok(body)
390}
391
392fn if_cmd(input: &mut &str) -> ModalResult<Cmd> {
393    eat_keyword(input, "if")?;
394    ws.parse_next(input)?;
395    let mut branches = vec![cond_then_body.parse_next(input)?];
396    let mut else_body = None;
397
398    loop {
399        sep.parse_next(input)?;
400        if eat_keyword(input, "elif").is_ok() {
401            ws.parse_next(input)?;
402            branches.push(cond_then_body.parse_next(input)?);
403        } else if eat_keyword(input, "else").is_ok() {
404            sep.parse_next(input)?;
405            else_body = Some(script.parse_next(input)?);
406            break;
407        } else {
408            break;
409        }
410    }
411
412    sep.parse_next(input)?;
413    eat_keyword(input, "fi")?;
414    Ok(Cmd::If { branches, else_body })
415}
416
417fn cond_then_body(input: &mut &str) -> ModalResult<Branch> {
418    let cond = script.parse_next(input)?;
419    sep.parse_next(input)?;
420    eat_keyword(input, "then")?;
421    sep.parse_next(input)?;
422    let body = script.parse_next(input)?;
423    Ok(Branch { cond, body })
424}
425
426fn name(input: &mut &str) -> ModalResult<String> {
427    take_while(1.., |c: char| c.is_ascii_alphanumeric() || c == '_')
428        .map(|s: &str| s.to_string())
429        .parse_next(input)
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    fn p(input: &str) -> Script {
437        parse(input).unwrap_or_else(|| panic!("failed to parse: {input}"))
438    }
439
440    fn words(script: &Script) -> Vec<String> {
441        match &script.0[0].pipeline.commands[0] {
442            Cmd::Simple(s) => s.words.iter().map(|w| w.eval()).collect(),
443            _ => panic!("expected simple command"),
444        }
445    }
446
447    fn simple(script: &Script) -> &SimpleCmd {
448        match &script.0[0].pipeline.commands[0] {
449            Cmd::Simple(s) => s,
450            _ => panic!("expected simple command"),
451        }
452    }
453
454    #[test]
455    fn simple_command() { assert_eq!(words(&p("echo hello")), ["echo", "hello"]); }
456    #[test]
457    fn flags() { assert_eq!(words(&p("ls -la")), ["ls", "-la"]); }
458    #[test]
459    fn single_quoted() { assert_eq!(words(&p("echo 'hello world'")), ["echo", "hello world"]); }
460    #[test]
461    fn double_quoted() { assert_eq!(words(&p("echo \"hello world\"")), ["echo", "hello world"]); }
462    #[test]
463    fn mixed_quotes() { assert_eq!(words(&p("jq '.key' file.json")), ["jq", ".key", "file.json"]); }
464
465    #[test]
466    fn pipeline_test() { assert_eq!(p("grep foo | head -5").0[0].pipeline.commands.len(), 2); }
467    #[test]
468    fn sequence_and() { assert_eq!(p("ls && echo done").0[0].op, Some(ListOp::And)); }
469    #[test]
470    fn sequence_semi() { assert_eq!(p("ls; echo done").0.len(), 2); }
471    #[test]
472    fn newline_separator() { assert_eq!(p("echo foo\necho bar").0.len(), 2); }
473    #[test]
474    fn background() { assert_eq!(p("ls & echo done").0[0].op, Some(ListOp::Amp)); }
475
476    #[test]
477    fn redirect_dev_null() {
478        let s = p("echo hello > /dev/null");
479        let cmd = simple(&s);
480        assert_eq!(cmd.words.len(), 2);
481        assert!(matches!(&cmd.redirs[0], Redir::Write { fd: 1, append: false, .. }));
482    }
483    #[test]
484    fn redirect_stderr() {
485        assert!(matches!(&simple(&p("echo hello 2>&1")).redirs[0], Redir::DupFd { src: 2, dst } if dst == "1"));
486    }
487    #[test]
488    fn here_string() {
489        assert!(matches!(&simple(&p("grep -c , <<< 'hello,world,test'")).redirs[0], Redir::HereStr(_)));
490    }
491    #[test]
492    fn heredoc_bare() {
493        assert!(matches!(&simple(&p("cat <<EOF")).redirs[0], Redir::HereDoc { delimiter, strip_tabs: false } if delimiter == "EOF"));
494    }
495    #[test]
496    fn heredoc_with_content() {
497        let s = p("cat <<EOF\nhello world\nEOF");
498        assert!(matches!(&simple(&s).redirs[0], Redir::HereDoc { delimiter, .. } if delimiter == "EOF"));
499    }
500    #[test]
501    fn heredoc_quoted_delimiter() {
502        assert!(matches!(&simple(&p("cat <<'EOF'")).redirs[0], Redir::HereDoc { delimiter, .. } if delimiter == "EOF"));
503    }
504    #[test]
505    fn heredoc_strip_tabs() {
506        assert!(matches!(&simple(&p("cat <<-EOF")).redirs[0], Redir::HereDoc { strip_tabs: true, .. }));
507    }
508    #[test]
509    fn heredoc_then_pipe() {
510        let s = p("cat <<EOF\nhello\nEOF | grep hello");
511        assert_eq!(s.0[0].pipeline.commands.len(), 2);
512    }
513    #[test]
514    fn heredoc_then_pipe_next_line() {
515        let s = p("cat <<EOF\nhello\nEOF\n| grep hello");
516        assert_eq!(s.0[0].pipeline.commands.len(), 2);
517    }
518
519    #[test]
520    fn env_prefix() {
521        let s = p("FOO='bar baz' ls -la");
522        let cmd = simple(&s);
523        assert_eq!(cmd.env[0].0, "FOO");
524        assert_eq!(cmd.env[0].1.eval(), "bar baz");
525    }
526    #[test]
527    fn cmd_substitution() { assert!(matches!(&simple(&p("echo $(ls)")).words[1].0[0], WordPart::CmdSub(_))); }
528    #[test]
529    fn backtick_substitution() { assert_eq!(simple(&p("ls `pwd`")).words[1].eval(), "__SAFE_CHAINS_SUB__"); }
530    #[test]
531    fn nested_substitution() {
532        if let WordPart::CmdSub(inner) = &simple(&p("echo $(echo $(ls))")).words[1].0[0] {
533            assert!(matches!(&simple(inner).words[1].0[0], WordPart::CmdSub(_)));
534        } else { panic!("expected CmdSub"); }
535    }
536
537    #[test]
538    fn subshell_test() { assert!(matches!(&p("(echo hello)").0[0].pipeline.commands[0], Cmd::Subshell(_))); }
539    #[test]
540    fn negation() { assert!(p("! echo hello").0[0].pipeline.bang); }
541
542    #[test]
543    fn for_loop() { assert!(matches!(&p("for x in 1 2 3; do echo $x; done").0[0].pipeline.commands[0], Cmd::For { var, .. } if var == "x")); }
544    #[test]
545    fn while_loop() { assert!(matches!(&p("while test -f /tmp/foo; do sleep 1; done").0[0].pipeline.commands[0], Cmd::While { .. })); }
546    #[test]
547    fn if_then_fi() {
548        if let Cmd::If { branches, else_body } = &p("if test -f foo; then echo exists; fi").0[0].pipeline.commands[0] {
549            assert_eq!(branches.len(), 1);
550            assert!(else_body.is_none());
551        } else { panic!("expected If"); }
552    }
553    #[test]
554    fn if_elif_else() {
555        if let Cmd::If { branches, else_body } = &p("if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi").0[0].pipeline.commands[0] {
556            assert_eq!(branches.len(), 2);
557            assert!(else_body.is_some());
558        } else { panic!("expected If"); }
559    }
560
561    #[test]
562    fn escaped_outside_quotes() { assert_eq!(words(&p("echo hello\\ world")), ["echo", "hello world"]); }
563    #[test]
564    fn double_quoted_escape() { assert_eq!(words(&p("echo \"hello\\\"world\"")), ["echo", "hello\"world"]); }
565    #[test]
566    fn assign_subst() { assert_eq!(simple(&p("out=$(ls)")).env[0].0, "out"); }
567
568    #[test]
569    fn unmatched_single_quote_fails() { assert!(parse("echo 'hello").is_none()); }
570    #[test]
571    fn unmatched_double_quote_fails() { assert!(parse("echo \"hello").is_none()); }
572    #[test]
573    fn unclosed_subshell_fails() { assert!(parse("(echo hello").is_none()); }
574    #[test]
575    fn unclosed_cmd_sub_fails() { assert!(parse("echo $(ls").is_none()); }
576    #[test]
577    fn for_missing_do_fails() { assert!(parse("for x in 1 2 3; echo $x; done").is_none()); }
578    #[test]
579    fn if_missing_fi_fails() { assert!(parse("if true; then echo hello").is_none()); }
580
581    #[test]
582    fn subshell_for() {
583        if let Cmd::Subshell(inner) = &p("(for x in 1 2; do echo $x; done)").0[0].pipeline.commands[0] {
584            assert!(matches!(&inner.0[0].pipeline.commands[0], Cmd::For { .. }));
585        } else { panic!("expected Subshell"); }
586    }
587    #[test]
588    fn quoted_redirect_in_echo() {
589        let s = p("echo 'greater > than' test");
590        let cmd = simple(&s);
591        assert_eq!(cmd.words.len(), 3);
592        assert_eq!(cmd.redirs.len(), 0);
593    }
594
595    #[test]
596    fn parses_all_safe_commands() {
597        let cmds = [
598            "grep foo file.txt", "cat /etc/hosts", "jq '.key' file.json", "base64 -d",
599            "ls -la", "wc -l file.txt", "ps aux", "echo hello", "cat file.txt",
600            "echo $(ls)", "ls `pwd`", "echo $(echo $(ls))", "echo \"$(ls)\"",
601            "out=$(ls)", "out=$(git status)", "a=$(ls) b=$(pwd)",
602            "(echo hello)", "(ls)", "(ls && echo done)", "(echo hello; echo world)",
603            "(ls | grep foo)", "(echo hello) | grep hello", "(ls) && echo done",
604            "((echo hello))", "(for x in 1 2; do echo $x; done)",
605            "echo 'greater > than' test", "echo '$(safe)' arg",
606            "FOO='bar baz' ls -la", "FOO=\"bar baz\" ls -la",
607            "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
608            "grep foo file.txt | head -5", "cat file | sort | uniq",
609            "ls && echo done", "ls; echo done", "ls & echo done",
610            "grep -c , <<< 'hello,world,test'",
611            "cat <<EOF\nhello world\nEOF",
612            "cat <<'MARKER'\nsome text\nMARKER",
613            "cat <<-EOF\n\thello\nEOF",
614            "echo foo\necho bar", "ls\ncat file.txt",
615            "git log --oneline -20 | head -5",
616            "echo hello > /dev/null", "echo hello 2> /dev/null",
617            "echo hello >> /dev/null", "git log > /dev/null 2>&1",
618            "ls 2>&1", "cargo clippy 2>&1", "git log < /dev/null",
619            "for x in 1 2 3; do echo $x; done",
620            "for f in *.txt; do cat $f | grep pattern; done",
621            "for x in 1 2 3; do; done",
622            "for x in 1 2; do echo $x; done; for y in a b; do echo $y; done",
623            "for x in 1 2; do for y in a b; do echo $x $y; done; done",
624            "for x in 1 2; do echo $x; done && echo finished",
625            "for x in $(seq 1 5); do echo $x; done",
626            "while test -f /tmp/foo; do sleep 1; done",
627            "while ! test -f /tmp/done; do sleep 1; done",
628            "until test -f /tmp/ready; do sleep 1; done",
629            "if test -f foo; then echo exists; fi",
630            "if test -f foo; then echo yes; else echo no; fi",
631            "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
632            "for x in 1 2; do if test $x = 1; then echo one; fi; done",
633            "if true; then for x in 1 2; do echo $x; done; fi",
634            "! echo hello", "! test -f foo",
635            "echo for; echo done; echo if; echo fi",
636        ];
637        let mut failures = Vec::new();
638        for cmd in &cmds {
639            if parse(cmd).is_none() { failures.push(*cmd); }
640        }
641        assert!(failures.is_empty(), "failed on {} commands:\n{}", failures.len(), failures.join("\n"));
642    }
643}