没有;宏的结果必须是一个完整的语法结构,如表达式或项目。您绝对不能使用随机的语法位,例如逗号或右大括号。
您可以通过在获得完整的最终表达式之前不输出任何内容来解决此问题。看!
#![feature(trace_macros)]
macro_rules! pascal_impl {
/*
The input to this macro takes the following form:
```ignore
(
// The current output accumulator.
($($out:tt)*);
// The current additive prefix.
$prefix:expr;
// The remaining, comma-terminated elements.
...
)
```
*/
/*
Termination condition: there is no input left. As
such, dump the output.
*/
(
$out:expr;
$_prefix:expr;
) => {
$out
};
/*
Otherwise, we have more to scrape!
*/
(
($($out:tt)*);
$prefix:expr;
$e:expr, $($rest:tt)*
) => {
pascal_impl!(
($($out)* $prefix+$e,);
$prefix+$e;
$($rest)*
)
};
}
macro_rules! pascal {
($($es:expr),+) => { pascal_impl!((); 0; $($es),+,) };
}
trace_macros!(true);
fn main() {
println!("{:?}", pascal!(1, 2, 3, 4));
}
注意:要在稳定的编译器上使用它,您需要删除 #![feature(trace_macros)] 和 trace_macros!(true); 行。其他都应该没问题。
它的作用是递归地咀嚼输入,将部分(并且可能语义上无效)输出作为输入传递到下一级递归。这让我们可以建立一个“开放列表”,否则我们无法做到。
然后,一旦我们没有输入,我们只需将部分输出重新解释为完整的表达式,然后......完成。
我包含跟踪内容的原因是为了向您展示它运行时的样子:
pascal! { 1 , 2 , 3 , 4 }
pascal_impl! { ( ) ; 0 ; 1 , 2 , 3 , 4 , }
pascal_impl! { ( 0 + 1 , ) ; 0 + 1 ; 2 , 3 , 4 , }
pascal_impl! { ( 0 + 1 , 0 + 1 + 2 , ) ; 0 + 1 + 2 ; 3 , 4 , }
pascal_impl! { ( 0 + 1 , 0 + 1 + 2 , 0 + 1 + 2 + 3 , ) ; 0 + 1 + 2 + 3 ; 4 , }
pascal_impl! { ( 0 + 1 , 0 + 1 + 2 , 0 + 1 + 2 + 3 , 0 + 1 + 2 + 3 + 4 , ) ; 0 + 1 + 2 + 3 + 4 ; }
输出是:
(1, 3, 6, 10)
需要注意的一点:大量未注释的整数文字会导致编译时间急剧增加。如果发生这种情况,您可以通过简单地注释 all 整数文字(如 1i32)来解决它。