1mod function;
2
3use super::budget::{self, DepthGuard};
4use super::escape::{self, dq_escape, escaped, fd_target, join_continuation, only_continuations, skip_continuation};
5use super::heredocs;
6use super::sub_close::find_sub_close;
7use super::*;
8use function::function_def;
9use winnow::ModalResult;
10use winnow::combinator::{alt, delimited, not, opt, preceded, repeat, separated, terminated};
11use winnow::error::{ContextError, ErrMode};
12use winnow::prelude::*;
13use winnow::token::{any, take_while};
14
15pub fn parse(input: &str) -> Option<Script> {
16 heredocs::reset();
17 budget::reset(input.len());
18 escape::begin(input);
19 let result = script.parse(input).ok().filter(|_| !budget::spent() && heredocs::drained() && escape::all_plain());
20 heredocs::reset();
21 result
22}
23
24fn backtrack<T>() -> ModalResult<T> {
25 Err(ErrMode::Backtrack(ContextError::new()))
26}
27
28fn step() -> ModalResult<()> {
30 if budget::charge(1, 0) { Ok(()) } else { backtrack() }
31}
32
33fn scan(bytes: usize) -> ModalResult<()> {
35 if budget::charge(0, bytes) { Ok(()) } else { backtrack() }
36}
37
38fn consumed<'a, O>(input: &mut &'a str, p: impl FnOnce(&mut &'a str) -> ModalResult<O>) -> ModalResult<O> {
40 let before = input.len();
41 let out = p(input);
42 scan(before - input.len())?;
43 out
44}
45
46fn comment(input: &mut &str) -> ModalResult<()> {
47 if input.starts_with('#') {
48 *input = input.find('\n').map_or("", |pos| &input[pos..]);
49 }
50 Ok(())
51}
52
53fn ws(input: &mut &str) -> ModalResult<()> {
54 consumed(input, ws_raw)
55}
56
57fn ws_raw(input: &mut &str) -> ModalResult<()> {
58 loop {
59 take_while(0.., [' ', '\t']).void().parse_next(input)?;
60 if input.starts_with('#') {
61 comment(input)?;
62 } else if !skip_continuation(input) {
63 break;
64 }
65 }
66 Ok(())
67}
68
69fn sep(input: &mut &str) -> ModalResult<()> {
70 while consumed(input, sep_raw)? {
71 heredocs::drain(input);
72 }
73 Ok(())
74}
75
76fn sep_raw(input: &mut &str) -> ModalResult<bool> {
77 loop {
78 while let Some(c) = input.chars().next() {
81 if input.starts_with(";;") {
82 return Ok(false);
83 }
84 if !matches!(c, ' ' | '\t' | ';' | '\n') {
85 break;
86 }
87 *input = &input[c.len_utf8()..];
88 if c == '\n' && heredocs::pending() {
89 return Ok(true);
90 }
91 }
92 if input.starts_with('#') {
93 comment(input)?;
94 } else {
95 break;
96 }
97 }
98 Ok(false)
99}
100
101fn eat_keyword(input: &mut &str, kw: &str) -> ModalResult<()> {
102 if !input.starts_with(kw) {
103 return backtrack();
104 }
105 if input.as_bytes().get(kw.len()).is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_') {
106 return backtrack();
107 }
108 *input = &input[kw.len()..];
109 Ok(())
110}
111
112const SCRIPT_STOPS: &[&str] = &["do", "done", "elif", "else", "esac", "fi", "then"];
113
114fn at_script_stop(input: &str) -> bool {
115 input.starts_with(')')
116 || input.starts_with('}')
117 || input.starts_with(";;")
120 || SCRIPT_STOPS.iter().any(|kw| {
121 input.starts_with(kw)
122 && !input
123 .as_bytes()
124 .get(kw.len())
125 .is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_')
126 })
127}
128
129fn is_word_boundary(c: char) -> bool {
130 matches!(c, ' ' | '\t' | '\n' | ';' | '|' | '&' | ')' | '>' | '<')
131}
132
133fn is_word_literal(c: char) -> bool {
134 !is_word_boundary(c) && !matches!(c, '\'' | '"' | '`' | '\\' | '(' | '$')
135}
136
137fn is_dq_literal(c: char) -> bool {
138 !matches!(c, '"' | '\\' | '`' | '$')
139}
140
141fn script(input: &mut &str) -> ModalResult<Script> {
144 let Some(_depth) = DepthGuard::enter() else {
147 return backtrack();
148 };
149 sep.parse_next(input)?;
150 let mut stmts = Vec::new();
151 while let Some(pl) = opt(pipeline).parse_next(input)? {
152 ws.parse_next(input)?;
153 let before = *input;
154 let op = opt(list_op).parse_next(input)?;
155 stmts.push(Stmt { pipeline: pl, op });
156 if before[..before.len() - input.len()].ends_with('\n') {
157 heredocs::drain(input);
158 }
159 if op.is_none() {
160 break;
161 }
162 sep.parse_next(input)?;
163 }
164 Ok(Script(stmts))
165}
166
167fn list_op(input: &mut &str) -> ModalResult<ListOp> {
168 ws.parse_next(input)?;
169 alt((
170 "&&".value(ListOp::And),
171 "||".value(ListOp::Or),
172 '\n'.value(ListOp::Semi),
173 (';', not(';')).value(ListOp::Semi),
176 ('&', not('>')).value(ListOp::Amp),
177 ))
178 .parse_next(input)
179}
180
181fn pipe_sep(input: &mut &str) -> ModalResult<()> {
185 (ws, alt(("|&".void(), ('|', not('|')).void())), ws).void().parse_next(input)
186}
187
188fn pipeline(input: &mut &str) -> ModalResult<Pipeline> {
191 ws.parse_next(input)?;
192 if at_script_stop(input) {
193 return backtrack();
194 }
195 let bang = opt(terminated('!', ws)).parse_next(input)?.is_some();
196 opt_time_keyword_before_compound(input);
197 let commands: Vec<Cmd> = separated(1.., command, pipe_sep).parse_next(input)?;
198 Ok(Pipeline { bang, commands })
199}
200
201fn opt_time_keyword_before_compound(input: &mut &str) -> bool {
224 let mut probe = *input;
225 if eat_keyword(&mut probe, "time").is_err() || !probe.starts_with([' ', '\t', '\n']) {
226 return false;
227 }
228 if ws.parse_next(&mut probe).is_err() {
229 return false;
230 }
231 if probe.starts_with("-p") {
233 let mut with_flag = &probe[2..];
234 if with_flag.starts_with([' ', '\t', '\n']) && ws.parse_next(&mut with_flag).is_ok() {
235 probe = with_flag;
236 }
237 }
238 if !probe.starts_with(['(', '{']) {
239 return false;
240 }
241 *input = probe;
242 true
243}
244
245fn command(input: &mut &str) -> ModalResult<Cmd> {
248 step()?;
249 ws.parse_next(input)?;
250 if at_script_stop(input) {
251 return backtrack();
252 }
253 let committed = super::reserved::opens_compound(input);
254 alt((subshell, brace_group, for_cmd, while_cmd, until_cmd, if_cmd, case_cmd, double_bracket_cmd, function_def, move |i: &mut &str| {
255 if committed { backtrack() } else { simple_cmd.map(Cmd::Simple).parse_next(i) }
256 }))
257 .parse_next(input)
258}
259
260fn run<'a>(input: &mut &'a str, pred: fn(char) -> bool) -> ModalResult<&'a str> {
262 consumed(input, |i| take_while(1.., pred).parse_next(i))
263}
264
265fn trailing_redirs(input: &mut &str) -> ModalResult<Vec<Redir>> {
266 let mut redirs = Vec::new();
267 loop {
268 ws.parse_next(input)?;
269 if let Some(r) = opt(redirect).parse_next(input)? {
270 redirs.push(r);
271 } else {
272 break;
273 }
274 }
275 Ok(redirs)
276}
277
278fn subshell(input: &mut &str) -> ModalResult<Cmd> {
279 let body = delimited(('(', ws), script, (ws, ')')).parse_next(input)?;
280 let redirs = trailing_redirs(input)?;
281 Ok(Cmd::Subshell { body, redirs })
282}
283
284fn brace_group(input: &mut &str) -> ModalResult<Cmd> {
285 if !input.starts_with('{') {
286 return backtrack();
287 }
288 if !input.as_bytes().get(1).is_some_and(|b| matches!(b, b' ' | b'\t' | b'\n')) {
289 return backtrack();
290 }
291 *input = &input[1..];
292 sep.parse_next(input)?;
293 let body = script.parse_next(input)?;
294 if body.0.is_empty() {
295 return backtrack();
296 }
297 sep.parse_next(input)?;
298 if !input.starts_with('}') {
299 return backtrack();
300 }
301 let last_op = body.0.last().and_then(|s| s.op);
302 if last_op.is_none() {
303 return backtrack();
304 }
305 *input = &input[1..];
306 let redirs = trailing_redirs(input)?;
307 Ok(Cmd::BraceGroup { body, redirs })
308}
309
310fn simple_cmd(input: &mut &str) -> ModalResult<SimpleCmd> {
313 let env: Vec<(String, Word)> = repeat(0.., terminated(assignment, ws)).parse_next(input)?;
314 let mut words = Vec::new();
315 let mut redirs = Vec::new();
316
317 loop {
318 ws.parse_next(input)?;
319 if at_cmd_end(input) {
320 break;
321 }
322 if let Some(r) = opt(redirect).parse_next(input)? {
323 redirs.push(r);
324 } else if let Some(w) = opt(word).parse_next(input)? {
325 words.push(w);
326 } else {
327 break;
328 }
329 }
330
331 if env.is_empty() && words.is_empty() && redirs.is_empty() {
332 return backtrack();
333 }
334 Ok(SimpleCmd { env, words, redirs })
335}
336
337fn at_cmd_end(input: &str) -> bool {
338 if input.starts_with("&>") {
341 return false;
342 }
343 input.is_empty() || matches!(input.as_bytes().first(), Some(b'\n' | b';' | b'|' | b'&' | b')'))
344}
345
346fn assignment(input: &mut &str) -> ModalResult<(String, Word)> {
347 let n = run(input, |c| c.is_ascii_alphanumeric() || c == '_')?;
348 '='.parse_next(input)?;
349 let value = opt(word).parse_next(input)?.unwrap_or(Word(vec![WordPart::Lit(String::new())]));
350 Ok((n.to_string(), value))
351}
352
353fn redirect(input: &mut &str) -> ModalResult<Redir> {
356 let fd = opt(fd_prefix).parse_next(input)?;
357 alt((
358 preceded("<<<", (ws, word)).map(|(_, target)| Redir::HereStr(target)),
359 heredoc,
360 preceded(">>", (ws, word)).map(move |(_, target)| Redir::Write { fd: fd.unwrap_or(1), target, mode: WriteMode::Append }),
361 preceded("&>>", (ws, word)).map(|(_, target)| Redir::Write { fd: 1, target, mode: WriteMode::AppendBoth }),
364 preceded("&>", (ws, word)).map(|(_, target)| Redir::Write { fd: 1, target, mode: WriteMode::TruncateBoth }),
365 preceded(">&", fd_target).map(move |dst| Redir::DupFd { src: fd.unwrap_or(1), dst }),
366 preceded(">&", (ws, word)).map(|(_, target)| Redir::Write { fd: 1, target, mode: WriteMode::TruncateBoth }),
370 preceded(">|", (ws, word)).map(move |(_, target)| Redir::Write { fd: fd.unwrap_or(1), target, mode: WriteMode::Clobber }),
374 preceded('>', (ws, word)).map(move |(_, target)| Redir::Write { fd: fd.unwrap_or(1), target, mode: WriteMode::Truncate }),
375 preceded("<>", (ws, word)).map(move |(_, target)| Redir::ReadWrite { fd: fd.unwrap_or(0), target }),
378 preceded('<', (ws, word)).map(move |(_, target)| Redir::Read { fd: fd.unwrap_or(0), target }),
379 ))
380 .parse_next(input)
381}
382
383fn heredoc(input: &mut &str) -> ModalResult<Redir> {
384 "<<".parse_next(input)?;
385 let strip_tabs = opt('-').parse_next(input)?.is_some();
386 ws.parse_next(input)?;
387 let before = input.len();
388 let delimiter = heredoc_delimiter.parse_next(input);
389 scan(if delimiter.is_ok() { before - input.len() } else { before })?;
390 let (delimiter, expands) = delimiter?;
391 if delimiter.contains('\n') {
392 escape::refuse();
393 }
394 let start = heredocs::expected_body_start(input);
398 let body = if expands { heredoc_body_word(input, start, &delimiter, strip_tabs)? } else { Word(Vec::new()) };
399 let start = start.map_or(0, |s| s.as_ptr() as usize);
405 heredocs::push(heredocs::Pending { delimiter: delimiter.clone(), strip_tabs, joins: expands, start });
406 Ok(Redir::HereDoc { delimiter, strip_tabs, body })
407}
408
409fn heredoc_body_word(input: &str, start: Option<&str>, delimiter: &str, strip_tabs: bool) -> ModalResult<Word> {
417 let Some((body, after)) = start.and_then(|rest| heredocs::split_body(rest, delimiter, strip_tabs, true)) else {
418 scan(input.len())?;
419 return Ok(Word(Vec::new()));
420 };
421 scan(input.len() - after.len())?;
422 let mut text = body;
423 let parts: Vec<WordPart> = repeat(0.., heredoc_part).parse_next(&mut text)?;
424 if !text.is_empty() {
425 return backtrack();
426 }
427 Ok(Word(parts))
428}
429
430fn is_heredoc_literal(c: char) -> bool {
434 !matches!(c, '"' | '\\' | '`' | '$')
435}
436
437fn heredoc_part(input: &mut &str) -> ModalResult<WordPart> {
438 step()?;
439 if input.is_empty() {
440 return backtrack();
441 }
442 if input.starts_with('"') {
443 *input = &input[1..];
444 return Ok(WordPart::Lit("\"".to_string()));
445 }
446 alt((dq_escape, arith_sub, cmd_sub, backtick_part, dollar_lit(is_heredoc_literal), lit(is_heredoc_literal))).parse_next(input)
447}
448
449fn heredoc_delimiter(input: &mut &str) -> ModalResult<(String, bool)> {
454 alt((
455 delimited('\'', take_while(0.., |c| c != '\''), '\'').map(|s: &str| (s.to_string(), false)),
456 delimited('"', take_while(0.., |c| c != '"'), '"').map(|s: &str| (s.to_string(), false)),
457 escaped_delimiter,
458 take_while(1.., |c: char| c.is_ascii_alphanumeric() || c == '_').map(|s: &str| (s.to_string(), true)),
459 ))
460 .parse_next(input)
461}
462
463fn escaped_delimiter(input: &mut &str) -> ModalResult<(String, bool)> {
468 let mut rest = *input;
469 let mut name = String::new();
470 let mut quoted = false;
471 let mut joined = false;
472 loop {
473 let mut chars = rest.chars();
474 match chars.next() {
475 Some('\\') if join_continuation(&mut rest) => joined = true,
476 Some('\\') => match chars.next() {
477 Some(c) => {
478 name.push(c);
479 quoted = true;
480 rest = &rest[1 + c.len_utf8()..];
481 }
482 None => break,
483 },
484 Some(q @ ('\'' | '"')) => {
485 let inner_end = rest[1..].find(q).map(|i| i + 1);
486 let Some(end) = inner_end else { break };
487 name.push_str(&rest[1..end]);
488 quoted = true;
489 rest = &rest[end + 1..];
490 }
491 Some(c) if c.is_ascii_alphanumeric() || c == '_' => {
492 name.push(c);
493 rest = &rest[c.len_utf8()..];
494 }
495 _ => break,
496 }
497 }
498 if !(quoted || joined) || name.is_empty() {
499 return backtrack();
500 }
501 *input = rest;
502 Ok((name, !quoted))
503}
504
505fn fd_prefix(input: &mut &str) -> ModalResult<u32> {
506 let b = input.as_bytes();
507 if b.len() >= 2 && b[0].is_ascii_digit() && matches!(b[1], b'>' | b'<') {
508 let d = (b[0] - b'0') as u32;
509 *input = &input[1..];
510 Ok(d)
511 } else {
512 backtrack()
513 }
514}
515
516fn word(input: &mut &str) -> ModalResult<Word> {
519 repeat(1.., word_part).map(Word).verify(|w: &Word| !only_continuations(&w.0)).parse_next(input)
520}
521
522fn word_part(input: &mut &str) -> ModalResult<WordPart> {
523 step()?;
524 if input.is_empty() {
525 return backtrack();
526 }
527 if input.starts_with("<(") || input.starts_with(">(") {
528 return proc_sub(input);
529 }
530 if is_word_boundary(input.as_bytes()[0] as char) {
531 return backtrack();
532 }
533 alt((
534 single_quoted,
535 double_quoted,
536 dollar_quoted,
537 arith_sub,
538 cmd_sub,
539 backtick_part,
540 escaped,
541 dollar_lit(is_word_literal),
542 lit(is_word_literal),
543 ))
544 .parse_next(input)
545}
546
547fn single_quoted(input: &mut &str) -> ModalResult<WordPart> {
548 delimited_scan(input, '\'', |i| {
549 delimited('\'', take_while(0.., |c| c != '\''), '\'')
550 .map(|s: &str| WordPart::SQuote(s.to_string()))
551 .parse_next(i)
552 })
553}
554
555fn double_quoted(input: &mut &str) -> ModalResult<WordPart> {
556 delimited('"', repeat(0.., dq_part).map(Word), '"').map(WordPart::DQuote).parse_next(input)
557}
558
559fn dollar_quoted(input: &mut &str) -> ModalResult<WordPart> {
560 alt((super::ansi_c::ansi_c_quoted, |i: &mut &str| super::ansi_c::locale_quoted(i, double_quoted))).parse_next(input)
561}
562
563fn sub_body(input: &mut &str, open_len: usize) -> ModalResult<Script> {
581 let body = &input[open_len..];
582 let close = find_sub_close(body);
583 scan(close.map_or(2 * body.len(), |rel| 3 * rel))?;
584 let Some(rel) = close else {
585 return if body.contains("<<") { sub_body_via_grammar(input, body) } else { backtrack() };
586 };
587 let interior = &body[..rel];
593 if !interior.contains("<<") && !interior.contains("case") {
599 let mut fast: &str = interior;
600 let parsed = script.parse_next(&mut fast)?;
601 ws.parse_next(&mut fast)?;
602 if !fast.is_empty() {
603 return backtrack();
604 }
605 *input = &body[rel + 1..];
606 return Ok(parsed);
607 }
608 sub_body_via_grammar(input, body)
609}
610
611fn sub_body_via_grammar<'a>(input: &mut &'a str, body: &'a str) -> ModalResult<Script> {
614 let mut rest: &str = body;
615 ws.parse_next(&mut rest)?;
616 let parsed = script.parse_next(&mut rest)?;
617 ws.parse_next(&mut rest)?;
618 if !rest.starts_with(')') {
619 return backtrack();
620 }
621 *input = &rest[1..];
622 Ok(parsed)
623}
624
625fn cmd_sub(input: &mut &str) -> ModalResult<WordPart> {
626 if !input.starts_with("$(") {
627 return backtrack();
628 }
629 heredocs::own(|| sub_body(input, 2)).map(WordPart::CmdSub)
630}
631
632fn proc_sub(input: &mut &str) -> ModalResult<WordPart> {
633 if !(input.starts_with("<(") || input.starts_with(">(")) {
634 return backtrack();
635 }
636 heredocs::own(|| sub_body(input, 2)).map(WordPart::ProcSub)
637}
638
639fn arith_body_part(input: &mut &str) -> ModalResult<WordPart> {
641 step()?;
642 if input.is_empty() {
643 return backtrack();
644 }
645 alt((
646 dq_escape,
647 arith_sub,
652 cmd_sub,
653 backtick_part,
654 dollar_lit(is_heredoc_literal),
655 lit(is_heredoc_literal),
656 ))
657 .parse_next(input)
658}
659
660fn arith_sub(input: &mut &str) -> ModalResult<WordPart> {
661 if !input.starts_with("$((") {
662 return backtrack();
663 }
664 let Some(_depth) = DepthGuard::enter() else {
671 return backtrack();
672 };
673 let body_start = 3;
674 let bytes = input.as_bytes();
675 let mut depth: i32 = 1;
676 let mut i = body_start;
677 while i < bytes.len() {
678 match bytes[i] {
679 b'(' => depth += 1,
680 b')' => {
681 if depth == 1 && i + 1 < bytes.len() && bytes[i + 1] == b')' {
682 scan(i)?;
694 let mut body = &input[body_start..i];
695 let parts: Vec<WordPart> = repeat(0.., arith_body_part).parse_next(&mut body)?;
696 if !body.is_empty() {
697 return backtrack();
698 }
699 *input = &input[i + 2..];
700 return Ok(WordPart::Arith(Word(parts)));
701 }
702 depth -= 1;
703 if depth < 0 {
704 scan(i)?;
705 return backtrack();
706 }
707 }
708 _ => {}
709 }
710 i += 1;
711 }
712 scan(i)?;
713 backtrack()
714}
715
716fn backtick_part(input: &mut &str) -> ModalResult<WordPart> {
717 delimited_scan(input, '`', |i| delimited('`', backtick_inner, '`').map(escape::backtick).parse_next(i))
718}
719
720fn delimited_scan<O>(input: &mut &str, open: char, p: impl FnOnce(&mut &str) -> ModalResult<O>) -> ModalResult<O> {
723 if !input.starts_with(open) {
724 return backtrack();
725 }
726 let before = input.len();
727 let out = p(input);
728 scan(if out.is_ok() { before - input.len() } else { before })?;
729 out
730}
731
732fn lit(pred: fn(char) -> bool) -> impl FnMut(&mut &str) -> ModalResult<WordPart> {
733 move |input: &mut &str| {
734 let s: &str = consumed(input, |i| take_while(1.., pred).parse_next(i))?;
735 Ok(WordPart::Lit(s.to_string()))
736 }
737}
738
739fn dollar_lit(pred: fn(char) -> bool) -> impl FnMut(&mut &str) -> ModalResult<WordPart> {
740 move |input: &mut &str| {
741 ('$', not('(')).void().parse_next(input)?;
742 let rest: &str = consumed(input, |i| take_while(0.., pred).parse_next(i))?;
743 Ok(WordPart::Lit(format!("${rest}")))
744 }
745}
746
747fn dq_part(input: &mut &str) -> ModalResult<WordPart> {
750 step()?;
751 if input.is_empty() || input.starts_with('"') {
752 return backtrack();
753 }
754 alt((dq_escape, arith_sub, cmd_sub, backtick_part, dollar_lit(is_dq_literal), lit(is_dq_literal))).parse_next(input)
755}
756
757fn backtick_inner(input: &mut &str) -> ModalResult<String> {
760 repeat(0.., alt((bt_escape, bt_literal)))
761 .fold(String::new, |mut acc, chunk: &str| {
762 acc.push_str(chunk);
763 acc
764 })
765 .parse_next(input)
766}
767
768fn bt_escape<'a>(input: &mut &'a str) -> ModalResult<&'a str> {
769 ('\\', any).take().parse_next(input)
770}
771
772fn bt_literal<'a>(input: &mut &'a str) -> ModalResult<&'a str> {
773 take_while(1.., |c: char| c != '`' && c != '\\').parse_next(input)
774}
775
776fn for_cmd(input: &mut &str) -> ModalResult<Cmd> {
779 eat_keyword(input, "for")?;
780 ws.parse_next(input)?;
781 let var = name.parse_next(input)?;
782 ws.parse_next(input)?;
783
784 let items = if eat_keyword(input, "in").is_ok() {
785 ws.parse_next(input)?;
786 repeat(0.., terminated(word, ws)).parse_next(input)?
787 } else {
788 vec![]
789 };
790
791 let body = do_done_body.parse_next(input)?;
792 let redirs = trailing_redirs(input)?;
793 Ok(Cmd::For { var, items, body, redirs })
794}
795
796fn while_cmd(input: &mut &str) -> ModalResult<Cmd> {
797 eat_keyword(input, "while")?;
798 ws.parse_next(input)?;
799 let cond = script.parse_next(input)?;
800 let body = do_done_body.parse_next(input)?;
801 let redirs = trailing_redirs(input)?;
802 Ok(Cmd::While { cond, body, redirs })
803}
804
805fn until_cmd(input: &mut &str) -> ModalResult<Cmd> {
806 eat_keyword(input, "until")?;
807 ws.parse_next(input)?;
808 let cond = script.parse_next(input)?;
809 let body = do_done_body.parse_next(input)?;
810 let redirs = trailing_redirs(input)?;
811 Ok(Cmd::Until { cond, body, redirs })
812}
813
814fn do_done_body(input: &mut &str) -> ModalResult<Script> {
815 sep.parse_next(input)?;
816 eat_keyword(input, "do")?;
817 sep.parse_next(input)?;
818 let body = script.parse_next(input)?;
819 sep.parse_next(input)?;
820 eat_keyword(input, "done")?;
821 Ok(body)
822}
823
824fn if_cmd(input: &mut &str) -> ModalResult<Cmd> {
825 eat_keyword(input, "if")?;
826 ws.parse_next(input)?;
827 let mut branches = vec![cond_then_body.parse_next(input)?];
828 let mut else_body = None;
829
830 loop {
831 sep.parse_next(input)?;
832 if eat_keyword(input, "elif").is_ok() {
833 ws.parse_next(input)?;
834 branches.push(cond_then_body.parse_next(input)?);
835 } else if eat_keyword(input, "else").is_ok() {
836 sep.parse_next(input)?;
837 else_body = Some(script.parse_next(input)?);
838 break;
839 } else {
840 break;
841 }
842 }
843
844 sep.parse_next(input)?;
845 eat_keyword(input, "fi")?;
846 let redirs = trailing_redirs(input)?;
847 Ok(Cmd::If { branches, else_body, redirs })
848}
849
850fn cond_then_body(input: &mut &str) -> ModalResult<Branch> {
851 let cond = script.parse_next(input)?;
852 sep.parse_next(input)?;
853 eat_keyword(input, "then")?;
854 sep.parse_next(input)?;
855 let body = script.parse_next(input)?;
856 Ok(Branch { cond, body })
857}
858
859fn case_cmd(input: &mut &str) -> ModalResult<Cmd> {
861 eat_keyword(input, "case")?;
862 ws.parse_next(input)?;
863 let subject = word.parse_next(input)?;
864 blank.parse_next(input)?;
865 eat_keyword(input, "in")?;
866
867 let mut arms = Vec::new();
868 loop {
869 blank.parse_next(input)?;
870 if eat_keyword(input, "esac").is_ok() {
871 break;
872 }
873 let arm = case_arm.parse_next(input)?;
874 let had_terminator = opt(";;").parse_next(input)?.is_some();
875 arms.push(arm);
876 if !had_terminator {
879 blank.parse_next(input)?;
880 eat_keyword(input, "esac")?;
881 break;
882 }
883 }
884
885 let redirs = trailing_redirs(input)?;
886 Ok(Cmd::Case { subject, arms, redirs })
887}
888
889fn case_arm(input: &mut &str) -> ModalResult<CaseArm> {
890 blank.parse_next(input)?;
891 opt('(').parse_next(input)?;
892 let mut patterns = Vec::new();
893 loop {
894 ws.parse_next(input)?;
895 patterns.push(word.parse_next(input)?);
896 ws.parse_next(input)?;
897 if opt('|').parse_next(input)?.is_none() {
898 break;
899 }
900 }
901 ')'.parse_next(input)?;
902 let body = script.parse_next(input)?;
903 blank.parse_next(input)?;
904 Ok(CaseArm { patterns, body })
905}
906
907fn blank(input: &mut &str) -> ModalResult<()> {
909 consumed(input, heredocs::skip_blank)
910}
911
912fn double_bracket_cmd(input: &mut &str) -> ModalResult<Cmd> {
913 if !input.starts_with("[[") {
914 return backtrack();
915 }
916 let bytes = input.as_bytes();
917 if bytes.len() < 3 || !matches!(bytes[2], b' ' | b'\t' | b'\n') {
918 return backtrack();
919 }
920 *input = &input[2..];
921
922 let mut words: Vec<Word> = Vec::new();
923 loop {
924 ws.parse_next(input)?;
925 if at_double_bracket_end(input) {
926 *input = &input[2..];
927 let redirs = trailing_redirs(input)?;
928 return Ok(Cmd::DoubleBracket { words, redirs });
929 }
930 if input.is_empty() {
931 return backtrack();
932 }
933 let w = bracket_word.parse_next(input)?;
934 words.push(w);
935 }
936}
937
938fn at_double_bracket_end(input: &str) -> bool {
939 if !input.starts_with("]]") {
940 return false;
941 }
942 let after = &input[2..];
943 after.is_empty() || after.starts_with([' ', '\t', '\n', ';', '&', '|', ')', '>', '<'])
944}
945
946fn bracket_word(input: &mut &str) -> ModalResult<Word> {
947 repeat(1.., bracket_word_part).map(Word).parse_next(input)
948}
949
950fn bracket_word_part(input: &mut &str) -> ModalResult<WordPart> {
951 step()?;
952 if input.is_empty() {
953 return backtrack();
954 }
955 if matches!(input.as_bytes()[0], b' ' | b'\t' | b'\n') {
956 return backtrack();
957 }
958 if at_double_bracket_end(input) {
959 return backtrack();
960 }
961 alt((
962 single_quoted,
963 double_quoted,
964 dollar_quoted,
965 arith_sub,
966 cmd_sub,
967 backtick_part,
968 escaped,
969 dollar_lit(is_bracket_literal),
970 bracket_lit,
971 ))
972 .parse_next(input)
973}
974
975fn is_bracket_literal(c: char) -> bool {
976 !matches!(c, '\'' | '"' | '`' | '\\' | '$' | ' ' | '\t' | '\n')
977}
978
979fn bracket_lit(input: &mut &str) -> ModalResult<WordPart> {
980 let bytes = input.as_bytes();
985 let mut end = 0;
986 while end < bytes.len() {
987 let c = bytes[end] as char;
988 if !is_bracket_literal(c) {
989 break;
990 }
991 if c == ']' && at_double_bracket_end(&input[end..]) {
992 break;
993 }
994 end += 1;
995 }
996 scan(end)?;
997 if end == 0 {
998 return backtrack();
999 }
1000 let lit = input[..end].to_string();
1001 *input = &input[end..];
1002 Ok(WordPart::Lit(lit))
1003}
1004
1005fn name(input: &mut &str) -> ModalResult<String> {
1006 run(input, |c| c.is_ascii_alphanumeric() || c == '_').map(String::from)
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011 use super::budget::MAX_PARSE_WORK_CEILING;
1012 #[test]
1030 fn the_parse_work_budget_bounds_nesting_without_refusing_real_commands() {
1031 let worst_real = crate::registry::corpus_examples()
1032 .into_iter()
1033 .flat_map(|(_, safe, denied)| safe.iter().chain(denied.iter()).cloned().collect::<Vec<_>>())
1034 .map(|ex| {
1035 let _ = super::parse(&ex);
1036 budget::work()
1037 })
1038 .max()
1039 .expect("the registry ships examples");
1040 assert!(
1041 worst_real * 100 < MAX_PARSE_WORK_CEILING,
1042 "a real example needs {worst_real} entries against a {MAX_PARSE_WORK_CEILING} ceiling; \
1043 the margin that makes this constant safe is gone"
1044 );
1045
1046 let flat = format!("echo {}", "$((1)) ".repeat(400));
1052 let _ = super::parse(&flat);
1053 let flat_work = budget::work();
1054 assert!(
1055 flat_work < MAX_PARSE_WORK_CEILING / 10,
1056 "flat input cost {flat_work}, close to the {MAX_PARSE_WORK_CEILING} ceiling — a long \
1057 flat command is at risk of being refused"
1058 );
1059
1060 let work_at = |depth: usize| {
1066 let deep = format!("echo {}1{}", "$((1+".repeat(depth), "))".repeat(depth));
1067 let _ = super::parse(&deep);
1068 assert!(budget::spent(), "the nest should actually reach a bound, or this proves nothing");
1069 budget::work()
1070 };
1071 let (w2k, w4k) = (work_at(2000), work_at(4000));
1072 assert!(w4k <= w2k + w2k / 10, "work still scales with input length: depth 2000 used {w2k}, depth 4000 used {w4k}");
1073 assert!(w4k < MAX_PARSE_WORK_CEILING + MAX_PARSE_WORK_CEILING / 10, "work {w4k} ran far past the {MAX_PARSE_WORK_CEILING} ceiling");
1074 }
1075
1076 use super::*;
1077
1078 #[test]
1087 fn unclosed_compound_nesting_costs_linear_work() {
1088 let unclosed = |opener: &str| match opener {
1089 "{" => "{\n",
1090 "[[" => "[[ a\n",
1091 "if" => "if a; then\n",
1092 "for" => "for x in a; do\n",
1093 "while" => "while a; do\n",
1094 "until" => "until a; do\n",
1095 "case" => "case x in a)\n",
1096 "function" => "function f {\n",
1097 other => panic!("no unclosed form for the reserved word {other:?}; add one here"),
1098 };
1099 let tail = "\"$([[ <<\"\"<\"$( [[ x ]] ) $(ls <<EOF\n)\nEOF\n)\" ls";
1100 let openers = super::super::reserved::BLANK_OPENERS.iter().chain(super::super::reserved::KEYWORD_OPENERS.iter());
1101 for opener in openers {
1102 let unit = unclosed(opener);
1103 for prefix in [unit.to_string(), format!("{unit}{{\n")] {
1104 for depth in [10u64, 20, 40] {
1105 let text = format!("{}{tail}", prefix.repeat(depth as usize));
1106 let _ = parse(&text);
1107 let work = budget::work();
1108 assert!(
1109 work <= 4 * depth + 64,
1110 "{depth} nested unclosed {prefix:?} cost {work} parse entries, more than \
1111 linear in the nesting: a failed compound is being re-read another way"
1112 );
1113 }
1114 }
1115 }
1116 }
1117
1118 #[test]
1126 fn refused_substitution_nesting_costs_linear_work() {
1127 for refused in ["[[ a", "{ a", "if a", "a; }"] {
1128 for (open, close) in [("$(", ")"), ("\"$(", ")\""), ("<(", ")")] {
1129 for depth in [10u64, 20, 40] {
1130 let n = depth as usize;
1131 let text = format!("echo {}x{}", format!("{open}{refused} ").repeat(n), close.repeat(n));
1132 let _ = parse(&text);
1133 let work = budget::work();
1134 assert!(
1135 work <= 4 * depth + 64,
1136 "{depth} nested {open}{refused} cost {work} parse entries, more than linear: \
1137 a refused interior is being parsed a second time"
1138 );
1139 }
1140 }
1141 }
1142 }
1143
1144 #[test]
1152 fn a_backtracking_nest_over_a_long_tail_is_stopped_by_what_it_reads() {
1153 let tail = "a ".repeat(50_000);
1154 for (open, close) in [("$(( $({ ", ") ))"), ("\"$(( $( [[ ", ") ))\"")] {
1155 let text = format!("echo {}x {tail}{}", open.repeat(20), close.repeat(20));
1156 assert!(parse(&text).is_none(), "{open:?} nest parsed");
1157 assert!(budget::spent(), "{open:?} nest was refused, but not by the budget");
1158 let work = budget::work();
1159 assert!(work < 1_000, "{open:?} nest ran {work} entries before the step budget stopped it");
1160 }
1161 }
1162
1163 #[test]
1171 fn the_explain_render_timeout_seed_scales_linearly_in_its_braces() {
1172 let seed = include_bytes!("../../fuzz/corpus/explain_render/seed-unclosed-brace-nest");
1173 let seed = String::from_utf8_lossy(seed);
1174 let body = seed.split('`').nth(1).expect("the seed carries a backtick body");
1175 let deep = body.find("$([[").expect("the seed's tail opens a `$([[`");
1176 let tail = &body[body[..deep].rfind("\n{").expect("the nest ends before the tail") + 2..];
1177 let cost = |k: usize| {
1178 let _ = parse(&format!("{}{tail}", "{\n".repeat(k)));
1179 assert!(!budget::spent(), "{k} braces spent the budget; the nest is not linear");
1180 (budget::work(), budget::steps())
1181 };
1182 let [(w10, s10), (w20, s20), (w40, s40)] = [cost(10), cost(20), cost(40)];
1183 assert!(w40 - w20 <= 2 * (w20 - w10) + 4, "entries {w10}/{w20}/{w40} for 10/20/40 braces");
1184 assert!(s40 - s20 <= 2 * (s20 - s10) + 16, "steps {s10}/{s20}/{s40} for 10/20/40 braces");
1185 assert!(!crate::is_safe_command(&seed));
1186 }
1187
1188 proptest::proptest! {
1189 #![proptest_config(proptest::prelude::ProptestConfig::with_cases(300))]
1190
1191 #[test]
1204 fn a_random_unclosed_nest_parses_in_linear_work(
1205 opener in proptest::sample::select(OPENERS.to_vec()),
1206 depth in 0..24usize,
1207 mixed in proptest::collection::vec(proptest::sample::select(OPENERS.to_vec()), 0..8),
1208 tail in proptest::collection::vec(proptest::sample::select(vec![
1209 "}", " ]]", "fi", "done", ";;", "esac", ")", "\"", "<<", "<<E\n", "\n", ";", "a ",
1210 "$(", "[[ ", "`",
1211 ]), 0..24),
1212 closes in 0..24usize,
1213 ) {
1214 let input = format!(
1215 "{}{}{}{}", opener.repeat(depth), mixed.concat(), tail.concat(), ")".repeat(closes)
1216 );
1217 let _ = parse(&input);
1218 let work = budget::work();
1219 let tokens = (depth + mixed.len() + tail.len() + closes) as u64;
1220 proptest::prop_assert!(!budget::spent(), "spent the budget on {input:?}");
1221 proptest::prop_assert!(work <= 4 * tokens + 16, "{work} entries for {tokens} tokens: {input:?}");
1222 }
1223 }
1224
1225 const OPENERS: [&str; 14] = [
1226 "{\n", "{ ", "[[ a\n", "if a; then\n", "for x in a; do\n", "while a; do\n", "case x in a)\n", "function f {\n", "(\n", "$(",
1227 "\"$(", "<(", "$([[ ", "$({ ",
1228 ];
1229
1230 #[test]
1238 fn committed_command_seeds_parse_in_linear_work() {
1239 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fuzz/corpus");
1240 let mut checked = 0;
1241 for target in ["parse", "explain_render"] {
1242 let dir = std::fs::read_dir(root.join(target)).expect("the fuzz corpus is committed");
1243 for path in dir.flatten().map(|e| e.path()) {
1244 if !path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("seed-")) {
1245 continue;
1246 }
1247 let text = String::from_utf8_lossy(&std::fs::read(&path).expect("readable seed")).into_owned();
1248 for piece in std::iter::once(text.as_str()).chain(text.split('`').skip(1).step_by(2)) {
1251 let _ = parse(piece);
1252 let (work, len) = (budget::work(), piece.len() as u64);
1253 assert!(!budget::spent(), "{} spent the parse budget", path.display());
1254 assert!(work <= len + 16, "{} cost {work} entries for {len} bytes", path.display());
1255 }
1256 checked += 1;
1257 }
1258 }
1259 assert!(checked >= 16, "only {checked} seeds found; the corpus has moved");
1260 }
1261
1262 #[test]
1265 fn the_step_budget_refuses_nothing_real() {
1266 for (_, safe, denied) in crate::registry::corpus_examples() {
1267 for example in safe.iter().chain(denied.iter()) {
1268 let _ = parse(example);
1269 assert!(!budget::spent(), "a registry example spent the step budget: {example}");
1270 }
1271 }
1272 let message = "it's a line of prose (with parens) and $vars\n".repeat(5_000);
1273 for text in [format!("git commit -m \"$(cat <<'EOF'\n{message}EOF\n)\""), "ls -la foo/bar; ".repeat(20_000)] {
1274 assert!(parse(&text).is_some(), "a long real command no longer parses");
1275 let (steps, len) = (budget::steps(), text.len() as u64);
1276 assert!(
1277 steps * 4 < budget::STEPS_PER_BYTE * len,
1278 "{len} bytes of ordinary input spent {steps} steps, within 4x of the allowance"
1279 );
1280 }
1281 }
1282
1283 fn p(input: &str) -> Script {
1284 parse(input).unwrap_or_else(|| panic!("failed to parse: {input}"))
1285 }
1286
1287 fn words(script: &Script) -> Vec<String> {
1288 match &script.0[0].pipeline.commands[0] {
1289 Cmd::Simple(s) => s.words.iter().map(|w| w.eval()).collect(),
1290 _ => panic!("expected simple command"),
1291 }
1292 }
1293
1294 fn simple(script: &Script) -> &SimpleCmd {
1295 match &script.0[0].pipeline.commands[0] {
1296 Cmd::Simple(s) => s,
1297 _ => panic!("expected simple command"),
1298 }
1299 }
1300
1301 #[test]
1302 fn simple_command() {
1303 assert_eq!(words(&p("echo hello")), ["echo", "hello"]);
1304 }
1305 #[test]
1306 fn flags() {
1307 assert_eq!(words(&p("ls -la")), ["ls", "-la"]);
1308 }
1309 #[test]
1310 fn single_quoted() {
1311 assert_eq!(words(&p("echo 'hello world'")), ["echo", "hello world"]);
1312 }
1313 #[test]
1314 fn double_quoted() {
1315 assert_eq!(words(&p("echo \"hello world\"")), ["echo", "hello world"]);
1316 }
1317 #[test]
1318 fn mixed_quotes() {
1319 assert_eq!(words(&p("jq '.key' file.json")), ["jq", ".key", "file.json"]);
1320 }
1321
1322 #[test]
1323 fn pipeline_test() {
1324 assert_eq!(p("grep foo | head -5").0[0].pipeline.commands.len(), 2);
1325 }
1326 #[test]
1327 fn sequence_and() {
1328 assert_eq!(p("ls && echo done").0[0].op, Some(ListOp::And));
1329 }
1330 #[test]
1331 fn sequence_semi() {
1332 assert_eq!(p("ls; echo done").0.len(), 2);
1333 }
1334 #[test]
1335 fn newline_separator() {
1336 assert_eq!(p("echo foo\necho bar").0.len(), 2);
1337 }
1338 #[test]
1339 fn blank_line_between_statements() {
1340 assert_eq!(p("echo foo\n\necho bar").0.len(), 2);
1341 }
1342 #[test]
1343 fn multiple_blank_lines() {
1344 assert_eq!(p("echo foo\n\n\n\necho bar").0.len(), 2);
1345 }
1346 #[test]
1347 fn blank_line_with_whitespace() {
1348 assert_eq!(p("echo foo\n \necho bar").0.len(), 2);
1349 }
1350 #[test]
1351 fn comment_between_statements() {
1352 assert_eq!(p("echo foo\n# comment\necho bar").0.len(), 2);
1353 }
1354 #[test]
1355 fn semi_then_blank() {
1356 assert_eq!(p("echo foo;\n\necho bar").0.len(), 2);
1357 }
1358 #[test]
1359 fn and_then_blank() {
1360 assert_eq!(p("echo foo &&\n\necho bar").0.len(), 2);
1361 }
1362
1363 #[test]
1364 fn brace_group_simple() {
1365 assert!(matches!(
1366 &p("{ echo hello; }").0[0].pipeline.commands[0],
1367 Cmd::BraceGroup { body, redirs } if body.0.len() == 1 && redirs.is_empty()
1368 ));
1369 }
1370 #[test]
1371 fn brace_group_multiple_stmts() {
1372 if let Cmd::BraceGroup { body, .. } = &p("{ echo a; echo b; echo c; }").0[0].pipeline.commands[0] {
1373 assert_eq!(body.0.len(), 3);
1374 } else {
1375 panic!("expected BraceGroup");
1376 }
1377 }
1378 #[test]
1379 fn brace_group_with_redirect() {
1380 if let Cmd::BraceGroup { redirs, .. } = &p("{ echo a; echo b; } > /tmp/out.txt").0[0].pipeline.commands[0] {
1381 assert_eq!(redirs.len(), 1);
1382 assert!(matches!(redirs[0], Redir::Write { .. }));
1383 } else {
1384 panic!("expected BraceGroup");
1385 }
1386 }
1387 #[test]
1388 fn brace_group_with_append_redirect() {
1389 if let Cmd::BraceGroup { redirs, .. } = &p("{ echo a; } >> log.txt").0[0].pipeline.commands[0] {
1390 assert!(matches!(redirs[0], Redir::Write { mode: WriteMode::Append, .. }));
1391 } else {
1392 panic!("expected BraceGroup");
1393 }
1394 }
1395 #[test]
1396 fn brace_group_with_stderr_redirect() {
1397 if let Cmd::BraceGroup { redirs, .. } = &p("{ echo a; } 2>&1").0[0].pipeline.commands[0] {
1398 assert!(matches!(redirs[0], Redir::DupFd { src: 2, .. }));
1399 } else {
1400 panic!("expected BraceGroup");
1401 }
1402 }
1403 #[test]
1404 fn brace_group_newline_separated() {
1405 if let Cmd::BraceGroup { body, .. } = &p("{\n echo a\n echo b\n}").0[0].pipeline.commands[0] {
1406 assert_eq!(body.0.len(), 2);
1407 } else {
1408 panic!("expected BraceGroup");
1409 }
1410 }
1411 #[test]
1418 fn time_keyword_prefixes_a_compound() {
1419 for (src, want_subshell) in [("time (ls)", true), ("time -p (ls)", true), ("time { ls; }", false)] {
1420 let pl = &p(src).0[0].pipeline;
1421 assert_eq!(pl.commands.len(), 1, "{src}: one compound command");
1422 if want_subshell {
1423 assert!(matches!(&pl.commands[0], Cmd::Subshell { .. }), "{src}: kept the subshell");
1424 } else {
1425 assert!(matches!(&pl.commands[0], Cmd::BraceGroup { .. }), "{src}: kept the group");
1426 }
1427 }
1428 let pl = &p("time (ls | head -5)").0[0].pipeline;
1430 assert!(matches!(&pl.commands[0], Cmd::Subshell { .. }));
1431
1432 let pl = &p("time ls").0[0].pipeline;
1435 assert!(matches!(&pl.commands[0], Cmd::Simple(_)), "time ls stays a simple command");
1436
1437 let pl = &p("timeout 5 ls").0[0].pipeline;
1439 assert!(matches!(&pl.commands[0], Cmd::Simple(_)), "timeout is not the time keyword");
1440
1441 let pl = &p("! time (ls)").0[0].pipeline;
1446 assert!(pl.bang, "the bang survives the time keyword");
1447 assert!(matches!(&pl.commands[0], Cmd::Subshell { .. }), "and the compound survives too");
1448 }
1449
1450 #[test]
1451 fn brace_group_in_pipeline() {
1452 let pl = &p("{ echo a; echo b; } | grep a").0[0].pipeline;
1453 assert_eq!(pl.commands.len(), 2);
1454 assert!(matches!(&pl.commands[0], Cmd::BraceGroup { .. }));
1455 }
1456 #[test]
1457 fn brace_group_followed_by_other() {
1458 let stmts = &p("{ echo a; }; echo b").0;
1459 assert_eq!(stmts.len(), 2);
1460 assert!(matches!(&stmts[0].pipeline.commands[0], Cmd::BraceGroup { .. }));
1461 }
1462 #[test]
1463 fn brace_group_nested() {
1464 if let Cmd::BraceGroup { body, .. } = &p("{ { echo inner; }; echo outer; }").0[0].pipeline.commands[0] {
1465 assert_eq!(body.0.len(), 2);
1466 assert!(matches!(&body.0[0].pipeline.commands[0], Cmd::BraceGroup { .. }));
1467 } else {
1468 panic!("expected outer BraceGroup");
1469 }
1470 }
1471 #[test]
1472 fn brace_group_with_subshell_inside() {
1473 if let Cmd::BraceGroup { body, .. } = &p("{ (echo sub); echo grp; }").0[0].pipeline.commands[0] {
1474 assert_eq!(body.0.len(), 2);
1475 assert!(matches!(&body.0[0].pipeline.commands[0], Cmd::Subshell { .. }));
1476 } else {
1477 panic!("expected BraceGroup");
1478 }
1479 }
1480 #[test]
1481 fn brace_open_requires_whitespace() {
1482 let cmds = &p("{echo a}").0;
1486 if !cmds.is_empty() {
1489 assert!(!matches!(&cmds[0].pipeline.commands[0], Cmd::BraceGroup { .. }));
1490 }
1491 }
1492 #[test]
1493 fn subshell_with_redirect() {
1494 if let Cmd::Subshell { redirs, .. } = &p("(echo hello) > /tmp/out.txt").0[0].pipeline.commands[0] {
1495 assert_eq!(redirs.len(), 1);
1496 } else {
1497 panic!("expected Subshell with redir");
1498 }
1499 }
1500 #[test]
1501 fn for_loop_with_redirect() {
1502 if let Cmd::For { redirs, .. } = &p("for f in a b; do echo $f; done 2>/dev/null").0[0].pipeline.commands[0] {
1503 assert_eq!(redirs.len(), 1);
1504 } else {
1505 panic!("expected For with redir");
1506 }
1507 }
1508 #[test]
1509 fn for_loop_redirect_then_pipe() {
1510 let pl = &p("for f in a b; do echo $f; done 2>&1 | head -5").0[0].pipeline;
1512 assert_eq!(pl.commands.len(), 2);
1513 assert!(matches!(&pl.commands[0], Cmd::For { redirs, .. } if redirs.len() == 1));
1514 }
1515 #[test]
1516 fn while_and_if_with_redirect() {
1517 assert!(matches!(
1518 &p("while true; do echo x; done 2>/dev/null").0[0].pipeline.commands[0],
1519 Cmd::While { redirs, .. } if redirs.len() == 1
1520 ));
1521 assert!(matches!(
1522 &p("if true; then echo x; fi 2>&1").0[0].pipeline.commands[0],
1523 Cmd::If { redirs, .. } if redirs.len() == 1
1524 ));
1525 }
1526 #[test]
1527 fn background() {
1528 assert_eq!(p("ls & echo done").0[0].op, Some(ListOp::Amp));
1529 }
1530
1531 #[test]
1532 fn redirect_dev_null() {
1533 let s = p("echo hello > /dev/null");
1534 let cmd = simple(&s);
1535 assert_eq!(cmd.words.len(), 2);
1536 assert!(matches!(&cmd.redirs[0], Redir::Write { fd: 1, mode: WriteMode::Truncate, .. }));
1537 }
1538 #[test]
1539 fn redirect_stderr() {
1540 assert!(matches!(&simple(&p("echo hello 2>&1")).redirs[0], Redir::DupFd { src: 2, dst } if dst == "1"));
1541 }
1542 #[test]
1543 fn here_string() {
1544 assert!(matches!(&simple(&p("grep -c , <<< 'hello,world,test'")).redirs[0], Redir::HereStr(_)));
1545 }
1546 #[test]
1547 fn heredoc_bare() {
1548 assert!(matches!(&simple(&p("cat <<EOF")).redirs[0], Redir::HereDoc { delimiter, strip_tabs: false, .. } if delimiter == "EOF"));
1549 }
1550 #[test]
1551 fn heredoc_with_content() {
1552 let s = p("cat <<EOF\nhello world\nEOF");
1553 assert!(matches!(&simple(&s).redirs[0], Redir::HereDoc { delimiter, .. } if delimiter == "EOF"));
1554 }
1555 #[test]
1556 fn heredoc_quoted_delimiter() {
1557 assert!(matches!(&simple(&p("cat <<'EOF'")).redirs[0], Redir::HereDoc { delimiter, .. } if delimiter == "EOF"));
1558 }
1559 #[test]
1560 fn heredoc_strip_tabs() {
1561 assert!(matches!(&simple(&p("cat <<-EOF")).redirs[0], Redir::HereDoc { strip_tabs: true, .. }));
1562 }
1563 #[test]
1564 fn heredoc_pipe_on_command_line() {
1565 let s = p("cat <<EOF | grep hello\nhello\nEOF");
1568 assert_eq!(s.0[0].pipeline.commands.len(), 2);
1569 }
1570 #[test]
1571 fn heredoc_body_does_not_swallow_pipe() {
1572 let s = p("cat <<EOF | bash\nrm\nEOF");
1576 assert_eq!(s.0[0].pipeline.commands.len(), 2, "pipeline must keep `bash` as a second command");
1577 }
1578 #[test]
1579 fn heredoc_followed_by_next_statement() {
1580 let s = p("cat <<EOF\nhello\nEOF\nls");
1583 assert_eq!(s.0.len(), 2);
1584 }
1585
1586 #[test]
1587 fn a_heredoc_body_starts_after_the_line_not_after_the_separator() {
1588 for line in [
1589 "cat <<EOF; rm -rf ~/x\nhi\nEOF",
1590 "cat <<EOF && rm -rf ~/x\nhi\nEOF",
1591 "cat <<EOF; echo ok\nhi $(rm -rf ~/x)\nEOF",
1592 "cat <<EOF\nhi\nEOF\nrm -rf ~/x",
1593 "cat <<EOF\necho $(rm -rf ~/x)",
1594 "cat <<EOF; echo \"a\nEOF\n\"\n$(rm -rf ~/x)\nEOF",
1595 "cat <<EOF; echo $(\nrm -rf ~/x\nEOF\necho)",
1596 "echo $(cat <<EOF)\nrm -rf ~/x\nEOF",
1597 "cat <<true; echo \"[$(cat <<'ls')]\"\ntrue\nls\necho '$(rm -rf ~/x)'\ntrue",
1598 "echo \"[$(cat <<'ls')]\"\nls\necho hi",
1599 ] {
1600 assert!(!crate::is_safe_command(line), "{line:?} must not approve");
1601 }
1602 for line in [
1603 "cat <<EOF; echo ok\nhi\nEOF",
1604 "cat <<EOF | grep h\nhi\nEOF",
1605 "cat <<EOF;\nhi\nEOF\necho done",
1606 "cat <<EOF &&\nhi\nEOF\necho done",
1607 "cat <<A <<B; echo x\na\nA\nb\nB",
1608 "{ cat <<EOF; }\nhi\nEOF",
1609 "x=$(cat <<EOF\nhi\nEOF\n); echo $x",
1610 "cat <<true; echo \"[`cat <<'ls'`]\"\ntrue\nls\necho '$(rm -rf ~/x)'\ntrue",
1611 ] {
1612 assert!(crate::is_safe_command(line), "{line:?} should approve");
1613 }
1614 assert_eq!(p("cat <<EOF; ls\nhi\nEOF").0.len(), 2);
1615 }
1616
1617 #[test]
1618 fn env_prefix() {
1619 let s = p("FOO='bar baz' ls -la");
1620 let cmd = simple(&s);
1621 assert_eq!(cmd.env[0].0, "FOO");
1622 assert_eq!(cmd.env[0].1.eval(), "bar baz");
1623 }
1624 #[test]
1625 fn cmd_substitution() {
1626 assert!(matches!(&simple(&p("echo $(ls)")).words[1].0[0], WordPart::CmdSub(_)));
1627 }
1628 #[test]
1629 fn backtick_substitution() {
1630 assert_eq!(simple(&p("ls `pwd`")).words[1].eval(), "__SAFE_CHAINS_CMDSUB_WORKTREE__");
1633 assert_eq!(simple(&p("ls `hostname`")).words[1].eval(), "__SAFE_CHAINS_CMDSUB__");
1635 }
1636 #[test]
1637 fn nested_substitution() {
1638 if let WordPart::CmdSub(inner) = &simple(&p("echo $(echo $(ls))")).words[1].0[0] {
1639 assert!(matches!(&simple(inner).words[1].0[0], WordPart::CmdSub(_)));
1640 } else {
1641 panic!("expected CmdSub");
1642 }
1643 }
1644
1645 #[test]
1646 fn subshell_test() {
1647 assert!(matches!(&p("(echo hello)").0[0].pipeline.commands[0], Cmd::Subshell { .. }));
1648 }
1649 #[test]
1650 fn negation() {
1651 assert!(p("! echo hello").0[0].pipeline.bang);
1652 }
1653
1654 #[test]
1655 fn for_loop() {
1656 assert!(matches!(&p("for x in 1 2 3; do echo $x; done").0[0].pipeline.commands[0], Cmd::For { var, .. } if var == "x"));
1657 }
1658 #[test]
1659 fn while_loop() {
1660 assert!(matches!(&p("while test -f /tmp/foo; do sleep 1; done").0[0].pipeline.commands[0], Cmd::While { .. }));
1661 }
1662 #[test]
1663 fn if_then_fi() {
1664 if let Cmd::If { branches, else_body, .. } = &p("if test -f foo; then echo exists; fi").0[0].pipeline.commands[0] {
1665 assert_eq!(branches.len(), 1);
1666 assert!(else_body.is_none());
1667 } else {
1668 panic!("expected If");
1669 }
1670 }
1671 #[test]
1672 fn if_elif_else() {
1673 if let Cmd::If { branches, else_body, .. } =
1674 &p("if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi").0[0].pipeline.commands[0]
1675 {
1676 assert_eq!(branches.len(), 2);
1677 assert!(else_body.is_some());
1678 } else {
1679 panic!("expected If");
1680 }
1681 }
1682
1683 #[test]
1684 fn escaped_outside_quotes() {
1685 assert_eq!(words(&p("echo hello\\ world")), ["echo", "hello world"]);
1686 }
1687 #[test]
1688 fn a_line_continuation_joins_a_word() {
1689 assert_eq!(words(&p("imp\\\nort a")), ["import", "a"]);
1690 assert_eq!(words(&p("echo \"incl\\\nude\"")), ["echo", "include"]);
1691 assert_eq!(words(&p("echo 'incl\\\nude'")), ["echo", "incl\\\nude"]);
1692 }
1693 #[test]
1694 fn a_line_continuation_between_words_is_whitespace() {
1695 assert_eq!(words(&p("echo a \\\n b")), ["echo", "a", "b"]);
1696 assert_eq!(words(&p("echo a\\\n b")), ["echo", "a", "b"]);
1697 assert_eq!(words(&p("echo \\\n\\\nb")), ["echo", "b"]);
1698 }
1699 #[test]
1700 fn double_quoted_escape() {
1701 assert_eq!(words(&p("echo \"hello\\\"world\"")), ["echo", "hello\"world"]);
1702 }
1703 #[test]
1704 fn assign_subst() {
1705 assert_eq!(simple(&p("out=$(ls)")).env[0].0, "out");
1706 }
1707
1708 #[test]
1709 fn unmatched_single_quote_fails() {
1710 assert!(parse("echo 'hello").is_none());
1711 }
1712 #[test]
1713 fn unmatched_double_quote_fails() {
1714 assert!(parse("echo \"hello").is_none());
1715 }
1716 #[test]
1717 fn unclosed_subshell_fails() {
1718 assert!(parse("(echo hello").is_none());
1719 }
1720 #[test]
1721 fn unclosed_cmd_sub_fails() {
1722 assert!(parse("echo $(ls").is_none());
1723 }
1724 #[test]
1725 fn for_missing_do_fails() {
1726 assert!(parse("for x in 1 2 3; echo $x; done").is_none());
1727 }
1728 #[test]
1729 fn if_missing_fi_fails() {
1730 assert!(parse("if true; then echo hello").is_none());
1731 }
1732
1733 #[test]
1734 fn subshell_for() {
1735 if let Cmd::Subshell { body, .. } = &p("(for x in 1 2; do echo $x; done)").0[0].pipeline.commands[0] {
1736 assert!(matches!(&body.0[0].pipeline.commands[0], Cmd::For { .. }));
1737 } else {
1738 panic!("expected Subshell");
1739 }
1740 }
1741 #[test]
1742 fn proc_sub_input() {
1743 let s = p("diff <(sort a.txt) <(sort b.txt)");
1744 let cmd = simple(&s);
1745 assert_eq!(cmd.words.len(), 3);
1746 assert!(matches!(&cmd.words[1].0[0], WordPart::ProcSub(_)));
1747 assert!(matches!(&cmd.words[2].0[0], WordPart::ProcSub(_)));
1748 }
1749 #[test]
1750 fn proc_sub_output() {
1751 let s = p("tee >(grep error > /dev/null)");
1752 let cmd = simple(&s);
1753 assert_eq!(cmd.words.len(), 2);
1754 assert!(matches!(&cmd.words[1].0[0], WordPart::ProcSub(_)));
1755 }
1756
1757 fn func_def(s: &Script) -> (&str, &Script) {
1759 match &s.0[0].pipeline.commands[0] {
1760 Cmd::FunctionDef { name, body } => (name.as_str(), body),
1761 other => panic!("expected FunctionDef, got {other:?}"),
1762 }
1763 }
1764 #[test]
1765 fn function_def_posix_form() {
1766 let s = p("probe(){ echo hi; }");
1767 let (name, body) = func_def(&s);
1768 assert_eq!(name, "probe");
1769 assert_eq!(words(body), ["echo", "hi"]);
1770 }
1771 #[test]
1772 fn function_def_spaced_and_keyword_forms() {
1773 assert_eq!(func_def(&p("foo () { echo hi; }")).0, "foo");
1774 assert_eq!(func_def(&p("function foo { echo hi; }")).0, "foo");
1775 assert_eq!(func_def(&p("function foo () { echo hi; }")).0, "foo");
1776 }
1777 #[test]
1778 fn function_def_subshell_body() {
1779 let s = p("foo() ( echo sub )");
1780 assert_eq!(func_def(&s).0, "foo");
1781 }
1782 #[test]
1783 fn function_def_body_on_next_line() {
1784 assert_eq!(func_def(&p("foo()\n{\n echo hi\n}")).0, "foo");
1785 }
1786 #[test]
1787 fn function_def_name_with_dashes_and_dots() {
1788 assert_eq!(func_def(&p("my-func.v2(){ echo hi; }")).0, "my-func.v2");
1789 }
1790 #[test]
1791 fn plain_command_is_not_a_function_def() {
1792 assert!(matches!(&p("ls -la").0[0].pipeline.commands[0], Cmd::Simple(_)));
1794 assert!(matches!(&p("echo foo bar").0[0].pipeline.commands[0], Cmd::Simple(_)));
1795 }
1796 #[test]
1797 fn function_def_roundtrips() {
1798 let rendered = p("greet(){ echo hi; }").to_string();
1799 assert!(parse(&rendered).is_some(), "did not reparse: {rendered}");
1800 assert_eq!(func_def(&p(&rendered)).0, "greet");
1801 }
1802 #[test]
1803 fn comment_only() {
1804 let s = p("# just a comment");
1805 assert!(s.0.is_empty());
1806 }
1807 #[test]
1808 fn comment_before_command() {
1809 let s = p("# comment\necho hello");
1810 assert_eq!(words(&s), ["echo", "hello"]);
1811 }
1812 #[test]
1813 fn inline_comment() {
1814 let s = p("echo hello # this is a comment");
1815 assert_eq!(words(&s), ["echo", "hello"]);
1816 }
1817 #[test]
1818 fn comment_between_commands() {
1819 let s = p("echo hello\n# middle comment\necho world");
1820 assert_eq!(s.0.len(), 2);
1821 }
1822 #[test]
1823 fn comment_after_semicolon() {
1824 let s = p("echo hello; # comment\necho world");
1825 assert_eq!(s.0.len(), 2);
1826 }
1827 #[test]
1828 fn comment_in_for_loop() {
1829 assert!(parse("for x in 1 2; do\n# loop body\necho $x\ndone").is_some());
1830 }
1831 #[test]
1832 fn quoted_redirect_in_echo() {
1833 let s = p("echo 'greater > than' test");
1834 let cmd = simple(&s);
1835 assert_eq!(cmd.words.len(), 3);
1836 assert_eq!(cmd.redirs.len(), 0);
1837 }
1838
1839 #[test]
1840 fn parses_all_safe_commands() {
1841 let cmds = [
1842 "grep foo file.txt",
1843 "cat /etc/hosts",
1844 "jq '.key' file.json",
1845 "base64 -d",
1846 "ls -la",
1847 "wc -l file.txt",
1848 "ps aux",
1849 "echo hello",
1850 "cat file.txt",
1851 "echo $(ls)",
1852 "ls `pwd`",
1853 "echo $(echo $(ls))",
1854 "echo \"$(ls)\"",
1855 "out=$(ls)",
1856 "out=$(git status)",
1857 "a=$(ls) b=$(pwd)",
1858 "(echo hello)",
1859 "(ls)",
1860 "(ls && echo done)",
1861 "(echo hello; echo world)",
1862 "(ls | grep foo)",
1863 "(echo hello) | grep hello",
1864 "(ls) && echo done",
1865 "((echo hello))",
1866 "(for x in 1 2; do echo $x; done)",
1867 "echo 'greater > than' test",
1868 "echo '$(safe)' arg",
1869 "FOO='bar baz' ls -la",
1870 "FOO=\"bar baz\" ls -la",
1871 "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
1872 "grep foo file.txt | head -5",
1873 "cat file | sort | uniq",
1874 "ls && echo done",
1875 "ls; echo done",
1876 "ls & echo done",
1877 "grep -c , <<< 'hello,world,test'",
1878 "cat <<EOF\nhello world\nEOF",
1879 "cat <<'MARKER'\nsome text\nMARKER",
1880 "cat <<-EOF\n\thello\nEOF",
1881 "echo foo\necho bar",
1882 "ls\ncat file.txt",
1883 "git log --oneline -20 | head -5",
1884 "echo hello > /dev/null",
1885 "echo hello 2> /dev/null",
1886 "echo hello >> /dev/null",
1887 "git log > /dev/null 2>&1",
1888 "ls 2>&1",
1889 "cargo clippy 2>&1",
1890 "git log < /dev/null",
1891 "for x in 1 2 3; do echo $x; done",
1892 "for f in *.txt; do cat $f | grep pattern; done",
1893 "for x in 1 2 3; do; done",
1894 "for x in 1 2; do echo $x; done; for y in a b; do echo $y; done",
1895 "for x in 1 2; do for y in a b; do echo $x $y; done; done",
1896 "for x in 1 2; do echo $x; done && echo finished",
1897 "for x in $(seq 1 5); do echo $x; done",
1898 "while test -f /tmp/foo; do sleep 1; done",
1899 "while ! test -f /tmp/done; do sleep 1; done",
1900 "until test -f /tmp/ready; do sleep 1; done",
1901 "if test -f foo; then echo exists; fi",
1902 "if test -f foo; then echo yes; else echo no; fi",
1903 "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
1904 "for x in 1 2; do if test $x = 1; then echo one; fi; done",
1905 "if true; then for x in 1 2; do echo $x; done; fi",
1906 "diff <(sort a.txt) <(sort b.txt)",
1907 "comm -23 file.txt <(sort other.txt)",
1908 "cat <(echo hello)",
1909 "# comment only",
1910 "# comment\necho hello",
1911 "echo hello # inline comment",
1912 "echo one\n# between\necho two",
1913 "! echo hello",
1914 "! test -f foo",
1915 "echo for; echo done; echo if; echo fi",
1916 ];
1917 let mut failures = Vec::new();
1918 for cmd in &cmds {
1919 if parse(cmd).is_none() {
1920 failures.push(*cmd);
1921 }
1922 }
1923 assert!(failures.is_empty(), "failed on {} commands:\n{}", failures.len(), failures.join("\n"));
1924 }
1925
1926 fn inner_sub(s: &Script) -> &Script {
1932 match &simple(s).words[1].0[0] {
1933 WordPart::CmdSub(inner) | WordPart::ProcSub(inner) => inner,
1934 other => panic!("expected a substitution, got {other:?}"),
1935 }
1936 }
1937
1938 #[test]
1939 fn cmd_sub_squote_paren_is_not_close() {
1940 assert_eq!(words(inner_sub(&p("echo $(echo ')')"))), ["echo", ")"]);
1941 }
1942 #[test]
1943 fn cmd_sub_dquote_paren_is_not_close() {
1944 assert_eq!(words(inner_sub(&p("echo $(echo \")\")"))), ["echo", ")"]);
1945 }
1946 #[test]
1947 fn cmd_sub_escaped_paren_is_not_close() {
1948 assert_eq!(words(inner_sub(&p("echo $(echo \\))"))), ["echo", ")"]);
1949 }
1950 #[test]
1951 fn cmd_sub_backtick_paren_is_not_close() {
1952 let s = p("echo $(x `)` y)");
1954 let inner = simple(inner_sub(&s));
1955 assert_eq!(inner.words.len(), 3);
1956 assert!(matches!(&inner.words[1].0[0], WordPart::Backtick(_)));
1957 }
1958 #[test]
1959 fn cmd_sub_escaped_backtick_does_not_end_span() {
1960 let s = p("echo $(`\\`)`)");
1964 assert!(matches!(&simple(&s).words[1].0[0], WordPart::CmdSub(_)));
1965 }
1966 #[test]
1967 fn proc_sub_squote_paren_is_not_close() {
1968 assert_eq!(words(inner_sub(&p("cat <(grep ')' f)"))), ["grep", ")", "f"]);
1969 }
1970 #[test]
1971 fn proc_sub_out_squote_paren_is_not_close() {
1972 assert_eq!(words(inner_sub(&p("tee >(grep ')' f)"))), ["grep", ")", "f"]);
1973 }
1974 #[test]
1975 fn cmd_sub_nested_picks_outer_close() {
1976 let s = p("echo $(a $(b) c)");
1977 let inner = simple(inner_sub(&s));
1978 assert_eq!(inner.words.len(), 3);
1979 assert!(matches!(&inner.words[1].0[0], WordPart::CmdSub(_)));
1980 }
1981 #[test]
1982 fn cmd_sub_literal_after_close_stays_in_outer_word() {
1983 let s = p("echo $(ls)tail");
1984 let w = &simple(&s).words[1];
1985 assert_eq!(w.0.len(), 2);
1986 assert!(matches!(&w.0[0], WordPart::CmdSub(_)));
1987 assert!(matches!(&w.0[1], WordPart::Lit(s) if s == "tail"));
1988 }
1989 #[test]
1990 fn cmd_sub_heredoc_body_paren_does_not_close() {
1991 let s = p("x=$(cat <<EOF\na)b\nEOF\n)");
1995 assert!(matches!(&simple(&s).env[0].1.0[0], WordPart::CmdSub(_)));
1996 }
1997 #[test]
1998 fn cmd_sub_with_only_a_quoted_paren_is_unclosed() {
1999 assert!(parse("echo $(echo ')").is_none());
2001 }
2002 #[test]
2003 fn proc_sub_with_only_a_quoted_paren_is_unclosed() {
2004 assert!(parse("cat <(grep ')").is_none());
2005 }
2006}