Sub topic 7
Follow-set rules and ambiguity errors
This chapter assumes you can write macro_rules! macros with several arms, use fragment specifiers such as expr, ident, and ty, and use repetitions with separators. It explains two families of compile errors that come from how the macro parser works: follow-set errors and ambiguity errors.
Why the parser has restrictions
The macro matcher reads the invocation from left to right, one token at a time, and never backs up. When a matcher reaches a fragment like $x:expr, it calls the real Rust expression parser. That parser consumes as many tokens as it can and returns. The matcher then moves on to whatever follows $x:expr in the pattern.
This creates a problem. Suppose a macro says $a:expr $b:expr and receives 1 - 2. The expression parser would take all of 1 - 2 as $a, and $b would have nothing left. Or it might stop after 1, leaving - 2 as a second expression. The macro author cannot tell which, and the answer could change when a later Rust version adds new expression syntax.
Rust avoids this by limiting which tokens may come directly after each fragment. These limits are the follow-set rules. The compiler checks them when it reads the macro definition, not when you invoke it. A macro that breaks them is rejected even if you never call it.
The follow-set table
Each fragment specifier has a set of tokens that may follow it in a matcher.
| Fragment | May be followed by | Column |
|---|---|---|
| `expr`, `stmt` | `=>`, `,`, `;` | |
| `pat` (2021 edition and later) | `=>`, `,`, `=`, `if`, `in` | |
| `pat_param` (and `pat` in 2018) | `=>`, `,`, `=`, `\ | `, `if`, `in` |
| `ty`, `path` | `{`, `[`, `=>`, `,`, `>`, `=`, `:`, `;`, `\ | `, `as`, `where`, or a `block` fragment |
| `vis` | `,`, an identifier other than `priv`, a token that can start a type, or an `ident`, `ty`, or `path` fragment | |
| `block`, `ident`, `item`, `lifetime`, `literal`, `meta`, `tt` | anything |
The pattern behind the table: fragments that parse open-ended syntax (expr, stmt, pat, ty, path) have the tightest limits. Fragments that are a single token or a delimited group (ident, lifetime, literal, tt, block) have none, because their end is unambiguous.
Reading a follow-set error
This macro tries to take two expressions side by side.
macro_rules! add_pair {
($a:expr $b:expr) => {
$a + $b
};
}The compiler rejects the definition with a message like this:
error: `$a:expr` is followed by `$b:expr`, which is not allowed for `expr` fragments
|
| ($a:expr $b:expr) => {
| ^^^^^^^ not allowed after `expr` fragments
|
= note: allowed there are: `=>`, `,` or `;`The note lists the allowed tokens, which is the row of the table for that fragment. You have three ways to fix the error.
- Put an allowed token between the fragments, such as a comma.
- Wrap each fragment in delimiters.
- Change the fragment to
ttoridentif you do not need a full expression.
Delimiters work because a closing ], ), or } ends the fragment unambiguously.
macro_rules! add_pair {
([$a:expr] [$b:expr]) => {
$a + $b
};
}
fn main() {
println!("{}", add_pair!([1 + 2] [3 * 4]));
}This prints 15. The matcher parses 1 + 2 as one expression, sees ], and then continues with the second group.
Restrictions apply across repetitions
Repetitions create follow positions that are not obvious from reading the pattern. In $($e:expr)*, an expr can be followed by another expr on the next iteration, so the compiler rejects it. With a separator, the separator is what follows.
macro_rules! sum {
($($e:expr),* $(,)?) => {
0 $(+ $e)*
};
}
fn main() {
println!("{}", sum!(1, 2, 3,));
}This prints 6. The , separator is in the allowed set for expr. The optional trailing $(,)? is also fine, because the comma is allowed after expr too.
The same reasoning explains why $($e:expr)=>* is accepted, while $($t:ty)+ is not. In the second case + is not in the follow set of ty, and a repetition of ty can also be followed by another ty.
A few common cases that fail:
$t:ty +is rejected because+is not in the follow set ofty.$p:pat | $q:patis rejected in the 2021 edition because|is part ofpatitself. Use$p:pat_param | $q:pat_paramto match alternatives yourself.$e:expr then $b:blockis rejected becausethenis an identifier, not an allowed token.
Using `ident` and `tt` as separators of intent
Because ident and tt have no follow restrictions, they are the usual way to build keyword-like syntax. This macro accepts name = value pairs with a literal =. The ident fragment can be followed by anything, and expr is followed by , or the end of the group.
macro_rules! config {
($($key:ident = $val:expr),* $(,)?) => {{
let mut out = Vec::new();
$( out.push((stringify!($key), $val.to_string())); )*
out
}};
}
fn main() {
let c = config!(port = 8080, host = "localhost",);
println!("{:?}", c);
}This prints [("port", "8080"), ("host", "localhost")].
Ambiguity errors
Follow-set errors are about the definition. Ambiguity errors happen when you invoke a macro, and they mean that at some point the matcher had more than one valid way to continue and could not choose.
The classic example is a list followed by a final item.
macro_rules! last_of {
($($i:ident)* $last:ident) => {
stringify!($last)
};
}This definition passes the follow-set check, because ident is unrestricted. The invocation last_of!(a b c) fails:
error: local ambiguity when calling macro `last_of`: multiple parsing options: built-in NTs ident ('i') or ident ('last').After matching a, the matcher sees b. It cannot know whether b is another $i or the final $last. Looking ahead to find the end of the input would be backtracking, which the matcher does not do.
You can remove the ambiguity in three ways:
- Add a distinct token before the last item, for example
$($i:ident)* ; $last:ident. - Reverse the structure, taking the first item and then the rest:
$first:ident $($rest:ident)*. - Use recursion to peel one item at a time. The next chapters cover this pattern.
Fragments commit, and rules do not fall through
A second rule explains many confusing errors. Once the matcher starts parsing a fragment, a parse failure inside the fragment is a hard error. It does not mean "this arm does not match, try the next one."
macro_rules! describe {
(struct $n:ident) => {
concat!("struct ", stringify!($n))
};
($e:expr) => {
"expression"
};
}
fn main() {
println!("{}", describe!(struct Foo));
println!("{}", describe!(1 + 2));
}This prints struct Foo and then expression. The literal struct arm is first. For 1 + 2, the first token 1 fails to match the literal struct before any fragment parser runs, so the matcher moves to the next arm.
If you swap the two arms, describe!(struct Foo) fails. The matcher tries $e:expr first and calls the expression parser on struct, which is a keyword that cannot start an expression. The result is an error such as expected expression, found keyword 'struct', and the second arm is never tried.
The rule of thumb: order arms from most specific to least specific, and put arms that start with literal tokens before arms that start with a broad fragment like expr, ty, or pat.
A decision process for these errors
Practical guidelines
- Check the table before choosing a fragment. If you need to follow
exprwith something other than,,;, or=>, plan to use delimiters. - Treat
$(...)*on a fragment with no separator as a warning sign forexpr,ty,pat, andstmt. Usettor a separator. - Prefer a leading keyword for each arm, such as
struct,fn, orlet, so arms are distinguishable from the first token. - When matching fails in a confusing way, reduce the macro to one arm and add arms back one at a time.
Exercise
Why does macro_rules! m { ($t:ty $e:expr) => { }; } fail to compile, and how would you change the matcher so the macro accepts m!(i32, 5)?
Show answer
In a matcher, ty may be followed only by {, [, =>, ,, >, =, :, ;, |, as, where, or a block fragment. The $e:expr fragment right after $t:ty is not in that set, so the compiler rejects the definition before any call. Insert a comma: ($t:ty, $e:expr) => { };. Then m!(i32, 5) matches, since , is allowed after ty.
Exercise
A macro has the arms ($e:expr) => { 1 }; followed by (let $n:ident) => { 2 };. Calling it as m!(let x) fails with "expected expression, found let statement". Explain the cause and give the fix.
Show answer
The first arm starts with an expr fragment, so the matcher runs the expression parser on let x. That parser fails, and a failure inside a fragment is a hard error, not a signal to try the next arm. Move the let arm first. Its leading let token is a literal, so for any input that does not start with let the arm fails before any fragment parser runs, and the matcher falls through to the expr arm.
Exercise
Why does ($($i:ident)* $last:ident) produce a "local ambiguity" error even though ident has no follow-set restrictions? Give one way to fix it.
Show answer
The follow-set check only restricts which tokens may come after a fragment, and ident has no limits. The ambiguity arises at invocation time. After each identifier, the matcher cannot tell whether it belongs to the repetition or is $last, and it does not backtrack. One fix is to add a separator token before the last item, for example ($($i:ident)* ; $last:ident). Another is to take the first item and then the rest, for example ($first:ident $($rest:ident)*).