我可以在宏中通过多个规则重复匹配吗?

rin*_*ind 4 macros rust rust-macros

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

my_dsl! {
    foo <other tokens>;
    bar <other tokens>;
    foo <other tokens>;
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Jmb*_*Jmb 5

您应该阅读《Rust Macros 小书》,特别针对您的问题第 4.2 节:增量 TT 咀嚼者

例如:

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)*);
        }
    };
}
Run Code Online (Sandbox Code Playgroud)