Macro group

Source
macro_rules! group {
    ($tokens:ident in $input:expr) => { ... };
}
Expand description

A macro to easily parse a delimited group.

Similar in concept to syn::parenthesized and family, but compatible with anything implementing the Delimiters trait.


enum Statement {
    Block(Block),
    Number(LitInt, Punct![";"]),
    // Other nodes
}

impl Parse for Statement {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        if input.peek(Punct!["{"]) {
            Ok(Statement::Block(input.parse()?))
        } else if input.peek(LitInt) {
            Ok(Statement::Number(input.parse()?, input.parse()?))
        } else {
            // Other nodes
        }
    }
}

struct Block {
    braces: Braces,
    statements: Vec<Statement>,
}

impl Parse for Block {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let content;
        Ok(Block {
            braces: group!(content in input),
            statements: parse_repeated(&content)?,
        })
    }
}

let ast: Statement = parse_string("{
    3; 5;
}".to_string()).unwrap();