S-expression in Rust macro_rules

Viewed 212

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
}

1 Answers

You need a separate macros to parse arguments. Try this code:

#[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_arg!($left)), OP::Add, Box::new(ast_arg!($right)))
    };
}

#[macro_export]
macro_rules! ast_arg {
    ( ( $e:tt ) ) => (ast!($e));
    ( ( $($e:tt)* ) ) => ( ast!( $($e)* ) );
    ($e:expr) => (Expression::from($e));
}

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)); // also works now
}

Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e35fcd9aa7b126cd34aea6b33857e6c9

If you want to create Lisp-like language with macros check this project: https://github.com/JunSuzukiJapan/macro-lisp

Related