1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
// `$(..)` repetition — 28% of the `macro_rules!` in a 400-crate sample. The
// matcher binds each fragment once per iteration, and the transcriber emits
// its body once per iteration, joined by the separator.
macro_rules! sum_all {
($($x:expr),*) => {
0 $(+ $x)*
};
}
macro_rules! max_of {
($first:expr $(, $rest:expr)*) => {{
let mut m = $first;
$( if $rest > m { m = $rest; } )*
m
}};
}
macro_rules! count_args {
($($x:expr),*) => {
0 $(+ { let _ = $x; 1 })*
};
}
macro_rules! pairs_sum {
($($a:expr => $b:expr),*) => {
0 $(+ $a * $b)*
};
}
fn main() {
println!("{}", sum_all!());
println!("{}", sum_all!(1));
println!("{}", sum_all!(1, 2, 3, 4));
// Precedence survives: each capture is parenthesised.
println!("{}", sum_all!(1 + 1, 2 * 3));
println!("{}", max_of!(3));
println!("{}", max_of!(3, 9, 2));
println!("{}", max_of!(-5, -9, -1));
println!("{}", count_args!(7, 8, 9));
println!("{}", count_args!());
println!("{}", pairs_sum!(2 => 3, 4 => 5));
}
|