mod function;
use super::budget::{self, DepthGuard};
use super::escape::{self, dq_escape, escaped, fd_target, join_continuation, only_continuations, skip_continuation};
use super::heredocs;
use super::sub_close::find_sub_close;
use super::*;
use function::function_def;
use winnow::ModalResult;
use winnow::combinator::{alt, delimited, not, opt, preceded, repeat, separated, terminated};
use winnow::error::{ContextError, ErrMode};
use winnow::prelude::*;
use winnow::token::{any, take_while};
pub fn parse(input: &str) -> Option<Script> {
heredocs::reset();
budget::reset(input.len());
escape::begin(input);
let result = script.parse(input).ok().filter(|_| !budget::spent() && heredocs::drained() && escape::all_plain());
heredocs::reset();
result
}
fn backtrack<T>() -> ModalResult<T> {
Err(ErrMode::Backtrack(ContextError::new()))
}
fn step() -> ModalResult<()> {
if budget::charge(1, 0) { Ok(()) } else { backtrack() }
}
fn scan(bytes: usize) -> ModalResult<()> {
if budget::charge(0, bytes) { Ok(()) } else { backtrack() }
}
fn consumed<'a, O>(input: &mut &'a str, p: impl FnOnce(&mut &'a str) -> ModalResult<O>) -> ModalResult<O> {
let before = input.len();
let out = p(input);
scan(before - input.len())?;
out
}
fn comment(input: &mut &str) -> ModalResult<()> {
if input.starts_with('#') {
*input = input.find('\n').map_or("", |pos| &input[pos..]);
}
Ok(())
}
fn ws(input: &mut &str) -> ModalResult<()> {
consumed(input, ws_raw)
}
fn ws_raw(input: &mut &str) -> ModalResult<()> {
loop {
take_while(0.., [' ', '\t']).void().parse_next(input)?;
if input.starts_with('#') {
comment(input)?;
} else if !skip_continuation(input) {
break;
}
}
Ok(())
}
fn sep(input: &mut &str) -> ModalResult<()> {
while consumed(input, sep_raw)? {
heredocs::drain(input);
}
Ok(())
}
fn sep_raw(input: &mut &str) -> ModalResult<bool> {
loop {
while let Some(c) = input.chars().next() {
if input.starts_with(";;") {
return Ok(false);
}
if !matches!(c, ' ' | '\t' | ';' | '\n') {
break;
}
*input = &input[c.len_utf8()..];
if c == '\n' && heredocs::pending() {
return Ok(true);
}
}
if input.starts_with('#') {
comment(input)?;
} else {
break;
}
}
Ok(false)
}
fn eat_keyword(input: &mut &str, kw: &str) -> ModalResult<()> {
if !input.starts_with(kw) {
return backtrack();
}
if input.as_bytes().get(kw.len()).is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_') {
return backtrack();
}
*input = &input[kw.len()..];
Ok(())
}
const SCRIPT_STOPS: &[&str] = &["do", "done", "elif", "else", "esac", "fi", "then"];
fn at_script_stop(input: &str) -> bool {
input.starts_with(')')
|| input.starts_with('}')
|| input.starts_with(";;")
|| SCRIPT_STOPS.iter().any(|kw| {
input.starts_with(kw)
&& !input
.as_bytes()
.get(kw.len())
.is_some_and(|&b| b.is_ascii_alphanumeric() || b == b'_')
})
}
fn is_word_boundary(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n' | ';' | '|' | '&' | ')' | '>' | '<')
}
fn is_word_literal(c: char) -> bool {
!is_word_boundary(c) && !matches!(c, '\'' | '"' | '`' | '\\' | '(' | '$')
}
fn is_dq_literal(c: char) -> bool {
!matches!(c, '"' | '\\' | '`' | '$')
}
fn script(input: &mut &str) -> ModalResult<Script> {
let Some(_depth) = DepthGuard::enter() else {
return backtrack();
};
sep.parse_next(input)?;
let mut stmts = Vec::new();
while let Some(pl) = opt(pipeline).parse_next(input)? {
ws.parse_next(input)?;
let before = *input;
let op = opt(list_op).parse_next(input)?;
stmts.push(Stmt { pipeline: pl, op });
if before[..before.len() - input.len()].ends_with('\n') {
heredocs::drain(input);
}
if op.is_none() {
break;
}
sep.parse_next(input)?;
}
Ok(Script(stmts))
}
fn list_op(input: &mut &str) -> ModalResult<ListOp> {
ws.parse_next(input)?;
alt((
"&&".value(ListOp::And),
"||".value(ListOp::Or),
'\n'.value(ListOp::Semi),
(';', not(';')).value(ListOp::Semi),
('&', not('>')).value(ListOp::Amp),
))
.parse_next(input)
}
fn pipe_sep(input: &mut &str) -> ModalResult<()> {
(ws, alt(("|&".void(), ('|', not('|')).void())), ws).void().parse_next(input)
}
fn pipeline(input: &mut &str) -> ModalResult<Pipeline> {
ws.parse_next(input)?;
if at_script_stop(input) {
return backtrack();
}
let bang = opt(terminated('!', ws)).parse_next(input)?.is_some();
opt_time_keyword_before_compound(input);
let commands: Vec<Cmd> = separated(1.., command, pipe_sep).parse_next(input)?;
Ok(Pipeline { bang, commands })
}
fn opt_time_keyword_before_compound(input: &mut &str) -> bool {
let mut probe = *input;
if eat_keyword(&mut probe, "time").is_err() || !probe.starts_with([' ', '\t', '\n']) {
return false;
}
if ws.parse_next(&mut probe).is_err() {
return false;
}
if probe.starts_with("-p") {
let mut with_flag = &probe[2..];
if with_flag.starts_with([' ', '\t', '\n']) && ws.parse_next(&mut with_flag).is_ok() {
probe = with_flag;
}
}
if !probe.starts_with(['(', '{']) {
return false;
}
*input = probe;
true
}
fn command(input: &mut &str) -> ModalResult<Cmd> {
step()?;
ws.parse_next(input)?;
if at_script_stop(input) {
return backtrack();
}
let committed = super::reserved::opens_compound(input);
alt((subshell, brace_group, for_cmd, while_cmd, until_cmd, if_cmd, case_cmd, double_bracket_cmd, function_def, move |i: &mut &str| {
if committed { backtrack() } else { simple_cmd.map(Cmd::Simple).parse_next(i) }
}))
.parse_next(input)
}
fn run<'a>(input: &mut &'a str, pred: fn(char) -> bool) -> ModalResult<&'a str> {
consumed(input, |i| take_while(1.., pred).parse_next(i))
}
fn trailing_redirs(input: &mut &str) -> ModalResult<Vec<Redir>> {
let mut redirs = Vec::new();
loop {
ws.parse_next(input)?;
if let Some(r) = opt(redirect).parse_next(input)? {
redirs.push(r);
} else {
break;
}
}
Ok(redirs)
}
fn subshell(input: &mut &str) -> ModalResult<Cmd> {
let body = delimited(('(', ws), script, (ws, ')')).parse_next(input)?;
let redirs = trailing_redirs(input)?;
Ok(Cmd::Subshell { body, redirs })
}
fn brace_group(input: &mut &str) -> ModalResult<Cmd> {
if !input.starts_with('{') {
return backtrack();
}
if !input.as_bytes().get(1).is_some_and(|b| matches!(b, b' ' | b'\t' | b'\n')) {
return backtrack();
}
*input = &input[1..];
sep.parse_next(input)?;
let body = script.parse_next(input)?;
if body.0.is_empty() {
return backtrack();
}
sep.parse_next(input)?;
if !input.starts_with('}') {
return backtrack();
}
let last_op = body.0.last().and_then(|s| s.op);
if last_op.is_none() {
return backtrack();
}
*input = &input[1..];
let redirs = trailing_redirs(input)?;
Ok(Cmd::BraceGroup { body, redirs })
}
fn simple_cmd(input: &mut &str) -> ModalResult<SimpleCmd> {
let env: Vec<(String, Word)> = repeat(0.., terminated(assignment, ws)).parse_next(input)?;
let mut words = Vec::new();
let mut redirs = Vec::new();
loop {
ws.parse_next(input)?;
if at_cmd_end(input) {
break;
}
if let Some(r) = opt(redirect).parse_next(input)? {
redirs.push(r);
} else if let Some(w) = opt(word).parse_next(input)? {
words.push(w);
} else {
break;
}
}
if env.is_empty() && words.is_empty() && redirs.is_empty() {
return backtrack();
}
Ok(SimpleCmd { env, words, redirs })
}
fn at_cmd_end(input: &str) -> bool {
if input.starts_with("&>") {
return false;
}
input.is_empty() || matches!(input.as_bytes().first(), Some(b'\n' | b';' | b'|' | b'&' | b')'))
}
fn assignment(input: &mut &str) -> ModalResult<(String, Word)> {
let n = run(input, |c| c.is_ascii_alphanumeric() || c == '_')?;
let (appends, _) = (opt('+'), '=').parse_next(input)?;
let value = opt(word).parse_next(input)?.unwrap_or(Word(vec![WordPart::Lit(String::new())]));
Ok((n.to_string(), Word(appends.map(|_| WordPart::Lit(format!("${{{n}}}"))).into_iter().chain(value.0).collect())))
}
fn redirect(input: &mut &str) -> ModalResult<Redir> {
let fd = opt(fd_prefix).parse_next(input)?;
alt((
preceded("<<<", (ws, word)).map(|(_, target)| Redir::HereStr(target)),
heredoc,
preceded(">>", (ws, word)).map(move |(_, target)| Redir::Write { fd: fd.unwrap_or(1), target, mode: WriteMode::Append }),
preceded("&>>", (ws, word)).map(|(_, target)| Redir::Write { fd: 1, target, mode: WriteMode::AppendBoth }),
preceded("&>", (ws, word)).map(|(_, target)| Redir::Write { fd: 1, target, mode: WriteMode::TruncateBoth }),
preceded(">&", fd_target).map(move |dst| Redir::DupFd { src: fd.unwrap_or(1), dst }),
preceded(">&", (ws, word)).map(|(_, target)| Redir::Write { fd: 1, target, mode: WriteMode::TruncateBoth }),
preceded(">|", (ws, word)).map(move |(_, target)| Redir::Write { fd: fd.unwrap_or(1), target, mode: WriteMode::Clobber }),
preceded('>', (ws, word)).map(move |(_, target)| Redir::Write { fd: fd.unwrap_or(1), target, mode: WriteMode::Truncate }),
preceded("<>", (ws, word)).map(move |(_, target)| Redir::ReadWrite { fd: fd.unwrap_or(0), target }),
preceded('<', (ws, word)).map(move |(_, target)| Redir::Read { fd: fd.unwrap_or(0), target }),
))
.parse_next(input)
}
fn heredoc(input: &mut &str) -> ModalResult<Redir> {
"<<".parse_next(input)?;
let strip_tabs = opt('-').parse_next(input)?.is_some();
ws.parse_next(input)?;
let before = input.len();
let delimiter = heredoc_delimiter.parse_next(input);
scan(if delimiter.is_ok() { before - input.len() } else { before })?;
let (delimiter, expands) = delimiter?;
if delimiter.contains('\n') {
escape::refuse();
}
let start = heredocs::expected_body_start(input);
let body = if expands { heredoc_body_word(input, start, &delimiter, strip_tabs)? } else { Word(Vec::new()) };
let start = start.map_or(0, |s| s.as_ptr() as usize);
heredocs::push(heredocs::Pending { delimiter: delimiter.clone(), strip_tabs, joins: expands, start });
Ok(Redir::HereDoc { delimiter, strip_tabs, body })
}
fn heredoc_body_word(input: &str, start: Option<&str>, delimiter: &str, strip_tabs: bool) -> ModalResult<Word> {
let Some((body, after)) = start.and_then(|rest| heredocs::split_body(rest, delimiter, strip_tabs, true)) else {
scan(input.len())?;
return Ok(Word(Vec::new()));
};
scan(input.len() - after.len())?;
let mut text = body;
let parts: Vec<WordPart> = repeat(0.., heredoc_part).parse_next(&mut text)?;
if !text.is_empty() {
return backtrack();
}
Ok(Word(parts))
}
fn is_heredoc_literal(c: char) -> bool {
!matches!(c, '"' | '\\' | '`' | '$')
}
fn heredoc_part(input: &mut &str) -> ModalResult<WordPart> {
step()?;
if input.is_empty() {
return backtrack();
}
if input.starts_with('"') {
*input = &input[1..];
return Ok(WordPart::Lit("\"".to_string()));
}
alt((dq_escape, arith_sub, cmd_sub, backtick_part, dollar_lit(is_heredoc_literal), lit(is_heredoc_literal))).parse_next(input)
}
fn heredoc_delimiter(input: &mut &str) -> ModalResult<(String, bool)> {
alt((
delimited('\'', take_while(0.., |c| c != '\''), '\'').map(|s: &str| (s.to_string(), false)),
delimited('"', take_while(0.., |c| c != '"'), '"').map(|s: &str| (s.to_string(), false)),
escaped_delimiter,
take_while(1.., |c: char| c.is_ascii_alphanumeric() || c == '_').map(|s: &str| (s.to_string(), true)),
))
.parse_next(input)
}
fn escaped_delimiter(input: &mut &str) -> ModalResult<(String, bool)> {
let mut rest = *input;
let mut name = String::new();
let mut quoted = false;
let mut joined = false;
loop {
let mut chars = rest.chars();
match chars.next() {
Some('\\') if join_continuation(&mut rest) => joined = true,
Some('\\') => match chars.next() {
Some(c) => {
name.push(c);
quoted = true;
rest = &rest[1 + c.len_utf8()..];
}
None => break,
},
Some(q @ ('\'' | '"')) => {
let inner_end = rest[1..].find(q).map(|i| i + 1);
let Some(end) = inner_end else { break };
name.push_str(&rest[1..end]);
quoted = true;
rest = &rest[end + 1..];
}
Some(c) if c.is_ascii_alphanumeric() || c == '_' => {
name.push(c);
rest = &rest[c.len_utf8()..];
}
_ => break,
}
}
if !(quoted || joined) || name.is_empty() {
return backtrack();
}
*input = rest;
Ok((name, !quoted))
}
fn fd_prefix(input: &mut &str) -> ModalResult<u32> {
let b = input.as_bytes();
if b.len() >= 2 && b[0].is_ascii_digit() && matches!(b[1], b'>' | b'<') {
let d = (b[0] - b'0') as u32;
*input = &input[1..];
Ok(d)
} else {
backtrack()
}
}
fn word(input: &mut &str) -> ModalResult<Word> {
repeat(1.., word_part).map(Word).verify(|w: &Word| !only_continuations(&w.0)).parse_next(input)
}
fn word_part(input: &mut &str) -> ModalResult<WordPart> {
step()?;
if input.is_empty() {
return backtrack();
}
if input.starts_with("<(") || input.starts_with(">(") {
return proc_sub(input);
}
if is_word_boundary(input.as_bytes()[0] as char) {
return backtrack();
}
alt((
single_quoted,
double_quoted,
dollar_quoted,
arith_sub,
cmd_sub,
backtick_part,
escaped,
dollar_lit(is_word_literal),
lit(is_word_literal),
))
.parse_next(input)
}
fn single_quoted(input: &mut &str) -> ModalResult<WordPart> {
delimited_scan(input, '\'', |i| {
delimited('\'', take_while(0.., |c| c != '\''), '\'')
.map(|s: &str| WordPart::SQuote(s.to_string()))
.parse_next(i)
})
}
fn double_quoted(input: &mut &str) -> ModalResult<WordPart> {
delimited('"', repeat(0.., dq_part).map(Word), '"').map(WordPart::DQuote).parse_next(input)
}
fn dollar_quoted(input: &mut &str) -> ModalResult<WordPart> {
alt((super::ansi_c::ansi_c_quoted, |i: &mut &str| super::ansi_c::locale_quoted(i, double_quoted))).parse_next(input)
}
fn sub_body(input: &mut &str, open_len: usize) -> ModalResult<Script> {
let body = &input[open_len..];
let close = find_sub_close(body);
scan(close.map_or(2 * body.len(), |rel| 3 * rel))?;
let Some(rel) = close else {
return if body.contains("<<") { sub_body_via_grammar(input, body) } else { backtrack() };
};
let interior = &body[..rel];
if !interior.contains("<<") && !interior.contains("case") {
let mut fast: &str = interior;
let parsed = script.parse_next(&mut fast)?;
ws.parse_next(&mut fast)?;
if !fast.is_empty() {
return backtrack();
}
*input = &body[rel + 1..];
return Ok(parsed);
}
sub_body_via_grammar(input, body)
}
fn sub_body_via_grammar<'a>(input: &mut &'a str, body: &'a str) -> ModalResult<Script> {
let mut rest: &str = body;
ws.parse_next(&mut rest)?;
let parsed = script.parse_next(&mut rest)?;
ws.parse_next(&mut rest)?;
if !rest.starts_with(')') {
return backtrack();
}
*input = &rest[1..];
Ok(parsed)
}
fn cmd_sub(input: &mut &str) -> ModalResult<WordPart> {
if !input.starts_with("$(") {
return backtrack();
}
heredocs::own(|| sub_body(input, 2)).map(WordPart::CmdSub)
}
fn proc_sub(input: &mut &str) -> ModalResult<WordPart> {
if !(input.starts_with("<(") || input.starts_with(">(")) {
return backtrack();
}
heredocs::own(|| sub_body(input, 2)).map(WordPart::ProcSub)
}
fn arith_body_part(input: &mut &str) -> ModalResult<WordPart> {
step()?;
if input.is_empty() {
return backtrack();
}
alt((
dq_escape,
arith_sub,
cmd_sub,
backtick_part,
dollar_lit(is_heredoc_literal),
lit(is_heredoc_literal),
))
.parse_next(input)
}
fn arith_sub(input: &mut &str) -> ModalResult<WordPart> {
if !input.starts_with("$((") {
return backtrack();
}
let Some(_depth) = DepthGuard::enter() else {
return backtrack();
};
let body_start = 3;
let bytes = input.as_bytes();
let mut depth: i32 = 1;
let mut i = body_start;
while i < bytes.len() {
match bytes[i] {
b'(' => depth += 1,
b')' => {
if depth == 1 && i + 1 < bytes.len() && bytes[i + 1] == b')' {
scan(i)?;
let mut body = &input[body_start..i];
let parts: Vec<WordPart> = repeat(0.., arith_body_part).parse_next(&mut body)?;
if !body.is_empty() {
return backtrack();
}
*input = &input[i + 2..];
return Ok(WordPart::Arith(Word(parts)));
}
depth -= 1;
if depth < 0 {
scan(i)?;
return backtrack();
}
}
_ => {}
}
i += 1;
}
scan(i)?;
backtrack()
}
fn backtick_part(input: &mut &str) -> ModalResult<WordPart> {
delimited_scan(input, '`', |i| delimited('`', backtick_inner, '`').map(escape::backtick).parse_next(i))
}
fn delimited_scan<O>(input: &mut &str, open: char, p: impl FnOnce(&mut &str) -> ModalResult<O>) -> ModalResult<O> {
if !input.starts_with(open) {
return backtrack();
}
let before = input.len();
let out = p(input);
scan(if out.is_ok() { before - input.len() } else { before })?;
out
}
fn lit(pred: fn(char) -> bool) -> impl FnMut(&mut &str) -> ModalResult<WordPart> {
move |input: &mut &str| {
let s: &str = consumed(input, |i| take_while(1.., pred).parse_next(i))?;
Ok(WordPart::Lit(s.to_string()))
}
}
fn dollar_lit(pred: fn(char) -> bool) -> impl FnMut(&mut &str) -> ModalResult<WordPart> {
move |input: &mut &str| {
(not(escape::opens_function_substitution), '$', not('(')).void().parse_next(input)?;
let rest: &str = consumed(input, |i| take_while(0.., pred).parse_next(i))?;
Ok(WordPart::Lit(format!("${rest}")))
}
}
fn dq_part(input: &mut &str) -> ModalResult<WordPart> {
step()?;
if input.is_empty() || input.starts_with('"') {
return backtrack();
}
alt((dq_escape, arith_sub, cmd_sub, backtick_part, dollar_lit(is_dq_literal), lit(is_dq_literal))).parse_next(input)
}
fn backtick_inner(input: &mut &str) -> ModalResult<String> {
repeat(0.., alt((bt_escape, bt_literal)))
.fold(String::new, |mut acc, chunk: &str| {
acc.push_str(chunk);
acc
})
.parse_next(input)
}
fn bt_escape<'a>(input: &mut &'a str) -> ModalResult<&'a str> {
('\\', any).take().parse_next(input)
}
fn bt_literal<'a>(input: &mut &'a str) -> ModalResult<&'a str> {
take_while(1.., |c: char| c != '`' && c != '\\').parse_next(input)
}
fn for_cmd(input: &mut &str) -> ModalResult<Cmd> {
eat_keyword(input, "for")?;
ws.parse_next(input)?;
let var = name.parse_next(input)?;
ws.parse_next(input)?;
let items = if eat_keyword(input, "in").is_ok() {
ws.parse_next(input)?;
repeat(0.., terminated(word, ws)).parse_next(input)?
} else {
vec![]
};
let body = do_done_body.parse_next(input)?;
let redirs = trailing_redirs(input)?;
Ok(Cmd::For { var, items, body, redirs })
}
fn while_cmd(input: &mut &str) -> ModalResult<Cmd> {
eat_keyword(input, "while")?;
ws.parse_next(input)?;
let cond = script.parse_next(input)?;
let body = do_done_body.parse_next(input)?;
let redirs = trailing_redirs(input)?;
Ok(Cmd::While { cond, body, redirs })
}
fn until_cmd(input: &mut &str) -> ModalResult<Cmd> {
eat_keyword(input, "until")?;
ws.parse_next(input)?;
let cond = script.parse_next(input)?;
let body = do_done_body.parse_next(input)?;
let redirs = trailing_redirs(input)?;
Ok(Cmd::Until { cond, body, redirs })
}
fn do_done_body(input: &mut &str) -> ModalResult<Script> {
sep.parse_next(input)?;
eat_keyword(input, "do")?;
sep.parse_next(input)?;
let body = script.parse_next(input)?;
sep.parse_next(input)?;
eat_keyword(input, "done")?;
Ok(body)
}
fn if_cmd(input: &mut &str) -> ModalResult<Cmd> {
eat_keyword(input, "if")?;
ws.parse_next(input)?;
let mut branches = vec![cond_then_body.parse_next(input)?];
let mut else_body = None;
loop {
sep.parse_next(input)?;
if eat_keyword(input, "elif").is_ok() {
ws.parse_next(input)?;
branches.push(cond_then_body.parse_next(input)?);
} else if eat_keyword(input, "else").is_ok() {
sep.parse_next(input)?;
else_body = Some(script.parse_next(input)?);
break;
} else {
break;
}
}
sep.parse_next(input)?;
eat_keyword(input, "fi")?;
let redirs = trailing_redirs(input)?;
Ok(Cmd::If { branches, else_body, redirs })
}
fn cond_then_body(input: &mut &str) -> ModalResult<Branch> {
let cond = script.parse_next(input)?;
sep.parse_next(input)?;
eat_keyword(input, "then")?;
sep.parse_next(input)?;
let body = script.parse_next(input)?;
Ok(Branch { cond, body })
}
fn case_cmd(input: &mut &str) -> ModalResult<Cmd> {
eat_keyword(input, "case")?;
ws.parse_next(input)?;
let subject = word.parse_next(input)?;
blank.parse_next(input)?;
eat_keyword(input, "in")?;
let mut arms = Vec::new();
loop {
blank.parse_next(input)?;
if eat_keyword(input, "esac").is_ok() {
break;
}
let arm = case_arm.parse_next(input)?;
let had_terminator = opt(";;").parse_next(input)?.is_some();
arms.push(arm);
if !had_terminator {
blank.parse_next(input)?;
eat_keyword(input, "esac")?;
break;
}
}
let redirs = trailing_redirs(input)?;
Ok(Cmd::Case { subject, arms, redirs })
}
fn case_arm(input: &mut &str) -> ModalResult<CaseArm> {
blank.parse_next(input)?;
opt('(').parse_next(input)?;
let mut patterns = Vec::new();
loop {
ws.parse_next(input)?;
patterns.push(word.parse_next(input)?);
ws.parse_next(input)?;
if opt('|').parse_next(input)?.is_none() {
break;
}
}
')'.parse_next(input)?;
let body = script.parse_next(input)?;
blank.parse_next(input)?;
Ok(CaseArm { patterns, body })
}
fn blank(input: &mut &str) -> ModalResult<()> {
consumed(input, heredocs::skip_blank)
}
fn double_bracket_cmd(input: &mut &str) -> ModalResult<Cmd> {
if !input.starts_with("[[") {
return backtrack();
}
let bytes = input.as_bytes();
if bytes.len() < 3 || !matches!(bytes[2], b' ' | b'\t' | b'\n') {
return backtrack();
}
*input = &input[2..];
let mut words: Vec<Word> = Vec::new();
loop {
ws.parse_next(input)?;
if at_double_bracket_end(input) {
*input = &input[2..];
let redirs = trailing_redirs(input)?;
return Ok(Cmd::DoubleBracket { words, redirs });
}
if input.is_empty() {
return backtrack();
}
let w = bracket_word.parse_next(input)?;
words.push(w);
}
}
fn at_double_bracket_end(input: &str) -> bool {
if !input.starts_with("]]") {
return false;
}
let after = &input[2..];
after.is_empty() || after.starts_with([' ', '\t', '\n', ';', '&', '|', ')', '>', '<'])
}
fn bracket_word(input: &mut &str) -> ModalResult<Word> {
repeat(1.., bracket_word_part).map(Word).parse_next(input)
}
fn bracket_word_part(input: &mut &str) -> ModalResult<WordPart> {
step()?;
if input.is_empty() {
return backtrack();
}
if matches!(input.as_bytes()[0], b' ' | b'\t' | b'\n') {
return backtrack();
}
if at_double_bracket_end(input) {
return backtrack();
}
alt((
single_quoted,
double_quoted,
dollar_quoted,
arith_sub,
cmd_sub,
backtick_part,
escaped,
dollar_lit(is_bracket_literal),
bracket_lit,
))
.parse_next(input)
}
fn is_bracket_literal(c: char) -> bool {
!matches!(c, '\'' | '"' | '`' | '\\' | '$' | ' ' | '\t' | '\n')
}
fn bracket_lit(input: &mut &str) -> ModalResult<WordPart> {
let bytes = input.as_bytes();
let mut end = 0;
while end < bytes.len() {
let c = bytes[end] as char;
if !is_bracket_literal(c) {
break;
}
if c == ']' && at_double_bracket_end(&input[end..]) {
break;
}
end += 1;
}
scan(end)?;
if end == 0 {
return backtrack();
}
let lit = input[..end].to_string();
*input = &input[end..];
Ok(WordPart::Lit(lit))
}
fn name(input: &mut &str) -> ModalResult<String> {
run(input, |c| c.is_ascii_alphanumeric() || c == '_').map(String::from)
}
#[cfg(test)]
mod tests {
use super::budget::MAX_PARSE_WORK_CEILING;
#[test]
fn the_parse_work_budget_bounds_nesting_without_refusing_real_commands() {
let worst_real = crate::registry::corpus_examples()
.into_iter()
.flat_map(|(_, safe, denied)| safe.iter().chain(denied.iter()).cloned().collect::<Vec<_>>())
.map(|ex| {
let _ = super::parse(&ex);
budget::work()
})
.max()
.expect("the registry ships examples");
assert!(
worst_real * 100 < MAX_PARSE_WORK_CEILING,
"a real example needs {worst_real} entries against a {MAX_PARSE_WORK_CEILING} ceiling; \
the margin that makes this constant safe is gone"
);
let flat = format!("echo {}", "$((1)) ".repeat(400));
let _ = super::parse(&flat);
let flat_work = budget::work();
assert!(
flat_work < MAX_PARSE_WORK_CEILING / 10,
"flat input cost {flat_work}, close to the {MAX_PARSE_WORK_CEILING} ceiling — a long \
flat command is at risk of being refused"
);
let work_at = |depth: usize| {
let deep = format!("echo {}1{}", "$((1+".repeat(depth), "))".repeat(depth));
let _ = super::parse(&deep);
assert!(budget::spent(), "the nest should actually reach a bound, or this proves nothing");
budget::work()
};
let (w2k, w4k) = (work_at(2000), work_at(4000));
assert!(w4k <= w2k + w2k / 10, "work still scales with input length: depth 2000 used {w2k}, depth 4000 used {w4k}");
assert!(w4k < MAX_PARSE_WORK_CEILING + MAX_PARSE_WORK_CEILING / 10, "work {w4k} ran far past the {MAX_PARSE_WORK_CEILING} ceiling");
}
use super::*;
#[test]
fn unclosed_compound_nesting_costs_linear_work() {
let unclosed = |opener: &str| match opener {
"{" => "{\n",
"[[" => "[[ a\n",
"if" => "if a; then\n",
"for" => "for x in a; do\n",
"while" => "while a; do\n",
"until" => "until a; do\n",
"case" => "case x in a)\n",
"function" => "function f {\n",
other => panic!("no unclosed form for the reserved word {other:?}; add one here"),
};
let tail = "\"$([[ <<\"\"<\"$( [[ x ]] ) $(ls <<EOF\n)\nEOF\n)\" ls";
let openers = super::super::reserved::BLANK_OPENERS.iter().chain(super::super::reserved::KEYWORD_OPENERS.iter());
for opener in openers {
let unit = unclosed(opener);
for prefix in [unit.to_string(), format!("{unit}{{\n")] {
for depth in [10u64, 20, 40] {
let text = format!("{}{tail}", prefix.repeat(depth as usize));
let _ = parse(&text);
let work = budget::work();
assert!(
work <= 4 * depth + 64,
"{depth} nested unclosed {prefix:?} cost {work} parse entries, more than \
linear in the nesting: a failed compound is being re-read another way"
);
}
}
}
}
#[test]
fn refused_substitution_nesting_costs_linear_work() {
for refused in ["[[ a", "{ a", "if a", "a; }"] {
for (open, close) in [("$(", ")"), ("\"$(", ")\""), ("<(", ")")] {
for depth in [10u64, 20, 40] {
let n = depth as usize;
let text = format!("echo {}x{}", format!("{open}{refused} ").repeat(n), close.repeat(n));
let _ = parse(&text);
let work = budget::work();
assert!(
work <= 4 * depth + 64,
"{depth} nested {open}{refused} cost {work} parse entries, more than linear: \
a refused interior is being parsed a second time"
);
}
}
}
}
#[test]
fn a_backtracking_nest_over_a_long_tail_is_stopped_by_what_it_reads() {
let tail = "a ".repeat(50_000);
for (open, close) in [("$(( $({ ", ") ))"), ("\"$(( $( [[ ", ") ))\"")] {
let text = format!("echo {}x {tail}{}", open.repeat(20), close.repeat(20));
assert!(parse(&text).is_none(), "{open:?} nest parsed");
assert!(budget::spent(), "{open:?} nest was refused, but not by the budget");
let work = budget::work();
assert!(work < 1_000, "{open:?} nest ran {work} entries before the step budget stopped it");
}
}
#[test]
fn the_explain_render_timeout_seed_scales_linearly_in_its_braces() {
let seed = include_bytes!("../../fuzz/corpus/explain_render/seed-unclosed-brace-nest");
let seed = String::from_utf8_lossy(seed);
let body = seed.split('`').nth(1).expect("the seed carries a backtick body");
let deep = body.find("$([[").expect("the seed's tail opens a `$([[`");
let tail = &body[body[..deep].rfind("\n{").expect("the nest ends before the tail") + 2..];
let cost = |k: usize| {
let _ = parse(&format!("{}{tail}", "{\n".repeat(k)));
assert!(!budget::spent(), "{k} braces spent the budget; the nest is not linear");
(budget::work(), budget::steps())
};
let [(w10, s10), (w20, s20), (w40, s40)] = [cost(10), cost(20), cost(40)];
assert!(w40 - w20 <= 2 * (w20 - w10) + 4, "entries {w10}/{w20}/{w40} for 10/20/40 braces");
assert!(s40 - s20 <= 2 * (s20 - s10) + 16, "steps {s10}/{s20}/{s40} for 10/20/40 braces");
assert!(!crate::is_safe_command(&seed));
}
proptest::proptest! {
#![proptest_config(proptest::prelude::ProptestConfig::with_cases(300))]
#[test]
fn a_random_unclosed_nest_parses_in_linear_work(
opener in proptest::sample::select(OPENERS.to_vec()),
depth in 0..24usize,
mixed in proptest::collection::vec(proptest::sample::select(OPENERS.to_vec()), 0..8),
tail in proptest::collection::vec(proptest::sample::select(vec![
"}", " ]]", "fi", "done", ";;", "esac", ")", "\"", "<<", "<<E\n", "\n", ";", "a ",
"$(", "[[ ", "`",
]), 0..24),
closes in 0..24usize,
) {
let input = format!(
"{}{}{}{}", opener.repeat(depth), mixed.concat(), tail.concat(), ")".repeat(closes)
);
let _ = parse(&input);
let work = budget::work();
let tokens = (depth + mixed.len() + tail.len() + closes) as u64;
proptest::prop_assert!(!budget::spent(), "spent the budget on {input:?}");
proptest::prop_assert!(work <= 4 * tokens + 16, "{work} entries for {tokens} tokens: {input:?}");
}
}
const OPENERS: [&str; 14] = [
"{\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", "$(",
"\"$(", "<(", "$([[ ", "$({ ",
];
#[test]
fn committed_command_seeds_parse_in_linear_work() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("fuzz/corpus");
let mut checked = 0;
for target in ["parse", "explain_render"] {
let dir = std::fs::read_dir(root.join(target)).expect("the fuzz corpus is committed");
for path in dir.flatten().map(|e| e.path()) {
if !path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with("seed-")) {
continue;
}
let text = String::from_utf8_lossy(&std::fs::read(&path).expect("readable seed")).into_owned();
for piece in std::iter::once(text.as_str()).chain(text.split('`').skip(1).step_by(2)) {
let _ = parse(piece);
let (work, len) = (budget::work(), piece.len() as u64);
assert!(!budget::spent(), "{} spent the parse budget", path.display());
assert!(work <= len + 16, "{} cost {work} entries for {len} bytes", path.display());
}
checked += 1;
}
}
assert!(checked >= 16, "only {checked} seeds found; the corpus has moved");
}
#[test]
fn the_step_budget_refuses_nothing_real() {
for (_, safe, denied) in crate::registry::corpus_examples() {
for example in safe.iter().chain(denied.iter()) {
let _ = parse(example);
assert!(!budget::spent(), "a registry example spent the step budget: {example}");
}
}
let message = "it's a line of prose (with parens) and $vars\n".repeat(5_000);
for text in [format!("git commit -m \"$(cat <<'EOF'\n{message}EOF\n)\""), "ls -la foo/bar; ".repeat(20_000)] {
assert!(parse(&text).is_some(), "a long real command no longer parses");
let (steps, len) = (budget::steps(), text.len() as u64);
assert!(
steps * 4 < budget::STEPS_PER_BYTE * len,
"{len} bytes of ordinary input spent {steps} steps, within 4x of the allowance"
);
}
}
fn p(input: &str) -> Script {
parse(input).unwrap_or_else(|| panic!("failed to parse: {input}"))
}
fn words(script: &Script) -> Vec<String> {
match &script.0[0].pipeline.commands[0] {
Cmd::Simple(s) => s.words.iter().map(|w| w.eval()).collect(),
_ => panic!("expected simple command"),
}
}
fn simple(script: &Script) -> &SimpleCmd {
match &script.0[0].pipeline.commands[0] {
Cmd::Simple(s) => s,
_ => panic!("expected simple command"),
}
}
#[test]
fn simple_command() {
assert_eq!(words(&p("echo hello")), ["echo", "hello"]);
}
#[test]
fn flags() {
assert_eq!(words(&p("ls -la")), ["ls", "-la"]);
}
#[test]
fn single_quoted() {
assert_eq!(words(&p("echo 'hello world'")), ["echo", "hello world"]);
}
#[test]
fn double_quoted() {
assert_eq!(words(&p("echo \"hello world\"")), ["echo", "hello world"]);
}
#[test]
fn mixed_quotes() {
assert_eq!(words(&p("jq '.key' file.json")), ["jq", ".key", "file.json"]);
}
#[test]
fn pipeline_test() {
assert_eq!(p("grep foo | head -5").0[0].pipeline.commands.len(), 2);
}
#[test]
fn sequence_and() {
assert_eq!(p("ls && echo done").0[0].op, Some(ListOp::And));
}
#[test]
fn sequence_semi() {
assert_eq!(p("ls; echo done").0.len(), 2);
}
#[test]
fn newline_separator() {
assert_eq!(p("echo foo\necho bar").0.len(), 2);
}
#[test]
fn blank_line_between_statements() {
assert_eq!(p("echo foo\n\necho bar").0.len(), 2);
}
#[test]
fn multiple_blank_lines() {
assert_eq!(p("echo foo\n\n\n\necho bar").0.len(), 2);
}
#[test]
fn blank_line_with_whitespace() {
assert_eq!(p("echo foo\n \necho bar").0.len(), 2);
}
#[test]
fn comment_between_statements() {
assert_eq!(p("echo foo\n# comment\necho bar").0.len(), 2);
}
#[test]
fn semi_then_blank() {
assert_eq!(p("echo foo;\n\necho bar").0.len(), 2);
}
#[test]
fn and_then_blank() {
assert_eq!(p("echo foo &&\n\necho bar").0.len(), 2);
}
#[test]
fn brace_group_simple() {
assert!(matches!(
&p("{ echo hello; }").0[0].pipeline.commands[0],
Cmd::BraceGroup { body, redirs } if body.0.len() == 1 && redirs.is_empty()
));
}
#[test]
fn brace_group_multiple_stmts() {
if let Cmd::BraceGroup { body, .. } = &p("{ echo a; echo b; echo c; }").0[0].pipeline.commands[0] {
assert_eq!(body.0.len(), 3);
} else {
panic!("expected BraceGroup");
}
}
#[test]
fn brace_group_with_redirect() {
if let Cmd::BraceGroup { redirs, .. } = &p("{ echo a; echo b; } > /tmp/out.txt").0[0].pipeline.commands[0] {
assert_eq!(redirs.len(), 1);
assert!(matches!(redirs[0], Redir::Write { .. }));
} else {
panic!("expected BraceGroup");
}
}
#[test]
fn brace_group_with_append_redirect() {
if let Cmd::BraceGroup { redirs, .. } = &p("{ echo a; } >> log.txt").0[0].pipeline.commands[0] {
assert!(matches!(redirs[0], Redir::Write { mode: WriteMode::Append, .. }));
} else {
panic!("expected BraceGroup");
}
}
#[test]
fn brace_group_with_stderr_redirect() {
if let Cmd::BraceGroup { redirs, .. } = &p("{ echo a; } 2>&1").0[0].pipeline.commands[0] {
assert!(matches!(redirs[0], Redir::DupFd { src: 2, .. }));
} else {
panic!("expected BraceGroup");
}
}
#[test]
fn brace_group_newline_separated() {
if let Cmd::BraceGroup { body, .. } = &p("{\n echo a\n echo b\n}").0[0].pipeline.commands[0] {
assert_eq!(body.0.len(), 2);
} else {
panic!("expected BraceGroup");
}
}
#[test]
fn time_keyword_prefixes_a_compound() {
for (src, want_subshell) in [("time (ls)", true), ("time -p (ls)", true), ("time { ls; }", false)] {
let pl = &p(src).0[0].pipeline;
assert_eq!(pl.commands.len(), 1, "{src}: one compound command");
if want_subshell {
assert!(matches!(&pl.commands[0], Cmd::Subshell { .. }), "{src}: kept the subshell");
} else {
assert!(matches!(&pl.commands[0], Cmd::BraceGroup { .. }), "{src}: kept the group");
}
}
let pl = &p("time (ls | head -5)").0[0].pipeline;
assert!(matches!(&pl.commands[0], Cmd::Subshell { .. }));
let pl = &p("time ls").0[0].pipeline;
assert!(matches!(&pl.commands[0], Cmd::Simple(_)), "time ls stays a simple command");
let pl = &p("timeout 5 ls").0[0].pipeline;
assert!(matches!(&pl.commands[0], Cmd::Simple(_)), "timeout is not the time keyword");
let pl = &p("! time (ls)").0[0].pipeline;
assert!(pl.bang, "the bang survives the time keyword");
assert!(matches!(&pl.commands[0], Cmd::Subshell { .. }), "and the compound survives too");
}
#[test]
fn brace_group_in_pipeline() {
let pl = &p("{ echo a; echo b; } | grep a").0[0].pipeline;
assert_eq!(pl.commands.len(), 2);
assert!(matches!(&pl.commands[0], Cmd::BraceGroup { .. }));
}
#[test]
fn brace_group_followed_by_other() {
let stmts = &p("{ echo a; }; echo b").0;
assert_eq!(stmts.len(), 2);
assert!(matches!(&stmts[0].pipeline.commands[0], Cmd::BraceGroup { .. }));
}
#[test]
fn brace_group_nested() {
if let Cmd::BraceGroup { body, .. } = &p("{ { echo inner; }; echo outer; }").0[0].pipeline.commands[0] {
assert_eq!(body.0.len(), 2);
assert!(matches!(&body.0[0].pipeline.commands[0], Cmd::BraceGroup { .. }));
} else {
panic!("expected outer BraceGroup");
}
}
#[test]
fn brace_group_with_subshell_inside() {
if let Cmd::BraceGroup { body, .. } = &p("{ (echo sub); echo grp; }").0[0].pipeline.commands[0] {
assert_eq!(body.0.len(), 2);
assert!(matches!(&body.0[0].pipeline.commands[0], Cmd::Subshell { .. }));
} else {
panic!("expected BraceGroup");
}
}
#[test]
fn brace_open_requires_whitespace() {
let cmds = &p("{echo a}").0;
if !cmds.is_empty() {
assert!(!matches!(&cmds[0].pipeline.commands[0], Cmd::BraceGroup { .. }));
}
}
#[test]
fn subshell_with_redirect() {
if let Cmd::Subshell { redirs, .. } = &p("(echo hello) > /tmp/out.txt").0[0].pipeline.commands[0] {
assert_eq!(redirs.len(), 1);
} else {
panic!("expected Subshell with redir");
}
}
#[test]
fn for_loop_with_redirect() {
if let Cmd::For { redirs, .. } = &p("for f in a b; do echo $f; done 2>/dev/null").0[0].pipeline.commands[0] {
assert_eq!(redirs.len(), 1);
} else {
panic!("expected For with redir");
}
}
#[test]
fn for_loop_redirect_then_pipe() {
let pl = &p("for f in a b; do echo $f; done 2>&1 | head -5").0[0].pipeline;
assert_eq!(pl.commands.len(), 2);
assert!(matches!(&pl.commands[0], Cmd::For { redirs, .. } if redirs.len() == 1));
}
#[test]
fn while_and_if_with_redirect() {
assert!(matches!(
&p("while true; do echo x; done 2>/dev/null").0[0].pipeline.commands[0],
Cmd::While { redirs, .. } if redirs.len() == 1
));
assert!(matches!(
&p("if true; then echo x; fi 2>&1").0[0].pipeline.commands[0],
Cmd::If { redirs, .. } if redirs.len() == 1
));
}
#[test]
fn background() {
assert_eq!(p("ls & echo done").0[0].op, Some(ListOp::Amp));
}
#[test]
fn redirect_dev_null() {
let s = p("echo hello > /dev/null");
let cmd = simple(&s);
assert_eq!(cmd.words.len(), 2);
assert!(matches!(&cmd.redirs[0], Redir::Write { fd: 1, mode: WriteMode::Truncate, .. }));
}
#[test]
fn redirect_stderr() {
assert!(matches!(&simple(&p("echo hello 2>&1")).redirs[0], Redir::DupFd { src: 2, dst } if dst == "1"));
}
#[test]
fn here_string() {
assert!(matches!(&simple(&p("grep -c , <<< 'hello,world,test'")).redirs[0], Redir::HereStr(_)));
}
#[test]
fn heredoc_bare() {
assert!(matches!(&simple(&p("cat <<EOF")).redirs[0], Redir::HereDoc { delimiter, strip_tabs: false, .. } if delimiter == "EOF"));
}
#[test]
fn heredoc_with_content() {
let s = p("cat <<EOF\nhello world\nEOF");
assert!(matches!(&simple(&s).redirs[0], Redir::HereDoc { delimiter, .. } if delimiter == "EOF"));
}
#[test]
fn heredoc_quoted_delimiter() {
assert!(matches!(&simple(&p("cat <<'EOF'")).redirs[0], Redir::HereDoc { delimiter, .. } if delimiter == "EOF"));
}
#[test]
fn heredoc_strip_tabs() {
assert!(matches!(&simple(&p("cat <<-EOF")).redirs[0], Redir::HereDoc { strip_tabs: true, .. }));
}
#[test]
fn heredoc_pipe_on_command_line() {
let s = p("cat <<EOF | grep hello\nhello\nEOF");
assert_eq!(s.0[0].pipeline.commands.len(), 2);
}
#[test]
fn heredoc_body_does_not_swallow_pipe() {
let s = p("cat <<EOF | bash\nrm\nEOF");
assert_eq!(s.0[0].pipeline.commands.len(), 2, "pipeline must keep `bash` as a second command");
}
#[test]
fn heredoc_followed_by_next_statement() {
let s = p("cat <<EOF\nhello\nEOF\nls");
assert_eq!(s.0.len(), 2);
}
#[test]
fn a_heredoc_body_starts_after_the_line_not_after_the_separator() {
for line in [
"cat <<EOF; rm -rf ~/x\nhi\nEOF",
"cat <<EOF && rm -rf ~/x\nhi\nEOF",
"cat <<EOF; echo ok\nhi $(rm -rf ~/x)\nEOF",
"cat <<EOF\nhi\nEOF\nrm -rf ~/x",
"cat <<EOF\necho $(rm -rf ~/x)",
"cat <<EOF; echo \"a\nEOF\n\"\n$(rm -rf ~/x)\nEOF",
"cat <<EOF; echo $(\nrm -rf ~/x\nEOF\necho)",
"echo $(cat <<EOF)\nrm -rf ~/x\nEOF",
"cat <<true; echo \"[$(cat <<'ls')]\"\ntrue\nls\necho '$(rm -rf ~/x)'\ntrue",
"echo \"[$(cat <<'ls')]\"\nls\necho hi",
] {
assert!(!crate::is_safe_command(line), "{line:?} must not approve");
}
for line in [
"cat <<EOF; echo ok\nhi\nEOF",
"cat <<EOF | grep h\nhi\nEOF",
"cat <<EOF;\nhi\nEOF\necho done",
"cat <<EOF &&\nhi\nEOF\necho done",
"cat <<A <<B; echo x\na\nA\nb\nB",
"{ cat <<EOF; }\nhi\nEOF",
"x=$(cat <<EOF\nhi\nEOF\n); echo $x",
"cat <<true; echo \"[`cat <<'ls'`]\"\ntrue\nls\necho '$(rm -rf ~/x)'\ntrue",
] {
assert!(crate::is_safe_command(line), "{line:?} should approve");
}
assert_eq!(p("cat <<EOF; ls\nhi\nEOF").0.len(), 2);
}
#[test]
fn env_prefix() {
let s = p("FOO='bar baz' ls -la");
let cmd = simple(&s);
assert_eq!(cmd.env[0].0, "FOO");
assert_eq!(cmd.env[0].1.eval(), "bar baz");
}
#[test]
fn an_appending_assignment_is_the_old_value_followed_by_the_new() {
for (src, name, value) in [
("PATH+=:/tmp/evil; ls", "PATH", "${PATH}:/tmp/evil"),
("LD_PRELOAD+=/tmp/e.so ls", "LD_PRELOAD", "${LD_PRELOAD}/tmp/e.so"),
("X+='a b'", "X", "${X}a b"),
("X+=", "X", "${X}"),
] {
let s = p(src);
let cmd = simple(&s);
assert_eq!((cmd.env[0].0.as_str(), cmd.env[0].1.eval().as_str()), (name, value), "{src}");
}
}
#[test]
fn cmd_substitution() {
assert!(matches!(&simple(&p("echo $(ls)")).words[1].0[0], WordPart::CmdSub(_)));
}
#[test]
fn backtick_substitution() {
assert_eq!(simple(&p("ls `pwd`")).words[1].eval(), "__SAFE_CHAINS_CMDSUB_WORKTREE__");
assert_eq!(simple(&p("ls `hostname`")).words[1].eval(), "__SAFE_CHAINS_CMDSUB__");
}
#[test]
fn nested_substitution() {
if let WordPart::CmdSub(inner) = &simple(&p("echo $(echo $(ls))")).words[1].0[0] {
assert!(matches!(&simple(inner).words[1].0[0], WordPart::CmdSub(_)));
} else {
panic!("expected CmdSub");
}
}
#[test]
fn subshell_test() {
assert!(matches!(&p("(echo hello)").0[0].pipeline.commands[0], Cmd::Subshell { .. }));
}
#[test]
fn negation() {
assert!(p("! echo hello").0[0].pipeline.bang);
}
#[test]
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"));
}
#[test]
fn while_loop() {
assert!(matches!(&p("while test -f /tmp/foo; do sleep 1; done").0[0].pipeline.commands[0], Cmd::While { .. }));
}
#[test]
fn if_then_fi() {
if let Cmd::If { branches, else_body, .. } = &p("if test -f foo; then echo exists; fi").0[0].pipeline.commands[0] {
assert_eq!(branches.len(), 1);
assert!(else_body.is_none());
} else {
panic!("expected If");
}
}
#[test]
fn if_elif_else() {
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]
{
assert_eq!(branches.len(), 2);
assert!(else_body.is_some());
} else {
panic!("expected If");
}
}
#[test]
fn escaped_outside_quotes() {
assert_eq!(words(&p("echo hello\\ world")), ["echo", "hello world"]);
}
#[test]
fn a_line_continuation_joins_a_word() {
assert_eq!(words(&p("imp\\\nort a")), ["import", "a"]);
assert_eq!(words(&p("echo \"incl\\\nude\"")), ["echo", "include"]);
assert_eq!(words(&p("echo 'incl\\\nude'")), ["echo", "incl\\\nude"]);
}
#[test]
fn a_line_continuation_between_words_is_whitespace() {
assert_eq!(words(&p("echo a \\\n b")), ["echo", "a", "b"]);
assert_eq!(words(&p("echo a\\\n b")), ["echo", "a", "b"]);
assert_eq!(words(&p("echo \\\n\\\nb")), ["echo", "b"]);
}
#[test]
fn double_quoted_escape() {
assert_eq!(words(&p("echo \"hello\\\"world\"")), ["echo", "hello\"world"]);
}
#[test]
fn assign_subst() {
assert_eq!(simple(&p("out=$(ls)")).env[0].0, "out");
}
#[test]
fn unmatched_single_quote_fails() {
assert!(parse("echo 'hello").is_none());
}
#[test]
fn unmatched_double_quote_fails() {
assert!(parse("echo \"hello").is_none());
}
#[test]
fn unclosed_subshell_fails() {
assert!(parse("(echo hello").is_none());
}
#[test]
fn unclosed_cmd_sub_fails() {
assert!(parse("echo $(ls").is_none());
}
#[test]
fn for_missing_do_fails() {
assert!(parse("for x in 1 2 3; echo $x; done").is_none());
}
#[test]
fn if_missing_fi_fails() {
assert!(parse("if true; then echo hello").is_none());
}
#[test]
fn subshell_for() {
if let Cmd::Subshell { body, .. } = &p("(for x in 1 2; do echo $x; done)").0[0].pipeline.commands[0] {
assert!(matches!(&body.0[0].pipeline.commands[0], Cmd::For { .. }));
} else {
panic!("expected Subshell");
}
}
#[test]
fn proc_sub_input() {
let s = p("diff <(sort a.txt) <(sort b.txt)");
let cmd = simple(&s);
assert_eq!(cmd.words.len(), 3);
assert!(matches!(&cmd.words[1].0[0], WordPart::ProcSub(_)));
assert!(matches!(&cmd.words[2].0[0], WordPart::ProcSub(_)));
}
#[test]
fn proc_sub_output() {
let s = p("tee >(grep error > /dev/null)");
let cmd = simple(&s);
assert_eq!(cmd.words.len(), 2);
assert!(matches!(&cmd.words[1].0[0], WordPart::ProcSub(_)));
}
fn func_def(s: &Script) -> (&str, &Script) {
match &s.0[0].pipeline.commands[0] {
Cmd::FunctionDef { name, body } => (name.as_str(), body),
other => panic!("expected FunctionDef, got {other:?}"),
}
}
#[test]
fn function_def_posix_form() {
let s = p("probe(){ echo hi; }");
let (name, body) = func_def(&s);
assert_eq!(name, "probe");
assert_eq!(words(body), ["echo", "hi"]);
}
#[test]
fn function_def_spaced_and_keyword_forms() {
assert_eq!(func_def(&p("foo () { echo hi; }")).0, "foo");
assert_eq!(func_def(&p("function foo { echo hi; }")).0, "foo");
assert_eq!(func_def(&p("function foo () { echo hi; }")).0, "foo");
}
#[test]
fn function_def_subshell_body() {
let s = p("foo() ( echo sub )");
assert_eq!(func_def(&s).0, "foo");
}
#[test]
fn function_def_body_on_next_line() {
assert_eq!(func_def(&p("foo()\n{\n echo hi\n}")).0, "foo");
}
#[test]
fn function_def_name_with_dashes_and_dots() {
assert_eq!(func_def(&p("my-func.v2(){ echo hi; }")).0, "my-func.v2");
}
#[test]
fn plain_command_is_not_a_function_def() {
assert!(matches!(&p("ls -la").0[0].pipeline.commands[0], Cmd::Simple(_)));
assert!(matches!(&p("echo foo bar").0[0].pipeline.commands[0], Cmd::Simple(_)));
}
#[test]
fn function_def_roundtrips() {
let rendered = p("greet(){ echo hi; }").to_string();
assert!(parse(&rendered).is_some(), "did not reparse: {rendered}");
assert_eq!(func_def(&p(&rendered)).0, "greet");
}
#[test]
fn comment_only() {
let s = p("# just a comment");
assert!(s.0.is_empty());
}
#[test]
fn comment_before_command() {
let s = p("# comment\necho hello");
assert_eq!(words(&s), ["echo", "hello"]);
}
#[test]
fn inline_comment() {
let s = p("echo hello # this is a comment");
assert_eq!(words(&s), ["echo", "hello"]);
}
#[test]
fn comment_between_commands() {
let s = p("echo hello\n# middle comment\necho world");
assert_eq!(s.0.len(), 2);
}
#[test]
fn comment_after_semicolon() {
let s = p("echo hello; # comment\necho world");
assert_eq!(s.0.len(), 2);
}
#[test]
fn comment_in_for_loop() {
assert!(parse("for x in 1 2; do\n# loop body\necho $x\ndone").is_some());
}
#[test]
fn quoted_redirect_in_echo() {
let s = p("echo 'greater > than' test");
let cmd = simple(&s);
assert_eq!(cmd.words.len(), 3);
assert_eq!(cmd.redirs.len(), 0);
}
#[test]
fn parses_all_safe_commands() {
let cmds = [
"grep foo file.txt",
"cat /etc/hosts",
"jq '.key' file.json",
"base64 -d",
"ls -la",
"wc -l file.txt",
"ps aux",
"echo hello",
"cat file.txt",
"echo $(ls)",
"ls `pwd`",
"echo $(echo $(ls))",
"echo \"$(ls)\"",
"out=$(ls)",
"out=$(git status)",
"a=$(ls) b=$(pwd)",
"(echo hello)",
"(ls)",
"(ls && echo done)",
"(echo hello; echo world)",
"(ls | grep foo)",
"(echo hello) | grep hello",
"(ls) && echo done",
"((echo hello))",
"(for x in 1 2; do echo $x; done)",
"echo 'greater > than' test",
"echo '$(safe)' arg",
"FOO='bar baz' ls -la",
"FOO=\"bar baz\" ls -la",
"RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
"grep foo file.txt | head -5",
"cat file | sort | uniq",
"ls && echo done",
"ls; echo done",
"ls & echo done",
"grep -c , <<< 'hello,world,test'",
"cat <<EOF\nhello world\nEOF",
"cat <<'MARKER'\nsome text\nMARKER",
"cat <<-EOF\n\thello\nEOF",
"echo foo\necho bar",
"ls\ncat file.txt",
"git log --oneline -20 | head -5",
"echo hello > /dev/null",
"echo hello 2> /dev/null",
"echo hello >> /dev/null",
"git log > /dev/null 2>&1",
"ls 2>&1",
"cargo clippy 2>&1",
"git log < /dev/null",
"for x in 1 2 3; do echo $x; done",
"for f in *.txt; do cat $f | grep pattern; done",
"for x in 1 2 3; do; done",
"for x in 1 2; do echo $x; done; for y in a b; do echo $y; done",
"for x in 1 2; do for y in a b; do echo $x $y; done; done",
"for x in 1 2; do echo $x; done && echo finished",
"for x in $(seq 1 5); do echo $x; done",
"while test -f /tmp/foo; do sleep 1; done",
"while ! test -f /tmp/done; do sleep 1; done",
"until test -f /tmp/ready; do sleep 1; done",
"if test -f foo; then echo exists; fi",
"if test -f foo; then echo yes; else echo no; fi",
"if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
"for x in 1 2; do if test $x = 1; then echo one; fi; done",
"if true; then for x in 1 2; do echo $x; done; fi",
"diff <(sort a.txt) <(sort b.txt)",
"comm -23 file.txt <(sort other.txt)",
"cat <(echo hello)",
"# comment only",
"# comment\necho hello",
"echo hello # inline comment",
"echo one\n# between\necho two",
"! echo hello",
"! test -f foo",
"echo for; echo done; echo if; echo fi",
];
let mut failures = Vec::new();
for cmd in &cmds {
if parse(cmd).is_none() {
failures.push(*cmd);
}
}
assert!(failures.is_empty(), "failed on {} commands:\n{}", failures.len(), failures.join("\n"));
}
fn inner_sub(s: &Script) -> &Script {
match &simple(s).words[1].0[0] {
WordPart::CmdSub(inner) | WordPart::ProcSub(inner) => inner,
other => panic!("expected a substitution, got {other:?}"),
}
}
#[test]
fn cmd_sub_squote_paren_is_not_close() {
assert_eq!(words(inner_sub(&p("echo $(echo ')')"))), ["echo", ")"]);
}
#[test]
fn cmd_sub_dquote_paren_is_not_close() {
assert_eq!(words(inner_sub(&p("echo $(echo \")\")"))), ["echo", ")"]);
}
#[test]
fn cmd_sub_escaped_paren_is_not_close() {
assert_eq!(words(inner_sub(&p("echo $(echo \\))"))), ["echo", ")"]);
}
#[test]
fn cmd_sub_backtick_paren_is_not_close() {
let s = p("echo $(x `)` y)");
let inner = simple(inner_sub(&s));
assert_eq!(inner.words.len(), 3);
assert!(matches!(&inner.words[1].0[0], WordPart::Backtick(_)));
}
#[test]
fn cmd_sub_escaped_backtick_does_not_end_span() {
let s = p("echo $(`\\`)`)");
assert!(matches!(&simple(&s).words[1].0[0], WordPart::CmdSub(_)));
}
#[test]
fn proc_sub_squote_paren_is_not_close() {
assert_eq!(words(inner_sub(&p("cat <(grep ')' f)"))), ["grep", ")", "f"]);
}
#[test]
fn proc_sub_out_squote_paren_is_not_close() {
assert_eq!(words(inner_sub(&p("tee >(grep ')' f)"))), ["grep", ")", "f"]);
}
#[test]
fn cmd_sub_nested_picks_outer_close() {
let s = p("echo $(a $(b) c)");
let inner = simple(inner_sub(&s));
assert_eq!(inner.words.len(), 3);
assert!(matches!(&inner.words[1].0[0], WordPart::CmdSub(_)));
}
#[test]
fn cmd_sub_literal_after_close_stays_in_outer_word() {
let s = p("echo $(ls)tail");
let w = &simple(&s).words[1];
assert_eq!(w.0.len(), 2);
assert!(matches!(&w.0[0], WordPart::CmdSub(_)));
assert!(matches!(&w.0[1], WordPart::Lit(s) if s == "tail"));
}
#[test]
fn cmd_sub_heredoc_body_paren_does_not_close() {
let s = p("x=$(cat <<EOF\na)b\nEOF\n)");
assert!(matches!(&simple(&s).env[0].1.0[0], WordPart::CmdSub(_)));
}
#[test]
fn cmd_sub_with_only_a_quoted_paren_is_unclosed() {
assert!(parse("echo $(echo ')").is_none());
}
#[test]
fn proc_sub_with_only_a_quoted_paren_is_unclosed() {
assert!(parse("cat <(grep ')").is_none());
}
}