Quantum Captures @Kivooeo
macro_rules! capture {
($e:expr) => {
transform!($e)
};
}
macro_rules! transform {
($a:tt + $b:tt) => {
$a * $b
};
($other:expr) => {
$other
};
}
fn main() {
let x = capture!(2 + 3);
eprintln!("{}", x);
}
Solution
5
Once a token is captured as an expression (:expr), it becomes opaque to macro pattern matching and cannot be destructured into its component tokens.
When capture!(2 + 3) is invoked, the $e:expr matcher captures 2 + 3 as a single expression token tree. This captured expression is then passed to transform!($e), which attempts to match it against the pattern $a:tt + $b:tt.
However, because $e was already captured as an :expr, it cannot be pattern-matched as separate tokens anymore. The first arm $a:tt + $b:tt fails to match, so the second arm $other:expr matches instead, and the expression 2 + 3 is returned as-is, evaluating to 5.