by efaref · 4y ago · 0 comments
It's not stabilized yet, but RFC3086[1] introduces macro metavariable expressions, which make counting trivial!
The example macro becomes:
macro_rules! define_error {
($($err:ident,)*) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
$($err,)*
}
impl Error {
pub fn from_code(code: u32) -> Option<Error> {
match code {
$( ${index()} => Some(Error::$err), )*
_ => None,
}
}
}
};
}
You can see this in practice on the playground[2].[1]: https://github.com/rust-lang/rfcs/blob/master/text/3086-macr... [2]: https://play.rust-lang.org/?version=nightly&mode=debug&editi...
macro_rules! count {
() => (0);
($odd:tt ($a:tt $b:tt)*) => ((count!($($a)*) << 1) | 1);
(($a:tt $b:tt)*) => (count!($($a)*) << 1);
}
It uses bit twiddling to avoid generating very big AST and eventually crashing the compiler. Though I have to admit using `${count()}` is better.