首页 > 解决方案 > 我可以通过宏中的多个规则重复匹配吗?

问题描述

我可以在 Rust 宏中重复匹配吗?我希望能够做类似的事情:

my_dsl! {
    foo <other tokens>;
    bar <other tokens>;
    foo <other tokens>;
    ...
}

基本上,任意数量的分号分隔语句,并且每个语句由不同的规则处理。

我知道我可以有几个foo!(),bar!()宏 - 每个语句,但理想情况下我想避免这种情况。

我在想是否可以捕获类似$($t:tt)*, 但不包括分号的内容,然后委托给其他宏?

标签: macrosrustrust-macros

解决方案


您应该阅读The Little Book of Rust Macros并专门针对您的问题第 4.2 节:Incremental TT munchers

例如:

macro_rules! my_dsl {
    () => {};
    (foo $name:ident; $($tail:tt)*) => {
        {
            println!(concat!("foo ", stringify!($name));
            my_dsl!($($tail)*);
        }
    };
    (bar $name:ident; $($tail:tt)*) => {
        {
            println!(concat!("bar ", stringify!($name));
            my_dsl!($($tail)*);
        }
    };
}

推荐阅读