Skip to main content

arb/
parser.rs

1//! Token stream -> command tree. A command is the run of args between two
2//! separators; the first arg is the verb. Block tokens are parsed recursively.
3
4use crate::ast::{Arg, Command};
5use crate::lexer::{lex, Tok};
6
7/// Parse spec source into a command tree.
8pub fn parse(src: &str) -> Result<Vec<Command>, String> {
9    let toks = lex(src)?;
10    parse_tokens(&toks)
11}
12
13fn parse_tokens(toks: &[Tok]) -> Result<Vec<Command>, String> {
14    let mut cmds = Vec::new();
15    let mut cur: Vec<Arg> = Vec::new();
16    for t in toks {
17        match t {
18            Tok::Sep => {
19                if !cur.is_empty() {
20                    cmds.push(finish(std::mem::take(&mut cur))?);
21                }
22            }
23            Tok::Word(w) => cur.push(Arg::Word(w.clone())),
24            Tok::Str(s) => cur.push(Arg::Str(s.clone())),
25            Tok::Block(raw) => cur.push(Arg::Block(parse(raw)?)),
26        }
27    }
28    if !cur.is_empty() {
29        cmds.push(finish(cur)?);
30    }
31    Ok(cmds)
32}
33
34fn finish(mut args: Vec<Arg>) -> Result<Command, String> {
35    let name = match args.first() {
36        Some(Arg::Word(s)) | Some(Arg::Str(s)) => s.clone(),
37        Some(Arg::Block(_)) => return Err("command cannot start with a block".into()),
38        None => return Err("empty command".into()),
39    };
40    args.remove(0);
41    Ok(Command { name, args })
42}