You can have ($left:tt == $right:expr)
, which matches 5 == 2 + 3
.
Of course it won’t match the other way, 2 + 3 == 5
, since expressions can contain ==
, so the parser has no way of knowing when to stop parsing expr
and when to parse ==
in the macro. But instead of an error, there can be a generic fallback in such case:
macro_rules! assert2 {
($left:tt == $right:expr) => {
match (&$left, &$right) {
(left_val, right_val) => if !(*left_val == *right_val) {
panic!("{0} == {1} was false\n\t{0} = {2:?}, {1} = {3:?}",
stringify!($left), stringify!($right),
left_val, right_val);
}
}
};
($right:expr) => {assert!($right)};
}
fn main() {
assert2!(5 == 2 + 3);
assert2!(2 + 3 == 5);
}