Sub topic 6
Repetitions, Separators, and Optional Trailing Commas
This chapter assumes you can write a macro_rules! macro with several arms, and that you know the expr and ident fragment specifiers and how a transcriber builds the expanded code. Here you will make macros accept any number of arguments.
The repetition syntax
A repetition has three parts:
$( pattern ) separator? operatorpatternis any matcher or transcriber fragment.separatoris an optional single token, such as,or;. It must not be a repetition operator.operatoris*(zero or more),+(one or more), or?(zero or one).
The ? operator takes no separator, because there is never a second match to separate from the first.
A variable-length macro
This is a simplified vec!:
macro_rules! my_vec {
() => {
Vec::new()
};
($($x:expr),+ $(,)?) => {{
let mut v = Vec::new();
$( v.push($x); )+
v
}};
}
fn main() {
let a: Vec<i32> = my_vec![];
let b = my_vec![1, 2, 3,];
println!("{:?} {:?}", a, b);
}The program prints [] [1, 2, 3].
$($x:expr),+matches one or more expressions separated by commas. Each match binds to$x.$(,)?matches zero or one comma at the end. This is how the macro accepts a trailing comma.- The empty-input case needs its own first arm because
+requires at least one item. - The transcriber's
$( v.push($x); )+repeats once per captured$x. The extra braces in{{ ... }}make the expansion a single block expression.
Separators in the transcriber
The transcriber can use a separator too. It is independent of the matcher's separator. Here the matcher splits on commas and the transcriber joins with +:
macro_rules! sum {
($($x:expr),* $(,)?) => {
0 $(+ $x)*
};
}
fn main() {
println!("{}", sum!(1, 2, 3,));
println!("{}", sum!());
}This prints 6 and 0. The leading 0 makes the empty case valid. With *, no separate empty arm is needed.
Depth must match
A variable captured inside a repetition must be used inside a repetition of the same depth. Using $x outside the $( ... ) in the transcriber is an error: variable 'x' is still repeating at this depth. Nesting works the same way. A variable captured in two nested repetitions must appear in two nested repetitions.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `my_vec![1, 2,]` fails to compile | The matcher has `,+` but no `$(,)?`. After the comma it expects another expression. | Add `$(,)?` after the repetition. |
| `` `?` macro repetition does not allow a separator `` | A separator was written before `?`. | Remove the separator. |
| `variable 'x' is still repeating at this depth` | The variable was used outside a repetition. | Wrap the use in `$( ... )*`. |
| `my_vec![]` fails with `+` | `+` requires at least one match. | Add an empty arm, or use `*`. |
Exercise
Write a macro max_of! that accepts one or more comma-separated expressions, with an optional trailing comma, and returns the largest. Which repetition operator do you use, and why not *?
Show answer
Use +, because the largest of zero values is undefined. One arm is ($x:expr) => { $x }; and the other is ($x:expr, $($rest:expr),+ $(,)?) => { { let a = $x; let b = max_of!($($rest),+); if a > b { a } else { b } } };. The macro is recursive. It peels off one expression and compares it with the maximum of the rest. Put the single-expression arm first so the recursion ends. A single expression with a trailing comma, such as max_of!(5,), is not matched by either arm, and the answer may point this out. Adding $(,)? to the first arm fixes it.