I'm writing my own language compiler, and I want to describe AST as S-expression with my macro.
The following is the minimal sample code that doesn't work.
#[derive(Debug, PartialEq)]
pub enum Expression {
BinOP(Box<Expression>, OP, Box<Expression>),
Number(f64),
}
#[derive(Debug, PartialEq)]
pub enum OP {
Add,
}
macro_rules! ast {
(+ $left:tt $right:tt) => {
Expression::BinOP(Box::new(ast!($left)), OP::Add, Box::new(ast!($right)))
};
($other:tt) => {
Expression::from($other)
};
}
impl From<usize> for Expression {
fn from(u: usize) -> Self {
Expression::Number(u as f64)
}
}
fn main() {
dbg!(ast!(+ 1 2)); // this works.
dbg!(ast!(+ (+ 3 4) 2)); // error: expected expression, found `+`
// ^ expected expression
}