我见过的多个例子表明这应该是可能的,但显然不是:
lib.rs
:
#![feature(trace_macros)]
#[macro_export]
macro_rules! inner_macro (
(f32) => {"float"};
);
#[macro_export]
macro_rules! outer_macro {
($T:ty) => {
inner_macro!($T)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_nested() {
trace_macros!(true);
s1: String = String::from(outer_macro!(f32));
s2: String = String::from(inner_macro!(f32));
trace_macros!(false);
}
}
运行cargo test
给出以下输出:
error: no rules expected the token `f32`
--> src/lib.rs:11:22
|
4 | / macro_rules! inner_macro (
5 | | (f32) => {"float"};
6 | | );
| |__- when calling this macro
...
11 | inner_macro!($T)
| ^^ no rules expected the token `f32`
...
21 | s1: String = String::from(outer_macro!(f32));
| ----------------- in this macro invocation
这很令人困惑,因为似乎有一条规则需要 token f32
。
这两个宏的扩展轨迹也有注释。第一个不起作用:
= note: expanding `outer_macro! { f32 }`
= note: to `inner_macro ! ( f32 )`
= note: expanding `inner_macro! { f32 }`
而第二个是:
= note: expanding `inner_macro! { f32 }`
= note: to `"float"`
为什么第一次扩展inner_macro!
失败,而当它没有嵌套在另一个宏中时,完全相同的扩展成功?
编辑:如果我们手动执行替换,它会起作用并给出预期的输出:
macro_rules! unknown {
($T:ty) => {
inner_macro!(f32)
}
}