Sub topic 6
Repetitions, separators, and optional trailing commas
This chapter assumes you can write a basic macro_rules! macro with several arms and that you know the fragment specifiers expr, ident, and ty. Here you learn how a macro accepts input of variable length.
The repetition syntax
A repetition has three parts:
$( pattern ) separator? operatorpatternis any matcher, including fragments such as$x:expr.separatoris optional. It is a single token that must appear between repeats, usually,or;. It cannot be a delimiter ((,[,{) or another repetition operator.operatoris*,+, or?.
| Operator | Meaning | Repeats allowed |
|---|---|---|
| `*` | zero or more | 0 to any number |
| `+` | one or more | 1 to any number |
| `?` | optional | 0 or 1 |
The ? operator never takes a separator, because at most one repeat can occur.
The same syntax appears in the transcriber, where it produces output once per matched repeat.
A worked example: 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);
}This prints [] [1, 2, 3]. The second arm has two repetitions:
$($x:expr),+matches one or more expressions separated by commas. Each match is stored under$x.$(,)?matches zero or one comma. It is the optional trailing comma.
In the transcriber, $( v.push($x); )+ emits one v.push(...) statement for each captured $x. There is no separator here, so the statements follow one another.
The empty-input case is a separate arm because the second arm uses +. You could change + to * and drop the first arm, but the body would then build a mut vector even when empty, which triggers an unused_mut warning. Keeping the arms apart gives each case its own expansion.
Choosing a separator
A separator sits between repeats, so it never appears before the first repeat or after the last one. That is why a trailing comma needs its own $(,)?.
The same idea works for other punctuation. A macro that takes statements separated by semicolons can use ;:
macro_rules! run_all {
($($stmt:expr);* $(;)?) => {
$( $stmt; )*
};
}
fn main() {
run_all!(println!("one"); println!("two"););
}The separator can also be a multi-character token that the lexer treats as one token, such as =>:
macro_rules! hashmap {
($($k:expr => $v:expr),* $(,)?) => {{
let mut map = ::std::collections::HashMap::new();
$( map.insert($k, $v); )*
map
}};
}
fn main() {
let m = hashmap!{ "a" => 1, "b" => 2, };
println!("{}", m.len());
}Here => is part of the repeated pattern, and , is the separator between pairs. This prints 2.
Repetitions in the transcriber
The transcriber can repeat any code that contains at least one variable captured by a repetition. It can also include its own separator:
macro_rules! sum {
($($x:expr),* $(,)?) => {
0 $(+ $x)*
};
}
fn main() {
println!("{}", sum!(1, 2, 3,));
println!("{}", sum!());
}sum!(1, 2, 3,) expands to 0 + 1 + 2 + 3, and sum!() expands to 0. The leading 0 gives the empty case a valid value. The first program prints 6, the second 0.
A transcriber separator goes in the same position as in the matcher. For example, $( $x ),* in the output would write the captured values with commas between them. The separator in the transcriber does not need to match the one in the matcher, so you can match on , and emit +.
Several variables in one repetition
When one repetition captures more than one variable, they advance together, in lockstep:
macro_rules! print_pairs {
($($name:ident = $val:expr),* $(,)?) => {
$( println!("{} = {}", stringify!($name), $val); )*
};
}
fn main() {
print_pairs!(a = 1, b = 2 + 3);
}This prints a = 1 and b = 5. The first iteration uses the first $name with the first $val, and so on. If a transcriber repetition uses variables that matched a different number of times, the compiler rejects it:
error: meta-variable `a` repeats 2 times, but `b` repeats 3 timesOptional pieces with ?
Use ? for an optional part of the input. The transcriber can use it too, to emit extra code only when the piece was present:
macro_rules! point {
($x:expr, $y:expr $(, $z:expr)?) => {
($x, $y $(, $z)?)
};
}
fn main() {
println!("{:?}", point!(1, 2));
println!("{:?}", point!(1, 2, 3));
}The output is (1, 2) and then (1, 2, 3). The comma belongs inside the ? repetition, so it appears only if $z does.
Nested repetitions and depth
A repetition inside another repetition creates a variable with depth 2. Every variable has a depth equal to the number of repetitions that enclose it in the matcher. In the transcriber, you must use the variable inside the same number of repetitions.
macro_rules! matrix {
($([$($x:expr),* $(,)?]),* $(,)?) => {
vec![ $( vec![ $($x),* ] ),* ]
};
}
fn main() {
let m: Vec<Vec<i32>> = matrix![[1, 2], [3, 4]];
println!("{:?}", m);
}This prints [[1, 2], [3, 4]]. In the matcher, $x is inside two repetitions: the outer one over rows and the inner one over elements. In the transcriber, $($x),* is nested inside $( vec![ ... ] ),* to match. Each row gets its own inner vector.
Each inner row ends with its own optional $(,)?, and the whole list ends with another one. Rows may have different lengths, because each inner repetition is counted separately.
Common errors
| Error message | Cause | Fix |
|---|---|---|
| `variable 'x' is still repeating at this depth` | The transcriber uses a repeated variable outside any repetition | Wrap the use in `$( ... )*` |
| `attempted to repeat an expression containing no syntax variables matched as repeating at this depth` | A transcriber repetition contains no repeating variable | Include a captured variable, or remove the repetition |
| `meta-variable ... repeats N times, but ... repeats M times` | Variables with different counts in one transcriber repetition | Repeat them in separate repetitions, or change the matcher |
| `no rules expected the token ','` | A trailing comma was given but the matcher has no `$(,)?` | Add `$(,)?` |
| `local ambiguity when calling macro` | The parser cannot tell which arm part to take | Restructure the matcher; see the follow-set chapter |
The ambiguity error appears when a repetition can start with the same tokens as whatever follows it. For example, $($x:expr),* , $y:expr fails: after each comma, the parser cannot tell whether the next expression belongs to the repetition or is $y. Fragment follow rules cover this in the next chapter.
Design guidance
- Add
$(,)?to any macro that takes a comma-separated list. Rust code often puts one item per line with a trailing comma, and rustfmt adds it. - Use
+when empty input makes no sense, and give an explicit empty arm when it does but needs different output. - Prefer the simplest depth that fits. Depth 2 is rarely needed, and depth 3 usually means a helper macro would be clearer.
- Put separators in the pattern that the caller can see and remember, such as
=>for maps and;for statements.
Exercise
Write a macro max_of! that takes one or more comma-separated expressions, accepts an optional trailing comma, and returns the largest value using std::cmp::max. What arms do you need, and what does max_of!(3, 9, 4,) return?
Show answer
Use two arms: ($x:expr $(,)?) => { $x }; and ($x:expr, $($rest:expr),+ $(,)?) => { ::std::cmp::max($x, max_of!($($rest),+)) };. The first handles one value, and the second splits off the head and recurses on the tail. max_of!(3, 9, 4,) returns 9.
Exercise
A macro has the matcher ($($k:ident = $v:expr),*) and the transcriber $( let $k = $v; )* $( println!("{}", $v); )*. Why might this fail to compile or misbehave, and how would you fix it?
Show answer
It compiles, but $v is evaluated twice, once in each repetition, so any side effects in the expressions happen twice. It also has no optional trailing comma. Fix it by using only the first repetition and printing the bound name: $( let $k = $v; println!("{}", $k); )*, and add $(,)? to the matcher.