rustmacro-rules

How to use & and | signs in macro_rules pattern


I'm trying to write a simple macro like this, to facilitate the writing of my code

enum Term {
    Or(Box<Term>, Box<Term>),
    And(Box<Term>, Box<Term>),
    Value(u8),
}

macro_rules! term {
    ($value_1:expr & $value_2:expr) => {
        Term::And(Box::new($value_1), Box::new($value_2))
    };
    ($value_1:expr | $value_2: expr) => {
        Term::Or(Box::new($value_1), Box::new($value_2))
    };
    ($value: expr) => {
        Term::Value($value)
    };
}

However, I cannot put a & or | after an expr in my pattern. I tried using tt, but it didn't work because I'm not always just putting one token in my $value. pat_param doesn't seem to work with & either.
The only option that seems to work would be to use (($value_1:expr) & ($value_2:expr)), but if I could do without the extra parentheses, it'd be better.
Is there a way to do this?


Solution

  • & isn't allowed to avoid ambiguity, there is no way to have & as a token directly after an expr parameter in a declarative macro.

    expr and stmt may only be followed by one of: =>, ,, or ;.